descriptor: use per-slot reader-writer lock (BrLock) for VIEWS #203

Open
github-bot wants to merge 2 commits from github-bot/gh-203 into main AGit
Owner

@⁠Lciarallo on GitHub · 2026-12-02 16:25 UTC · original
Lciarallo:pr-brlock-views → main · +148 −23 · 3 files · 2 commits · open

Follow-up to #136, split into a focused standalone PR as suggested by @⁠goldfishdev.

Problem

static VIEWS in crates/victory-gpu/src/descriptor.rs is looked up on every frame by multiple command-list recording threads in parallel, while writes are rare (only when a new view/shape is registered or a resource is released). With std::sync::RwLock<Views>, all concurrent readers increment and decrement the same single atomic counter, causing heavy cache-line bouncing across CPU cores during multi-threaded recording.

Solution

Adds a small, self-contained distributed reader-writer lock (BrLock<T> in crates/victory-gpu/src/brlock.rs) and switches VIEWS to use it:

  • 32 reader slots padded to 128 bytes (#[repr(align(128))]), assigned per thread via thread_local!, so concurrent readers only touch their own cache line and do not contend with one another.
  • Writers serialize via a Mutex<()>, raise an AtomicBool (writing), and wait for all 32 reader slots to drain before mutating Views; readers that observe writing back off and wait until it clears.
  • Only touches 3 files (brlock.rs, descriptor.rs, lib.rs) with no new dependencies or runtime switches required.

Testing

  • Environment: Fedora Linux, Intel Core i7-14700F (28 threads), 32 GB RAM, AMD Radeon RX 9070 XT 16 GB (RADV GFX1201, patched Mesa 26.3.1 + vkd3d-proton), Gamescope + GE-Proton11-12.
  • Game / Profile: Xbox Series X profile, RT enabled, 1280×720 → 2560×1440 FSR4 Performance.
  • Results:
    • Isolated A/B test on the same scene showed 29.4 fps vs ~27.3 fps (~+2.1 fps) from removing read-side lock contention on VIEWS.
    • Stability verified across extended gameplay sessions and automated 5–10 minute runs with zero races, deadlocks, or crashes.
    • cargo xwin check --workspace --locked --target x86_64-pc-windows-msvc passes cleanly (0 errors, 0 warnings); workspace unit tests pass.
**@⁠Lciarallo** on GitHub · 2026-12-02 16:25 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/203) `Lciarallo:pr-brlock-views` → `main` · +148 −23 · 3 files · 2 commits · open Follow-up to #136, split into a focused standalone PR as suggested by @⁠goldfishdev. ### Problem `static VIEWS` in `crates/victory-gpu/src/descriptor.rs` is looked up on every frame by multiple command-list recording threads in parallel, while writes are rare (only when a new view/shape is registered or a resource is released). With `std::sync::RwLock<Views>`, all concurrent readers increment and decrement the same single atomic counter, causing heavy cache-line bouncing across CPU cores during multi-threaded recording. ### Solution Adds a small, self-contained distributed reader-writer lock (`BrLock<T>` in `crates/victory-gpu/src/brlock.rs`) and switches `VIEWS` to use it: - 32 reader slots padded to 128 bytes (`#[repr(align(128))]`), assigned per thread via `thread_local!`, so concurrent readers only touch their own cache line and do not contend with one another. - Writers serialize via a `Mutex<()>`, raise an `AtomicBool` (`writing`), and wait for all 32 reader slots to drain before mutating `Views`; readers that observe `writing` back off and wait until it clears. - Only touches 3 files (`brlock.rs`, `descriptor.rs`, `lib.rs`) with no new dependencies or runtime switches required. ### Testing - **Environment:** Fedora Linux, Intel Core i7-14700F (28 threads), 32 GB RAM, AMD Radeon RX 9070 XT 16 GB (RADV GFX1201, patched Mesa 26.3.1 + vkd3d-proton), Gamescope + GE-Proton11-12. - **Game / Profile:** Xbox Series X profile, RT enabled, 1280×720 → 2560×1440 FSR4 Performance. - **Results:** - Isolated A/B test on the same scene showed **29.4 fps vs ~27.3 fps** (~+2.1 fps) from removing read-side lock contention on `VIEWS`. - Stability verified across extended gameplay sessions and automated 5–10 minute runs with zero races, deadlocks, or crashes. - `cargo xwin check --workspace --locked --target x86_64-pc-windows-msvc` passes cleanly (0 errors, 0 warnings); workspace unit tests pass.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-02 16:59:14 +00:00
Author
Owner

@⁠Kal0s-design on GitHub · 2026-12-03 19:05 UTC · original

Tested this on Windows 11 native (MSVC toolchain), CPU-only, at 322192a and also merged onto current main, where it merges cleanly.

I went through brlock.rs with the ordering in mind. The reader does fetch_add on its slot and then loads writing, the writer stores writing and then loads every slot, and all four are SeqCst, so the Dekker handshake holds. Either the reader sees the flag and backs off or the writer sees the count. The Release on read guard drop pairs with the writer's SeqCst slot load, and the Release store of writing = false pairs with the reader's load, so the next reader sees what the writer did. Writers are serialized by the mutex, poisoning is ignored the same way the old unwrap_or_else(into_inner) did, and the Sync bound (T: Send + Sync) matches RwLock. In descriptor.rs no read guard is held while write() is taken, and I didn't find anything running under a guard that takes VIEWS again.

I added some local stress tests under cfg(test) in brlock.rs (not pushed) and ran them in debug and release.

  • 40 readers (more than SLOTS, so slots get shared) and 4 writers for 1.5s on a non-atomic [u64; 8] that writers keep all equal. No torn read, and the final value matches the number of writes. In release over 5 runs that was about 2.8 billion reads and between 275 and 1362 writes per run, all clean.
  • 64 threads mixing reads with non-atomic read-modify-write increments under write(). The final count is exact.
  • A panic while holding a read guard and while holding a write guard leaves the lock usable.
  • A ReadGuard moved to another thread and dropped there (it is Send, unlike std's) still lets a later write() go through. That one is only a smoke test, I didn't manage to force the two threads onto different slots.
  • Recursive read() on one thread while a writer waits deadlocks. std::sync::RwLock deadlocked the same way in the same test on Windows, and no call site does this, so it's not a regression. Maybe worth a line in the doc comment in case VIEWS ever gets a reentrant path.

All five pass in debug and release.

For the existing suite I ran cargo test -p victory-gpu --lib -- --test-threads=4. descriptor::tests::views_die_with_their_resource, the test this PR touches, crashes with an access violation here, but it does that on the PR's base and on main as well, so I had to skip it. Without it the PR head gives 294 passed, 9 failed, 23 ignored, identical to its base with the same failing tests. Merged onto main it's 338 passed, 5 failed, 23 ignored, identical to main alone. The same set of tests fails here without the PR.

Clippy (-p victory-gpu --all-targets) shows no new warnings compared to base.

One small note that isn't a bug. While a writer holds the lock, waiting readers spin and then yield_now instead of parking, so a long write section like forget() with many entries keeps them busy. Probably fine given how rare writes are.

Looks correct to me.

AI-assisted: yes

**@⁠Kal0s-design** on GitHub · 2026-12-03 19:05 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/203#issuecomment-7389127370) Tested this on Windows 11 native (MSVC toolchain), CPU-only, at 322192a and also merged onto current main, where it merges cleanly. I went through brlock.rs with the ordering in mind. The reader does fetch_add on its slot and then loads `writing`, the writer stores `writing` and then loads every slot, and all four are SeqCst, so the Dekker handshake holds. Either the reader sees the flag and backs off or the writer sees the count. The Release on read guard drop pairs with the writer's SeqCst slot load, and the Release store of `writing = false` pairs with the reader's load, so the next reader sees what the writer did. Writers are serialized by the mutex, poisoning is ignored the same way the old `unwrap_or_else(into_inner)` did, and the Sync bound (T: Send + Sync) matches RwLock. In descriptor.rs no read guard is held while write() is taken, and I didn't find anything running under a guard that takes VIEWS again. I added some local stress tests under cfg(test) in brlock.rs (not pushed) and ran them in debug and release. - 40 readers (more than SLOTS, so slots get shared) and 4 writers for 1.5s on a non-atomic [u64; 8] that writers keep all equal. No torn read, and the final value matches the number of writes. In release over 5 runs that was about 2.8 billion reads and between 275 and 1362 writes per run, all clean. - 64 threads mixing reads with non-atomic read-modify-write increments under write(). The final count is exact. - A panic while holding a read guard and while holding a write guard leaves the lock usable. - A ReadGuard moved to another thread and dropped there (it is Send, unlike std's) still lets a later write() go through. That one is only a smoke test, I didn't manage to force the two threads onto different slots. - Recursive read() on one thread while a writer waits deadlocks. std::sync::RwLock deadlocked the same way in the same test on Windows, and no call site does this, so it's not a regression. Maybe worth a line in the doc comment in case VIEWS ever gets a reentrant path. All five pass in debug and release. For the existing suite I ran `cargo test -p victory-gpu --lib -- --test-threads=4`. `descriptor::tests::views_die_with_their_resource`, the test this PR touches, crashes with an access violation here, but it does that on the PR's base and on main as well, so I had to skip it. Without it the PR head gives 294 passed, 9 failed, 23 ignored, identical to its base with the same failing tests. Merged onto main it's 338 passed, 5 failed, 23 ignored, identical to main alone. The same set of tests fails here without the PR. Clippy (`-p victory-gpu --all-targets`) shows no new warnings compared to base. One small note that isn't a bug. While a writer holds the lock, waiting readers spin and then yield_now instead of parking, so a long write section like forget() with many entries keeps them busy. Probably fine given how rare writes are. Looks correct to me. AI-assisted: yes
A second read() on a thread that already holds a read guard deadlocks
once a writer is waiting, as with std::sync::RwLock. Noted in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Author
Owner

@⁠Luxuride on GitHub · 2026-12-04 12:01 UTC · original

The motivation is real — recording threads do hit VIEWS constantly — but nobody, including you, can tell whether this is a win without a number, and it replaces a std primitive on the frame path with 140 lines of new unsafe and no tests of its own.

  • Writers and blocked readers both busy-spin (brlock.rs:77 and the wait loop in write()), with no parking; a slow write (a resize of the 20k-entry table) burns a core per waiting recording thread. std's RwLock parks on a futex, and a convoy is exactly the case this is meant to fix.
  • brlock.rs:3 says each reader counts on a cache line of its own, but NEXT.fetch_add(1, Relaxed) % SLOTS with SLOTS = 32 means thread 33 shares slot 0, and the instance is not per-lock, so two BrLocks share one thread→slot map. Harmless for counting, misleading for a reader.
  • ReadGuard::drop uses Release while everything else is SeqCst (brlock.rs:111,137): correct, but the whole safety argument lives in those orderings, so comment or make them uniform.

Rebase, add a stress test (N readers, 1 writer, no torn read, no lost update) and one bench at 1 and 8 threads; with the number this becomes an easy yes.

**@⁠Luxuride** on GitHub · 2026-12-04 12:01 UTC · [original](https://github.com/lobomfz/VIctory-xmem/pull/203#issuecomment-7410866166) The motivation is real — recording threads do hit VIEWS constantly — but nobody, including you, can tell whether this is a win without a number, and it replaces a std primitive on the frame path with 140 lines of new `unsafe` and no tests of its own. - Writers and blocked readers both busy-spin (`brlock.rs:77` and the wait loop in `write()`), with no parking; a slow write (a resize of the 20k-entry table) burns a core per waiting recording thread. std's `RwLock` parks on a futex, and a convoy is exactly the case this is meant to fix. - `brlock.rs:3` says each reader counts on a cache line of its own, but `NEXT.fetch_add(1, Relaxed) % SLOTS` with `SLOTS = 32` means thread 33 shares slot 0, and the instance is not per-lock, so two `BrLock`s share one thread→slot map. Harmless for counting, misleading for a reader. - `ReadGuard::drop` uses `Release` while everything else is `SeqCst` (brlock.rs:111,137): correct, but the whole safety argument lives in those orderings, so comment or make them uniform. Rebase, add a stress test (N readers, 1 writer, no torn read, no lost update) and one bench at 1 and 8 threads; with the number this becomes an easy yes.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/203/head:github-bot/gh-203'
git switch 'github-bot/gh-203'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-203'
git switch 'github-bot/gh-203'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-203'
git switch 'github-bot/gh-203'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-203'
git switch 'main'
git merge --squash 'github-bot/gh-203'
git switch 'main'
git merge --ff-only 'github-bot/gh-203'
git switch 'main'
git merge 'github-bot/gh-203'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.