فهرست منبع

Scope bindless refreshes to their heap and bound speculative staging

codec_d 23 ساعت پیش
والد
کامیت
18bdf7932b

+ 4 - 0
crates/victory-gpu/src/descriptor/host.rs

@@ -112,6 +112,8 @@ impl Made {
 }
 
 pub(crate) struct HostHeap {
+    pub(crate) buffer_sweep: Mutex<crate::draw::BufferSweep>,
+    pub(crate) buffer_frame: std::sync::atomic::AtomicU64,
     pub(crate) heap: ID3D12DescriptorHeap,
     cpu: usize,
     step: u32,
@@ -1524,6 +1526,8 @@ impl HostHeap {
             })
             .flatten();
         let h = HostHeap {
+            buffer_sweep: Mutex::default(),
+            buffer_frame: std::sync::atomic::AtomicU64::new(u64::MAX),
             heap,
             cpu,
             step,

+ 55 - 41
crates/victory-gpu/src/draw.rs

@@ -157,7 +157,7 @@ thread_local! {
     /// While `State::early_textures` runs the texture pass: the
     /// milliseconds and the bytes that run may take, in place of the
     /// pass's own per frame.
-    static PASS_BUDGET: std::cell::Cell<Option<(u64, u64)>> = const { std::cell::Cell::new(None) };
+    static PASS_BUDGET: std::cell::Cell<Option<(u64, u64, bool)>> = const { std::cell::Cell::new(None) };
 }
 
 /// The milliseconds of every frame the pass that uploads textures picked
@@ -600,6 +600,20 @@ fn heap_spread() -> bool {
 #[derive(Default)]
 struct HeapRanges<T>(Vec<Option<(T, u64, u64)>>);
 
+/// Descriptor-derived references belong to the heap that produced them.
+pub(crate) struct BufferSweep {
+    passes: u64,
+    ranges: HeapRanges<std::sync::Arc<crate::shadow::Shadow>>,
+    // Last refresh frame and covered interval for throttled, unwatched copies.
+    unwatched: std::collections::HashMap<u64, (u64, u64, u64)>,
+}
+
+impl Default for BufferSweep {
+    fn default() -> Self {
+        Self { passes: 0, ranges: HeapRanges(Vec::new()), unwatched: Default::default() }
+    }
+}
+
 impl<T> HeapRanges<T> {
     fn set(&mut self, slot: u32, range: Option<(T, u64, u64)>) {
         let slot = slot as usize;
@@ -839,14 +853,8 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
     // at best); all of them every 16 passes, because a view of a
     // released resource goes stale without a write, and a slot written
     // before its memory had a host copy is only made then.
-    type Ranges = HeapRanges<std::sync::Arc<crate::shadow::Shadow>>;
-    static RANGES: std::sync::Mutex<Option<std::collections::HashMap<usize, (u64, Ranges)>>> =
-        std::sync::Mutex::new(None);
-    let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner());
-    let (passes, ranges) = kept
-        .get_or_insert_with(Default::default)
-        .entry(std::ptr::from_ref(host) as usize)
-        .or_insert_with(|| (0, HeapRanges(Vec::new())));
+    let mut kept = host.buffer_sweep.lock().unwrap_or_else(|e| e.into_inner());
+    let BufferSweep { passes, ranges, unwatched } = &mut *kept;
     let changed = host.buffer_changes();
     let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread());
     let slots = if all {
@@ -942,7 +950,6 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
         span.1 = span.1.min(*from);
         span.2 = span.2.max(*to);
     }
-    drop(kept);
     let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum();
     // Memory that is not write-watched is copied whole by every refresh.
     // It was once refreshed only every 120 frames (unmapped pages read
@@ -951,32 +958,27 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
     // the garbage ended runs (the card stopped answering 14-90 frames
     // into the opening cutscene; with every frame it ran on). The pass
     // costs some 30 ms a frame this way.
-    static WHOLE: std::sync::Mutex<Option<std::collections::HashMap<usize, u64>>> = std::sync::Mutex::new(None);
-    let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner());
-    let whole = whole.get_or_insert_with(Default::default);
+    static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
+    let every = *EVERY.get_or_init(|| {
+        std::env::var("VICTORY_UNWATCHED_FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(1)
+    });
     let mut found = Vec::with_capacity(spans.len());
+    let mut next_unwatched = std::collections::HashMap::new();
     for (shadow, from, to) in spans.values() {
-        if shadow.unwatched() {
-            // By the copy's number: a copy made where one let go was
-            // (`shadow::let_go_idle`) has never been refreshed.
-            let key = shadow.id() as usize;
-            // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame).
-            static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
-            let every = *EVERY.get_or_init(|| {
-                std::env::var("VICTORY_UNWATCHED_FRAMES")
-                    .ok()
-                    .and_then(|v| v.parse().ok())
-                    .unwrap_or(1)
-            });
-            match whole.get(&key) {
-                Some(&last) if frame < last + every => continue,
-                _ => {
-                    whole.insert(key, frame);
-                }
+        if every > 1 && shadow.unwatched() {
+            let id = shadow.id();
+            if let Some(&(last, low, high)) = unwatched.get(&id)
+                && frame >= last && frame - last < every && low <= *from && *to <= high
+            {
+                next_unwatched.insert(id, (last, low, high));
+                continue;
             }
+            next_unwatched.insert(id, (frame, *from, *to));
         }
         found.push((shadow.clone(), *from, (*to).min(*from + shadow.left(*from))));
     }
+    *unwatched = next_unwatched;
+    drop(kept);
     #[cfg(feature = "diagnostics")]
     let refreshed = std::time::Instant::now();
     crate::watch::look_at_holes();
@@ -2012,9 +2014,9 @@ impl State {
             .find(|h| !h.samplers())?;
         let host = heap.host()?;
         let gpu = host.strides_gpu()?;
-        // One key per list, as textures have: no title resource is there.
-        const ONCE: usize = usize::MAX - 0x5e;
-        if !list.first_use(ONCE) {
+        // Stride buffers have aligned GPU addresses. Tag the list key so it
+        // is distinct from aligned guest resource pointers.
+        if !list.first_use(gpu as usize | 1) {
             return Some(gpu);
         }
         // The list may outlive the title's heap object, which owns the table.
@@ -2026,9 +2028,8 @@ impl State {
         // frame (2026-11-24, run 11).
         // shortcut: what the title writes into such buffers between lists
         // of one frame is seen a frame late.
-        static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
         let frame = crate::frame::current();
-        if FRAME.swap(frame, Ordering::Relaxed) == frame {
+        if host.buffer_frame.swap(frame, Ordering::Relaxed) == frame {
             return Some(gpu);
         }
         let started = std::time::Instant::now();
@@ -2036,7 +2037,11 @@ impl State {
         if crate::host::aside::on() {
             let at = std::ptr::from_ref(heap) as usize;
             list.refreshes_coming(move || {
-                crate::descriptor::with_heap(at, |heap| heap.host().map(|host| heap_buffer_pass(heap, host, frame)))
+                crate::descriptor::with_heap(at, |heap| {
+                    // The list retains the original stride buffer. A newly
+                    // allocated heap at the same CPU address has another one.
+                    heap.host().filter(|h| h.strides_gpu() == Some(gpu)).map(|h| heap_buffer_pass(heap, h, frame))
+                })
                     .flatten()
                     .unwrap_or_default()
             });
@@ -2121,7 +2126,7 @@ impl State {
             );
         }
         let began = std::time::Instant::now();
-        PASS_BUDGET.set(Some(budget));
+        PASS_BUDGET.set(Some((budget.0, budget.1, bake)));
         crate::texture::BAKING.set(bake && bake_exact());
         self.heap_textures(list, heap, host);
         crate::texture::BAKING.set(false);
@@ -2241,12 +2246,11 @@ impl State {
             Some(mb) => mb << 20,
             None => {
                 let base = staging_budget_per_frame(memory.map(|[budget, ..]| budget));
-                let capped = if crate::residency::limited_host_ram() {
+                if crate::residency::limited_host_ram() {
                     base.min(128 << 20)
                 } else {
                     base
-                };
-                crate::residency::prefetch_limit(capped, crate::residency::pressured())
+                }
             }
         };
         static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
@@ -2351,11 +2355,21 @@ impl State {
         // own: its bytes on top of what the frame has spent so far.
         // (Not `most`: that is the longest wait between looks, used below.)
         let (span, bytes_at_most) = match PASS_BUDGET.get() {
-            Some((ms, bytes)) => {
+            Some((ms, bytes, _)) => {
                 (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes))
             }
             None => (span, per_frame),
         };
+        // Apply the shared frame ceiling after early-pass and catch-up budgets.
+        // A bake samples its inputs immediately and cannot retry that draw.
+        let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake);
+        let bytes_at_most = if required || asked.is_some() {
+            bytes_at_most
+        } else {
+            crate::residency::prefetch_limit(bytes_at_most, crate::residency::pressured(),
+                crate::residency::limited_host_ram(), crate::texture::live_staging_bytes())
+        };
+
         let began = std::time::Instant::now();
         BAKE_SERVED.store(0, Ordering::Relaxed);
         let mut served = true;

+ 41 - 4
crates/victory-gpu/src/pool.rs

@@ -42,7 +42,18 @@ static SPARES: AtomicUsize = AtomicUsize::new(SPARE);
 /// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`].
 /// Asked once a second.
 pub(crate) fn room(memory: Option<[u64; 4]>) {
-    SPARES.store(spares(memory, crate::host::keep_freed()), Ordering::Relaxed);
+    let pressure = crate::residency::pressured();
+    let limit = spares(memory, crate::host::keep_freed() && !pressure);
+    SPARES.store(limit, Ordering::Relaxed);
+    let tick = now();
+    // A full pool can become idle while another subsystem needs the VRAM.
+    // A busy allocator observes the new limit on its next allocation or tick.
+    if let Ok(mut pool) = TEXTURES.try_lock() {
+        pool.reclaim(tick, limit, true);
+    }
+    if let Ok(mut pool) = STAGING.try_lock() {
+        pool.reclaim(tick, if pressure { 0 } else { limit }, true);
+    }
 }
 
 fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize {
@@ -272,6 +283,10 @@ impl<B: Clone> Pool<B> {
     /// Makes the pieces that rested long enough free, and lets go of empty
     /// blocks past [`SPARE`].
     fn rested(&mut self, now: u64) {
+        self.reclaim(now, SPARES.load(Ordering::Relaxed), false);
+    }
+
+    fn reclaim(&mut self, now: u64, limit: usize, sweep: bool) {
         let mut any = false;
         while let Some(&(ready, piece)) = self.resting.front()
             && ready <= now
@@ -283,9 +298,9 @@ impl<B: Clone> Pool<B> {
             }
         }
         // (Without a piece given back too, once there is less room.)
-        let most = SPARES.load(Ordering::Relaxed).min(self.most);
-        if any || most < self.spare {
-            self.spare = most;
+        let most = limit.min(self.most);
+        let previous = std::mem::replace(&mut self.spare, most);
+        if sweep || any || most < previous {
             let mut spare = 0;
             for block in &mut self.blocks {
                 if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) {
@@ -560,6 +575,28 @@ mod tests {
         assert_eq!(spares(None, true), SPARE);
     }
 
+    #[test]
+    fn budget_tick_reclaims_idle_blocks_without_reusing_live_or_resting_pieces() {
+        let mut pool = Pool::new(STAGING_KEPT);
+        let (held, _, _) = pool.take(BLOCK / 2, 1, 0, || Some(1)).unwrap();
+        let (resting, _, _) = pool.take(BLOCK / 2, 1, 0, || Some(2)).unwrap();
+        pool.give(resting, 0);
+        for i in 0..12 {
+            pool.add(i, 0);
+        }
+        pool.reclaim(0, SPARE_KEPT, true);
+        assert_eq!(pool.blocks(), STAGING_KEPT + 1);
+        pool.reclaim(REST - 1, SPARE, true);
+        assert_eq!(pool.blocks(), SPARE + 1);
+        assert_eq!(pool.resting.len(), 1);
+        pool.reclaim(REST, 0, true);
+        assert_eq!(pool.blocks(), 1);
+        assert!(pool.resting.is_empty());
+        pool.give(held, REST);
+        pool.reclaim(2 * REST, 0, true);
+        assert_eq!(pool.blocks(), 0);
+    }
+
     #[test]
     fn pieces_never_overlap_and_rest_before_they_are_used_again() {
         let mut pool: Pool<u32> = Pool::new(SPARE);

+ 15 - 6
crates/victory-gpu/src/residency.rs

@@ -65,8 +65,14 @@ pub(crate) fn pressured() -> bool {
 
 /// A soft per-frame admission limit. A single texture can cross it. The
 /// queue retains unserved slots so they can be retried on later frames.
-pub(crate) fn prefetch_limit(bytes: u64, pressure: bool) -> u64 {
-    if pressure { bytes.min(16 << 20) } else { bytes }
+pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, limited: bool, staging: u64) -> u64 {
+    if pressure {
+        bytes.min(16 << 20)
+    } else if limited && staging >= GIB {
+        bytes.min(32 << 20)
+    } else {
+        bytes
+    }
 }
 
 #[cfg(test)]
@@ -85,9 +91,12 @@ mod tests {
 
     #[test]
     fn prefetch_respects_existing_budgets_and_resumes_after_recovery() {
-        assert_eq!(prefetch_limit(0, true), 0);
-        assert_eq!(prefetch_limit(8 << 20, true), 8 << 20);
-        assert_eq!(prefetch_limit(512 << 20, true), 16 << 20);
-        assert_eq!(prefetch_limit(192 << 20, false), 192 << 20);
+        assert_eq!(prefetch_limit(512 << 20, false, true, GIB), 32 << 20);
+        assert_eq!(prefetch_limit(512 << 20, false, true, GIB - 1), 512 << 20);
+        assert_eq!(prefetch_limit(512 << 20, false, false, 2 * GIB), 512 << 20);
+        assert_eq!(prefetch_limit(0, true, false, 0), 0);
+        assert_eq!(prefetch_limit(8 << 20, true, false, 0), 8 << 20);
+        assert_eq!(prefetch_limit(512 << 20, true, false, 0), 16 << 20);
+        assert_eq!(prefetch_limit(192 << 20, false, false, 0), 192 << 20);
     }
 }

+ 11 - 0
docs/bug-journal.md

@@ -0,0 +1,11 @@
+# GPU residency bug journal
+
+## 2026-11-25, Pacific time
+
+- **15:38, source verification.** The default `Play-VIctory.cmd` and its `fast` selector use the same local release. Its SHA-256 matches the build from `pareto-rtx-fast` at `fabb872`. The live window showed 81.4 ms/frame for an interval with 4,463 draws/frame. This observation has no controlled scene match.
+- **15:39, descriptor lifetime and idle pools.** Moved the bindless buffer sweep and its previous ranges onto their owning host heap. A list holds each stride buffer it uses. A deferred sweep verifies the stride buffer identity before reading a heap. The periodic budget check can now drain expired pieces and trim completely free blocks from the texture and upload pools. Busy allocators retry on their next opportunity.
+- **15:41-15:42, initial comparison.** Both releases used fresh copies of the same opening save and warmed cache. The first comparison stopped each process when Windows commit headroom dipped below 2 GiB. Neither reached the 1,000 draws/frame threshold. The baseline reported 4,241 MiB of live texture staging, 277 MiB of commit headroom and 7,648 MiB of free physical memory in its pressure log. The first candidate reported 2,870 MiB of staging when it first signaled pressure, at a different frame. Those samples cannot quantify memory savings.
+- **15:45, staging admission.** The pressure cap had applied before catch-up tripled the budget, and early prefetch could add its own allowance. On auto settings, the final shared budget now limits speculative staging to 16 MiB/frame under pressure or 32 MiB/frame on a limited-RAM host with at least 1 GiB of live staging. A single texture can cross the limit. Required material bakes keep their existing budget and explicit stage-budget overrides take precedence. The maintenance pass also releases all eligible spare staging blocks under host pressure. Release GPU suite: 329 passed, 34 ignored.
+- **15:46-15:48, release comparison on the RTX 5090.** Repeated from the same copied save and the same initial cache with the normal Pareto rendering settings. Allowed transient Windows commit dips and stopped after 15 distinct title-bar intervals with at least 1,000 draws/frame. Baseline median 64.2 ms/frame, candidate 54.8. Both reached 50 ms or better in four intervals. Median draws/frame were 2,868 and 2,839. Peak process commit was 27.15 and 26.12 GiB. Sampled peak whole-adapter use was 18.67 and 17.45 GiB. The two runs progressed at different rates and window capture overlapped part of the baseline, so this pair is directional.
+- **15:49-15:50, visual verification.** Window capture confirmed the candidate renders the opening street and characters with textures and colored lighting. In this longer capture run the median was 57.7 ms/frame over 23 heavy caption intervals, six at or below 50 ms. The slowest interval was 566 ms, peak process commit was 28.74 GiB, and sampled whole-adapter use peaked at 19.12 GiB. The original GDI captures returned white surfaces; Windows Graphics Capture returned the game image. PresentMon produced no events in this session, so there is no individual-present latency distribution. The two controlled releases used the same general shader and material paths. Wave64-to-Wave32 translation warnings remain in the logs. Sustained 50 ms/frame and full material coverage remain open.
+- **Local build.** The optional launcher selector is `pareto-residency`. SHA-256 `4d5f1e9a0aa6d13c96dfdf69526c3128077588ed4f18df81f16bf3c8b3afc191`. Comparison receipts and window captures are under `../XCL-frame-timing/pareto-residency-comparison` relative to the checkout.