Prechádzať zdrojové kódy

Back off refused GPU pool growth and defer uploads under low commit

codec_d 23 hodín pred
rodič
commit
ab75ac3e02

+ 26 - 2
crates/victory-gpu/src/draw.rs

@@ -2297,6 +2297,11 @@ impl State {
         if room {
             host.texture_slots_waiting(frame);
         }
+        let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake);
+        if !crate::residency::admit_texture_pass(required) {
+            BAKE_SERVED.store(0, Ordering::Relaxed);
+            return;
+        }
         let baking = crate::texture::BAKING.get();
         let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 });
         // (Those that are due later after all that are due.)
@@ -2362,7 +2367,6 @@ impl State {
         };
         // 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 {
@@ -2374,7 +2378,9 @@ impl State {
         BAKE_SERVED.store(0, Ordering::Relaxed);
         let mut served = true;
         for (index, write) in due {
-            if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span {
+            if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span
+                || !crate::residency::admit_texture_pass(required)
+            {
                 served = false;
                 break;
             }
@@ -2539,6 +2545,10 @@ impl State {
                 }
             };
             let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture);
+            if crate::residency::upload_refused() {
+                served = false;
+                break;
+            }
             let resource = match placed.as_ref().or(view.as_ref()) {
                 Some(&View::Shader(resource, _)) => resource as This,
                 _ => {
@@ -2548,6 +2558,10 @@ impl State {
                 }
             };
             let texture = crate::resource::host_resource(resource);
+            if crate::residency::upload_refused() {
+                served = false;
+                break;
+            }
             let title_fills = texture.is_some_and(crate::texture::title_written);
             if !title_fills {
                 at_once();
@@ -2606,6 +2620,10 @@ impl State {
                     crate::texture::ahead::send(job);
                 }
             }
+            if ahead.is_none() && crate::residency::upload_refused() {
+                served = false;
+                break;
+            }
             let late = late && ahead.is_none();
             if let Some(view) = &view
                 && ahead.is_none()
@@ -2616,6 +2634,12 @@ impl State {
                 readable(list, sampled.kind, view);
                 crate::texture::PICKING.set(None);
             }
+            // A failed allocation leaves this slot due. Publishing it or
+            // marking it served would lose the only retry for some materials.
+            if ahead.is_none() && crate::residency::upload_refused() {
+                served = false;
+                break;
+            }
             if shows_other && let Some(handle) = heap.handle(index) {
                 host.texture_slot_flip(list, index, handle);
             }

+ 1 - 0
crates/victory-gpu/src/host.rs

@@ -8597,6 +8597,7 @@ impl Host {
         match made {
             Ok(()) => Some((buffer?, data.cast())),
             Err(e) => {
+                crate::residency::allocation_error(&e);
                 tracing::warn!(error = %e, size, "no upload buffer");
                 None
             }

+ 31 - 3
crates/victory-gpu/src/pool.rs

@@ -191,11 +191,12 @@ struct Pool<B> {
     /// The empty blocks it was last told to keep, and the most it keeps.
     spare: usize,
     most: usize,
+    retry_growth_at: u64,
 }
 
 impl<B: Clone> Pool<B> {
     const fn new(most: usize) -> Pool<B> {
-        Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most }
+        Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0 }
     }
 
     /// A piece of `len` bytes and the memory it lies in, and whether that
@@ -237,10 +238,13 @@ impl<B: Clone> Pool<B> {
             unripe.sort_unstable();
             found = unripe.into_iter().find_map(|(_, i)| Some((i, self.blocks[i].as_mut()?.free.take(len, align)?)));
         }
+        // A failed 64 MiB block must not trigger another driver call for each
+        // small texture. Existing free ranges remain usable during backoff.
         let (i, start) = match found {
             Some(found) => found,
             None => {
-                let i = self.add(make()?, ripe.started);
+                let memory = self.grow(now, &mut make)?;
+                let i = self.add(memory, ripe.started);
                 (i, self.blocks[i].as_mut()?.free.take(len, align)?)
             }
         };
@@ -253,7 +257,7 @@ impl<B: Clone> Pool<B> {
             }
             let empty = self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count();
             if empty < ripe.ahead
-                && let Some(memory) = make()
+                && let Some(memory) = self.grow(now, &mut make)
             {
                 self.add(memory, ripe.started);
             }
@@ -264,6 +268,17 @@ impl<B: Clone> Pool<B> {
         Some((Piece { block: i, start, len }, block.memory.clone(), again))
     }
 
+    fn grow(&mut self, now: u64, make: &mut impl FnMut() -> Option<B>) -> Option<B> {
+        if now < self.retry_growth_at {
+            return None;
+        }
+        let block = make();
+        if block.is_none() {
+            self.retry_growth_at = now.saturating_add(500);
+        }
+        block
+    }
+
     fn add(&mut self, memory: B, made: u64) -> usize {
         let i = match self.blocks.iter().position(Option::is_none) {
             Some(i) => i,
@@ -503,6 +518,7 @@ pub(crate) unsafe fn texture(
         let mut heap: Option<ID3D12Heap> = None;
         // SAFETY: plain creation.
         if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } {
+            crate::residency::allocation_error(&e);
             tracing::warn!(error = %e, "no block of texture memory");
         }
         if let Some(h) = &heap
@@ -575,6 +591,18 @@ mod tests {
         assert_eq!(spares(None, true), SPARE);
     }
 
+    #[test]
+    fn a_failed_block_is_not_retried_for_each_small_upload() {
+        let mut pool: Pool<u32> = Pool::new(2);
+        let calls = std::cell::Cell::new(0);
+        let refuse = || { calls.set(calls.get() + 1); None };
+        for size in [704008, 179720, 179720, 24080, 48648, 524288, 89616, 351760] {
+            assert!(pool.take(size, 512, 12, refuse).is_none());
+        }
+        assert_eq!(calls.get(), 1);
+        assert!(pool.take(24080, 512, 1012, || Some(1)).is_some());
+    }
+
     #[test]
     fn budget_tick_reclaims_idle_blocks_without_reusing_live_or_resting_pieces() {
         let mut pool = Pool::new(STAGING_KEPT);

+ 47 - 0
crates/victory-gpu/src/residency.rs

@@ -14,6 +14,43 @@ fn memory_status() -> Option<MEMORYSTATUSEX> {
     (unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status)
 }
 
+// The texture sweep may run for seconds inside a single submitted frame.
+static NEXT_COMMIT_SAMPLE: AtomicU64 = AtomicU64::new(0);
+static AVAILABLE_COMMIT: AtomicU64 = AtomicU64::new(u64::MAX);
+static RETRY_UPLOAD_AT: AtomicU64 = AtomicU64::new(0);
+
+pub(crate) fn allocation_error(error: &windows::core::Error) {
+    if error.code() == windows::Win32::Foundation::E_OUTOFMEMORY {
+        RETRY_UPLOAD_AT.fetch_max(crate::host::coarse_ms().saturating_add(500), Ordering::Relaxed);
+    }
+}
+
+pub(crate) fn upload_refused() -> bool {
+    crate::host::coarse_ms() < RETRY_UPLOAD_AT.load(Ordering::Relaxed)
+}
+
+fn has_upload_reserve(commit: u64, bake: bool) -> bool {
+    commit >= if bake { 2 * GIB } else { 4 * GIB }
+}
+
+/// Leave commit for game allocations and submissions already in flight. Direct
+/// texture consumers bypass this gate. Bake prefetch gets priority over lookahead.
+pub(crate) fn admit_texture_pass(bake: bool) -> bool {
+    let now = crate::host::coarse_ms();
+    if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
+        return false;
+    }
+    let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed);
+    if now >= next && NEXT_COMMIT_SAMPLE.compare_exchange(
+        next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed,
+    ).is_ok() {
+        if let Some(status) = memory_status() {
+            AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed);
+        }
+    }
+    has_upload_reserve(AVAILABLE_COMMIT.load(Ordering::Relaxed), bake)
+}
+
 pub(crate) fn limited_host_ram() -> bool {
     static LIMITED: OnceLock<bool> = OnceLock::new();
     *LIMITED.get_or_init(|| memory_status().is_some_and(|s| s.ullTotalPhys <= 32 * GIB))
@@ -79,6 +116,16 @@ pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, limited: bool, staging:
 mod tests {
     use super::*;
 
+    #[test]
+    fn bake_and_lookahead_leave_room_for_live_game_allocations() {
+        for (commit, bake, lookahead) in [
+            (277 << 20, false, false), (2 * GIB, true, false), (4 * GIB, true, true),
+        ] {
+            assert_eq!(has_upload_reserve(commit, true), bake);
+            assert_eq!(has_upload_reserve(commit, false), lookahead);
+        }
+    }
+
     #[test]
     fn either_constraint_enters_pressure_and_both_must_recover() {
         assert!(next_pressure(false, 12 * GIB, 6 * GIB));

+ 1 - 0
crates/victory-gpu/src/resource.rs

@@ -2533,6 +2533,7 @@ fn host_texture_as(
         }
     };
     if let Err(e) = &made {
+        crate::residency::allocation_error(&e);
         tracing::warn!(error = %e, desc = ?d, reserved, "no host texture");
     }
     if !reserved

+ 4 - 0
docs/bug-journal.md

@@ -9,3 +9,7 @@
 - **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.
+- **15:53, manual run.** Windows returned E_OUTOFMEMORY (0x8007000E) for a series of 64 MiB pool requests and individual uploads as small as 24,080 bytes. Rust subsequently aborted on a 786,432-byte allocation. The pasted log does not identify the Rust allocation site or a particular resource as the initial cause.
+- **15:56–15:59, reproducer and repair.** Replayed eight reported upload sizes through the release pool with a failing block allocator. The unpatched test made eight block creation attempts in one burst. Each pool now backs off growth for 500 ms after a failed creation while still reusing space in its existing blocks. An out-of-memory return from host upload or texture allocation interrupts the descriptor texture sweep, leaving interrupted work eligible for retry. The sweep checks available Windows commit at most once per 32 ms, including during a long pass. It defers ordinary prefetch below 4 GiB and bake prefetch below 2 GiB; explicitly bound textures can still request upload memory. GPU unit and device suite: 331 passed, 34 ignored.
+- **16:00–16:03, first opening-save retest.** Windows Graphics Capture showed a character, textured buildings and street lighting. The log contained no failed upload-buffer allocations or Rust allocation aborts. The harness timed out during shutdown and lost its timing receipt. The renderer logged a dropped draw due to exhausted dynamic descriptor slots.
+- **16:04–16:07, confirmation and install.** From a fresh copy of the opening save, the release ran 135 seconds after the first interval above 1,000 draws/frame and remained live until the harness closed it. Peak process commit was 34.42 GiB; the lowest sampled Windows commit headroom was 1.30 GiB. Zero E_OUTOFMEMORY returns and zero Rust allocation aborts appeared in the log. Across 120 high-draw caption intervals the median was 54.3 ms/frame, with 39 at or below 50 ms. The descriptor-slot warning recurred. Installed and hash-verified the release behind the existing `pareto-residency` selector. SHA-256 `d580328bf90fe54e643dad60c04481d7e4b0d7134b9b6ce70c5e0f5c77ff3cf1`. Receipt and log: `../XCL-frame-timing/pareto-residency-comparison/oom-confirm/`.