Repository navigation
perf(gpu,hle): unlock page guards across VirtualProtect, fast-path view/pool regions, and add beside-guard copy-back - #399
Conversation
…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.
|
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 Results
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:
The first full run, and Cause: the tests share the frame clock
The hot leases, the fault window and the rest expiry all count frames on the one /// 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 The contention test, and what the primitives cost here
No lost writes in any run. Two notes:
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:
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.
|
Added
|
|
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. |
…guard and the untracked page checks
|
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. |
Under Wine + Rosetta on macOS,
VirtualProtect,VirtualQuery, andGetWriteWatch(WRITE_WATCH_FLAG_RESET)acquire Wine's process-widevirtual_mutexand issue per-page hostmprotectcalls. Three bottlenecks and two subtle guard-page synchronization hazards compound on multi-threaded CPU/GPU workloads:GUARDSlock held across kernel memory calls & parallelvirtual_mutexstampedes (watch.rs): HoldingGUARDSwhile callingVirtualProtectandVirtualQueryserializes every faulting title thread (on_write),Tracked::take,writing, andDropbehind kernel page-protection round trips—while letting parallel refresh workers callVirtualQuery/VirtualProtectsimultaneously stampedes Wine'svirtual_mutexand starves fault handlers.VirtualQueryoverhead & repeated write-fault storms on hot/aliased views (watch.rs,xmem.rs): Querying every 64 KiB view page viaVirtualQueryon each guard pass adds thousands of wineserver/page-table walks per frame; meanwhile, frequently written CPU pages and aliasedxmemsection views fault and re-protect every submission, and opening every aliased view on each fault multipliesVirtualProtectsyscalls.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 undervirtual_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.PAGE_GUARDsubpages & concurrentwriting()/on_writeraces (watch.rs): CallingVirtualProtect(..., PAGE_READONLY)over a 64 KiB block containing a titlePAGE_GUARDsubpage silently strips the title's guard bit; and whenVirtualProtect(..., PAGE_READWRITE)runs outsideGUARDS, concurrent callers ofwriting()oron_writeon the same 64 KiB page must wait until the reopen finishes or kernelNtReadFile(seek_read) fails withERROR_NOACCESS(0x800703e6).Changes
GUARDSacrossVirtualProtect/VirtualQuerywith atomicon_commitreconciliation &PROTECT_SYSCALLserialization (watch.rs):Held::unlock_forwith(op_id, cancelled)guardingentries (GUARDING_CV) andopeningranges (OPENING_CV) soprotect_innerandopen_sorted_pagescoalesce contiguous page runs and run kernel calls outsideGUARDS.on_commitunder the sameGUARDSlock acquisition that inserts intog.protected—beforeopen_sorted_pagesunlocksGUARDSto reopen cancelled pages—so a write fault arriving during cancellation reopen cannot have its dirty bit wiped afterward.protect_inner'sVirtualQuery/VirtualProtectbatch behindPROTECT_SYSCALL(outsideGUARDS) so parallel refresh workers (perf(gpu): parallelize multi-shadow buffer refreshes and disjoint copy-back #280) queue orderly without stampeding Wine'svirtual_mutex, while fault handlers (on_write) never wait behindVirtualProtectbatches.watch::writingandon_writewait on bothOPENING_CVand cancelledGUARDING_CVtransitions (and extend test(gpu): keep a test's memory allocated while the guards still hold it (#31) #305'sstill_watchedtest guard withg.guarding/g.opening).write_watchedpools & registeredxmemview spans while preserving titlePAGE_GUARD(watch.rs,xmem.rs):write_watchedfast-path ahead ofVirtualQueryinRuntimeRegions::classifywhenPAGE_GUARDchecking has not been triggered.xmemsection view spans viatitle_memory_mappedsoRuntimeRegions::classifyresolves view bounds in memory without per-64 KiBVirtualQuerysyscalls unlessPAGE_GUARDchecking is active (cfg!(test),VICTORY_CHECK_PAGE_GUARD=1, ornote_page_guard()). When active,PageClass::Alikeverifies full-64 KiBMEM_COMMITPAGE_READONLY | PAGE_READWRITEregions so titlePAGE_GUARDsubpages in primary or aliased views are never stripped.watch.rs):VICTORY_HOT_PAGES, default on) and recently faulted pages (VICTORY_GUARD_REST_MS, default3ms) across linkedalias_ofsection views so steady-state CPU writes take zeroVirtualProtectcalls while cooling immediately when armed for GPU shader writes; inTracked::arm, gate cooling onHOT_COUNT != 0 || RESTING_COUNT != 0and slicechanged.hot.range(first..last)soarm()skipsO(range_pages)vector allocation andGUARDSacquisition whenever no hot pages fall insidefirst..last; open only the faulting view by default (VICTORY_OPEN_ONE_VIEW=0opt-out).xmemsection copy-back & bounded 4 KiB subpage filtering (watch.rs,shadow.rs,xmem.rs,d3d12x.rs,copystat.rs):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) usingSection::existing_whole()so GPU copy-back writes and userspaceread_own_viewreads touch only already-mapped persistent section views (never callingMapViewOfFileunderPHYSICAL), paired withVICTORY_LAND_ECHOto skip unchanged GPU copy-back echoes.VICTORY_PAGE_PARTSto!rosetta()(avoiding WineWRITE_WATCH_FLAG_RESETmprotectstorms unless explicitly enabled) and compare seeded 4 KiB subpages in userspace for<= 256 KiBruns (VICTORY_SHADOW_COMPARE_4K, default on), fast-pathing unseeded and> 256 KiBbulk 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,600concurrentwriting()+ kernelFileExt::seek_readcalls into disjoint 624-byte slices of onePAGE_READONLY64 KiB section view) —0ERROR_NOACCESSfailures.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 cuttingVirtualProtectcalls andGUARDSlock hold/wait times.repeated_writes_through_aliased_views_promote_hot_with_zero_protects:0VirtualProtectcalls and0 nsGUARDShold 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 / 16modified 4 KiB subpages copy8,192 Binstead of65,536 B, and unchanged GPU copy-back echoes copy0 B.Verification
watch::tests:37/37passed × 3 parallel rounds (coveringPAGE_GUARDpreservation in primary and aliased views, atomicon_commitunder contention, and concurrentwriting()+NtReadFilesynchronization).shadow::tests:34/34passed;xmem::tests:16/16passed; native macOS workspace suite passed.cargo xtask policy(256 files ok),git diff --check, andcargo clippy(-- -D warnings, with and without--features diagnostics,0warnings) passed. All test inputs are synthetic.Live M5 Max Verification (Combined Build on CrossOver Preview + D3DMetal)
CrossOver Preview+ D3DMetal,wave32=true), the runtime reached and sustained the 3D world through+8, +24, +48, +90at1.5–1.8 FPS(549.7–672.1 ms/frameon1,021–1,258 draws/frame,1.275 FPSoverall across+8..+90) with02.48 sallocation stalls,7.2–9.0 ms/frameGUARDSlock hold time (down from4,887 ms/framebefore unlockingGUARDS),149–154 MB/framebuffer copy volume,0DirectStorage decompression or access-violation failures, and38/38over-32 KiB aligned mesh/pixel pairs linked with0host mesh refusals.