Skip to content
Merged
Show file tree
Hide file tree
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
159 changes: 159 additions & 0 deletions crates/victory-gpu/src/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ use crate::resource::{Memory, PAGEABLE_IIDS};

#[cfg(windows)]
pub(crate) mod host;
#[cfg(any(windows, test))]
mod slots;

thread_local! {
/// Set while this thread runs the pass over textures picked by index
Expand Down Expand Up @@ -849,6 +851,7 @@ pub(crate) fn with_heap<T>(heap: usize, f: impl FnOnce(&Heap) -> T) -> Option<T>
/// Gives back dynamic slots of the host heap behind the title heap at
/// `heap`, if that host heap instance (`id`) still exists.
#[cfg(windows)]
#[allow(dead_code)]
pub(crate) fn release_dynamic(heap: usize, id: u64, first: u32, n: u32) {
let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
if heaps.iter().any(|&(_, _, h)| h == heap)
Expand All @@ -859,6 +862,49 @@ pub(crate) fn release_dynamic(heap: usize, id: u64, first: u32, n: u32) {
}
}

/// Gives back a batch of `(heap, id, first, n)` dynamic slot ranges, acquiring
/// `SHADER_HEAPS` once for the whole batch and each host heap's dynamic-slot
/// lock once per distinct `(heap, id)` pair.
#[cfg(windows)]
pub(crate) fn release_dynamic_batch(ranges: &[(usize, u64, u32, u32)]) {
let Some(&(first_heap, first_id, _, _)) = ranges.first() else {
return;
};
let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
let host_for = |heap: usize| -> Option<&host::HostHeap> {
if heaps.iter().any(|&(_, _, h)| h == heap) {
// SAFETY: registered heaps are live (removed when dropped, which
// takes the `SHADER_HEAPS` write lock we hold shared here).
unsafe { &*(heap as *const Heap) }.host.get()?.as_ref()
} else {
None
}
};

// Fast path (the 99% case): every entry belongs to the same `(heap, id)`.
// Single `SHADER_HEAPS` lookup, single `HostHeap` lock, zero allocations.
if ranges
.iter()
.all(|&(h, id, _, _)| h == first_heap && id == first_id)
{
if let Some(host) = host_for(first_heap) {
host.release_batch(first_id, ranges.iter().map(|&(_, _, first, n)| (first, n)));
}
return;
}

// General path: group entries by `(heap, id)` so each distinct live host
// heap is looked up and locked at most once per identity.
let mut grouped = ranges.to_vec();
grouped.sort_unstable_by_key(|&(h, id, _, _)| (h, id));
for group in grouped.chunk_by(|a, b| a.0 == b.0 && a.1 == b.1) {
let (heap, id, _, _) = group[0];
if let Some(host) = host_for(heap) {
host.release_batch(id, group.iter().map(|&(_, _, first, n)| (first, n)));
}
}
}

/// Runs `f` with the host heap of the title's largest view heap, if there is
/// one (nothing is waited for).
#[cfg(windows)]
Expand Down Expand Up @@ -2509,3 +2555,116 @@ mod tests {
assert_ne!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address);
}
}

#[cfg(all(test, windows))]
mod dynamic_slots_tests {
use super::*;
use crate::object::S_OK;

#[repr(C)]
struct Extended(HeapDesc, Placement);

fn create(desc: HeapDesc, placement: Placement, out: &mut This) -> HRESULT {
let extended = Extended(desc, placement);
create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out)
}

/// Batched dynamic-slot reclamation handles empty batches, single-heap
/// fast path, multi-heap grouping, wrong host-heap identities, title-slot
/// indices below `host.count()`, and mixed valid/stale/dropped heap entries.
#[test]
fn release_dynamic_batch_handles_empty_single_multi_wrong_id_and_stale() {
// Empty batch is a safe no-op.
release_dynamic_batch(&[]);

let desc = HeapDesc { kind: VIEWS_KIND, count: 16, flags: SHADER_VISIBLE, nodes: 1 };
let make_heap = || -> This {
let mut h = std::ptr::null();
assert_eq!(create(desc, Placement { address: 0, size: 0 }, &mut h), S_OK);
h
};

let h1 = make_heap();
let Some(host1) = heap(h1).host() else {
release(h1);
return; // no host GPU
};
let h2 = make_heap();
let Some(host2) = heap(h2).host() else {
release(h2);
release(h1);
return;
};
let h_stale = make_heap();
let Some(host_stale) = heap(h_stale).host() else {
release(h_stale);
release(h2);
release(h1);
return;
};
let stale_addr = h_stale as usize;
let stale_id = host_stale.id();
let stale_slot = host_stale.dynamic(4).expect("stale heap slots");
// Drop `h_stale` so its address is removed from `SHADER_HEAPS`.
release(h_stale);

let addr1 = h1 as usize;
let id1 = host1.id();
let addr2 = h2 as usize;
let id2 = host2.id();
let free1_init = host1.free_dynamic();
let free2_init = host2.free_dynamic();

// Single-heap fast path: allocate several ranges, test wrong-id fast
// path first (no-op), then release with the right id (including
// duplicate and a title-slot index below `host1.count()`).
let a1 = host1.dynamic(5).unwrap();
let a2 = host1.dynamic(7).unwrap();
let a3 = host1.dynamic(3).unwrap();
assert_eq!(host1.free_dynamic(), free1_init - 15);

release_dynamic_batch(&[
(addr1, id1.wrapping_add(999), a1, 5),
(addr1, id1.wrapping_add(999), a2, 7),
]);
assert_eq!(host1.free_dynamic(), free1_init - 15, "wrong id must not free");

release_dynamic_batch(&[
(addr1, id1, 0, 4), // title slot (< host1.count()), ignored safely
(addr1, id1, a1, 5),
(addr1, id1, a2, 7),
(addr1, id1, a2, 7), // duplicate
(addr1, id1, a3, 3),
]);
assert_eq!(host1.free_dynamic(), free1_init, "single-heap fast path frees all once");

// Multi-heap + wrong-id + stale dropped heap + unknown address mixed in one batch.
let b1 = host1.dynamic(6).unwrap();
let b2 = host1.dynamic(4).unwrap();
let c1 = host2.dynamic(8).unwrap();
let c2 = host2.dynamic(2).unwrap();
let keep1 = host1.dynamic(3).unwrap();
assert_eq!(host1.free_dynamic(), free1_init - 13);
assert_eq!(host2.free_dynamic(), free2_init - 10);

release_dynamic_batch(&[
(addr2, id2, c1, 8),
(stale_addr, stale_id, stale_slot, 4), // dropped heap
(addr1, id1, b1, 6),
(addr1, id2, keep1, 3), // wrong id for h1
(0xDEAD_BEEF, 12345, 16, 4), // unregistered address
(addr2, id2, c2, 2),
(addr1, id1, b2, 4),
(addr2, id1, c2, 2), // wrong id for h2
]);
assert_eq!(host1.free_dynamic(), free1_init - 3, "only valid h1 ranges freed; keep1 stays taken");
assert_eq!(host2.free_dynamic(), free2_init, "all valid h2 ranges freed");

// Release remaining slot via single-range helper and verify cleanup.
release_dynamic(addr1, id1, keep1, 3);
assert_eq!(host1.free_dynamic(), free1_init);

release(h2);
release(h1);
}
}
99 changes: 38 additions & 61 deletions crates/victory-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;

use super::slots::DynamicSlots;
use super::{VIEW_TAG, View, view_at};
use crate::host::host;

Expand Down Expand Up @@ -173,24 +174,12 @@ pub(crate) struct HostHeap {
/// waited for most (5.6 % of their time, profile waits-1: each descriptor
/// made for a draw takes it, and lets go of what the slot held under it).
kept: Box<[Mutex<Option<ID3D12Resource>>]>,
/// Where the search for free dynamic slots starts, and which are taken
/// (by lists not yet reset).
next: Mutex<(u32, Vec<bool>)>,
/// How many dynamic slots are free (changed under `next`'s lock): with
/// fewer than a table needs, the search is not made. Once the world
/// had taken them all, every later table of the frame searched every
/// slot before it was refused.
/// Two-level 64-bit bitmap allocator for dynamic slots (taken by lists
/// not yet reset), with its next-fit cursor and `too_long` watermark.
next: Mutex<DynamicSlots>,
/// How many dynamic slots are free (mirrored from `next` under its lock
/// so lock-free readers and tests can observe it without locking).
free: std::sync::atomic::AtomicU32,
/// The shortest table that found no run of free slots since slots were
/// last given back (changed under `next`'s lock; `u32::MAX`: none).
/// Until something is given back the free runs only shrink, so a table
/// of that length or longer is refused without the search. Enough
/// slots were free, but in pieces, and every such table walked the
/// whole ring before it was refused: 0.33 ms each with 131,072 slots,
/// 1.0 s of the recording threads in a frame that refused 3,143 (run
/// 45), under the lock all of them need. (A free run that lies across
/// the place the search starts from is seen by neither.)
too_long: std::sync::atomic::AtomicU32,
/// View heaps: the bytes per element of the buffer view at each title
/// slot, for shaders that pick a buffer by an index they compute
/// (`victory_shader::emit::SLOT_STRIDES`): an upload buffer of
Expand Down Expand Up @@ -1795,7 +1784,7 @@ pub(crate) fn slot_story(slot: u32) -> String {
let mut text = if index < host.count {
format!("title slot {index}, made from {}", host.describe_slot(index).unwrap_or_default())
} else {
let taken = host.next.lock().unwrap_or_else(|e| e.into_inner()).1.get((index - host.count) as usize).copied();
let taken = host.next.lock().unwrap_or_else(|e| e.into_inner()).is_taken(index - host.count);
format!("dynamic slot {} (taken {taken:?})", index - host.count)
};
if twin {
Expand Down Expand Up @@ -2089,9 +2078,8 @@ impl HostHeap {
waiting: Mutex::default(),
away: Mutex::default(),
kept: (0..count + extra).map(|_| Mutex::new(None)).collect(),
next: Mutex::new((0, vec![false; extra as usize])),
next: Mutex::new(DynamicSlots::new(extra)),
free: std::sync::atomic::AtomicU32::new(extra),
too_long: std::sync::atomic::AtomicU32::new(u32::MAX),
strides,
buffers: Slots::new(count as usize),
changed: Slots::new(count as usize),
Expand Down Expand Up @@ -2267,36 +2255,9 @@ impl HostHeap {
let started = std::time::Instant::now();
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::DynamicAsked, 1);
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
let (next, taken) = &mut *guard;
let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n
&& n < self.too_long.load(std::sync::atomic::Ordering::Relaxed);
let n = n as usize;
// Search from `next` on, then from the start (extending past cursor by
// n - 1 so contiguous runs crossing the cursor are not missed).
let cursor = *next as usize;
let end = self.dynamic as usize;
let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end);
let starts = (cursor..end).chain(0..second_end);
let mut run = 0;
let mut found = None;
let mut last = usize::MAX;
for at in starts.take(if enough { usize::MAX } else { 0 }) {
// A run cannot wrap past the end.
if at != last.wrapping_add(1) {
run = 0;
}
last = at;
run = if taken[at] { 0 } else { run + 1 };
if run == n {
found = Some(at + 1 - n);
break;
}
}
let Some(first) = found else {
if enough {
self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed);
}
let mut slots = self.next.lock().unwrap_or_else(|e| e.into_inner());
let Some(first) = slots.alloc(n) else {
drop(slots);
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made"));
#[cfg(feature = "diagnostics")]
Expand All @@ -2307,12 +2268,11 @@ impl HostHeap {
}
return None;
};
self.free.store(slots.free(), std::sync::atomic::Ordering::Relaxed);
drop(slots);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64);
taken[first..first + n].fill(true);
self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed);
*next = ((first + n) % end) as u32;
Some(self.count + first as u32)
Some(self.count + first)
}

/// The title slots this heap has host slots for; fewer than the title's
Expand Down Expand Up @@ -3506,14 +3466,31 @@ impl HostHeap {
let Some(at) = first.checked_sub(self.count) else {
return;
};
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
let end = (at + n).min(self.dynamic) as usize;
if let Some(slots) = guard.1.get_mut(at as usize..end) {
let given = slots.iter().filter(|taken| **taken).count() as u32;
self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed);
self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed);
slots.fill(false);
let mut slots = self.next.lock().unwrap_or_else(|e| e.into_inner());
slots.release(at, n);
self.free.store(slots.free(), std::sync::atomic::Ordering::Relaxed);
}

/// Gives back a batch of `(first, n)` dynamic slot ranges belonging to
/// `id` under a single lock acquisition.
pub(crate) fn release_batch(&self, id: u64, ranges: impl IntoIterator<Item = (u32, u32)>) {
if id != self.id {
return;
}
let mut slots = self.next.lock().unwrap_or_else(|e| e.into_inner());
let base = self.count;
slots.release_batch(
ranges
.into_iter()
.filter_map(|(first, n)| Some((first.checked_sub(base)?, n))),
);
self.free.store(slots.free(), std::sync::atomic::Ordering::Relaxed);
}

/// Number of currently free dynamic slots (for tests).
#[cfg(test)]
pub(crate) fn free_dynamic(&self) -> u32 {
self.free.load(std::sync::atomic::Ordering::Relaxed)
}

/// Makes slot `index` (a dynamic one) from `view`; a null view if the
Expand Down
Loading