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
41 changes: 41 additions & 0 deletions crates/victory-gpu/src/bindless.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,47 @@ impl Viewed {
}
}

/// Batched [`Viewed::set`]: computes each unique view's entry outside the
/// lock (deduplicating repeated view pointers) and applies all slot
/// updates under one hold of `self.inner`.
#[cfg(windows)]
pub(crate) fn set_batch(&self, updates: &[(u32, Option<&View>, bool)]) {
if updates.is_empty() {
return;
}
let mut cache: HashMap<(usize, bool), Option<Seen>> = HashMap::new();
let mut entries: Vec<(u32, Option<Seen>)> = Vec::with_capacity(updates.len());
for &(index, view, made) in updates {
let entry = match view {
None => None,
Some(v) => {
let key = (std::ptr::from_ref(v) as usize, made);
cache
.entry(key)
.or_insert_with(|| {
if made {
seen(v)
} else {
Some(Seen::Left(left_kind(v)))
}
})
.clone()
}
};
entries.push((index, entry));
}
let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
for (index, entry) in entries {
if let Some(old) = inner.slots.remove(&index) {
inner.count(&old, false);
}
if let Some(entry) = entry {
inner.count(&entry, true);
inner.slots.insert(index, entry);
}
}
}

/// The buffer ranges views reach, merged per host copy and kind
/// (shader resource, unordered access): copy, start, bytes.
#[cfg(any(test, feature = "diagnostics"))]
Expand Down
177 changes: 176 additions & 1 deletion crates/victory-gpu/src/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,15 @@ pub(crate) fn sync_heaps() {
// 650,000 slots checked a frame, 29 submissions). A heap is not dropped
// while its page is made: `Heap::drop` takes the write lock to leave the
// list, so a heap still listed under the lock is alive.
#[cfg(windows)]
thread_local! {
static SYNC_PAGE_BUF: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
let page_size = crate::watch::PAGE;
let mut page_buf = vec![0u8; page_size];
let mut page_buf = SYNC_PAGE_BUF.with(|b| std::mem::take(&mut *b.borrow_mut()));
if page_buf.len() < page_size {
page_buf.resize(page_size, 0);
}
for (start, at, ranges) in work {
for (from, to) in ranges {
for page in (from & !(page_size - 1)..to).step_by(page_size) {
Expand Down Expand Up @@ -282,6 +289,9 @@ pub(crate) fn sync_heaps() {
}
}
}
SYNC_PAGE_BUF.with(|b| {
*b.borrow_mut() = page_buf;
});
}

/// Makes the views of slots `slots` that were left null (textures the title
Expand Down Expand Up @@ -629,6 +639,8 @@ fn record(handle: u64, view: View) {
views.list.len() as u32 - 1
}
};
let generation = views.list[i as usize].1;
set_view_gen(i, generation);
for r in view.resources().into_iter().filter(|&r| r != 0) {
views.by_resource.entry(r).or_default().push(i);
}
Expand All @@ -644,6 +656,50 @@ fn record(handle: u64, view: View) {
mirror(handle);
}

/// Lock-free mirror of each recorded view entry's active generation (0 when
/// free), chunked in 65,536-entry blocks up to 16M entries. Updated under
/// `VIEWS.write()` before publishing records or bumping `VIEWS_FORGOT`, so
/// heap syncs can check record liveness without locking `VIEWS`.
const VIEW_GEN_CHUNK_SHIFT: u32 = 16;
const VIEW_GEN_CHUNK_LEN: usize = 1 << VIEW_GEN_CHUNK_SHIFT;
const VIEW_GEN_CHUNKS: usize = 256;
static VIEW_GENS: [std::sync::OnceLock<Box<[std::sync::atomic::AtomicU32]>>; VIEW_GEN_CHUNKS] =
[const { std::sync::OnceLock::new() }; VIEW_GEN_CHUNKS];

fn set_view_gen(i: u32, generation: u32) {
let chunk = (i >> VIEW_GEN_CHUNK_SHIFT) as usize;
let offset = (i as usize) & (VIEW_GEN_CHUNK_LEN - 1);
if let Some(slot) = VIEW_GENS.get(chunk) {
let table = slot.get_or_init(|| {
(0..VIEW_GEN_CHUNK_LEN)
.map(|_| std::sync::atomic::AtomicU32::new(0))
.collect()
});
table[offset].store(generation, std::sync::atomic::Ordering::Release);
}
}

/// Lock-free check of whether view entry `i` is still live at `generation`.
#[cfg(any(windows, test))]
pub(crate) fn view_gen_current(i: u32, generation: u32) -> bool {
if generation == 0 {
return false;
}
let chunk = (i >> VIEW_GEN_CHUNK_SHIFT) as usize;
let offset = (i as usize) & (VIEW_GEN_CHUNK_LEN - 1);
if let Some(slot) = VIEW_GENS.get(chunk) {
slot.get().is_some_and(|table| {
table[offset].load(std::sync::atomic::Ordering::Acquire) == generation
})
} else {
let views = VIEWS.read().unwrap_or_else(|e| e.into_inner());
views
.list
.get(i as usize)
.is_some_and(|(_, current)| *current == generation)
}
}

/// Bumped whenever [`forget`] invalidates a recorded view while holding `VIEWS`.
static VIEWS_FORGOT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

Expand All @@ -668,6 +724,7 @@ pub(crate) fn forget(resource: usize) {
}
views.index.remove(&view);
views.list[i as usize].1 = generation.wrapping_add(1).max(1);
set_view_gen(i, 0);
// The view's other resource (a counter) keeps a stale entry, which
// `forget` of that resource skips.
views.free.push(i);
Expand Down Expand Up @@ -751,8 +808,55 @@ fn view_at(i: u32, generation: u32) -> Option<ViewPin> {
all.then_some(pin)
}

/// Batched [`view_at`] for a slice of packed `(generation << 32 | index)` keys
/// under one shared hold of `VIEWS`. Any partial pin whose other resource is
/// already dying is dropped after releasing `VIEWS`.
#[cfg(any(windows, test))]
pub(crate) fn views_at_batch(keys: &[u64]) -> Vec<Option<ViewPin>> {
let mut results = Vec::with_capacity(keys.len());
let mut failed = Vec::new();
{
let views = VIEWS.read().unwrap_or_else(|e| e.into_inner());
for &key in keys {
let i = key as u32;
let generation = (key >> 32) as u32;
let Some((view, current)) = views.list.get(i as usize) else {
results.push(None);
continue;
};
if *current != generation {
results.push(None);
continue;
}
let view = view.clone();
let mut held = [0usize; 2];
let mut all = true;
for (slot, r) in view.resources().into_iter().enumerate() {
if r == 0 {
continue;
}
if crate::object::try_add_ref(r as This) {
held[slot] = r;
} else {
all = false;
}
}
let pin = ViewPin { view, held };
if all {
results.push(Some(pin));
} else {
failed.push(pin);
results.push(None);
}
}
}
drop(failed);
results
}

/// For each record (tag, index, generation): whether it names a view that
/// is current, as [`view_at`] would find it (one lock for them all).
#[cfg(windows)]
fn views_current_into(records: &[[u32; 3]], out: &mut Vec<bool>) {
out.clear();
let views = VIEWS.read().unwrap_or_else(|e| e.into_inner());
Expand Down Expand Up @@ -1442,4 +1546,75 @@ pub(crate) mod tests {
assert!(queued, "the descriptor write reached the heap at the reused address");
}
}

#[test]
fn view_gen_current_tracks_record_forget_and_reuse() {
#[repr(C, align(8))]
struct AlignedDesc([u32; 14]);
let mut slot_a = [0u32; 4];
let mut slot_b = [0u32; 4];
let mut res_a = std::ptr::null();
let mut res_b = std::ptr::null();
let desc = AlignedDesc([1, 0, 0, 0, 64, 0, 1, 1 | 1 << 16, 0, 1, 0, 0, 0, 0]);
let properties = [1u32, 0, 0, 0, 0];
let iid = crate::object::guid(
0x696442be,
0xa72e,
0x4059,
[0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad],
);
assert_eq!(
crate::resource::create_committed(
std::ptr::null(),
properties.as_ptr().cast(),
0,
desc.0.as_ptr().cast(),
0,
std::ptr::null(),
&iid,
&mut res_a,
),
S_OK
);
assert_eq!(
crate::resource::create_committed(
std::ptr::null(),
properties.as_ptr().cast(),
0,
desc.0.as_ptr().cast(),
0,
std::ptr::null(),
&iid,
&mut res_b,
),
S_OK
);

create_srv(std::ptr::null(), res_a, std::ptr::null(), slot_a.as_mut_ptr() as u64);
let [tag, idx, gen_a] = [slot_a[0], slot_a[1], slot_a[2]];
assert_eq!(tag, VIEW_TAG);
assert!(gen_a >= 1);
assert!(view_gen_current(idx, gen_a));
assert!(!view_gen_current(idx, 0));
assert!(!view_gen_current(idx, gen_a.wrapping_add(1).max(1)));

let key_a = u64::from(gen_a) << 32 | u64::from(idx);
let batch = views_at_batch(&[key_a, 0]);
assert!(batch[0].is_some());
assert!(batch[1].is_none());
drop(batch);

forget(res_a as usize);
assert!(!view_gen_current(idx, gen_a));
assert!(views_at_batch(&[key_a])[0].is_none());

create_srv(std::ptr::null(), res_b, std::ptr::null(), slot_b.as_mut_ptr() as u64);
let [tag_b, idx_b, gen_b] = [slot_b[0], slot_b[1], slot_b[2]];
assert_eq!(tag_b, VIEW_TAG);
assert!(view_gen_current(idx_b, gen_b));
assert!(!view_gen_current(idx, gen_a));

crate::object::release(res_a);
crate::object::release(res_b);
}
}
Loading