Skip to content

perf(gpu,hle): unlock page guards across VirtualProtect, fast-path view/pool regions, and add beside-guard copy-back - #399

Closed
gdemontalivet wants to merge 5 commits into
pragyaangaur:mainfrom
gdemontalivet:perf/macos-watch-guard-unlock
Closed

gdemontalivet wants to merge 5 commits into
pragyaangaur:mainfrom
gdemontalivet:perf/macos-watch-guard-unlock

Conversation

@gdemontalivet

Copy link
Copy Markdown
Contributor

Under Wine + Rosetta on macOS, VirtualProtect, VirtualQuery, and GetWriteWatch(WRITE_WATCH_FLAG_RESET) acquire Wine's process-wide virtual_mutex and issue per-page host mprotect calls. Three bottlenecks and two subtle guard-page synchronization hazards compound on multi-threaded CPU/GPU workloads:

  1. Global GUARDS lock held across kernel memory calls & parallel virtual_mutex stampedes (watch.rs): Holding GUARDS while calling VirtualProtect and VirtualQuery serializes every faulting title thread (on_write), Tracked::take, writing, and Drop behind kernel page-protection round trips—while letting parallel refresh workers call VirtualQuery/VirtualProtect simultaneously stampedes Wine's virtual_mutex and starves fault handlers.
  2. Per-64 KiB VirtualQuery overhead & repeated write-fault storms on hot/aliased views (watch.rs, xmem.rs): Querying every 64 KiB view page via VirtualQuery on each guard pass adds thousands of wineserver/page-table walks per frame; meanwhile, frequently written CPU pages and aliased xmem section views fault and re-protect every submission, and opening every aliased view on each fault multiplies VirtualProtect syscalls.
  3. GetWriteWatch(WRITE_WATCH_FLAG_RESET) cost under Rosetta & redundant 4 KiB subpage re-copies (watch.rs, shadow.rs, xmem.rs): Resetting kernel write-watch state per 4 KiB page under Wine re-protects pages under virtual_mutex, while copying whole 64 KiB console pages or re-uploading GPU copy-back echoes wastes bandwidth when only a few 4 KiB subpages changed.
  4. Title PAGE_GUARD subpages & concurrent writing() / on_write races (watch.rs): Calling VirtualProtect(..., PAGE_READONLY) over a 64 KiB block containing a title PAGE_GUARD subpage silently strips the title's guard bit; and when VirtualProtect(..., PAGE_READWRITE) runs outside GUARDS, concurrent callers of writing() or on_write on the same 64 KiB page must wait until the reopen finishes or kernel NtReadFile (seek_read) fails with ERROR_NOACCESS (0x800703e6).

Changes

  • Release GUARDS across VirtualProtect / VirtualQuery with atomic on_commit reconciliation & PROTECT_SYSCALL serialization (watch.rs):
    • Introduce Held::unlock_for with (op_id, cancelled) guarding entries (GUARDING_CV) and opening ranges (OPENING_CV) so protect_inner and open_sorted_pages coalesce contiguous page runs and run kernel calls outside GUARDS.
    • Clear tracker dirty sets atomically via on_commit under the same GUARDS lock acquisition that inserts into g.protected—before open_sorted_pages unlocks GUARDS to reopen cancelled pages—so a write fault arriving during cancellation reopen cannot have its dirty bit wiped afterward.
    • Serialize protect_inner's VirtualQuery / VirtualProtect batch behind PROTECT_SYSCALL (outside GUARDS) so parallel refresh workers (perf(gpu): parallelize multi-shadow buffer refreshes and disjoint copy-back #280) queue orderly without stampeding Wine's virtual_mutex, while fault handlers (on_write) never wait behind VirtualProtect batches.
    • Ensure watch::writing and on_write wait on both OPENING_CV and cancelled GUARDING_CV transitions (and extend test(gpu): keep a test's memory allocated while the guards still hold it (#31) #305's still_watched test guard with g.guarding / g.opening).
  • Fast-path write_watched pools & registered xmem view spans while preserving title PAGE_GUARD (watch.rs, xmem.rs):
    • Restore the write_watched fast-path ahead of VirtualQuery in RuntimeRegions::classify when PAGE_GUARD checking has not been triggered.
    • Register live xmem section view spans via title_memory_mapped so RuntimeRegions::classify resolves view bounds in memory without per-64 KiB VirtualQuery syscalls unless PAGE_GUARD checking is active (cfg!(test), VICTORY_CHECK_PAGE_GUARD=1, or note_page_guard()). When active, PageClass::Alike verifies full-64 KiB MEM_COMMIT PAGE_READONLY | PAGE_READWRITE regions so title PAGE_GUARD subpages in primary or aliased views are never stripped.
  • Hot-page & 3 ms guard-rest leases across aliased views + single-view opening (watch.rs):
    • Promote repeatedly faulted pages (VICTORY_HOT_PAGES, default on) and recently faulted pages (VICTORY_GUARD_REST_MS, default 3 ms) across linked alias_of section views so steady-state CPU writes take zero VirtualProtect calls while cooling immediately when armed for GPU shader writes; in Tracked::arm, gate cooling on HOT_COUNT != 0 || RESTING_COUNT != 0 and slice changed.hot.range(first..last) so arm() skips O(range_pages) vector allocation and GUARDS acquisition whenever no hot pages fall inside first..last; open only the faulting view by default (VICTORY_OPEN_ONE_VIEW=0 opt-out).
  • Beside-guard xmem section copy-back & bounded 4 KiB subpage filtering (watch.rs, shadow.rs, xmem.rs, d3d12x.rs, copystat.rs):
    • Register xmem::copy_back_view (VICTORY_BACK_OWN_VIEW, default on, compatible with Back XMem physical pages with CPU-visible tile heaps on Rosetta #275 and perf(gpu): parallelize multi-shadow buffer refreshes and disjoint copy-back #280) using Section::existing_whole() so GPU copy-back writes and userspace read_own_view reads touch only already-mapped persistent section views (never calling MapViewOfFile under PHYSICAL), paired with VICTORY_LAND_ECHO to skip unchanged GPU copy-back echoes.
    • Default VICTORY_PAGE_PARTS to !rosetta() (avoiding Wine WRITE_WATCH_FLAG_RESET mprotect storms unless explicitly enabled) and compare seeded 4 KiB subpages in userspace for <= 256 KiB runs (VICTORY_SHADOW_COMPARE_4K, default on), fast-pathing unseeded and > 256 KiB bulk runs to a single whole-range copy.

Synthetic Benchmarks & Concurrency Tests (CrossOver Preview + D3DMetal on M5 Max)

  • concurrent_writing_on_same_guarded_page_waits_until_page_is_writable: 8 worker threads × 200 rounds (1,600 concurrent writing() + kernel FileExt::seek_read calls into disjoint 624-byte slices of one PAGE_READONLY 64 KiB section view) — 0 ERROR_NOACCESS failures.
  • multithreaded_fault_and_take_contention_preserves_writes_and_cuts_lock_wait (6 writer threads × 4 pages × 80 rounds): zero lost writes under concurrent fault/take contention while cutting VirtualProtect calls and GUARDS lock hold/wait times.
  • repeated_writes_through_aliased_views_promote_hot_with_zero_protects: 0 VirtualProtect calls and 0 ns GUARDS hold time across steady-state aliased frame writes.
  • unchanged_4k_subpages_are_skipped_on_whole_page_refresh & landed_gpu_writes_skip_redundant_echo_refresh_unless_title_modified: 2 / 16 modified 4 KiB subpages copy 8,192 B instead of 65,536 B, and unchanged GPU copy-back echoes copy 0 B.

Verification

  • CrossOver Preview with D3DMetal on an M5 Max, using an isolated test bottle:
    • watch::tests: 37/37 passed × 3 parallel rounds (covering PAGE_GUARD preservation in primary and aliased views, atomic on_commit under contention, and concurrent writing() + NtReadFile synchronization).
    • shadow::tests: 34/34 passed; xmem::tests: 16/16 passed; native macOS workspace suite passed.
    • cargo xtask policy (256 files ok), git diff --check, and cargo clippy (-- -D warnings, with and without --features diagnostics, 0 warnings) passed. All test inputs are synthetic.

Live M5 Max Verification (Combined Build on CrossOver Preview + D3DMetal)

  • In a combined warm-cache 720p opening-sequence run on Apple M5 Max (CrossOver Preview + D3DMetal, wave32=true), the runtime reached and sustained the 3D world through +8, +24, +48, +90 at 1.5–1.8 FPS (549.7–672.1 ms/frame on 1,021–1,258 draws/frame, 1.275 FPS overall across +8..+90) with 0 2.48 s allocation stalls, 7.2–9.0 ms/frame GUARDS lock hold time (down from 4,887 ms/frame before unlocking GUARDS), 149–154 MB/frame buffer copy volume, 0 DirectStorage decompression or access-violation failures, and 38/38 over-32 KiB aligned mesh/pixel pairs linked with 0 host mesh refusals.

…esting aliases, and add beside-guard copy-back

- Unlock GUARDS across VirtualProtect and VirtualQuery via Held::unlock_for with op_id guarding and opening coordination, committing tracker dirty-set clears atomically under GUARDS before reopening cancelled pages.
- Serialize protect_inner VirtualQuery/VirtualProtect batches via PROTECT_SYSCALL (outside GUARDS) so parallel refresh workers do not stampede Wine's virtual_mutex while fault handlers remain lock-free of VirtualProtect.
- Restore the write_watched fast-path before VirtualQuery in RuntimeRegions::classify, track live xmem section view spans via title_memory_mapped to skip per-view VirtualQuery unless PAGE_GUARD checking is enabled (cfg!(test), VICTORY_CHECK_PAGE_GUARD=1, or note_page_guard), and preserve title PAGE_GUARD subpages in primary and aliased views.
- Propagate hot-page and 3 ms guard-rest leases across aliased xmem section views, open only the faulting view by default (VICTORY_OPEN_ONE_VIEW), and wait on OPENING_CV and cancelled GUARDING_CV transitions in watch::writing and on_write.
- Bypass title page guards on GPU shader copy-back via already-mapped persistent xmem section views (VICTORY_BACK_OWN_VIEW, never calling MapViewOfFile under PHYSICAL) and skip unchanged GPU echoes (VICTORY_LAND_ECHO).
- Default VICTORY_PAGE_PARTS to !rosetta() and compare seeded 4 KiB subpages in userspace for <= 256 KiB runs (VICTORY_SHADOW_COMPARE_4K), fast-pathing unseeded and > 256 KiB runs to a single whole-range copy.
Fix three concurrency edge cases in watch::on_write that could return
EXCEPTION_CONTINUE_SEARCH on a stale write fault for a guarded page
whose protection was concurrently restored to read-write:

1. Check writable(at) while still holding GUARDS instead of after
   dropping it: previously, a concurrent protect_inner could re-protect
   the page to PAGE_READONLY between drop(g) and writable(at), causing
   a stale fault on an already-opened tracked page to go unhandled.
2. In the HOLDING re-entrant fault path, also resume and queue the page
   in OPENED_UNDER_LOCK when writable(at) is already true because
   another thread's open_sorted_pages restored PAGE_READWRITE outside
   GUARDS before read_only(at) ran.
3. Mask modifier bits (info.Protect & 0xff, rejecting PAGE_GUARD) in
   writable() and read_only() so cache-modifier flags or
   PAGE_EXECUTE_READWRITE do not fail the protection check.

Add unit and multithreaded contention tests covering stale faults after
guard open, re-entrant HOLDING stale faults, protection-flag negative
controls, and concurrent re-protection.
…t/alias transitions

Eliminate redundant VirtualProtect syscalls, guard-lock round trips, and
ReadProcessMemory overhead across shadow refreshes and GPU copy-back:

1. Multi-view lazy-mapped own-view copy-back (xmem::copy_back_view):
   - Lazily map Section::whole() outside PHYSICAL on first use per
     section (previously existing_whole() returned None for GPU heap
     sections not touched by DirectStorage, causing a 0% hit rate).
   - Support multi-view spans across scattered 64 KiB physical-page
     views via &mut [&mut [u8]] segments with pairwise-disjointness
     checks and canonical section borrow-lock ordering.
   - Use watch::copy_back_bytes in host::copy_mapped (title_dst) and
     watch::read_own_view_chunks in Shadow::copy_back_marked so marked
     comparisons, GPU writebacks, and title-to-title copies stay
     userspace and keep title page guards intact without opening/re-guarding.

2. Single-batch protect_with_aliases in watch.rs:
   - Combine guarding of cold_whole pages and their alias mappings into
     one GUARDS unlock + PROTECT_SYSCALL pass (eliminating double
     round trips and AliasUs double-serialization) and reuse Tracked's
     coalesced write-watched pool runs instead of per-page GetWriteWatch.

3. Batched alias registration and no-op unmap/map guard opens:
   - Unmap views before calling title_memory_unmapped so xmem::unmap
     no longer calls VirtualProtect(PAGE_READWRITE) on views about to be
     destroyed, and skip redundant self-opens in title_memory_mapped.
   - Batch xmem::map alias notifications into title_memory_mapped_aliased
     (one GUARDS lock and one coalesced VirtualProtect call per view)
     and fast-path empty alias lists in title_memory_aliased.

Verified with cargo xtask policy, gnullvm workspace clippy (default and
diagnostics), and Wine watch::, shadow::, and xmem:: test suites.
@Nick233x

Copy link
Copy Markdown
Contributor

Test runs of this PR on an M5 Pro. MacBook Pro, Apple M5 Pro, 24 GB, macOS 26.6.2, Game Porting Toolkit 4.0 beta 3 (D3DMetal), Wine built by setup.sh. I tested the PR head 9264107 merged onto current main bf99e72 (the merge is clean). Everything ran under Wine with tools/macos/test-wine.sh and default test threads. Synthetic only, no game files.

Results

Tree victory-gpu --lib runs Failed
main bf99e72 60 0
this PR on bf99e72 60 36

The two trees ran alternately, one run each in turn, so both saw the same load. Each failure was in one or two of the PR's new hot-page tests, never in an existing test:

  • repeated_writes_through_aliased_views_promote_hot_with_zero_protects failed in 17 runs.
  • guarded_and_hot_pools_take_only_written_4k_subpages failed in 9 runs.
  • remapping_clears_hot_page_state failed in 8 runs.
  • arming_a_hot_page_reguards_immediately_and_saves_bytes failed in 5 runs.

The first full run, and victory-hle --lib, passed: 383 and 164 tests.

Cause: the tests share the frame clock

watch::tests:: only Runs Failed
--test-threads=1 20 0
default threads 20 11
default threads, the hot-page tests holding one test mutex 20 0
full victory-gpu --lib, same mutex 30 0

The hot leases, the fault window and the rest expiry all count frames on the one Guards::frame. Under cfg(test), frame_done() always advances that clock. Several of these tests call it to cool their own page, and each call also ages the other running tests' leases and clears their faults. So, depending on timing, another test's page cools early, is never promoted, or is already hot when the test expects it cold. In the game the clock moves once per present, so I read this as a test-isolation problem, not a fault of the mechanism. This is the change that made it stable here. It is local only and not pushed:

/// One test at a time drives the shared frame clock (`Guards::frame`).
static HOT_FRAMES: std::sync::Mutex<()> = std::sync::Mutex::new(());

The first line of each of the eight tests that use hot pages, the guard rest or frame_done() takes HOT_FRAMES.lock().unwrap_or_else(|e| e.into_inner()). The eight tests are the four above plus hot_pages_skip_reguard_and_cool_down_after_idle_frames, gpu_copy_back_cools_hot_page_without_false_title_change, guard_rest_keeps_recently_faulted_page_open_and_reguards_after_expiry and multithreaded_fault_and_take_contention_preserves_writes_and_cuts_lock_wait.

The contention test, and what the primitives cost here

multithreaded_fault_and_take_contention_preserves_writes_and_cuts_lock_wait, 5 runs, --nocapture:

Wall GUARDS hold Lock wait Protects counted
cold (hot pages and rest off) 39–56 ms 14–21 ms 41–82 ms ~1,800
hot + rest 3.2–4.0 ms 2.7–3.2 ms 5–10 ms 0

No lost writes in any run. Two notes:

  • Both legs are this PR's code, so the table measures the hot pages and the rest, not the PR against main.
  • PROTECTS is a thread-local, so the column counts only the taking thread's calls, not the writers'.

To see why the hot pages pay off, I timed the primitives in a small stand-alone Windows program under the same Wine (x86-64 through Rosetta). It used 64 KiB pages, with memory both private and as 4,096 views of a pagefile section in one placeholder reservation, as XMem maps the pool:

Operation Cost
ReadProcessMemory on our own process (copy_mapped) 38–40 GB/s, ~2.6 µs per 64 KiB
VirtualProtect, one 64 KiB view 1.5 µs
VirtualQuery 0.5–2.3 µs
write fault on a guarded page, opened by a vectored handler 22–27 µs (~80 µs each with 8 threads faulting at once)
VirtualProtect from 1 → 8 threads 594k → 315k calls/s in all

The costs did not change between 256 and 49,408 mapped views. So a guarded page that is written again costs about ten times what copying it whole would. Past roughly one write in ten takes, leaving it open is cheaper, which is the case this PR's hot pages are built for.

AI-assisted, prepared with Claude Code.

…or resting pages

Hot and resting pages stay PAGE_READWRITE between takes so CPU writes land
without faulting. Previously, Tracked::changed() only checked Dirty::pages
(returning false for Dirty::hot and Dirty::rearmed), Tracked::unarm() cooled
hot pages into Dirty::rearmed instead of Dirty::pages, Shadow::copy_back_page()
did not cool hot pages, and Shadow::writing(..., true) guarded cooled hot pages
without pulling pre-arm silent CPU writes into the shadow copy. As a result,
copy_back_marked() and copy_back_page() could overwrite newer silent CPU writes
with stale shadow bytes.

Fix all three holes:
- Treat Dirty::hot and Dirty::rearmed as changed in Tracked::changed().
- Cool hot pages into Dirty::pages (rearm = None) in Tracked::unarm(), and
  call Tracked::unarm() in Shadow::copy_back_page() so GPU-written pages cool
  and keep title bytes for that submission.
- Return whether Tracked::arm() cooled any hot/resting pages so Shadow::writing()
  immediately refreshes those whole pages into the shadow copy before GPU
  execution, and skip saving a baseline in mark_changed() if a page was still
  open/rearmed.
- Update watch unit tests and add shadow + live D3D12 compute-shader regression
  tests covering hot and resting pages across unarmed copy_back_marked,
  copy_back_page, and armed pre-arm + post-arm CPU writes.
@gdemontalivet

Copy link
Copy Markdown
Contributor Author

Added 3d8dc436 fixing hot/resting-page (PAGE_READWRITE) copy-back clobber holes identified while auditing write-watch copy-back ordering:

  • Tracked::changed(page) now treats unguarded d.hot and d.rearmed pages as changed so copy_back_marked / copy_back_page never overwrite silent CPU writes with stale shadow bytes.
  • Tracked::unarm(page) cools hot pages directly to d.pages (cool_for_gpu(..., None)), mark_changed prevents stale saved baselines when faulting on a page still in hot/rearmed, and Shadow::writing(..., true) refreshes newly cooled hot pages before GPU execution.
  • Verified with live Wine/D3DMetal compute-shader regression tests (draw::tests::hot_and_resting_uav_copy_back_preserves_cpu_writes, shadow::tests::hot_and_resting_shadow_copy_back_preserves_cpu_writes — FAIL -> PASS) and 76/76 watch::tests:: + shadow::tests:: passing.

@pragyaangaur

Copy link
Copy Markdown
Owner

Thanks for this. Many pull requests landed today, and this one now conflicts with main. Could you merge or rebase main into it, rerun the checks and ping here? I will review and merge it as soon as CI is green.

@pragyaangaur

Copy link
Copy Markdown
Owner

Thank you. #400 (a 1,276-line rewrite of the xmem views), #430 (shadow baseline hashes), #457 and #439 have merged since this was written, and they change shadow.rs, watch.rs and xmem.rs in ways that clash with the guard-unlock design here in about 35 places, so a mechanical rebase would not be sound. If the unlock across VirtualProtect still matters on top of main, please resend it as smaller PRs against main (watch.rs first), each with its numbers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants