Skip to content
Open
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
1 change: 1 addition & 0 deletions crates/victory-gpu/src/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,7 @@ impl Drop for Heap {
// #589, AscilCH).
if let Some(Some(host)) = self.host.get() {
crate::memory::forget_heap(host);
crate::draw::forget_heap_ranges(host.id());
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions crates/victory-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ use windows::Win32::Graphics::Dxgi::Common::*;
use super::{VIEW_TAG, View, view_at};
use crate::host::host;

mod buffer_spans;
pub(crate) type BufferSpanIndex = buffer_spans::BufferSpans<std::sync::Arc<crate::shadow::Shadow>>;

/// The locks [`HostHeap::kept`] is spread over: slot `i` is behind lock
/// `i % KEPT_PIECES`, at place `i / KEPT_PIECES`. Neighbouring slots are
/// behind different locks on purpose: the recording threads take their
Expand Down
102 changes: 102 additions & 0 deletions crates/victory-gpu/src/descriptor/host/buffer_spans.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
//! Maintain the exact enclosing range for each backing buffer from its live slots.
use std::collections::{BTreeSet, HashMap};

struct Span<T> {
copy: T,
starts: BTreeSet<(u64, u32)>,
ends: BTreeSet<(u64, u32)>,
}

pub(crate) struct BufferSpans<T> {
copies: HashMap<usize, Span<T>>,
}

impl<T> Default for BufferSpans<T> {
fn default() -> Self {
Self { copies: HashMap::new() }
}
}

impl<T: Clone> BufferSpans<T> {
pub(crate) fn insert(&mut self, key: usize, slot: u32, copy: &T, from: u64, to: u64) {
let span = self.copies.entry(key).or_insert_with(|| Span {
copy: copy.clone(),
starts: BTreeSet::new(),
ends: BTreeSet::new(),
});
span.starts.insert((from, slot));
span.ends.insert((to, slot));
}

/// False means the caller must rebuild from its authoritative slot map.
pub(crate) fn remove(&mut self, key: usize, slot: u32, from: u64, to: u64) -> bool {
let Some(span) = self.copies.get_mut(&key) else {
return false;
};
let start = span.starts.remove(&(from, slot));
let end = span.ends.remove(&(to, slot));
if span.starts.is_empty() && span.ends.is_empty() {
self.copies.remove(&key);
}
start && end
}

/// Exactly the same per-buffer unions as walking all live descriptors.
pub(crate) fn snapshot(&self) -> HashMap<usize, (T, u64, u64)> {
self.copies.iter().map(|(&key, span)| {
let &(from, _) = span.starts.first().expect("nonempty span");
let &(to, _) = span.ends.last().expect("nonempty span");
(key, (span.copy.clone(), from, to))
}).collect()
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn span_index_matches_full_scan_after_slot_moves_and_removals() {
let mut index = BufferSpans::default();
let mut slots: HashMap<u32, (usize, u64, u64)> = HashMap::new();
for n in 0..2048u32 {
let slot = (n * 17) % 97;
if let Some((key, from, to)) = slots.remove(&slot) {
assert!(index.remove(key, slot, from, to));
}
if n % 5 != 0 {
let key = ((n * 13) % 11) as usize;
let from = u64::from(n % 7) * 64;
let to = from + u64::from((n % 9) + 1) * 32;
slots.insert(slot, (key, from, to));
index.insert(key, slot, &key, from, to);
}
let mut expected = HashMap::new();
for &(key, from, to) in slots.values() {
let span = expected.entry(key).or_insert((key, from, to));
span.1 = span.1.min(from);
span.2 = span.2.max(to);
}
assert_eq!(index.snapshot(), expected);
}
for (slot, (key, from, to)) in slots {
assert!(index.remove(key, slot, from, to));
}
assert!(index.snapshot().is_empty());
assert!(!index.remove(0, 0, 0, 1));
}

#[test]
fn duplicate_bounds_are_kept_until_the_last_slot_is_removed() {
let mut index = BufferSpans::default();
index.insert(1, 0, &1, 16, 64);
index.insert(1, 1, &1, 16, 64);
index.insert(1, 2, &1, 32, 48);
assert!(index.remove(1, 0, 16, 64));
assert_eq!(index.snapshot()[&1], (1, 16, 64));
assert!(index.remove(1, 1, 16, 64));
assert_eq!(index.snapshot()[&1], (1, 32, 48));
assert!(index.remove(1, 2, 32, 48));
assert!(index.snapshot().is_empty());
}
}
97 changes: 82 additions & 15 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -953,12 +953,55 @@ pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0);
/// level so that the marked pass can have this one start anew:
/// [`State::heap_buffers_marked`].)
type Ranges = std::collections::HashMap<u32, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)>;
static RANGES: std::sync::Mutex<Option<std::collections::HashMap<usize, (u64, Ranges)>>> =
#[derive(Default)]
struct BufferScan {
passes: u64,
ranges: Ranges,
span_index: Option<crate::descriptor::host::BufferSpanIndex>,
}
static RANGES: std::sync::Mutex<Option<std::collections::HashMap<u64, BufferScan>>> =
std::sync::Mutex::new(None);
/// Per host heap, for [`State::heap_buffers_marked`]: what the marked pass
/// keeps (`VICTORY_HEAP_PASS_MARKED`; nothing while that is unset).
type Marked = crate::heap_pass::Picked<std::sync::Arc<crate::shadow::Shadow>>;
static MARKED: std::sync::Mutex<Option<std::collections::HashMap<usize, Marked>>> = std::sync::Mutex::new(None);
static MARKED: std::sync::Mutex<Option<std::collections::HashMap<u64, Marked>>> = std::sync::Mutex::new(None);
/// Called when the title heap is destroyed, after the shader-heap registry
/// lock is released. Drop cached resource references outside both locks.
pub(crate) fn forget_heap_ranges(id: u64) {
let marked = MARKED.lock().unwrap_or_else(|e| e.into_inner())
.as_mut().and_then(|heaps| heaps.remove(&id));
let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner())
.as_mut().and_then(|heaps| heaps.remove(&id));
drop(marked);
drop(ranges);
}

#[cfg(test)]
#[test]
fn heap_range_cache_forgets_both_passes() {
// IDs are allocated monotonically from 1. Reserve a synthetic high ID.
let id = u64::MAX - 1;
let other = u64::MAX - 2;
{
let mut ranges = RANGES.lock().unwrap();
let heaps = ranges.get_or_insert_with(Default::default);
heaps.insert(id, BufferScan { passes: 17, ..Default::default() });
heaps.insert(other, BufferScan { passes: 3, ..Default::default() });
}
{
let mut marked = MARKED.lock().unwrap();
let heaps = marked.get_or_insert_with(Default::default);
heaps.insert(id, Marked::new(false));
heaps.insert(other, Marked::new(false));
}
forget_heap_ranges(id);
assert!(!RANGES.lock().unwrap().as_ref().unwrap().contains_key(&id));
assert!(!MARKED.lock().unwrap().as_ref().unwrap().contains_key(&id));
assert!(RANGES.lock().unwrap().as_ref().unwrap().contains_key(&other));
assert!(MARKED.lock().unwrap().as_ref().unwrap().contains_key(&other));
forget_heap_ranges(other);
}

pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0);
/// Where the pass over textures picked by index records its uploads: into
/// a list of the title's, or into lists of the thread that runs it ahead.
Expand Down Expand Up @@ -2154,13 +2197,18 @@ impl State {
// released resource goes stale without a write, and a slot written
// before its memory had a host copy is only made then.
let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner());
let (passes, ranges) = kept
let BufferScan { passes, ranges, span_index } = kept
.get_or_insert_with(Default::default)
.entry(std::ptr::from_ref(host) as usize)
.or_insert_with(|| (0, Ranges::new()));
.entry(host.id())
.or_default();
static INCREMENTAL_SPANS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let incremental_spans = *INCREMENTAL_SPANS.get_or_init(|| {
std::env::var_os("VICTORY_DESCRIPTOR_BUFFER_SPANS").is_some_and(|v| v == "1")
});
let changed = host.buffer_changes();
let slots = if *passes % 16 == 0 {
ranges.clear();
*span_index = None;
host.buffer_slots()
} else {
changed
Expand All @@ -2172,7 +2220,12 @@ impl State {
let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none();
HEAP_PASS_PARTS[1].fetch_add(slots.len() as u64, Ordering::Relaxed);
for (n, &index) in slots.iter().enumerate() {
ranges.remove(&index);
if let Some((shadow, from, to)) = ranges.remove(&index)
&& let Some(spans) = span_index
&& !spans.remove(std::sync::Arc::as_ptr(&shadow) as usize, index, from, to)
{
*span_index = None;
}
let Some(handle) = heap.handle(index) else {
continue;
};
Expand Down Expand Up @@ -2203,18 +2256,32 @@ impl State {
if host.shows(index, &shadow.buffer) == Some(false) {
HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed);
}
if let Some(spans) = span_index {
spans.insert(std::sync::Arc::as_ptr(&shadow) as usize, index, &shadow, address, address + len);
}
ranges.insert(index, (shadow, address, address + len));
}
let views = ranges.len() as u32;
// Per host copy, the span its picked views cover.
let mut spans: std::collections::HashMap<usize, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)> =
std::collections::HashMap::new();
for (shadow, from, to) in ranges.values() {
let key = std::sync::Arc::as_ptr(shadow) as usize;
let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to));
span.1 = span.1.min(*from);
span.2 = span.2.max(*to);
}
let spans = if incremental_spans {
span_index.get_or_insert_with(|| {
let mut spans = crate::descriptor::host::BufferSpanIndex::default();
for (&slot, (shadow, from, to)) in ranges.iter() {
spans.insert(std::sync::Arc::as_ptr(shadow) as usize, slot, shadow, *from, *to);
}
spans
}).snapshot()
} else {
let mut spans: std::collections::HashMap<usize, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)> =
std::collections::HashMap::new();
for (shadow, from, to) in ranges.values() {
let key = std::sync::Arc::as_ptr(shadow) as usize;
let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to));
span.1 = span.1.min(*from);
span.2 = span.2.max(*to);
}
spans
};
drop(kept);
let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum();
// Memory that is not write-watched is copied whole by every refresh.
Expand Down Expand Up @@ -2304,7 +2371,7 @@ impl State {
for picked in heaps.values_mut() {
picked.note_forgotten(forgotten.as_deref());
}
let ranges = heaps.entry(std::ptr::from_ref(host) as usize).or_insert_with(|| Marked::new(false));
let ranges = heaps.entry(host.id()).or_insert_with(|| Marked::new(false));
let changed = host.buffer_changes();
let record = |index: u32| heap.handle(index).map(crate::descriptor::record_at);
let slots = ranges.plan(changed, || host.buffer_slots(), record, crate::descriptor::record_entry);
Expand Down
Loading