From c5bd44a1f75632596f3b1e8f58aa80c017cf6402 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Wed, 2 Dec 2026 08:47:58 +0530 Subject: [PATCH] GPU readback: pool staging buffers and wait only for this render's submission (#4958) finish_and_read took a fresh MAP_READ staging buffer for every readback (~96 MB for a 24 MP export) and waited for everything on the queue. Staging buffers now share the free pool with storage buffers, matched on usage so neither is handed out as the other, and are returned after a clean copy-out (dropped after any failure). Gpu::submit returns the SubmissionIndex and the readback waits only on it; the 60 s timeout, the 10 s callback grace period and the lost-device handling are kept. --- crates/gpu/src/ctx.rs | 120 +++++++++++++++++++++++++++--------------- 1 file changed, 79 insertions(+), 41 deletions(-) diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index d2344fc77f..5135ebaa80 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -590,42 +590,43 @@ impl Gpu { self.over_limit(size); return Buf { buf: Some(Tracked::new(self.placeholder())), len }; } - let recycled = { - let mut f = self.free.lock().unwrap_or_else(|e| e.into_inner()); - // the smallest pooled buffer that holds `size` with at most 25 % to spare: photos of - // slightly different sizes reuse each other's buffers instead of piling up new ones - let b = f - .iter() - .enumerate() - .filter(|(_, b)| b.0.size() >= size && b.0.size() <= size + size / 4) - .min_by_key(|(_, b)| b.0.size()) - .map(|(i, _)| i) - .map(|i| f.swap_remove(i)); - if let Some(b) = &b { - POOLED.fetch_sub(b.0.size(), Ordering::Relaxed); - } - b - }; - let buf = recycled.unwrap_or_else(|| { - Tracked::new(self.device.create_buffer(&wgpu::BufferDescriptor { - label: None, - size, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - })) - }); + let buf = + self.take_pooled(size, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST).unwrap_or_else(|| { + Tracked::new(self.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })) + }); Buf { buf: Some(buf), len } } + /// Take the smallest pooled buffer of exactly `usage` that holds `size` with at most 25 % to + /// spare: photos of slightly different sizes reuse each other's buffers instead of piling up + /// new ones. Storage and readback (staging) buffers share the pool but never each other's use. + fn take_pooled(&self, size: u64, usage: wgpu::BufferUsages) -> Option { + let mut f = self.free.lock().unwrap_or_else(|e| e.into_inner()); + let i = f + .iter() + .enumerate() + .filter(|(_, b)| b.0.usage() == usage && b.0.size() >= size && b.0.size() <= size + size / 4) + .min_by_key(|(_, b)| b.0.size()) + .map(|(i, _)| i)?; + let b = f.swap_remove(i); + POOLED.fetch_sub(b.0.size(), Ordering::Relaxed); + Some(b) + } + /// Submit command buffers, then make the buffers this thread dropped before reusable. - /// Nothing is submitted once this render has failed: the render is discarded and recomputed - /// on the CPU, and the failure contract says no further GPU work runs after a fatal failure. - pub fn submit(&self, cmds: impl IntoIterator) { - if !failed() { - self.queue.submit(cmds); - } + /// Nothing is submitted once this render has failed (the render is discarded and recomputed + /// on the CPU, and the failure contract says no further GPU work runs after a fatal failure): + /// the result is then `None`, otherwise the submission's index. + pub fn submit(&self, cmds: impl IntoIterator) -> Option { + let index = if failed() { None } else { Some(self.queue.submit(cmds)) }; let retired = take_retired(); self.pool(retired); + index } /// Put reusable buffers into the free pool (trimmed to its limit). @@ -868,15 +869,22 @@ impl Gpu { return zeros(); } let size = (len * 4) as u64; - let staging = self.device.create_buffer(&wgpu::BufferDescriptor { - label: Some("readback"), - size: size.max(4), - usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, + // a pooled staging buffer when one fits: a fresh ~96 MB one per export costs more than the copy + let usage = wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST; + let staging = self.take_pooled(size.max(4), usage).unwrap_or_else(|| { + Tracked::new(self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("readback"), + size: size.max(4), + usage, + mapped_at_creation: false, + })) }); - enc.copy_buffer_to_buffer(src.raw(), 0, &staging, 0, size); - self.submit([enc.finish()]); - let slice = staging.slice(..size); + enc.copy_buffer_to_buffer(src.raw(), 0, &staging.0, 0, size); + let Some(index) = self.submit([enc.finish()]) else { + // the render failed between the check above and the submit: nothing was submitted + return zeros(); + }; + let slice = staging.0.slice(..size); let (tx, rx) = std::sync::mpsc::channel(); slice.map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); @@ -887,8 +895,9 @@ impl Gpu { }; // A lost device makes the wait fail ([`Gpu::poll`] turns wgpu's panic into the error) and // the map callback never run: checking both keeps this from blocking forever (or handing - // back an unwritten buffer as the image). - if let Err(e) = self.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(READBACK_TIMEOUT) }) { + // back an unwritten buffer as the image). The wait is for this submission only: the queue + // is ordered, so it also covers earlier ones, but not later ones from other threads. + if let Err(e) = self.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: Some(READBACK_TIMEOUT) }) { return failed(e); } // another thread's poll may be the one that runs the callback: allow it a moment @@ -913,7 +922,10 @@ impl Gpu { } }); drop(data); - staging.unmap(); + staging.0.unmap(); + // only a buffer that mapped and read cleanly goes back: after any failure above its map + // state is unknown, so it is dropped instead + self.pool([staging]); out } } @@ -1335,6 +1347,32 @@ mod tests { let back: Vec<[u32; 3]> = g.finish_and_read(g.encoder(), &b, data.len()); assert!(back.len() == 1 << 20 && back.as_flattened() == data.as_slice()); } + /// Readback staging buffers are pooled and reused, and never handed out as storage buffers. + #[test] + fn readback_staging_buffers_are_pooled_apart_from_storage() { + let Some(g) = crate::device() else { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + return; + }; + let len = 1_234_567usize; + let want = (len * 4) as u64; + let mapped = wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST; + let count = || { + let f = g.free.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + f.iter().filter(|b| b.0.usage() == mapped && b.0.size() >= want).count() + }; + let data: Vec = (0..len as u32).map(|i| i.wrapping_mul(2_654_435_761)).collect(); + let b = g.upload(&data); + let back: Vec = g.finish_and_read(g.encoder(), &b, len); + assert!(back == data); + assert!(count() >= 1, "the staging buffer went back to the pool"); + let before = count(); + let back: Vec = g.finish_and_read(g.encoder(), &b, len); + assert!(back == data, "a reused staging buffer reads back exactly"); + assert!(count() <= before, "the second readback reused a pooled buffer instead of adding one"); + assert!(g.buffer(len).raw().usage().contains(wgpu::BufferUsages::STORAGE), "a storage request got a staging buffer"); + } + /// An upload after this render has failed keeps the failure contract (`Gpu::submit` skips the /// submission, so nothing further runs on the GPU): the caller gets the placeholder with the /// requested length instead of a staging buffer holding a copy of the data for a submission