gpu: opt-in single-source GetWriteWatch collector thread (VICTORY_SUBMIT_PIPE=1) #4489
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/4489"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by lyufeng000 on 2026-11-30T21:10:49Z.
Motivation
On Windows 11 (measured on RTX 4090 + Ryzen 9 9950X, 4K DLSS Quality steady state on
e1251c31), write-watch collection accounts for ~5.05 ms/frame of CPU wall time across the critical path:Host::submit(asking the write watch): ~2.80 ms/framedescriptor::sync_heaps(victory-heap-sync,asking): ~2.25 ms/frameWith per-range
ASKINGlocks (hold_pages()),victory-submit/victory-askandvictory-heap-sync(plus occasional helper-thread fallbacks) callGetWriteWatch(WRITE_WATCH_FLAG_RESET)concurrently on disjoint address ranges. Insidentoskrnl, every resettingGetWriteWatchacquires process-wideAddressCreationLock/ working-set / PFN locks and broadcasts cross-core TLB shootdown IPIs, causing severe kernel lock contention whenever multiple threads query simultaneously.This PR introduces an opt-in, self-contained single-source collector thread (
victory-watch-pipe) behindVICTORY_SUBMIT_PIPE=1(off by default) that serialises allGetWriteWatch(WRITE_WATCH_FLAG_RESET)queries and overlaps submission write-watch collection withcard_stepsandsweep.Architecture
New module:
crates/victory-gpu/src/host/watch_pipe.rsvictory-watch-pipe):VICTORY_SUBMIT_PIPE=1(placed on fast cores viacores::keep_on_fast_coreswithcores::Priority, matchingvictory-askandvictory-heap-sync).highpriority for submission askings (begin_ask_once,ask_once,ask_once_delta_reask) andnormalpriority fordescriptor::sync_heaps(Tracked::take).SubmitAskrequests queued inhighcoalesce into a single normalizedask_once_directkernel pass while delivering individual monotonicWatchSnapshottokens to every waiter.Host::submitandvictory-heap-syncthrough one thread also reuses a singlewatch::FOUNDbuffer and unifieswatch::REFUSEDacross both callers.IN_COLLECTORexecutes nested calls inline without deadlock;catch_unwindinworker_loopensures a panic never hangs waiting callers or kills the collector thread (SubmitAskclears kept state and signalsNonefor safe fallback;Taskpropagates the panic cleanly viaresume_unwind).Overlapped Epoch-Isolated Collection (
WatchSnapshot+delta_ranges)Host::submitted,Host::submitreusesbatch.copy_spans(runs)(no extra list walk and no manifest dependency) to enqueuewatch_pipe::begin_ask_once(ranges)asynchronously onvictory-watch-pipe, overlapping kernel page walks withcard_steps,late_blocked, andsweep.ask_once_directruns on the collector thread, it snapshotshi_ep = watch::current_write_epoch()(SeqCst) and binds aWatchSnapshot { epoch, hi_ep, settle_gen }to theWatchTicket.watch_pipe::finish_early_watchcompletes the ticket:snap.is_current()(settle_genunchanged),writes_since_epoch(snap.hi_ep)returns complete log coverage, and bothuncovered = ticket.delta_ranges(&batch.ranges)andreask = intersecting_needed(&batch.ranges, &written)are empty, zero extraGetWriteWatchcalls are made.card_stepsadded anownlist (uncovered) or an asynchronous landing / DirectStorage write / remap overlappedbatch.ranges(reask, narrowed via exact two-pointer sub-range intersection),ask_once_delta_reask_directcarves only the overlapping pages fromjournal().ahead, runs a single coalesced pass overuncovered ∪ reask, and merges back intojournal().aheadwithout discarding unaffected spans.settle_genadvanced,WRITE_LOGoverflowed (> 256entries), or an unsized free (begin_write_epoch()) left an unlogged gap,finish_early_watchsafely falls back to a fullask_once(&batch.ranges).Process-Wide Kernel Serialization (
watch.rs)watch::ask_onceandTracked::takedelegate throughwatch_pipe::{ask_once, take_tracked}whenVICTORY_SUBMIT_PIPE=1, and executeask_once_direct/take_directinline when off.watch::KERNEL_WATCH_LOCKwrapsGetWriteWatch(WRITE_WATCH_FLAG_RESET)insidekernel_writtenonly whenwatch_pipe::on(), serialising any residual helper-thread queries (texture::Staging::refresh_now,shadow.rs,memory.rs,ask_early) strictly afterASKING.Opt-In Switches
VICTORY_SUBMIT_PIPE0/ unset)1enablesvictory-watch-pipe,KERNEL_WATCH_LOCK, overlappedearly_watch, andSeqCstwrite-epoch tracking (viaasked_for!, compatible withVICTORY_AB).VICTORY_WATCH_PIPE_EPOCHVICTORY_SUBMIT_PIPE=10disablesWatchSnapshot/ incrementaldelta_rangeswhile keeping single-source collector serialization. AlwaysfalsewhenVICTORY_SUBMIT_PIPEis off.When
VICTORY_SUBMIT_PIPEis unset or"0":victory-watch-pipethread is spawned (default_disabled_does_not_spawn_collector).KERNEL_WATCH_LOCK,record_write_epoch,bump_settle_gen, andlog_lineare completely bypassed.apps/victory/src/play.rsdefaults are untouched;Host::submitexecutes the exact upstreame1251c31path (includingVICTORY_ASK_FIRST=1).Correctness, Deadlock Safety & Compatibility Audit (
e1251c31)Host::submitted≺WatchPipe::state/Completion≺ASKING≺KERNEL_WATCH_LOCK/JOURNAL/GUARDS.SHADER_HEAPS.read()(held bydescriptor::sync_heapsaroundTracked::take) ≺WatchPipe::state/Completion; the collector thread never acquiresSHADER_HEAPS,SYNC_ROUNDS,Host::submitted, ortitle_memory_reading.WRITE_LOGis a strict leaf mutex;elsewhere/elsewhere_in(inplace::VIEWS) is resolved before acquiringWRITE_LOG.rangelock::RangeLock(VICTORY_RANGE_LOCK=1) /MAPPING: no caller holdstitle_memory_reading*while waiting onWatchPipe.descriptor.rs(VICTORY_HEAP_SYNC_AT_SUBMIT=1,VICTORY_HEAP_SYNC_FIRST=1,VICTORY_SYNC_FINE=1):sync_heapswatch queries (written.take(...), includingheap_hooks::reguard) route throughTracked::take→watch_pipe::take_trackedwith zero changes todescriptor.rs.waited_for_flightsorsettled_for_sweepoccurs inHost::submit,early_watch.cancel()awaits any in-flight collector pass and callsask_once_end()beforebegin_sync_heaps()starts a fresh round, closing any window wherevictory-heap-synccould observe a stale pre-settlejournal().ahead.30911195) &WRITTEN_EPOCHS:ask_once_directandask_once_delta_reask_directmaintainJournal::note(mirroring into lock-freeWRITTEN_EPOCHS), strictly sorted non-touchingj.ahead(merged(...)), and atomicKEPT(is_kept()) beforeBatch::refresh_front/Batch::flush_allrun.VICTORY_SUBMIT_PIPE=1,pipe_earlysupersedesVICTORY_ASK_FIRST=1sovictory-askandvictory-watch-pipenever race.SeqCstpost-write invariant):watch_pipe::on()):landed_direct,landed_beside,shadow::put_changed(RAII post-write guard),KernelWrite::drop(DirectStorage /ReadFile/fread),stream_written,title_memory_written,wrote,writing,title_memory_remapped,title_memory_unmapping,title_memory_allocated, andtitle_memory_freed(unsizedlen == 0triggers barebegin_write_epoch()gap\tofail-closed full fallback).record_write_epoch(ep != log.last_ep + 1advancesmin_lost_ep) ensures later logged writes can never mask an earlier unloggedbegin_write_epoch().Files Changed
crates/victory-gpu/src/host/watch_pipe.rs(new): single-source collector thread,WatchTicket/WatchSnapshot, concurrentSubmitAskcoalescing,delta_ranges, exact sub-range intersection,finish_early_watch, diagnostics line, and 11 unit tests.crates/victory-gpu/src/watch.rs:WRITING_EPOCH/WRITE_LOGwith gap detection,KERNEL_WATCH_LOCK(gated onwatch_pipe::on()),ask_once_direct,ask_once_delta_reask_direct,Tracked::take_direct, gated epoch hooks on write/remap/free entrypoints, and 2 unit tests.crates/victory-gpu/src/host.rs:mod watch_pipe, overlappedearly_watchstart/cancel/finish inHost::submit,bump_settle_geninsettle/settle_stale/WHY_READrelay_wait/Batch::title_written, andwatch_pipe::log_line.crates/victory-gpu/src/shadow.rs: post-write RAII epoch guard input_changed(gated onwatch_pipe::on()).crates/victory-gpu/src/queue/behind.rs:watch_pipe::ensure_started()onvictory-submitstartup (no-op when off).Verification & CI Gates
Executed against
--locked:PASS (13 passed, 0 failed)in both default (VICTORY_SUBMIT_PIPEunset) andVICTORY_SUBMIT_PIPE=1modes:default_disabled_does_not_spawn_collectorcollector_serializes_concurrent_callers_on_single_threadreentrant_run_on_collector_does_not_deadlockcollector_survives_task_panic_and_propagates_to_callerdelta_ranges_subtracts_covered_and_merges_overlapsintersecting_needed_returns_exact_overlapping_subrangesfifo_epoch_snapshot_and_settle_gen_invalidationconcurrent_submit_asks_coalesce_without_losing_dirty_pagesask_once_delta_runs_on_collector_and_preserves_aheadfinish_early_watch_fast_path_reasks_overlap_and_handles_settle_or_cancelconcurrent_submit_and_heap_tracked_serialize_without_deadlock_or_missed_pageswrite_log_tracks_ranges_gaps_and_overflow_falls_back_to_noneask_once_delta_reask_direct_carves_refreshes_and_updates_page_epochsvictory-gpufull suite withVICTORY_SUBMIT_PIPE=1+victory-hlea_read_by_range_waits_only_for_a_remapping_that_meets_it— all PR-related tests pass; zero regressions introduced.cargo clippy --workspace --all-targets --locked&--all-features— 0 warnings in all touched/added files (watch_pipe.rs,watch.rs,host.rsnew hunks,shadow.rsnew hunk,queue/behind.rs). (Note: upstream basee1251c31has pre-existing unrelated warnings invictory-shader/src/emit/lower.rs:114,copystat.rs:1470,shadow.rs:7206,host.rs:5092,xmem.rs:1933, pre-existing test failures inlist::thin::tests::bindings_record_no_work,shader_cache::tests::every_switch_of_the_translator_is_in_the_key,split_lds_wave32_read_after_read_barrier_coalescing_and_parity, and a pre-existingxtask policyfinding incrates/victory-shader/src/native.rs.)cargo xtask policy— 0 violations on all added/modified files.cargo build --release --locked -p victory—PASS.Local Benchmark Results (Same-Binary Off vs On)
Measured on the same Release build (
pr/watch-pipeone1251c31), RTX 4090 + Ryzen 9 9950X, Windows 11, 4K DLSS Quality + FrameGen 2x, identical settings (includingVICTORY_PLACED_COPIED=0), over two 13–14 minute free-play sessions:VICTORY_SUBMIT_PIPE=0(Off): 764 s steady / 17,483 frames, 0 errorsVICTORY_SUBMIT_PIPE=1(On): 720 s steady / 16,181 frames, 0 errorsExcluding 1-second buckets that contain first-run shader/PSO compilations (
PIPE=1ran first and warmed the DXCache forPIPE=0:PIPE=0600 clean s / 13,959 frames vsPIPE=1466 clean s / 11,045 frames; comparable workloadrefreshes8,759 vs 8,564,heap_pages482.1 vs 472.6):VICTORY_SUBMIT_PIPE=0(mean / p90)VICTORY_SUBMIT_PIPE=1(mean / p90)Host::submit: asking the write watch (sub_ask_ms)sub_ask_ms - find_ask_ms)descriptor::sync_heaps: asking (heap_ask_ms)normal-queue yield behindhighsubmit asks)descriptor::sync_heaps: read & compare (heap_cmp_ms)descriptor::sync_heaps: total (heap_ms)Host::submit: wait for heap sync (at_sub_wait)Host::submit: total preparing (prep_ms)ft_med) />50 msshareSteady-state
VICTORY_SUBMIT_PIPE=1collector line averages (all 720 steady seconds):22.10submit asks/frame,19.31heap-sync takes/frame;early-watch12.81fast hits +4.56delta/reask vs0.08full fallbacks (>99.5% incremental/fast-path hit rate).(Note: these are two full free-play runs rather than fixed-camera
VICTORY_ABsampling. For strict fixed-camera A/B reproduction on diagnostics builds, runVICTORY_AB=20,VICTORY_SUBMIT_PIPE.)Recommended extra matrix checks:
VICTORY_SUBMIT_PIPE=1 VICTORY_HEAP_SYNC_AT_SUBMIT=1 VICTORY_SYNC_FINE=1VICTORY_SUBMIT_PIPE=1 VICTORY_HEAP_SYNC_FIRST=1 VICTORY_RANGE_LOCK=1VICTORY_SUBMIT_PIPE=1 VICTORY_SUBMIT_SPLIT=1VICTORY_AB=20,VICTORY_SUBMIT_PIPEImported from trustno1-coder/VIctory-NVIDIA. Originally posted by IRennie74 on 2026-11-30T22:38:52Z.
Some notes relevant to 6-core CPUs.
VICTORY_SUBMIT_FRAMES=2andSUBMIT_SPLITgave nothing, because the work moved off the submitting thread came back as contention. So a 9950X result may not carry over. Your table already showssync_heapsasking +0.4 ms. I can runVICTORY_AB=…,VICTORY_SUBMIT_PIPEon that PC.record_write_epochruns on everywrote/title_memory_written/_remapped/_unmapping/ landing while the switch is on (watch.rs, the hooks listed in the description), including when no early ticket is in flight. Each call takeselsewhere()(the in-place views' lock) and thenWRITE_LOG. Some of those callers are title threads during remaps. Logging only betweenbegin_ask_onceandfinish_early_watch(an atomic count of tickets in flight) would remove that cost for the rest of the frame.wrote()used to return immediately when no asking was kept. With the switch on, it now always logs first.ask_once.ask_once_delta_reask_directcopies the old merge loop, so withVICTORY_ASK_BY_RESon it would still make merged askings across reservations. Whichever lands second has to route it through the same splitting.VICTORY_SWEEP_OFF_THREAD=1, the submitting thread no longer settles for the sweep, so thesettled_for_sweepcancellation never fires. The overlap "withsweep" from the description also disappears, which leaves onlycard_stepsand the planning to hide the asking behind. The two should combine cleanly, but the gain from the overlap will be smaller than with the sweep inline.The CI failure is main's (
lower.rs:114,shadow.rsranged,host.rs:5092), not this PR's.Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by lyufeng000 on 2026-12-01T12:33:49Z.
Hi @IRennie74,
Thank you so much for taking the time to review this PR, look into the implementation details, and offer to test it on your setup.
I'm really sorry for not properly considering lower-core-count / more CPU-constrained systems—this was developed and tuned on a 9950X, and I overlooked that moving work onto an extra collector thread and adding lock overhead can cause contention and backfire when the CPU is already near saturation.
To be honest, I'm feeling a bit burnt out from coding lately, so I don't have any plans for further optimizations at the moment. Thanks again for the thoughtful feedback!
Imported from trustno1-coder/VIctory-NVIDIA. Originally posted by trustno1-coder on 2026-12-01T18:39:59Z.
Closing this as part of moving main to the texture and video-memory rework (v2026.12.01.01-test). A lot of the code changed, and this pull request no longer applies cleanly to it; it would need to be rewritten against the new main rather than rebased. Thank you for the work. If the change is still needed, please open a new pull request based on the current main.
Pull request closed