GPU, HLE: opt-in guarded writes for title memcpy and memset #3375

Open
lhnizdo wants to merge 3 commits from upstream-pr/3375 into main
lhnizdo commented 2026-11-26 20:51:00 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by lhnizdo on 2026-11-26T20:51:00Z.


On Windows, a title import of memcpy or memset from VCRUNTIME140.dll can write through a writable view of the same physical section while its title mapping stays read-only. Enable the experiment with VICTORY_COPY_BESIDE=1. The default keeps the host CRT bindings and the existing section layout.

The hook processes one 64 KiB destination page at a time. It pins the view registration, verifies protection, marks the page and its aliases dirty, and lets armed trackers save the old bytes before writing under the guard lock. Ordinary writes run after releasing those locks. A small bit table skips registry lookups for ordinary address regions. A stale bit only causes another lookup. Remapping unregisters the view before unmapping it. The resolver still checks the host allow-list and the presence of the actual export.

Measurements

On a Ryzen 7 2700X, the ignored guarded_crt_copy_benchmark alternates 3,200 native and redirected 4 KiB writes per sample on the same 32 freshly guarded pages, including the tracker take. Every round checks the dirty range, and every sample verifies the final bytes. On the standalone branch the three native samples measured 7.36, 9.17 and 9.37 µs/copy. The redirected samples measured 0.70, 0.70 and 0.75 µs/copy.

On a separate RTX 2080 integration stack, two five-minute runs used the same diagnostic executable with the BVH builder held back. The enabled run logged a redirected CRT write. Both runs reached the world and ended at the cutoff without device removal. Medians below use complete reporting intervals after world entry with at least 500 draws per frame.

World metric Off On
Reporting intervals 23 27
Draws/frame 4,696 3,329
Faults entering the opening path/frame 1,206 1,006
Handler time (ms/frame) 785 647
Time opening pages (ms/frame) 552 448
Total ms/frame 3,366 3,405

Streaming and draw counts differed. An earlier pair, before the region filter, also varied substantially. These runs establish that the title uses the path and show lower guard overhead in the final pair. They do not establish higher world FPS.

Verification against main

  • The Windows tests cover a write crossing from a guarded page into an ordinary page, alias dirty marking, preservation of armed bytes, unregistration, and the region filter. Four concurrent writers exercised both CRT calls while the tracker refreshed a mirror. Ten separate process runs produced the expected final bytes on every page.
  • The HLE import-resolution and physical map/alias/unmap tests passed with the switch both off and on.
  • RTX 2080, Windows 10 19045, release diagnostics GPU library suite: 245 passed, 5 failed, 2 ignored. The clean main control had the same five failures (descriptor dynamic slots, placed texture views, compute rebind after depth conversion, shared table/view lifetime, and depth bounds), with 241 passed and 1 ignored. The added ignored test is the microbenchmark.

Integration

#3069 targets marked GPU copy-back and has independent evidence about readers overlapping a write. This change targets title CRT calls. It holds the guard lock from the dirty mark through the page chunk's write. A refresh that already obtained its dirty ranges can still overlap title activity. A multi-page CRT copy has ordinary CRT visibility. If #3035 lands, its optimistic snapshot validation will need to account for writes through retained guards and their aliases.

The CRT interception idea follows avatarmanz's VIctory work.

AI-assisted (Codex).

<!-- greyfinch-sync:Marvisak/VIctory:issue:5516975339 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3375). Originally posted by [lhnizdo](https://github.com/lhnizdo) on 2026-11-26T20:51:00Z. --- On Windows, a title import of `memcpy` or `memset` from `VCRUNTIME140.dll` can write through a writable view of the same physical section while its title mapping stays read-only. Enable the experiment with `VICTORY_COPY_BESIDE=1`. The default keeps the host CRT bindings and the existing section layout. The hook processes one 64 KiB destination page at a time. It pins the view registration, verifies protection, marks the page and its aliases dirty, and lets armed trackers save the old bytes before writing under the guard lock. Ordinary writes run after releasing those locks. A small bit table skips registry lookups for ordinary address regions. A stale bit only causes another lookup. Remapping unregisters the view before unmapping it. The resolver still checks the host allow-list and the presence of the actual export. ### Measurements On a Ryzen 7 2700X, the ignored `guarded_crt_copy_benchmark` alternates 3,200 native and redirected 4 KiB writes per sample on the same 32 freshly guarded pages, including the tracker take. Every round checks the dirty range, and every sample verifies the final bytes. On the standalone branch the three native samples measured 7.36, 9.17 and 9.37 µs/copy. The redirected samples measured 0.70, 0.70 and 0.75 µs/copy. On a separate RTX 2080 integration stack, two five-minute runs used the same diagnostic executable with the BVH builder held back. The enabled run logged a redirected CRT write. Both runs reached the world and ended at the cutoff without device removal. Medians below use complete reporting intervals after world entry with at least 500 draws per frame. | World metric | Off | On | |---|---:|---:| | Reporting intervals | 23 | 27 | | Draws/frame | 4,696 | 3,329 | | Faults entering the opening path/frame | 1,206 | 1,006 | | Handler time (ms/frame) | 785 | 647 | | Time opening pages (ms/frame) | 552 | 448 | | Total ms/frame | 3,366 | 3,405 | Streaming and draw counts differed. An earlier pair, before the region filter, also varied substantially. These runs establish that the title uses the path and show lower guard overhead in the final pair. They do not establish higher world FPS. ### Verification against main - The Windows tests cover a write crossing from a guarded page into an ordinary page, alias dirty marking, preservation of armed bytes, unregistration, and the region filter. Four concurrent writers exercised both CRT calls while the tracker refreshed a mirror. Ten separate process runs produced the expected final bytes on every page. - The HLE import-resolution and physical map/alias/unmap tests passed with the switch both off and on. - RTX 2080, Windows 10 19045, release diagnostics GPU library suite: 245 passed, 5 failed, 2 ignored. The clean main control had the same five failures (descriptor dynamic slots, placed texture views, compute rebind after depth conversion, shared table/view lifetime, and depth bounds), with 241 passed and 1 ignored. The added ignored test is the microbenchmark. ### Integration #3069 targets marked GPU copy-back and has independent evidence about readers overlapping a write. This change targets title CRT calls. It holds the guard lock from the dirty mark through the page chunk's write. A refresh that already obtained its dirty ranges can still overlap title activity. A multi-page CRT copy has ordinary CRT visibility. If #3035 lands, its optimistic snapshot validation will need to account for writes through retained guards and their aliases. The CRT interception idea follows [avatarmanz's VIctory work](https://github.com/avatarmanz/VIctory-7900XTX). AI-assisted (Codex).
Dukestar69 commented 2026-11-26 21:10:15 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T21:10:15Z.

Review: APPROVED


LGTM — verified on Windows against origin/main (63bcca4).

  • Opt-in guarded writes for title memcpy/memset are cleanly isolated behind the switch and well-covered across concurrent writes, armed aliases, straddling ranges, and host import policy.
  • cargo test -p victory-gpu --lib watch:: -- --test-threads=1: 19 passed, 0 failed (1 ignored).
  • cargo test -p victory-hle --lib host:: -- --test-threads=1: 3 passed, 0 failed (including crt_copy_imports_follow_the_switch_and_host_policy).
  • cargo clippy -p victory-gpu -p victory-hle --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

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

<!-- greyfinch-sync:Marvisak/VIctory:review:6080507779 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3375#pullrequestreview-6080507779). Originally posted by [Dukestar69](https://github.com/Dukestar69) on 2026-11-26T21:10:15Z. **Review:** APPROVED --- LGTM — verified on Windows against `origin/main` (`63bcca4`). - Opt-in guarded writes for title `memcpy`/`memset` are cleanly isolated behind the switch and well-covered across concurrent writes, armed aliases, straddling ranges, and host import policy. - `cargo test -p victory-gpu --lib watch:: -- --test-threads=1`: 19 passed, 0 failed (1 ignored). - `cargo test -p victory-hle --lib host:: -- --test-threads=1`: 3 passed, 0 failed (including `crt_copy_imports_follow_the_switch_and_host_policy`). - `cargo clippy -p victory-gpu -p victory-hle --all-targets -- -D warnings`: clean. - `cargo xtask policy`: 191 files ok. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
fuzeofficlal commented 2026-11-26 21:11:17 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-26T21:11:17Z.

Review: APPROVED


Clean, well-contained opt-in experiment (VICTORY_COPY_BESIDE=1), keeping default host CRT resolution and section layout unchanged. Verified merged onto origin/main (63bcca43) on Windows 11 x64 (NVIDIA GeForce RTX 5090, VICTORY_D3D12_DEBUG=1):

  • Lock ordering & lifetime safety:
    • Lock acquisition forms a strict cycle-free DAG (PHYSICAL -> BESIDE_VIEWS -> GUARDS -> Changed): xmem::map (crates/victory-hle/src/modules/xmem.rs:861-866) and xmem::unmap (xmem.rs:998-1005) hold PHYSICAL while updating BESIDE_VIEWS / GUARDS, watch::bulk_chunk (crates/victory-gpu/src/watch.rs:941-955) holds BESIDE_VIEWS.read() -> GUARDS, and GUARDS never calls back into BESIDE_VIEWS or PHYSICAL.
    • xmem::unmap calls title_memory_beside_gone(at, size) before unmapping or dropping the Slice/Arc<Section>, so Section.1 cannot be unmapped while a bulk_chunk write is in flight.
    • Confirmed live on Windows 11 with a SEC_RESERVE section (XMemAllocatePhysicalPages + XMemMapPhysicalPages with VICTORY_COPY_BESIDE=1, and a standalone SEC_RESERVE watch.rs test) that committing the title view commits the shared backing pages in Section.1 as well (ours_state = MEM_COMMIT, PAGE_READWRITE), and tracked_memset on a guarded SEC_RESERVE page succeeds without faulting.
  • Verification:
    • cargo xtask policy (191 files ok) and cargo clippy --locked -p victory-gpu -p victory-hle --all-targets -- -D warnings (both default and --features victory-gpu/diagnostics) pass cleanly.
    • victory-gpu watch::tests::* (19/19 passed, 1 ignored benchmark) and victory-hle host:: + xmem:: (17/17 with VICTORY_COPY_BESIDE unset and 17/17 with VICTORY_COPY_BESIDE=1) all pass.
    • Additional adversarial checks passed: zero-length and self-copy (dst == src) no-ops do not dirty pages; multiple consecutive redirected writes followed by a native write fault on an armed page preserve the original pre-first-write saved bytes; forward (dst > src) and backward (dst < src) overlapping tracked_memcpy across guarded pages preserve exact bytes and dirty ranges; misaligned multi-page copies spanning 3 guarded pages match byte-for-byte.

Minor non-blocking observation if this ever graduates past opt-in: bulk_chunk executes the caller's write closure while holding BESIDE_VIEWS.read() and guards(). Read faults on src won't deadlock on_write (since on_write returns EXCEPTION_CONTINUE_SEARCH when ExceptionInformation[0] != WRITE), though if a title ever caught a fault inside memcpy via SEH __try/__except, unwinding past an extern "C" frame would skip Rust guard drops. Completely fine for an opt-in experiment.

LGTM!

<!-- greyfinch-sync:Marvisak/VIctory:review:6080515177 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3375#pullrequestreview-6080515177). Originally posted by [fuzeofficlal](https://github.com/fuzeofficlal) on 2026-11-26T21:11:17Z. **Review:** APPROVED --- Clean, well-contained opt-in experiment (`VICTORY_COPY_BESIDE=1`), keeping default host CRT resolution and section layout unchanged. Verified merged onto `origin/main` (`63bcca43`) on Windows 11 x64 (NVIDIA GeForce RTX 5090, `VICTORY_D3D12_DEBUG=1`): - **Lock ordering & lifetime safety**: - Lock acquisition forms a strict cycle-free DAG (`PHYSICAL -> BESIDE_VIEWS -> GUARDS -> Changed`): `xmem::map` (`crates/victory-hle/src/modules/xmem.rs:861-866`) and `xmem::unmap` (`xmem.rs:998-1005`) hold `PHYSICAL` while updating `BESIDE_VIEWS` / `GUARDS`, `watch::bulk_chunk` (`crates/victory-gpu/src/watch.rs:941-955`) holds `BESIDE_VIEWS.read()` -> `GUARDS`, and `GUARDS` never calls back into `BESIDE_VIEWS` or `PHYSICAL`. - `xmem::unmap` calls `title_memory_beside_gone(at, size)` before unmapping or dropping the `Slice`/`Arc<Section>`, so `Section.1` cannot be unmapped while a `bulk_chunk` write is in flight. - Confirmed live on Windows 11 with a `SEC_RESERVE` section (`XMemAllocatePhysicalPages` + `XMemMapPhysicalPages` with `VICTORY_COPY_BESIDE=1`, and a standalone `SEC_RESERVE` `watch.rs` test) that committing the title view commits the shared backing pages in `Section.1` as well (`ours_state = MEM_COMMIT`, `PAGE_READWRITE`), and `tracked_memset` on a guarded `SEC_RESERVE` page succeeds without faulting. - **Verification**: - `cargo xtask policy` (`191 files ok`) and `cargo clippy --locked -p victory-gpu -p victory-hle --all-targets -- -D warnings` (both default and `--features victory-gpu/diagnostics`) pass cleanly. - `victory-gpu` `watch::tests::*` (19/19 passed, 1 ignored benchmark) and `victory-hle` `host::` + `xmem::` (17/17 with `VICTORY_COPY_BESIDE` unset and 17/17 with `VICTORY_COPY_BESIDE=1`) all pass. - Additional adversarial checks passed: zero-length and self-copy (`dst == src`) no-ops do not dirty pages; multiple consecutive redirected writes followed by a native write fault on an armed page preserve the original pre-first-write `saved` bytes; forward (`dst > src`) and backward (`dst < src`) overlapping `tracked_memcpy` across guarded pages preserve exact bytes and dirty ranges; misaligned multi-page copies spanning 3 guarded pages match byte-for-byte. Minor non-blocking observation if this ever graduates past opt-in: `bulk_chunk` executes the caller's `write` closure while holding `BESIDE_VIEWS.read()` and `guards()`. Read faults on `src` won't deadlock `on_write` (since `on_write` returns `EXCEPTION_CONTINUE_SEARCH` when `ExceptionInformation[0] != WRITE`), though if a title ever caught a fault inside `memcpy` via SEH `__try/__except`, unwinding past an `extern "C"` frame would skip Rust guard drops. Completely fine for an opt-in experiment. LGTM!
Jackster commented 2026-11-26 22:55:32 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Jackster on 2026-11-26T22:55:32Z.


Windows 11, 63bcca4 + this PR, Radeon RX 7900 XTX:

  • cargo test -p victory-gpu --lib: 235 passed / 0 failed / 2 ignored (unpatched 63bcca4 here: 231 passed / 1 ignored; +5 and one more ignored — the benchmark).
  • cargo test -p victory-hle: lib 153 passed / 0 failed (unpatched: 152; +1), plus the integration suites.
  • cargo clippy -p victory-gpu -p victory-hle --all-targets -- -D warnings: clean.

The guarded-write tests (crt_writes_across_guarded_and_ordinary_pages, crt_write_preserves_armed_alias_and_unregisters_before_remap, crt_fast_check_keeps_registered_pages_and_straddling_ranges, concurrent_crt_writes_are_visible_after_the_last_take) all pass with guarded writes on, and the import-level test (crt_copy_imports_follow_the_switch_and_host_policy) is the victory-hle one. Synthetic only. AI-assisted.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7205103045 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3375#issuecomment-7205103045). Originally posted by [Jackster](https://github.com/Jackster) on 2026-11-26T22:55:32Z. --- Windows 11, `63bcca4` + this PR, Radeon RX 7900 XTX: - `cargo test -p victory-gpu --lib`: 235 passed / 0 failed / 2 ignored (unpatched `63bcca4` here: 231 passed / 1 ignored; +5 and one more ignored — the benchmark). - `cargo test -p victory-hle`: lib 153 passed / 0 failed (unpatched: 152; +1), plus the integration suites. - `cargo clippy -p victory-gpu -p victory-hle --all-targets -- -D warnings`: clean. The guarded-write tests (`crt_writes_across_guarded_and_ordinary_pages`, `crt_write_preserves_armed_alias_and_unregisters_before_remap`, `crt_fast_check_keeps_registered_pages_and_straddling_ranges`, `concurrent_crt_writes_are_visible_after_the_last_take`) all pass with guarded writes on, and the import-level test (`crt_copy_imports_follow_the_switch_and_host_policy`) is the victory-hle one. Synthetic only. AI-assisted.
kilolimaVI commented 2026-11-27 14:11:54 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by kilolimaVI on 2026-11-27T14:11:54Z.


Checked the new tests for stability on head 8712ae3: Windows 11, Ryzen 7 8845HS / Radeon 780M (AMD), toolchain 1.98.1.

  • The five new tests pass: crt_writes_across_guarded_and_ordinary_pages, crt_write_preserves_armed_alias_and_unregisters_before_remap, crt_fast_check_keeps_registered_pages_and_straddling_ranges, concurrent_crt_writes_are_visible_after_the_last_take (victory-gpu) and crt_copy_imports_follow_the_switch_and_host_policy (victory-hle).
  • Whole cargo test -p victory-gpu --lib --locked, default parallel threads, 20 runs in a row: 0/20 failures, so the concurrent test doesn't interfere with the other watch tests on this host.

AI-assisted (Claude).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7220474843 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3375#issuecomment-7220474843). Originally posted by [kilolimaVI](https://github.com/kilolimaVI) on 2026-11-27T14:11:54Z. --- Checked the new tests for stability on head 8712ae3: Windows 11, Ryzen 7 8845HS / Radeon 780M (AMD), toolchain 1.98.1. - The five new tests pass: `crt_writes_across_guarded_and_ordinary_pages`, `crt_write_preserves_armed_alias_and_unregisters_before_remap`, `crt_fast_check_keeps_registered_pages_and_straddling_ranges`, `concurrent_crt_writes_are_visible_after_the_last_take` (victory-gpu) and `crt_copy_imports_follow_the_switch_and_host_policy` (victory-hle). - Whole `cargo test -p victory-gpu --lib --locked`, default parallel threads, 20 runs in a row: 0/20 failures, so the concurrent test doesn't interfere with the other watch tests on this host. AI-assisted (Claude).
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3375:upstream-pr/3375'
git switch 'upstream-pr/3375'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3375'
git switch 'upstream-pr/3375'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3375'
git switch 'upstream-pr/3375'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3375'
git switch 'main'
git merge --squash 'upstream-pr/3375'
git switch 'main'
git merge --ff-only 'upstream-pr/3375'
git switch 'main'
git merge 'upstream-pr/3375'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
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.

Reference
Marvisak/VIctory!3375
No description provided.