Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 145 additions & 8 deletions d3d12/crates/leonida-gpu/src/pool/small.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use windows::core::{GUID, HRESULT, IUnknown, Interface};

#[cfg(feature = "diagnostics")]
use super::lock;
use super::{BLOCK, Piece, Pool, now};
use super::{BLOCK, Piece, Pool, Ripe, Taken, now};

/// Buffers in the upload heap (write-combined for the CPU).
pub(crate) const UPLOAD: usize = 0;
Expand Down Expand Up @@ -68,6 +68,8 @@ fn piece_len(size: u64) -> Option<u64> {
pub(crate) struct Small {
kind: usize,
pool: Mutex<Pool<ID3D12Heap>>,
/// Only misses wait for heap creation; existing pieces stay available.
grow: Mutex<()>,
/// Pieces whose buffers went and whose submissions have run, put back in
/// [`Small::pool`] at its next use.
back: Mutex<Vec<Piece>>,
Expand All @@ -77,17 +79,67 @@ pub(crate) struct Small {

impl Small {
const fn new(kind: usize) -> Small {
Small { kind, pool: Mutex::new(Pool::new(KEPT)), back: Mutex::new(Vec::new()), held: AtomicU64::new(0) }
Small {
kind,
pool: Mutex::new(Pool::new(KEPT)),
grow: Mutex::new(()),
back: Mutex::new(Vec::new()),
held: AtomicU64::new(0),
}
}

/// The pool, with the pieces that came back free again.
fn pool(&self) -> std::sync::MutexGuard<'_, Pool<ID3D12Heap>> {
let back = std::mem::take(&mut *self.back.lock().unwrap_or_else(|e| e.into_inner()));
let mut pool = self.pool.lock().unwrap_or_else(|e| e.into_inner());
for piece in back {
pool.give_at(piece, 0);
returned(&self.pool, &self.back)
}
}

fn returned<'a, B: Clone>(
pool: &'a Mutex<Pool<B>>,
back: &Mutex<Vec<Piece>>,
) -> std::sync::MutexGuard<'a, Pool<B>> {
let back = std::mem::take(&mut *back.lock().unwrap_or_else(|e| e.into_inner()));
let mut pool = pool.lock().unwrap_or_else(|e| e.into_inner());
for piece in back {
pool.give_at(piece, 0);
}
pool
}

/// Driver work happens under `grow` alone. A waiter checks again because
/// the previous grower may have supplied enough memory for both requests.
fn take_with<B: Clone>(
pool: &Mutex<Pool<B>>,
back: &Mutex<Vec<Piece>>,
grow: &Mutex<()>,
len: u64,
make: impl FnOnce() -> Option<B>,
) -> Option<(Piece, B, bool)> {
match returned(pool, back).take_or_need(len, ALIGN, now(), Ripe::ALL) {
Taken::Piece(piece, memory, again, _) => return Some((piece, memory, again)),
Taken::Refused => return None,
Taken::NeedBlock => {}
}
let _grow = grow.lock().unwrap_or_else(|e| e.into_inner());
match returned(pool, back).take_or_need(len, ALIGN, now(), Ripe::ALL) {
Taken::Piece(piece, memory, again, _) => return Some((piece, memory, again)),
Taken::Refused => return None,
Taken::NeedBlock => {}
}
let memory = make();
let mut pool = returned(pool, back);
match memory {
Some(memory) => {
pool.add(memory, 0);
match pool.take_or_need(len, ALIGN, now(), Ripe::ALL) {
Taken::Piece(piece, memory, again, _) => Some((piece, memory, again)),
_ => None,
}
}
None => {
pool.growth_failed(now());
None
}
pool
}
}

Expand Down Expand Up @@ -234,7 +286,7 @@ fn block(device: &ID3D12Device, kind: usize) -> Option<ID3D12Heap> {
fn place(device: &ID3D12Device, small: &'static Small, size: u64, gone: fn(&'static Small, Piece)) -> Option<(ID3D12Resource, *mut u8, Piece)> {
let len = piece_len(size)?;
let kind = small.kind;
let (piece, heap, again) = small.pool().take(len, ALIGN, now(), || block(device, kind))?;
let (piece, heap, again) = take_with(&small.pool, &small.back, &small.grow, len, || block(device, kind))?;
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size.max(1),
Expand Down Expand Up @@ -330,6 +382,91 @@ pub(crate) fn memory() -> [u64; 4] {
mod tests {
use super::*;

#[test]
fn growth_unlocks_the_pool_and_concurrent_misses_share_one_block() {
use std::sync::{Barrier, atomic::AtomicUsize, mpsc};
let pool = Mutex::new(Pool::new(KEPT));
let back = Mutex::new(Vec::new());
let grow = Mutex::new(());
let a = {
let mut p = pool.lock().unwrap();
p.add(1u32, 0);
let Taken::Piece(a, _, _, _) = p.take_or_need(BLOCK / 2, ALIGN, 0, Ripe::ALL) else {
panic!("first half-block");
};
let Taken::Piece(_, _, _, _) = p.take_or_need(BLOCK / 2, ALIGN, 0, Ripe::ALL) else {
panic!("second half-block");
};
a
};
let made = AtomicUsize::new(0);
let (entered, creating) = mpsc::channel();
let release = Barrier::new(2);
let waiters_ready = Barrier::new(6);
std::thread::scope(|scope| {
// 1. Park the growing worker inside `make()` while holding `grow` alone.
let grower = scope.spawn(|| {
take_with(&pool, &back, &grow, ALIGN, || {
assert!(pool.try_lock().is_ok(), "heap creation must not own the pool lock");
made.fetch_add(1, Ordering::Relaxed);
entered.send(()).unwrap();
release.wait();
Some(2)
})
.unwrap()
});
creating.recv_timeout(std::time::Duration::from_secs(5)).unwrap();

// 2. While `grow` is held and no other workers can steal from block 1,
// return `a` and reuse the full existing half-block via the fast path.
back.lock().unwrap().push(a);
let reused = take_with(&pool, &back, &grow, BLOCK / 2, || panic!("free memory needs no growth")).unwrap();
assert_eq!(reused.1, 1);
assert!(reused.2);

// 3. Block 1 is full again and `back` is empty; spawn 5 concurrent misses
// that serialize behind the single in-flight growth and share block 2.
let mut workers = Vec::with_capacity(6);
workers.push(grower);
for _ in 0..5 {
let pool = &pool;
let back = &back;
let grow = &grow;
let waiters_ready = &waiters_ready;
workers.push(scope.spawn(move || {
waiters_ready.wait();
take_with(pool, back, grow, ALIGN, || panic!("concurrent misses must share one grown block"))
.unwrap()
}));
}
waiters_ready.wait();
std::thread::yield_now();
release.wait();

let pieces: Vec<_> = workers.into_iter().map(|w| w.join().unwrap()).collect();
assert_eq!(made.load(Ordering::Relaxed), 1);
for (i, &(piece, memory, _)) in pieces.iter().enumerate() {
assert_eq!(memory, 2);
for &(other, _, _) in &pieces[..i] {
assert!(piece.start + piece.len <= other.start || other.start + other.len <= piece.start);
}
}
});
}

#[test]
fn failed_growth_backs_off_but_existing_pieces_remain_usable() {
let pool = Mutex::new(Pool::new(KEPT));
let back = Mutex::new(Vec::new());
let grow = Mutex::new(());
assert!(take_with(&pool, &back, &grow, ALIGN, || None::<u32>).is_none());
// Use a deterministic future deadline even if the test was descheduled.
pool.lock().unwrap().retry_growth_at = u64::MAX;
assert!(take_with(&pool, &back, &grow, ALIGN, || panic!("growth is backed off")).is_none());
pool.lock().unwrap().add(7, 0);
assert_eq!(take_with(&pool, &back, &grow, ALIGN, || panic!("existing block")).unwrap().1, 7);
}

/// Buffers of up to [`MOST`] take whole 64 KiB; larger ones are their own.
#[test]
fn small_buffers_take_whole_64_kib_up_to_the_bound() {
Expand Down