GPU: title threads recording lists no longer wait on descriptor and buffer-copy locks #2819
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/2821"
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 Marvisak/VIctory. Originally posted by 0xkn0wh3r3 on 2026-11-25T21:28:45Z.
Removes the mutex contention the list benchmark in #2820 measures on the title's recording threads. This PR carries only the locking change. The benchmark lives in #2820 alone (see "Benchmark" below). Each commit's message has its own before/after numbers.
Changes
descriptor::SHADER_HEAPS→RwLock. Every view write and descriptor copy looked up its heap under a mutex, and held it for the whole host view creation. The list only changes when a shader-visible heap is made or dropped, which are the only two write-locked places. Holding the read lock still keeps a heap from being dropped while it is used.shadow::BUFFERS→RwLock.findnow looks up a host copy that already exists under the shared lock. Making a copy, registering a buffer and releasing one take the exclusive lock as before, and the lookup is redone under it.HostHeap::mirrorno longer takesmadefor slots that are already made. Each title slot gets an atomic copy of its record. It is set last, under the lock, once the slot is made and holds what a draw reads. It is cleared first whenever the slot is remade, nulled or evicted. A slot that reads as ready returns without the lock, just as the check under the lock would have.Two kinds of slot are never marked ready, because the checks under the lock look at more than the slot: a texture view left null, which is made when read, and a view of a texture placed in memory.
needs_remakechecks that second kind against the memory's current host texture (#1997).descriptor::VIEWS→RwLock. Lookups take the read lock.recordfinds an already-known view under the shared lock, which still stopsforgetfrom making the entry stale while the record is written.HostHeap::evictre-checks its slots undermade. The concurrency review below found a window: a slot rewritten between evict picking it and nulling it lost its new view. Draws could always hit that window; after commit 1, view writes can too. Evict now picks again, under the lock every title-slot rewrite holds, and leaves slots that view something else.Functions that may now run at the same time (review point 1)
The functions that read
SHADER_HEAPSaredescriptor::mirror,sync_heaps,make_read,read_textures,evict,release_dynamicandwith_host. Two facts narrow down which pairs are new:HostGpu::executeholdssubmittedfrom preparation through copy-back (host.rs), and that one function callsevict(throughresource::evict_unused),sync_heaps,make_readandread_texturesone after another.with_hostruns throughmemory::preparethere too. These never overlap each other, before or after this PR.SHADER_HEAPS. Draws bind slots throughHostHeap::mirrorwithout it (draw::State::table_entry). The same goes for dynamic slots (dynamic,make_at,raw_view_at,make_null) andHeap::host's replay. So on main, everyHostHeapoperation could already run at the same time as each submission-side reader, and was kept safe by the heap's own locks:madefor title slots,kept,nextandpairs, pluspendingwith theOnceLock.SHADER_HEAPSonly kept the heap list, and so each heap, alive.The new overlaps are therefore between title-thread readers, and between title-thread readers and the submission:
mirror×mirror(two threads writing views)HostHeap::mirror, the same path two drawing threads already took at once. Slot making is serialized per slot bymade, and the record is read again afterprepare, so the slot ends up made from the current record.pendingand the host heap'sOnceLockare published under thependinglock, as before.mirror×sync_heaps,mirror×make_read(title write during a submission)made, with whichever runs last making the slot from the latest record. This is what a drawing thread and a submission already did on main. Inmake_read,unmade_placedis a snapshot, and acting on a stale one only makes a placed texture that already exists.mirror×evict(title write while textures are given up)release_dynamic× anything (a list reset or released on a title thread)HostHeap::releasetouches onlynext, which draws taking dynamic slots already share.with_host× anything (memory::bindwhile recording,memory::prepareat submission)memory::SHARED, which serializes them with each other, pluspairsandview_addresses(OnceLock, thenmade). The submission-side readers touch neitherSHAREDnorpairs.Heapcreation and drop (write lock)shadow::BUFFERSandVIEWSwere each taken by single-entry functions: look up, clone, return. Their write paths are unchanged, so the read side adds no new interleaving of their own state.No nested read locks (review point 2)
std::sync::RwLockcan deadlock when a thread takes the read lock again while a writer waits. That needs the same thread to take the same lock twice. On main these werestdmutexes, which deadlock on any such nesting, so no executed path could do it. Here are the paths checked:VIEWS:view_at,viewandviews_currenttake it, clone and return.recorddrops its read guard before it callsmirror, and its write section calls nothing that takesVIEWS.forgetis self-contained.BUFFERS:find's read section is a map lookup and anArcclone. It drops the guard beforeloose(), which takesLOOSE.allandnearare plain reads.SHADER_HEAPS: these run with it held:mirrorandsync_heaps→HostHeap::mirror→prepare,make_marked,keep.make_read→HostHeap::mirrorandstamp_read.evict,read_textures,release_dynamic.with_host→ thememory.rsclosures named above.None of them reaches a
SHADER_HEAPSreader.keep→host::retireonly pushes ontoRETIRED, which is released after the submission on a thread of its own.draw::State::drop, which callsrelease_dynamic, runs at list reset or release, or in a host list's deferredafterwork. That work runs inexecuteaftermake_readhas returned (host.rs).evictis reached only fromevict_unusedat the top ofexecute.memory::bindandmemory::prepareare not called withSHADER_HEAPSheld.Numbers (list benchmark from #2820, 5 threads, RTX 5070 Ti, release)
Other builds were running on the machine at the same time, so the builds were run interleaved, 9 rounds each. The table gives best / median ns per call:
SHADER_HEAPSBUFFERSmadefast pathVIEWSFrom main to commit 4, the best run drops 22% (13% with
diagnostics) and the median 38%. One thread goes from 334 to 307 ns per call. Commit 5 only runs once per eviction, on the submitting thread. These numbers were measured before the rebase onto the current main. After these changes the profile haslock_contendedat 5.5% of recording time instead of 58%. What remains is cache-line traffic on theRwLockreader counts (shadow::find,view_at), which needs per-list caches or lock-free maps to remove.Benchmark (review point 3)
The benchmark files are no longer in this PR, which is main plus the five commits above. Whether the benchmark belongs in the tree is decided on #2820. If it doesn't land, the table above can be reproduced from that branch.
Overlap with #1356
#1356 (open, currently conflicting with main) also turns
SHADER_HEAPS,VIEWSandBUFFERSintoRwLocks, makesmadeanRwLock, and adds per-HostListshadow and view caches. Commits 1, 2 and 4 are a subset of it, offered as the smaller, measured version on current main. Commit 3 takes a different approach (lock-free reads of made slots), and commit 5 applies to either PR. #1356's caches go after theRwLockreader traffic that is left. #2121 also changesHostHeapslot making, so whichever of #2121 and this PR lands second must clear thereadymarks intake_back_pagesandremakes.Checks
cargo clippy -p victory-gpu --all-targets -- -D warnings, with and without--features diagnostics: clean.cargo test -p victory-gpu --lib: 229 passed. The two failures aredescriptor::host::tests::dynamic_slots_are_held_until_releasedandmemory::tests::lists_share_a_table_and_copies_keep_their_views. Both already fail on main on this NVIDIA card (the heap cap, fixed by #2121).--features diagnostics, the same results as main on this machine:host::present_plane_tests::compositor_failure_presents_primary_in_the_same_frame(from #1997) crashes the test process (exit 2173) every time it runs alone, on main's code too. It is skipped here.frame::tests::waits_end_on_ticks_and_count_framesanddescriptor::host::tests::placed_uav_textures_create_real_host_uavsfail intermittently on main and here alike.cargo xtask policy: ok.Measured in the title
@Jackster ran retail 1.0.2.1 on an RX 7900 XTX: a diagnostics build at
63bcca4with this PR on a stack of #2703, #1010, #2985, #2849, #2908, #2472, #2958 and #3118, two 300 s world runs (VICTORY_KEYS), warm caches, same save.MirrorWaitUs)One run each. Slot counts differ between the runs because the title rewrote different pages.
Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-25T21:40:54Z.
Verified
9b794b03on Windows 11 (RTX 5090 + WARP,--features diagnostics):cargo xtask policy: 186 files ok;cargo clippy --locked -p victory-gpu --all-targets -- -D warnings(default &--features diagnostics): 0 warnings.--features diagnostics --test-threads=1):descriptor::17 passed / 1 failed (only pre-existing >1M heap-limitdynamic_slots_are_held_until_released),shadow::tests8/8 passed,bindless::tests3/3 passed.VICTORY_D3D12_WARP=1,--features diagnostics --test-threads=1): 198 passed, 0 failed, 2 ignored.--releaselist_callsbenchmark on RTX 5090 (5threads ×8,310calls/frame ×10frames,0dropped, 2 runs each):f7579ca0):1495–1871 ns/call,12.79–15.97 ms/framewall (DrawIndexedInstanced6065–7521 ns,CreateCBV1344–1795 ns,CopyDescriptorsSimple2407–3165 ns,Dispatch1580–1867 ns)9b794b03):699–747 ns/call,6.23–6.65 ms/framewall (DrawIndexedInstanced2584–2708 ns,CreateCBV751–857 ns,CopyDescriptorsSimple1801–2090 ns,Dispatch1008–1084 ns) — ~53%–60% lower per-call time and >2× faster wall time.VIEWS.read()guards slot write againstforget()(write()),HostHeap::readypairsAcquire/Releasewithview_at(i, generation)validation and resets to0undermadebefore mutating or evicting (leaving placed textures at0forlazy()), andshadow::find()re-runsinnermost()and re-checksentry.shadow.is_none()after upgrading to the write lock.git merge-treeagainstorigin/main13f91ca, #2601, #2608, #2611, and #2668.Imported from Marvisak/VIctory. Originally posted by kotekompotek on 2026-11-25T22:10:41Z.
Review: COMMENTED
Scoped review (the bulk is the list_bench harness): the behavioral change is a clean Mutex->RwLock split — all hot lookup paths (view_at, read_textures, mirror, with_host readers) take read locks while only record/forget/sync_heaps write, preserving the single-lock discipline so no new ordering is introduced. The record-side comment about the lock keeping forget from invalidating an in-flight write is the right generational-slot reasoning. The benchmark making the cost visible on the title's own threads is a good way to justify it. One thing worth a maintainer look: RwLock on this platform can let a writer starve under a steady read stream — if forget/evict latency ever matters (resource teardown during streaming), worth confirming the writer path isn't delayed noticeably.
Imported from Marvisak/VIctory. Originally posted by 0xkn0wh3r3 on 2026-11-25T22:20:49Z.
A note for whichever of #2121 and #2821 lands second: they merge cleanly but clash in
HostHeap::mirror.readycheck that skips a slot already made from the same record.maderecord when it takes a page back, so a page placed again is never remade:host::tests::view_heap_pages_taken_back_are_placed_again_when_readfails at "made from the title's record".The fix is to clear
readyfor a page's slots intake_back_pagesand inremakes(crates/victory-gpu/src/descriptor/host.rs). I'll add it to whichever branch lands second.Imported from Marvisak/VIctory. Originally posted by Marvisak on 2026-11-26T02:21:57Z.
Automated triage for the maintainers.
Thanks for
af969fd. The benchmark files are gone, and the description now goes through each concurrent pair and the nested-lock question. I checked the main points against the code. InHostHeap::mirror,readyis set last undermadeand only for slots thatneeds_remakecan never pick (non-textures, and textures that are held and not placed). It is cleared before every remake, null and evict.recorddrops itsVIEWSread guard before callingmirror.evictnow picks its slots again undermade.One cross-PR point: #2895 (open) adds an
owner_movedcheck tomirrorthat remakes buffer slots when the innermost title buffer changes. Thereadyfast path here would return before that check. Whichever of the two lands second needs to clearreadyon owner changes, or leave buffer slots out of it. The same applies to #2121'stake_back_pages/remakes, as you noted.CI: passing.
Generated by Claude Code
Imported from Marvisak/VIctory. Originally posted by liandraraiane on 2026-11-26T02:48:13Z.
A/B on an RTX 3060 (driver 610.88) with a Ryzen 7 5700G (16 threads),
list_callswithLIST_BENCH_FRAMES=20, the bench-only commit against this PR's head, runs alternated, 0 dropped draws in every run. ms for all threads to record a frame, median of 5:cdc91bccfbb10aThe previous head (
9b794b0vsf7579ca) gave the same picture at 1, 5, 8 and 16 threads: 3.84 → 3.56, 14.21 → 7.74, 26.95 → 11.98 and 62.67 → 24.44 ms. With this PR, per-call cost still grows from one thread to sixteen (about 390 → 2,700 ns), so some contention remains. Not tested: a title; only this synthetic bench.AI use: Claude Code ran the benchmarks on this machine and drafted this comment.
Imported from Marvisak/VIctory. Originally posted by 0xkn0wh3r3 on 2026-11-26T06:42:00Z.
Addressed in
af969fd. The benchmark files are gone, so the PR now carries only the locking change (descriptor.rs,descriptor/host.rs,shadow.rs) on current main. The description now lists each pair of functions that can run at the same time under the read locks and why each pair is safe, and confirms that no path takesSHADER_HEAPS.read()orVIEWS.read()again while already holding it. The benchmark stays in #2820 for your decision.Imported from Marvisak/VIctory. Originally posted by passerbyyhx on 2026-11-26T07:52:18Z.
I checked the new
HostHeap::evictrecheck ataf969fdon an RTX 4090 Laptop and WARP with the D3D12 debug layer. Eviction first selects two slots that both view red texture A. Before it takesmade, a title write rebinds slot 0 to green texture B. The GPU reads both original heap slots directly as green / red before eviction resumes.On the parent
707b9396, the final read is transparent black / transparent black on both devices. Onaf969fd, it is green / transparent black on both: eviction preserves the rewrite and still clears the other slot viewing A. The readback never callsmirrorto refresh the slots.Portable test on the author branch · Coordination claim
Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T09:49:01Z.
Review: APPROVED
Verified on RTX 5090 against
origin/main(63bcca4):cargo test -p victory-gpu --lib draw:: -- --test-threads=1: 20/20 passed.cargo test -p victory-gpu --lib descriptor::host:: -- --test-threads=1 --skip dynamic_slots_are_held_until_released: 14/14 passed.cargo test -p victory-gpu --lib shadow:: -- --test-threads=1: 10/10 passed.cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.cargo xtask policy: 191 files ok.Cleanly reduces lock contention between title command-list recording threads and descriptor/buffer-copy updates.
Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-26T10:22:52Z.
Review: APPROVED
Audited all five commits for lock ordering, re-entrancy, and
HostHeap::ready/evictconcurrency invariants, and verified on Windows 11 (RTX 5090 + WARP + D3D12 Debug Layer).Concurrency audit summary
RwLockconversions (SHADER_HEAPS,VIEWS,shadow::BUFFERS): verified no reader re-enters the same lock and lock ordering is preserved across all call sites (recorddropsVIEWS.read()beforemirror;shadow::finddropsBUFFERS.read()beforeloose;all/neardrop the read guard before takingLOOSE;Heap::dropdropsSHADER_HEAPS.write()beforememory::release).HostHeap::readyfast path (descriptor/host.rs): matchesneeds_remake()exactly — generations start at 1 (wrapping with.max(1)) so valid keys are never 0; placed textures and null-kept texture views stay at0;readyis cleared before mutating or evicting a slot undermadeand published last withOrdering::Releaseafter stride, address, descriptor, mark,viewed, andkeptupdates, paired withOrdering::Acquire+view_at(i, generation)validation on read.HostHeap::evictre-check (af969fdc): re-filteringslotsundermade→keptkeeps the lock order identical tomirror(no ABBA deadlock) and closes the window where a concurrent view write rewrote a slot before eviction nulled it.Hardware & WARP verification (
origin/main63bcca43merge-tree clean)cargo clippy --workspace --all-targets --locked -- -D warnings(default &--all-features): clean;cargo xtask policy: 191 files ok.descriptor::default-parallel 5× consecutive runs 21/21 passed each round (skipping pre-existing NVIDIA 1M-capdynamic_slots_are_held_until_released);shadow::10/10,memory::7/7 (skipping pre-existing 1M-caplists_share_a_table_and_copies_keep_their_views),draw::20/20.VICTORY_D3D12_DEBUG=1:descriptor::+shadow::31/31 passed.VICTORY_D3D12_DEBUG=1(no 1M heap cap):descriptor::22/22,memory::+shadow::18/18,draw::20/20 (60/60 passed).Imported from Marvisak/VIctory. Originally posted by Jackster on 2026-11-26T12:15:33Z.
Confirmed on the retail title: 334 ms of title-thread waiting -> 0.1 ms
Setup: Windows 11, RX 7900 XTX (RDNA3, 64-lane waves), Ryzen 9 3950X; retail 1.0.2.1; diagnostics build at
63bcca4with this PR merged onto a stack of #2703 #1010 #2985 #2849 #2908 #2472 #2958 #3118; two 300 s world runs driven withVICTORY_KEYS, warm caches, same save.title threads waiting to write views(MirrorWaitUs)The counter is the one in
descriptor::mirroraroundSHADER_HEAPS, printed bycopystatas "title threads waiting to write views", so this is the title's recording threads on the engine itself, not the benchmark in #2820. With the wait gone the frame is 11% shorter at the same draw count.Caveats: one run each; the two runs differ in slot counts because the title rewrote different pages. Nothing else in the tree changed between them.
Written with an AI assistant.
Imported from Marvisak/VIctory. Originally posted by 0xkn0wh3r3 on 2026-11-26T12:16:53Z.
Thanks @Jackster, that's the in-game number this PR was missing: the title's recording threads stop waiting on the heap lock (334 ms to 0.1 ms per frame on that counter). I've added your table to the description, with the one-run caveat.
Imported from Marvisak/VIctory. Originally posted by KainanP on 2026-11-26T14:50:09Z.
Measured on main
63bcca4with this PR merged, with a different benchmark from #2820's: it draws with six textures through a table and three root constant buffers (RTX 4060 Laptop, release, median of 7 interleaved runs; method in https://github.com/Marvisak/VIctory/issues/2586#issuecomment-7195391455):HostHeap::mirrorfor an unchanged slot: 43 → 18 nsAI use: Claude Code (Claude Opus 5.5) ran the measurements and drafted this comment.
Imported from Marvisak/VIctory. Originally posted by KainanP on 2026-11-27T12:31:18Z.
This PR also makes
SHADER_HEAPSaRwLock, the change #3425 points at, so here are contention numbers (af969fdagainst its base63bcca4):sync_heapsTitle threads stop queueing behind the sync. The sync itself gets slower as more views are written while it runs, probably because it now contends with their
mirrors onmadeandVIEWS. That fits neonbyte1's in-game +30 ms of "preparing" for the same read-shared lock in #2848 (fd7de0f6, since dropped there). No views were lost or stale, and the fullvictory-gpusuite on RTX fails only the two tests thatmainalso fails here.Bench:
sync_contention_bench(#[ignore]d; commitf34bcfb8, cherry-picks onto any tree). A placed, write-watched view heap of 2^20 slots (the host heap caps it at 934,464 here). Each frame, one thread rewrites 200 random 64 KiB pages (50 changed records each) and runs onesync_heaps, while 5 title threads write a placed-buffer SRV every 20 µs into pages of their own. "Wait" is the title threads' time in view writes beyond the uncontended 2–3 µs, summed per frame. Release build, RTX 4060 Laptop, runs interleaved with the base, medians of 30 frames per run. The bench also checks that every view written before a sync is the slot's view address after it, and that every slot is right after a final quiet sync.AI use: Claude Code (Claude Opus 5.5).
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.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.