Skip to content

GPU: open guarded pages in runs, not one VirtualProtect at a time - #2849

Open
Therecalloftheonion wants to merge 2 commits into
Marvisak:mainfrom
Therecalloftheonion:perf/guard-open-runs
Open

Therecalloftheonion wants to merge 2 commits into
Marvisak:mainfrom
Therecalloftheonion:perf/guard-open-runs

Conversation

@Therecalloftheonion

Copy link
Copy Markdown

Problem

Issue #400 puts about 600 ms a frame in the guard lock on an RTX 2080, with ~3,800 VirtualProtect calls a frame. Two hot paths opened guarded pages one call at a time:

  • changed_here (a title write over a range, e.g. a memset or a file read) collected the protected pages of the range and called VirtualProtect per page.
  • Tracked::drop did the same for every page freed when the last tracker let go of it.

The pages are already in sorted order in both callers.

Change

open_pages groups consecutive guarded pages and open_range makes one VirtualProtect call per run. Only runs where every page is guarded are opened; unguarded pages are skipped exactly as before, and the guard set, changed marks and saved snapshots are unchanged.

This is not #1884: that sorts/deduplicates alias pages and replaces active-writer scans; this batches the write-access restore calls themselves. It does not touch the copy path or the listed copy PRs.

Benchmark

cargo test --release -p victory-gpu benchmark_guard_open_runs -- --ignored --test-threads=1 --nocapture, 512 pages, 20 rounds, RX 6700 XT, release:

path VirtualProtect calls time
one call per page (old) 10,240 4.27 ms
one call per run (new) 20 1.79 ms

The test-only switch runs both paths on the same protected pages, so this is a direct before/after. It measures the write-access restore step only, not game FPS; no title data was available here.

Tests

  • New watch::tests::a_bulk_write_opens_guarded_pages_in_one_call: an 8-page write opens the run with one call and every page is read-write again.
  • cargo test -p victory-gpu --lib: 227 passed, 2 ignored. Two unrelated upstream tests are filtered because they fail on main on this machine (the 2^21 view-heap assertion and the copy-pair placement test).
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • rustfmt --check on the file reports pre-existing differences (first at line 100, unrelated); the new code follows the surrounding style.

Regressions

  • open_pages relies on the sorted page lists both callers already provide; a future unsorted caller would lose batching but not correctness (unguarded pages are skipped).
  • Opening a run is only done when every page in it is guarded; a gap breaks the run.
  • Runtime behaviour and GPU synchronization are unchanged: this only restores page protection before the write that already caused it.

All Windows D3D12 vendors benefit equally; it is host CPU/kernel work, not GPU-specific.

A bulk title write and a dropped tracker both make guarded pages writable again: changed_here opened each protected page of a range with its own VirtualProtect, and Tracked::drop opened each freed page the same way. The pages are sorted in both callers, so open_pages now groups consecutive guarded pages and open_range makes one VirtualProtect call for the run.

The guard state, the pages opened and the changed marks are the same; only runs that are wholly guarded are opened, and pages not guarded are skipped as before.

Benchmark (512 pages, 20 rounds, release, RX 6700 XT): one call per page 10,240 VirtualProtect calls in 4.27 ms; one call per run 20 calls in 1.79 ms, a 2.4x reduction in the open step. This is not a game-FPS measurement.

Tests: a_bulk_write_opens_guarded_pages_in_one_call (8-page run, one call, every page read-write again); the watch suite passes (16 tests); the GPU suite passes apart from two unrelated upstream failures on this machine. A test-only switch runs the old per-page path in benchmark_guard_open_runs for the before/after numbers.
@fuzeofficlal

Copy link
Copy Markdown
Contributor

Tested 7be4f20d on Windows 11 (RTX 5090 + WARP) and benchmarked --release, but caught a real Windows VirtualProtect boundary bug in open_range:

Bug: VirtualProtect fails across adjacent VirtualAlloc regions without fallback

  • open_range removes [first, last) from g.protected and issues one VirtualProtect((first * PAGE) as ..., (last - first) * PAGE, PAGE_READWRITE, &mut old) while ignoring the BOOL return value.
  • On Windows, VirtualProtect fails with ERROR_INVALID_ADDRESS (487) and leaves all pages untouched whenever the range crosses two separate VirtualAlloc reservations/allocations (even if they are contiguous and all present in g.protected) or contains a freed/uncommitted page.
  • Confirmed locally on Windows 11 with two adjacent 64 KiB VirtualAlloc(..., PAGE_READONLY) regions: a single 128 KiB VirtualProtect(..., PAGE_READWRITE) returned ok=0, err=487, while per-page calls succeeded (ok=1).
  • Because g.protected already removed those pages, the next write hits a still-PAGE_READONLY page outside the guard set and crashes with an unhandled 0xc0000005.
  • Checking VirtualProtect(...) != 0 and falling back to per-page VirtualProtect when last - first > 1 (matching protect_noting in watch.rs) avoids this cleanly.

Local test & benchmark results

@kotekompotek kotekompotek left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct batching: the debug_assert that a run is fully guarded is exactly the safety property needed — one VirtualProtect over a partial run would silently change protection of pages that aren't ours or that another tracker watches. Collecting to_open first keeps the same semantics as the per-page loop. LGTM.

@Therecalloftheonion

Copy link
Copy Markdown
Author

Thanks @fuzeofficlal. Confirmed and accepted: VirtualProtect can fail across two separate VirtualAlloc regions, and my open_range removed the pages from protected before ignoring the return. A later write then faults on a still-read-only page outside the guard set.

I also see #2848 item 6 implements the same open-runs optimization. This PR is a duplicate of that item, so I am closing it rather than carrying a second copy. The failure and the fallback belong on #2848; I have left the detail there. No credit claimed here.

VirtualProtect returns 0 with ERROR_INVALID_ADDRESS (487) when a run crosses two separate VirtualAlloc regions or an uncommitted page, even when every page is guarded and ours. open_range removed the pages from the guard set first and ignored the BOOL, so on failure they stayed read-only but unguarded; the next write faulted and could access-violate.

Check the batch result and, when it fails, restore the run one page at a time as the old path did. The pages were already taken out of the guard set; the fallback opens each of them, and a page that is gone fails harmlessly as before.

Adds a regression test with two adjacent pages allocated separately: both are guarded, the batch is attempted, and both must end up PAGE_READWRITE with the guard set empty. The benchmark is unchanged when the batch succeeds (4.13 ms against 1.61 ms over 20 rounds of 512 pages).
@Therecalloftheonion

Copy link
Copy Markdown
Author

Reopened with the fix for the ERROR_INVALID_ADDRESS (487) failure found by @fuzeofficlal.

open_range now checks the batch VirtualProtect result and, when it is 0, restores the run one page at a time (the pages were already taken out of g.protected; the per-page calls put them back to PAGE_READWRITE and a page that is gone still fails harmlessly, as the old path did).

Added open_runs_falls_back_across_separate_allocations: two adjacent pages allocated separately, both guarded, then open_pages; both must be PAGE_READWRITE and no longer in protected. On this machine the two-page batch is the only run, so the test exercises the fallback path.

Benchmark unchanged when the batch succeeds: 512 pages, 20 rounds, release: 4.13 ms (10,240 calls) vs 1.61 ms (20 calls). The fix adds no work to the success path.

Still overlaps #2848 item 6 (2851648), which has the same batching and the same missing fallback; the fix applies there too. Maintainers can keep either; I am not claiming a separate contribution for the same optimization.

@Machad3x

Machad3x commented Nov 25, 2026 •

Copy link
Copy Markdown

Hardware result at head 7be4f20, cherry-picked onto a fork stack that opens a changed page's aliases too, RTX 3080 Ti, driver 621.24.

  1. A run can cross allocations: with two mapped views of one memory next to each other in the sorted pages, the single VirtualProtect fails (a call cannot span allocations), the pages are already removed from the guard set, and the next write faults for ever (access violation in a two-mapping tracker test the stack carries). Opening page by page when the call returns 0 fixed the test. On main this needs two adjacent views both in one run.
  2. Timing: correction of what this comment first said. We compared one run with the change (724 ms a frame, guard lock 305 ms) against one without (675 ms, 114 ms), but a later run without it measured 325 ms of guard lock, so that figure swings between runs by more than the difference. We have no measured effect either way.

Ran with AI assistance (Claude Code).

@liandraraiane

Copy link
Copy Markdown

Measured on a Ryzen 7 5700G (16 threads) + RTX 3060, Windows 11, release, against their base f3578e3, with a guard-lock contention benchmark (writer threads faulting on guarded pages while a submission thread arms and takes every tracker in rounds, plus a kernel-writer thread opening 8-page ranges with writing every 200 µs; guard_lock_contention_bench on branch liandraraiane/VIctory:perf/guard-lock-contention). Median of 5 rotated runs:

writers fault p99 µs (base / #2848 / #2849) 8-page writing p50 µs p99 µs
8 424 / 406 / 417 387 / 390 / 390 822 / 702 / 754
15 588 / 589 / 607 418 / 414 / 426 1131 / 1125 / 1150

With writers pausing 50 µs between writes the picture is the same. Under contention the time is waiting for the guard lock, not the open calls, so batching them does not show here. Even with one writer, an 8-page writing takes ~270 µs, almost all queued behind takes. Both pass a 12-thread stress test (writes vs takes and copies, no write lost, no stray fault) 20/20. Not tested: the title; ranges longer than 8 pages; #2848's other six changes.

AI use: Claude Code ran the builds and benchmarks on this machine and drafted this comment.

crashbashash added a commit to crashbashash/VIctory-proton that referenced this pull request Nov 26, 2026
After a submission, each 64 KiB page shaders marked as written through
views was compared and, if it differed, written back on its own: one hold
of the guard lock, the page opened, written and guarded again. In the
prison scene that is about 1,950 pages a frame and 61-62 ms, 45-48 ms of it
holding the guard lock that title threads' write faults wait for.

The pages come in order, so `copy_back_marks` hands each copy its runs of
consecutive pages, and `Shadow::copy_back_marked` compares them page by page
as before but writes the whole pages that differ, next to each other, in
one go: the copy holds the bytes of all of them (what goes back is its
bytes, or the merge `merge_writeback` leaves in both). `write_back_pages`
does for a run what `write_back_page` did for a page, under one hold of the
lock, opening (upstream PR Marvisak#2849) and guarding in runs. A page the title
wrote unarmed, one equal to title memory or a part page ends a run and is
handled as before.

Measured against the same build without it (two runs each): about 185
writes a frame instead of about 1,940, 44-47 ms instead of 61-62, and the
lock held 33 ms instead of 45-48 ms there; frame times within the noise.
Tests: a run with a page equal to title memory between written ones, two
armed pages merged and written as one run, and a two-page write-back taken
here and changed for another tracker.
crashbashash added a commit to crashbashash/VIctory-proton that referenced this pull request Nov 26, 2026
… in runs) and the view tree

Rows for the three GPU commits and the diagnostics with what they measured; the views section notes that our Proton build's wineserver finds views in a tree.

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Verdict: needs work (small). The batching in open_pages / open_range (crates/victory-gpu/src/watch.rs) looks correct. Runs are opened only when every page is guarded. The per-page fallback when the batched VirtualProtect returns 0 covers the cross-allocation failure fuzeofficlal found. The pages leave protected as before, and OpenPages still counts pages. What needs fixing before a merge:

  • The diff deletes the doc comment of the existing test writes_mark_every_tracker_of_their_page ("Everything is changed at first; …"). Please restore it.
  • The doc comment on open_pages links to [open], which this PR removes.

For the maintainers: #2848 (item 6) makes the same batching change in watch.rs without the fallback, and the two conflict. If that item is kept, it needs the same fallback. The microbenchmark shows the restore step about 2.4x faster. liandraraiane's contention benchmark and Machad3x's title run show no measured effect, so the gain in the title is unproven.

CI: passing (check).


Generated by Claude Code

iLucasRT pushed a commit to iLucasRT/VInAMD that referenced this pull request Nov 26, 2026
protect_here and protect_alias made PAGE_READONLY over a whole 64 KiB block,
or over a whole range, after looking at the first page's old protection
only. A PAGE_GUARD page the title set further on in that block lost its guard
with no fault and no write seen. Now a change of protection covers only
blocks that Windows says are alike (committed, one region, read-only or
read-write throughout). A block that is not gets no call and stays as it is,
with VICTORY_GUARD_RUNS on or off.

Runs (VICTORY_GUARD_RUNS, on; =0 keeps one call per block where a range is
not one alike region):
- unguard: blocks that follow one another in one view are opened with one
  call.
- protect_here: one call per run of alike blocks within each view the runtime
  told of. A call across two views is refused, so runs are cut there.
- cover: the other views of a run of guarded pages are made read-only with
  one call per run (protect_alias_runs); protect_alias takes what is left.

With =0 a range is asked for whole only when it is one alike region, so the
call across views that was refused is no longer made.

Counter on victory_gpu::host (diagnostics builds), on the 5 s lines: calls and
blocks per frame for giving write access back and for making read-only, and
the refused ones ("the guards' changes of protection per frame").

Tests (watch::tests): a_write_over_guarded_blocks_opens_them_with_one_call,
a_write_inside_guarded_blocks_opens_its_own_and_no_others,
runs_of_guarded_blocks_are_cut_where_views_meet,
other_memory_inside_a_run_keeps_its_protection,
the_other_views_of_a_guarded_run_are_guarded_with_one_call,
a_page_the_title_guards_inside_a_range_keeps_its_guard,
a_page_the_title_guards_in_another_view_keeps_its_guard.

Credits: Marvisak/VIctory PR Marvisak#2849 (Therecalloftheonion) for the idea of one
change of protection per run of guarded pages; PR Marvisak#2848 item 6 (pes7) for
giving guarded pages back in runs. As we read them, their runs ignore view
boundaries and the call's result, so their code does not fit this tree; this
is a new implementation for it.

(cherry picked from commit 8b8da9b06fe3a252184876d6e84f7f3d8238a93f)
clquwu added a commit to clquwu/leonida-ultimate that referenced this pull request Nov 26, 2026
…BVH hot-path & XDXR BOX16 fix

- XMA2: atomic CAS in XmaContextView::set_field (Marvisak/VIctory#1537, GPL-3.0), PacketSkipCount==0xFF EOS (Zettrox/ztrx#152, GPL-3.0), static precomputed IMDCT twiddle LUTs + stack buffers (Belobug/VIctory-Belobug-AMD#35, GPL-3.0)
- BCrypt: accept BCRYPT_RNG_ALG_HANDLE (0x81) pseudo-handle in gen_random and reject in close_algorithm_provider (ubiquitarianism/leonida#2132, GPL-3.0)
- XMem: batch contiguous VirtualProtect guard-page runs (Marvisak/VIctory#2849, GPL-3.0), cache/reuse placeholder prefix bounds (JMAN730/project-flamingo#777, GPL-3.0), guard write-tracking against MEM_FREE/MEM_IMAGE
- Xbox BVH builder: ScopedWaitLabel stall attribution (xbox_bvh_build/xbox_bvh_rehydrate), ReadableRegionCache + per-call BLAS header cache for TLAS, single-pass active partition, bulk array VA resolution
- XDXR: fix BOX16 sign-bit extraction in xdxr_build.comp (ubiquitarianism/leonida#1210, GPL-3.0) and recompile xdxr_build.inc via glslc + spirv-val
@MeMako

MeMako commented Nov 26, 2026

Copy link
Copy Markdown

Verified #2849 (7b1316a) on Windows 11 (10.0.26200, Ryzen 9 7950X, RX 9070 XT, driver 32.0.32029.2010, 32 GB RAM).

Tests & Microbenchmark

  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings: clean.
  • victory-gpu: 272/272 passed (including a_bulk_write_opens_guarded_pages_in_one_call).
  • benchmark_guard_open_runs (--release, 512 pages × 20 rounds):
    • One call per page (10,240 VirtualProtect calls): 5.120 ms
    • One call per run (20 VirtualProtect calls): 1.336 ms (3.83x faster)

Live Title Verification & Integration Note

  • Setup: Local integration branch (main 63bcca4 + #2051 + #2472 + #2918 + #1010 + #2130 with VRAM upload flags off + #3055 + #2914), adding #2985 + #2849 + #3035 together in the same live run (n=54 world frames / n=38 heavy frames vs. n=51 / n=38 baseline).
  • Result: 0 crashes or faults through the intro and opening world scene.
  • Subsystem metrics (steady tail, last 20 heavy frames — 6,186 draws vs. 5,290 draws in baseline):
    • prep → deferred: 92.7 → 71.8 ms (-20.9 ms / -22.5%)
    • copy_back: 99.2 → 75.5 ms (-23.7 ms / -23.9%)
    • (Both watch.rs timers reflect #2849 and #3035 combined; #2985 affects texture detile/upload separately.)
  • Combined frame-time delta (all three PRs #2985 + #2849 + #3035 together): steady-tail frame time dropped 453.3 → 423.6 ms (2.20 → 2.40 fps), even with +17% more draws.
  • Note for combining with #3035: Since #2849 replaces single-page open() with open_range(), #3035's opened(page).fetch_add(1, Ordering::Relaxed) bump simply moves inside open_range()'s if g.protected.remove(&page) loop (the single removal site) so both PRs compose cleanly.

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

@crashbashash

Copy link
Copy Markdown

On "the gain in the title is unproven": here is an in-game A/B from Linux, where every VirtualProtect is a Wine call
plus an mprotect, so the per-call cost the batching saves is larger than on Windows. RX 6800 XT, RADV,
GE-Proton11-14 (with a newer vkd3d-proton and the wineserver view tree), diag build of main 219878a plus our
Linux commits, with and without this PR (7b1316a, merges cleanly), a save in the prison, 120 s in the world, idle
machine, runs interleaved.

without with this PR
runs 2 2
world frame, median 619, 667 ms 490, 530 ms
of it preparing submissions 300, 303 ms 219, 249 ms
submissions per frame 23.3, 23.2 22.8, 23.0

No crash or change in behaviour in those runs, and the crate's tests pass under Wine, the fallback test included
(Wine also refuses a VirtualProtect whose range is not inside one view). Two runs a side is not a precise figure,
but both are well apart.

AI-assisted (Claude Code). No game data attached.

crashbashash added a commit to crashbashash/VIctory-proton that referenced this pull request Nov 26, 2026
After a submission, each 64 KiB page shaders marked as written through
views was compared and, if it differed, written back on its own: one hold
of the guard lock, the page opened, written and guarded again. In the
prison scene that is about 1,950 pages a frame and 61-62 ms, 45-48 ms of it
holding the guard lock that title threads' write faults wait for.

The pages come in order, so `copy_back_marks` hands each copy its runs of
consecutive pages, and `Shadow::copy_back_marked` compares them page by page
as before but writes the whole pages that differ, next to each other, in
one go: the copy holds the bytes of all of them (what goes back is its
bytes, or the merge `merge_writeback` leaves in both). `write_back_pages`
does for a run what `write_back_page` did for a page, under one hold of the
lock, opening (upstream PR Marvisak#2849) and guarding in runs. A page the title
wrote unarmed, one equal to title memory or a part page ends a run and is
handled as before.

Measured against the same build without it (two runs each): about 185
writes a frame instead of about 1,940, 44-47 ms instead of 61-62, and the
lock held 33 ms instead of 45-48 ms there; frame times within the noise.
Tests: a run with a page equal to title memory between written ones, two
armed pages merged and written as one run, and a two-page write-back taken
here and changed for another tracker.
crashbashash added a commit to crashbashash/VIctory-proton that referenced this pull request Nov 26, 2026
… in runs) and the view tree

Rows for the three GPU commits and the diagnostics with what they measured; the views section notes that our Proton build's wineserver finds views in a tree.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants