perf(gpu): cut per-draw and title-memory sync CPU overhead #127

Open
matheusfrta wants to merge 1 commit from upstream-pr/127 into main
matheusfrta commented 2026-11-25 15:02:33 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by matheusfrta on 2026-11-25T15:02:33Z.


The world frame rate is mostly CPU-bound across title recording and submission prep, so this targets the biggest hotspots there. Fixed sparse 2 GiB shadows losing write-watching after touching a mapped view, stopped synchronous copy-backs from pinning guarded blocks for two seconds, replaced per-batch thread spawning in in_parallel with a worker pool to avoid firing title TLS callbacks every submission, and trimmed per-draw locks and heap allocations.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:issue:6607448928 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/127). Originally posted by [matheusfrta](https://github.com/matheusfrta) on 2026-11-25T15:02:33Z. --- The world frame rate is mostly CPU-bound across title recording and submission prep, so this targets the biggest hotspots there. Fixed sparse 2 GiB shadows losing write-watching after touching a mapped view, stopped synchronous copy-backs from pinning guarded blocks for two seconds, replaced per-batch thread spawning in `in_parallel` with a worker pool to avoid firing title TLS callbacks every submission, and trimmed per-draw locks and heap allocations.
KernelSmoker commented 2026-11-25 18:44:53 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by KernelSmoker on 2026-11-25T18:44:53Z.


Compile check on PR head c9e45b4 (cargo check --workspace --all-targets --locked --offline --target x86_64-pc-windows-gnu, Rust 1.98.1) fails in crates/victory-gpu/src/host.rs:

error[E0425]: cannot find type `F` in this scope
    --> crates/victory-gpu/src/host.rs:3134:36
     |
3134 |         s.run = Some((run_job::<T, F>, (&raw const job) as usize));
     |                                    ^
error[E0425]: cannot find type `F` in this scope
    --> crates/victory-gpu/src/host.rs:3138:27
     |
3138 |     unsafe { run_job::<T, F>((&raw const job) as usize) };
     |                           ^

in_parallel takes f: impl Fn(&[T]) + Sync (line 3017) rather than a named generic F: Fn(&[T]) + Sync, so run_job::<T, F> cannot name F.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:comment:7171339317 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/127#issuecomment-7171339317). Originally posted by [KernelSmoker](https://github.com/KernelSmoker) on 2026-11-25T18:44:53Z. --- Compile check on PR head `c9e45b4` (`cargo check --workspace --all-targets --locked --offline --target x86_64-pc-windows-gnu`, Rust 1.98.1) fails in `crates/victory-gpu/src/host.rs`: ``` error[E0425]: cannot find type `F` in this scope --> crates/victory-gpu/src/host.rs:3134:36 | 3134 | s.run = Some((run_job::<T, F>, (&raw const job) as usize)); | ^ error[E0425]: cannot find type `F` in this scope --> crates/victory-gpu/src/host.rs:3138:27 | 3138 | unsafe { run_job::<T, F>((&raw const job) as usize) }; | ^ ``` `in_parallel` takes `f: impl Fn(&[T]) + Sync` (line 3017) rather than a named generic `F: Fn(&[T]) + Sync`, so `run_job::<T, F>` cannot name `F`.
MamaLeVrai commented 2026-11-26 05:10:24 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by MamaLeVrai on 2026-11-26T05:10:24Z.


One deadlock to look at when this is rebased. It comes from reading the code; I have not seen it happen.

readable_at runs readable(list, u, view) inside crate::descriptor::with_view, so the VIEWS read lock is held for the whole of readable. Before this PR, view() cloned the view and dropped the lock first. Inside readable there is a path to VIEWS.write() on the same thread:

  • readable → crate::descriptor::host::placed_texture(view) → crate::resource::texture_at(...).
  • texture_at releases the resource it has just made in two cases: when the host copy could not be made (resource(out).host.is_none()), and when another thread put the same (address, desc) in PLACED_TEXTURES first. In both it calls resource_release(out).
  • That is the last reference, so Resource's Drop runs and calls crate::descriptor::forget(...), which takes VIEWS.write().

Taking the write lock while this thread holds the read lock never returns: std::sync::RwLock is not re-entrant. The second case needs two recording threads to meet the same placed texture for the first time, which titles that record on several threads can do. Cloning the view before readable, as main does, or releasing those resources after the lock is gone, would avoid it.

Separately, the PR currently conflicts with main (descriptor.rs, draw.rs, indirect.rs). main already made VIEWS an RwLock.

AI-assisted (Claude Code); no game data.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:comment:7183245397 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/127#issuecomment-7183245397). Originally posted by [MamaLeVrai](https://github.com/MamaLeVrai) on 2026-11-26T05:10:24Z. --- One deadlock to look at when this is rebased. It comes from reading the code; I have not seen it happen. `readable_at` runs `readable(list, u, view)` inside `crate::descriptor::with_view`, so the `VIEWS` read lock is held for the whole of `readable`. Before this PR, `view()` cloned the view and dropped the lock first. Inside `readable` there is a path to `VIEWS.write()` on the same thread: - `readable` → `crate::descriptor::host::placed_texture(view)` → `crate::resource::texture_at(...)`. - `texture_at` releases the resource it has just made in two cases: when the host copy could not be made (`resource(out).host.is_none()`), and when another thread put the same `(address, desc)` in `PLACED_TEXTURES` first. In both it calls `resource_release(out)`. - That is the last reference, so `Resource`'s `Drop` runs and calls `crate::descriptor::forget(...)`, which takes `VIEWS.write()`. Taking the write lock while this thread holds the read lock never returns: `std::sync::RwLock` is not re-entrant. The second case needs two recording threads to meet the same placed texture for the first time, which titles that record on several threads can do. Cloning the view before `readable`, as `main` does, or releasing those resources after the lock is gone, would avoid it. Separately, the PR currently conflicts with `main` (`descriptor.rs`, `draw.rs`, `indirect.rs`). `main` already made `VIEWS` an `RwLock`. AI-assisted (Claude Code); no game data.
gut0to commented 2026-11-26 16:05:56 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gut0to on 2026-11-26T16:05:56Z.

Review: COMMENTED


AI-assisted review. I inspected the changed worker-pool initialization and accounting; I did not run tests or a game.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:review:6077250410 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/127#pullrequestreview-6077250410). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-26T16:05:56Z. **Review:** COMMENTED --- AI-assisted review. I inspected the changed worker-pool initialization and accounting; I did not run tests or a game.
gut0to commented 2026-11-26 16:05:56 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gut0to on 2026-11-26T16:05:56Z.

Code review location: crates/victory-gpu/src/host.rs; line 3085

@@ -2970,31 +2998,144 @@ impl Early {
     }
 }
 
-/// Runs `f` on pieces of `list`, of `least` items or more, on some threads.
+struct Pool {
+    state: Mutex<PoolState>,
+    wake_workers: Condvar,
+    wake_caller: Condvar,
+    workers: usize,
+}
+
+#[derive(Default)]
+struct PoolState {
+    seq: u64,
+    active: usize,
+    threads: usize,
+    run: Option<(unsafe fn(usize), usize)>,
+}
+
+/// Runs `f` on pieces of `list`, of `least` items or more, on persistent worker threads.
 pub(crate) fn in_parallel<T: Sync>(list: &[T], least: usize, f: impl Fn(&[T]) + Sync) {
     const THREADS: usize = 6;
     if list.len() <= least {
         return f(list);
     }
     // Small pieces, taken in turn: they are not equally long to do.
     let piece = (list.len() / (THREADS * 8)).max(least);
-    let next = std::sync::atomic::AtomicUsize::new(0);
-    let work = || {
+    let threads = THREADS.min(list.len().div_ceil(piece));
+    if threads <= 1 {
+        return f(list);
+    }
+    static BUSY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+    if BUSY.swap(true, Ordering::Acquire) {
+        return f(list);
+    }
+    struct Clear(&'static std::sync::atomic::AtomicBool);
+    impl Drop for Clear {
+        fn drop(&mut self) {
+            self.0.store(false, Ordering::Release);
+        }
+    }
+    let _busy = Clear(&BUSY);
+
+    static POOL: OnceLock<Arc<Pool>> = OnceLock::new();
+    let pool = POOL.get_or_init(|| {
+        let pool = Arc::new(Pool {
+            state: Mutex::default(),
+            wake_workers: Condvar::new(),
+            wake_caller: Condvar::new(),
+            workers: THREADS - 1,
+        });
+        let mut spawned = 0usize;
+        for id in 0..(THREADS - 1) {
+            let p = pool.clone();
+            let res = std::thread::Builder::new()
+                .name(format!("victory-parallel-{id}"))
+                .spawn(move || {
+                    let mut seen = 0u64;
+                    let mut s = p.state.lock().unwrap_or_else(|e| e.into_inner());
+                    loop {
+                        while s.seq == seen {
+                            s = p.wake_workers.wait(s).unwrap_or_else(|e| e.into_inner());
+                        }
+                        seen = s.seq;
+                        if id >= s.threads.saturating_sub(1) {
+                            continue;
+                        }
+                        let task = s.run;
+                        drop(s);
+                        if let Some((run, ctx)) = task {
+                            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+                                // SAFETY: caller keeps `ctx` alive until `active == 0`.
+                                unsafe { run(ctx) };
+                            }));
+                        }
+                        s = p.state.lock().unwrap_or_else(|e| e.into_inner());
+                        s.active -= 1;
+                        if s.active == 0 {
+                            p.wake_caller.notify_one();
+                        }
+                    }
+                });
+            if res.is_ok() {
+                spawned += 1;
+            }
+        }
+        // Only expose workers that actually spawned; if fewer spawned, threads < THREADS
+        // still leaves them idle only when id >= s.threads - 1, which is true for spawned.
+        let _ = spawned;

AI-assisted static review: I traced pool initialization and active-worker accounting; I did not run tests or a game. spawned is counted but discarded, while Pool.workers stays at THREADS - 1 and each run sets active from that fixed count. If even one thread creation fails, fewer workers can decrement active than WaitPool awaits, so in_parallel can hang. Could the pool use the actual spawned count (or fail initialization and fall back before publishing the pool)?

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:review-comment:4710856503 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/127#discussion_r4710856503). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-26T16:05:56Z. **Code review location:** `crates/victory-gpu/src/host.rs`; line 3085 ~~~~diff @@ -2970,31 +2998,144 @@ impl Early { } } -/// Runs `f` on pieces of `list`, of `least` items or more, on some threads. +struct Pool { + state: Mutex<PoolState>, + wake_workers: Condvar, + wake_caller: Condvar, + workers: usize, +} + +#[derive(Default)] +struct PoolState { + seq: u64, + active: usize, + threads: usize, + run: Option<(unsafe fn(usize), usize)>, +} + +/// Runs `f` on pieces of `list`, of `least` items or more, on persistent worker threads. pub(crate) fn in_parallel<T: Sync>(list: &[T], least: usize, f: impl Fn(&[T]) + Sync) { const THREADS: usize = 6; if list.len() <= least { return f(list); } // Small pieces, taken in turn: they are not equally long to do. let piece = (list.len() / (THREADS * 8)).max(least); - let next = std::sync::atomic::AtomicUsize::new(0); - let work = || { + let threads = THREADS.min(list.len().div_ceil(piece)); + if threads <= 1 { + return f(list); + } + static BUSY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if BUSY.swap(true, Ordering::Acquire) { + return f(list); + } + struct Clear(&'static std::sync::atomic::AtomicBool); + impl Drop for Clear { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } + } + let _busy = Clear(&BUSY); + + static POOL: OnceLock<Arc<Pool>> = OnceLock::new(); + let pool = POOL.get_or_init(|| { + let pool = Arc::new(Pool { + state: Mutex::default(), + wake_workers: Condvar::new(), + wake_caller: Condvar::new(), + workers: THREADS - 1, + }); + let mut spawned = 0usize; + for id in 0..(THREADS - 1) { + let p = pool.clone(); + let res = std::thread::Builder::new() + .name(format!("victory-parallel-{id}")) + .spawn(move || { + let mut seen = 0u64; + let mut s = p.state.lock().unwrap_or_else(|e| e.into_inner()); + loop { + while s.seq == seen { + s = p.wake_workers.wait(s).unwrap_or_else(|e| e.into_inner()); + } + seen = s.seq; + if id >= s.threads.saturating_sub(1) { + continue; + } + let task = s.run; + drop(s); + if let Some((run, ctx)) = task { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + // SAFETY: caller keeps `ctx` alive until `active == 0`. + unsafe { run(ctx) }; + })); + } + s = p.state.lock().unwrap_or_else(|e| e.into_inner()); + s.active -= 1; + if s.active == 0 { + p.wake_caller.notify_one(); + } + } + }); + if res.is_ok() { + spawned += 1; + } + } + // Only expose workers that actually spawned; if fewer spawned, threads < THREADS + // still leaves them idle only when id >= s.threads - 1, which is true for spawned. + let _ = spawned; ~~~~ --- AI-assisted static review: I traced pool initialization and active-worker accounting; I did not run tests or a game. `spawned` is counted but discarded, while `Pool.workers` stays at `THREADS - 1` and each run sets `active` from that fixed count. If even one thread creation fails, fewer workers can decrement `active` than `WaitPool` awaits, so `in_parallel` can hang. Could the pool use the actual spawned count (or fail initialization and fall back before publishing the pool)?
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/127:upstream-pr/127'
git switch 'upstream-pr/127'

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.

git switch 'main'
git merge --no-ff 'upstream-pr/127'
git switch 'upstream-pr/127'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/127'
git switch 'upstream-pr/127'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/127'
git switch 'main'
git merge --squash 'upstream-pr/127'
git switch 'main'
git merge --ff-only 'upstream-pr/127'
git switch 'main'
git merge 'upstream-pr/127'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Belobug/VIctory-Belobug-AMD!127
No description provided.