diff --git a/d3d12/crates/leonida-gpu/src/copystat.rs b/d3d12/crates/leonida-gpu/src/copystat.rs index 651eae7ab6..e041177317 100644 --- a/d3d12/crates/leonida-gpu/src/copystat.rs +++ b/d3d12/crates/leonida-gpu/src/copystat.rs @@ -811,10 +811,12 @@ fn log_memory() { { let [textures, staging] = crate::pool::memory(); let [uploads, shared, uploads_held, shared_held] = crate::pool::small::memory(); + let [(made, made_ms, made_most), (waits, waited_ms, waited_most)] = crate::pool::growth(); tracing::info!( "memory in blocks (LEONIDA_TEXTURE_POOL=0 turns them off): {textures} MB of textures, {staging} MB of their staging buffers; \ small buffers (LEONIDA_SMALL_BUFFER_POOL): {uploads} MB of upload buffers ({uploads_held} MB held), {shared} MB of shared \ - buffers ({shared_held} MB held)" + buffers ({shared_held} MB held); since the start, {made} blocks made in {made_ms:.0} ms (longest {made_most:.1} ms), \ + {waits} waits for their pools (LEONIDA_POOL_GROW_UNLOCKED) {waited_ms:.0} ms in all (longest {waited_most:.1} ms)" ); } // Textures the card had no room for are asked for again instead of diff --git a/d3d12/crates/leonida-gpu/src/pool.rs b/d3d12/crates/leonida-gpu/src/pool.rs index a2ea6bb7f8..c035377049 100644 --- a/d3d12/crates/leonida-gpu/src/pool.rs +++ b/d3d12/crates/leonida-gpu/src/pool.rs @@ -19,7 +19,7 @@ use std::collections::{BTreeMap, VecDeque}; use std::ffi::c_void; -use std::sync::Mutex; +use std::sync::{Condvar, Mutex}; use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering}; use windows::Win32::Graphics::Direct3D12::*; @@ -50,6 +50,7 @@ pub(crate) fn room(memory: Option<[u64; 4]>) { // 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); + TEXTURE_BLOCKS.store(pool.blocks(), Ordering::Relaxed); } if let Ok(mut pool) = STAGING.try_lock() { let staging_limit = if crate::residency::critical_commit() { @@ -60,6 +61,7 @@ pub(crate) fn room(memory: Option<[u64; 4]>) { limit }; pool.reclaim(tick, staging_limit, true); + STAGING_BLOCKS.store(pool.blocks(), Ordering::Relaxed); } small::room( tick, @@ -211,11 +213,25 @@ struct Pool { spare: usize, most: usize, retry_growth_at: u64, + /// Blocks being made with the lock not held ([`take_unlocked`]). + growing: usize, +} + +/// What [`Pool::take_or_need`] found. +enum Taken { + /// A piece, its block's memory, whether that part was used before, and + /// whether a block should be made ahead now. + Piece(Piece, B, bool, bool), + /// No block has room: one is to be made first. + NeedBlock, + /// Not pooled (no bytes, or too many), or a block failed to be made less + /// than half a second ago. + Refused, } impl Pool { const fn new(most: usize) -> Pool { - Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0 } + Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0, growing: 0 } } /// A piece of `len` bytes and the memory it lies in, and whether that @@ -234,10 +250,31 @@ impl Pool { ripe: Ripe, mut make: impl FnMut() -> Option, ) -> Option<(Piece, B, bool)> { + loop { + match self.take_or_need(len, align, now, ripe) { + Taken::Piece(piece, memory, again, ahead) => { + if ahead && let Some(memory) = self.grow(now, &mut make) { + self.add(memory, ripe.started); + } + return Some((piece, memory, again)); + } + Taken::NeedBlock => { + let memory = self.grow(now, &mut make)?; + self.add(memory, ripe.started); + } + Taken::Refused => return None, + } + } + } + + /// [`Pool::take_ripe`] without making anything: a piece (and whether a + /// block should be made ahead now), or that a block is needed first, so + /// that the caller can make it with no lock held ([`grow_unlocked`]). + fn take_or_need(&mut self, len: u64, align: u64, now: u64, ripe: Ripe) -> Taken { // With blocks made ahead, what would be an allocation of its own (and // new when the card first reads it) lies in one of those too. if len == 0 || len > if ripe.ahead > 0 { BLOCK } else { BLOCK / 2 } { - return None; + return Taken::Refused; } self.rested(now); let mut found = None; @@ -259,32 +296,25 @@ impl Pool { } // 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 memory = self.grow(now, &mut make)?; - let i = self.add(memory, ripe.started); - (i, self.blocks[i].as_mut()?.free.take(len, align)?) - } + // (A block being made meanwhile may have room: wait for it.) + let Some((i, start)) = found else { + return if now < self.retry_growth_at && self.growing == 0 { Taken::Refused } else { Taken::NeedBlock }; }; + let mut ahead = false; if ripe.ahead > 0 { - if !ripe.is(self.blocks[i].as_ref()?) { + if !self.blocks[i].as_ref().is_some_and(|b| ripe.is(b)) { let n = UNRIPE.fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() { tracing::info!("textures cut from blocks made while lists ran that still run: {n}"); } } let empty = self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count(); - if empty < ripe.ahead - && let Some(memory) = self.grow(now, &mut make) - { - self.add(memory, ripe.started); - } + ahead = empty + self.growing < ripe.ahead && now >= self.retry_growth_at; } - let block = self.blocks[i].as_mut()?; + let Some(block) = self.blocks[i].as_mut() else { return Taken::Refused }; let again = start < block.used_to; block.used_to = block.used_to.max(start + len); - Some((Piece { block: i, start, len }, block.memory.clone(), again)) + Taken::Piece(Piece { block: i, start, len }, block.memory.clone(), again, ahead) } fn grow(&mut self, now: u64, make: &mut impl FnMut() -> Option) -> Option { @@ -293,11 +323,17 @@ impl Pool { } let block = make(); if block.is_none() { - self.retry_growth_at = now.saturating_add(500); + self.growth_failed(now); } block } + /// A block could not be made: no other attempt for half a second from + /// `now` (a later one than an earlier failure's, never an earlier one). + fn growth_failed(&mut self, now: u64) { + self.retry_growth_at = self.retry_growth_at.max(now.saturating_add(500)); + } + fn add(&mut self, memory: B, made: u64) -> usize { let i = match self.blocks.iter().position(Option::is_none) { Some(i) => i, @@ -367,24 +403,225 @@ unsafe impl Send for Upload {} static TEXTURES: Mutex> = Mutex::new(Pool::new(SPARE_KEPT)); static STAGING: Mutex> = Mutex::new(Pool::new(STAGING_KEPT)); +/// A block of each made ([`take_unlocked`]). +static TEXTURES_GROWN: Condvar = Condvar::new(); +static STAGING_GROWN: Condvar = Condvar::new(); +/// Blocks of staging buffers now (as [`TEXTURE_BLOCKS`]). +static STAGING_BLOCKS: AtomicUsize = AtomicUsize::new(0); fn lock(m: &'static Mutex) -> std::sync::MutexGuard<'static, T> { - m.lock().unwrap_or_else(|e| e.into_inner()) + match m.try_lock() { + Ok(guard) => guard, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + let guard = m.lock().unwrap_or_else(|e| e.into_inner()); + #[cfg(feature = "diagnostics")] + LOCK_WAITS.add(started.elapsed()); + guard + } + } +} + +/// How many times something took time, the time in all and the longest +/// (µs), for the memory line. +#[cfg(feature = "diagnostics")] +struct Timed([AtomicU64; 3]); + +#[cfg(feature = "diagnostics")] +impl Timed { + const fn new() -> Timed { + Timed([AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]) + } + + fn add(&self, took: std::time::Duration) { + let us = u64::try_from(took.as_micros()).unwrap_or(u64::MAX); + self.0[0].fetch_add(1, Ordering::Relaxed); + self.0[1].fetch_add(us, Ordering::Relaxed); + self.0[2].fetch_max(us, Ordering::Relaxed); + } + + /// Times, ms in all, longest ms. + fn read(&self) -> (u64, f64, f64) { + let [n, all, most] = &self.0; + (n.load(Ordering::Relaxed), all.load(Ordering::Relaxed) as f64 / 1e3, most.load(Ordering::Relaxed) as f64 / 1e3) + } +} + +/// Waits for the lock of a pool of blocks, and for a block another thread +/// makes ([`take_unlocked`]). +#[cfg(feature = "diagnostics")] +static LOCK_WAITS: Timed = Timed::new(); +/// Blocks made (`CreateHeap` or an upload buffer, made resident, mapped). +#[cfg(feature = "diagnostics")] +static BLOCKS_MADE: Timed = Timed::new(); + +/// `make`, the blocks it makes timed into [`BLOCKS_MADE`]. +fn timed(mut make: impl FnMut() -> Option) -> impl FnMut() -> Option { + move || { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + let made = make(); + #[cfg(feature = "diagnostics")] + if made.is_some() { + BLOCKS_MADE.add(started.elapsed()); + } + made + } +} + +/// Whether a new block is made with its pool's lock released +/// (`LEONIDA_POOL_GROW_UNLOCKED`, on; `0`: under it, as before). Making one is +/// `CreateHeap` or a 64 MiB upload buffer, `MakeResident` and the wait for its +/// mapping: up to 270 ms in the world on an RTX 3080, 961 ms with the card +/// over its budget. +/// With blocks made ahead ([`ahead`]) one is made each time one is begun. +/// Under the lock, every texture let go, the sweep's [`room`] and every +/// other texture waited for it. +fn grow_unlocked() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_POOL_GROW_UNLOCKED").is_none_or(|v| v != "0")) +} + +/// [`Pool::take_ripe`] on `pool`, its blocks made while its lock is not held +/// ([`grow_unlocked`]). One block at a time is made for want of room: a +/// thread that needs one while another makes it waits for that one +/// (`grown`). `blocks` is set to the pool's blocks after each change. +fn take_unlocked( + pool: &'static Mutex>, + grown: &Condvar, + blocks: &AtomicUsize, + (len, align, ripe): (u64, u64, Ripe), + mut make: impl FnMut() -> Option, +) -> Option<(Piece, B, bool)> { + let mut guard = lock(pool); + loop { + let taken = guard.take_or_need(len, align, now(), ripe); + blocks.store(guard.blocks(), Ordering::Relaxed); + match taken { + Taken::Piece(piece, memory, again, ahead) => { + if ahead { + guard.growing += 1; + drop(guard); + drop(grow_outside(pool, grown, blocks, &mut make)); + } + return Some((piece, memory, again)); + } + Taken::NeedBlock if guard.growing > 0 => { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + guard = grown.wait(guard).unwrap_or_else(|e| e.into_inner()); + #[cfg(feature = "diagnostics")] + LOCK_WAITS.add(started.elapsed()); + } + Taken::NeedBlock => { + guard.growing += 1; + drop(guard); + let (back, made) = grow_outside(pool, grown, blocks, &mut make); + if !made { + return None; + } + // Still held since the block went in: its maker takes the + // first piece of it. + guard = back; + } + Taken::Refused => return None, + } + } +} + +/// Makes a block of `pool` with its lock not held, the maker counted in +/// [`Pool::growing`] by the caller, and adds it. Gives back the lock, held +/// since then, and whether a block was made. +fn grow_outside( + pool: &'static Mutex>, + grown: &Condvar, + blocks: &AtomicUsize, + make: &mut impl FnMut() -> Option, +) -> (std::sync::MutexGuard<'static, Pool>, bool) { + /// If making panics: takes the maker off [`Pool::growing`] and wakes + /// those waiting for a block. + struct Unwound<'a, B: Clone + 'static>(&'static Mutex>, &'a Condvar); + impl Drop for Unwound<'_, B> { + fn drop(&mut self) { + lock(self.0).growing -= 1; + self.1.notify_all(); + } + } + let unwound = Unwound(pool, grown); + let memory = make(); + // Submissions begun while it was made count as begun before it ([`Ripe`]). + let begun = crate::host::submissions().0; + let mut guard = lock(pool); + std::mem::forget(unwound); + guard.growing -= 1; + let made = match memory { + Some(memory) => { + guard.add(memory, begun); + true + } + None => { + guard.growth_failed(now()); + false + } + }; + blocks.store(guard.blocks(), Ordering::Relaxed); + // (They take the lock once the caller lets it go.) + grown.notify_all(); + (guard, made) +} + +/// A piece of a block of textures ([`take_unlocked`]; under the lock with +/// `LEONIDA_POOL_GROW_UNLOCKED=0`), `make` making a block. +fn take_texture(len: u64, align: u64, make: impl FnMut() -> Option) -> Option<(Piece, ID3D12Heap, bool)> { + let make = timed(make); + if grow_unlocked() { + return take_unlocked(&TEXTURES, &TEXTURES_GROWN, &TEXTURE_BLOCKS, (len, align, Ripe::now()), make); + } + // (The submissions begun asked for with the lock held, as before: a + // block made here counts those begun while another thread made one.) + let mut pool = lock(&TEXTURES); + let taken = pool.take_ripe(len, align, now(), Ripe::now(), make); + TEXTURE_BLOCKS.store(pool.blocks(), Ordering::Relaxed); + taken +} + +/// The same of staging buffers, at multiples of 512 bytes. +fn take_staging(len: u64, make: impl FnMut() -> Option) -> Option<(Piece, Upload, bool)> { + let make = timed(make); + if grow_unlocked() { + return take_unlocked(&STAGING, &STAGING_GROWN, &STAGING_BLOCKS, (len, 512, Ripe::ALL), make); + } + let mut pool = lock(&STAGING); + let taken = pool.take(len, 512, now(), make); + STAGING_BLOCKS.store(pool.blocks(), Ordering::Relaxed); + taken } /// Bytes of the pieces textures hold now. static HELD: AtomicU64 = AtomicU64::new(0); +/// Blocks of textures now, kept beside the pool so that [`texture_room`] +/// takes no lock. +static TEXTURE_BLOCKS: AtomicUsize = AtomicUsize::new(0); /// Bytes of the texture blocks no texture holds: the card's memory in use /// by us that new textures take first. pub(crate) fn texture_room() -> u64 { - (lock(&TEXTURES).blocks() as u64 * BLOCK).saturating_sub(HELD.load(Ordering::Relaxed)) + (TEXTURE_BLOCKS.load(Ordering::Relaxed) as u64 * BLOCK).saturating_sub(HELD.load(Ordering::Relaxed)) } /// For the memory line: blocks of textures and of staging buffers, in MiB. #[cfg(feature = "diagnostics")] pub(crate) fn memory() -> [u64; 2] { - [lock(&TEXTURES).blocks() as u64 * (BLOCK >> 20), lock(&STAGING).blocks() as u64 * (BLOCK >> 20)] + [&TEXTURE_BLOCKS, &STAGING_BLOCKS].map(|blocks| blocks.load(Ordering::Relaxed) as u64 * (BLOCK >> 20)) +} + +/// For the memory line: blocks made (times, ms in all, longest ms) and the +/// waits for the pools' locks (the same). +#[cfg(feature = "diagnostics")] +pub(crate) fn growth() -> [(u64, f64, f64); 2] { + [BLOCKS_MADE.read(), LOCK_WAITS.read()] } /// Part of a block of mapped upload memory, back in the pool when dropped. @@ -404,7 +641,7 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi } // Copies from a buffer begin at multiples of 512. let bytes = bytes.next_multiple_of(512); - let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || { + let (piece, memory, again) = take_staging(bytes, || { // Only gate speculative bindless prefetch on staging-pool growth // headroom; table-bound textures and decoration bakes are sampled // immediately and would otherwise read uninitialized/reused VRAM. @@ -623,7 +860,7 @@ pub(crate) unsafe fn texture_with_cast( return None; } #[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] - let (piece, heap, again) = lock(&TEXTURES).take_ripe(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), || { + let (piece, heap, again) = take_texture(info.SizeInBytes, info.Alignment.max(1), || { let desc = D3D12_HEAP_DESC { SizeInBytes: BLOCK, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, @@ -893,4 +1130,143 @@ mod tests { assert!(host.device.GetDeviceRemovedReason().is_ok()); } } + + /// The sweep asks for the room in texture blocks once a second on the + /// submitting thread: not behind a block being made. + #[test] + fn the_room_in_texture_blocks_is_read_without_their_lock() { + let held = lock(&TEXTURES); + let (sent, got) = std::sync::mpsc::channel(); + let reader = std::thread::spawn(move || sent.send(texture_room()).unwrap()); + let read = got.recv_timeout(std::time::Duration::from_secs(2)); + drop(held); + reader.join().unwrap(); + assert!(read.is_ok(), "the room waited for the lock of the texture blocks"); + } + + /// Without a block with room: one is needed (and none made); with one, a + /// piece, and whether to make one ahead counts those being made. + #[test] + fn a_piece_or_a_block_to_make_first() { + let mut pool: Pool = Pool::new(SPARE_KEPT); + let ripe = Ripe { started: 0, finished: 0, ahead: 2 }; + assert!(matches!(pool.take_or_need(BLOCK / 4, 65536, 0, ripe), Taken::NeedBlock)); + assert!(matches!(pool.take_or_need(0, 65536, 0, ripe), Taken::Refused)); + assert!(matches!(pool.take_or_need(BLOCK + 1, 65536, 0, ripe), Taken::Refused)); + pool.add(1, 0); + assert!(matches!(pool.take_or_need(BLOCK / 4, 65536, 0, ripe), Taken::Piece(_, 1, false, true))); + pool.growing = 1; + assert!(matches!(pool.take_or_need(BLOCK / 4, 65536, 0, ripe), Taken::Piece(_, 1, false, true))); + pool.growing = 2; + assert!(matches!(pool.take_or_need(BLOCK / 4, 65536, 0, ripe), Taken::Piece(_, 1, false, false))); + // A failed block: none needed for half a second, the room left used. + pool.growing = 0; + pool.growth_failed(10); + assert!(matches!(pool.take_or_need(BLOCK / 4, 65536, 10, ripe), Taken::Piece(_, 1, false, false))); + assert!(matches!(pool.take_or_need(BLOCK / 4, 65536, 509, ripe), Taken::Refused)); + assert!(matches!(pool.take_or_need(BLOCK / 4, 65536, 510, ripe), Taken::NeedBlock)); + // In the half second, with a block being made: wait for that one. + pool.growing = 1; + assert!(matches!(pool.take_or_need(BLOCK / 4, 65536, 509, ripe), Taken::NeedBlock)); + // A later failure never shortens the half second. + pool.growth_failed(5); + assert_eq!(pool.retry_growth_at, 510); + } + + /// While a block is made (`MakeResident`, up to 270 ms in the world), + /// the pool's lock is free for pieces given back and other textures. + #[test] + fn a_block_is_made_with_its_pools_lock_free() { + static POOL: Mutex> = Mutex::new(Pool::new(SPARE)); + static GROWN: Condvar = Condvar::new(); + static BLOCKS: AtomicUsize = AtomicUsize::new(0); + let (go, wait) = std::sync::mpsc::channel::<()>(); + let (making, started) = std::sync::mpsc::channel::<()>(); + let taker = std::thread::spawn(move || { + take_unlocked(&POOL, &GROWN, &BLOCKS, (65536, 65536, Ripe::ALL), || { + making.send(()).unwrap(); + wait.recv().unwrap(); + Some(7) + }) + }); + started.recv().unwrap(); + let (sent, got) = std::sync::mpsc::channel(); + let other = std::thread::spawn(move || { + let pool = lock(&POOL); + sent.send((pool.blocks(), pool.growing)).unwrap(); + }); + let seen = got.recv_timeout(std::time::Duration::from_secs(2)); + go.send(()).unwrap(); + other.join().unwrap(); + let (piece, memory, again) = taker.join().unwrap().unwrap(); + assert_eq!(seen, Ok((0, 1)), "the lock was held while the block was made"); + assert_eq!((piece, memory, again), (Piece { block: 0, start: 0, len: 65536 }, 7, false)); + assert_eq!(BLOCKS.load(Ordering::Relaxed), 1); + assert_eq!(lock(&POOL).growing, 0); + } + + /// Threads that find no room while a block is made wait for that one + /// rather than each make one more. + #[test] + fn threads_wanting_room_wait_for_the_block_being_made() { + static POOL: Mutex> = Mutex::new(Pool::new(SPARE)); + static GROWN: Condvar = Condvar::new(); + static BLOCKS: AtomicUsize = AtomicUsize::new(0); + static MADE: AtomicUsize = AtomicUsize::new(0); + let takers: Vec<_> = (0..4) + .map(|_| { + std::thread::spawn(|| { + take_unlocked(&POOL, &GROWN, &BLOCKS, (BLOCK / 8, 65536, Ripe::ALL), || { + std::thread::sleep(std::time::Duration::from_millis(100)); + Some(MADE.fetch_add(1, Ordering::Relaxed) as u64) + }) + .unwrap() + .0 + }) + }) + .collect(); + let mut pieces: Vec = takers.into_iter().map(|t| t.join().unwrap()).collect(); + assert_eq!(MADE.load(Ordering::Relaxed), 1, "one block for four eighths of one"); + pieces.sort_by_key(|p| p.start); + assert!(pieces.iter().all(|p| p.block == 0)); + assert!(pieces.windows(2).all(|w| w[0].start + w[0].len <= w[1].start)); + } + + /// A block that could not be made: none is asked for again for half a + /// second, and no maker is left counted. + #[test] + fn a_block_that_failed_is_not_made_again_at_once() { + static POOL: Mutex> = Mutex::new(Pool::new(SPARE)); + static GROWN: Condvar = Condvar::new(); + static BLOCKS: AtomicUsize = AtomicUsize::new(0); + let calls = std::cell::Cell::new(0); + let refuse = || { + calls.set(calls.get() + 1); + None + }; + let began = now(); + assert!(take_unlocked(&POOL, &GROWN, &BLOCKS, (65536, 65536, Ripe::ALL), refuse).is_none()); + assert!(take_unlocked(&POOL, &GROWN, &BLOCKS, (65536, 65536, Ripe::ALL), refuse).is_none()); + if now() < began + 500 { + assert_eq!(calls.get(), 1); + } + assert!(lock(&POOL).retry_growth_at >= began + 500); + assert_eq!(lock(&POOL).growing, 0); + } + + /// A maker that panics is not left counted: the next thread that needs + /// room makes a block rather than wait for it forever. + #[test] + fn a_maker_that_panics_leaves_no_one_waiting() { + static POOL: Mutex> = Mutex::new(Pool::new(SPARE)); + static GROWN: Condvar = Condvar::new(); + static BLOCKS: AtomicUsize = AtomicUsize::new(0); + let panicked = std::panic::catch_unwind(|| { + take_unlocked(&POOL, &GROWN, &BLOCKS, (65536, 65536, Ripe::ALL), || -> Option { panic!("making a block") }) + }); + assert!(panicked.is_err()); + assert_eq!(lock(&POOL).growing, 0); + let (piece, memory, _) = take_unlocked(&POOL, &GROWN, &BLOCKS, (65536, 65536, Ripe::ALL), || Some(3)).unwrap(); + assert_eq!((piece.block, memory), (0, 3)); + } }