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
316 changes: 249 additions & 67 deletions crates/victory-gpu/src/shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,38 +40,52 @@ pub(crate) struct Shadow {
/// Ranges shaders of a submission not yet copied back may be writing:
/// title memory there is older than the copy.
pending: Mutex<Vec<(usize, usize)>>,
/// The copy's bytes before the submission ran, from an offset on,
/// covering the ranges its shaders write: what the GPU wrote differs.
before: Mutex<Option<(usize, Vec<u8>)>>,
/// The copy's bytes before the submission ran, by title page, covering
/// the ranges its shaders write: what the GPU wrote differs.
before: Mutex<Before>,
}

/// Snapshot memory kept for reuse (already touched, so no page faults).
static POOL: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new());

/// An empty buffer with room for `n` bytes, from the pool if it has one.
fn pooled(n: usize) -> Vec<u8> {
let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
let fit = pool
.iter()
.enumerate()
.filter(|(_, v)| v.capacity() >= n)
.min_by_key(|(_, v)| v.capacity())
.map(|(i, _)| i);
let mut v = match fit {
Some(i) => pool.swap_remove(i),
None => Vec::with_capacity(n),
};
v.clear();
v
/// A copy's bytes before a submission ran.
#[derive(Default)]
struct Before {
/// By title page.
pages: BTreeMap<usize, Snap>,
/// The ranges taken (offsets in the copy, merged where they meet): a
/// range declared again (the world's are, dozens of times) is inside
/// one and needs no walk over its pages.
spans: Vec<(usize, usize)>,
}

/// A title page's bytes in the copy before the submission ran: `[lo, hi)`
/// of `bytes` (offsets in the page; a page's buffer is a page long).
struct Snap {
lo: usize,
hi: usize,
bytes: Box<[u8]>,
}

/// Returns a snapshot buffer to the pool (at most 8 kept, the largest).
fn give_back(v: Vec<u8>) {
let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
pool.push(v);
if pool.len() > 8 {
pool.sort_by_key(|v| std::cmp::Reverse(v.capacity()));
pool.truncate(8);
/// Page buffers kept for reuse (already touched, so no page faults). A
/// snapshot as one buffer grown to the submission's bounding range took a
/// fresh buffer whenever the few kept were in use or too small, and copied
/// all of the old one into it at each growth.
static PAGES: Mutex<Vec<Box<[u8]>>> = Mutex::new(Vec::new());
/// At most this many page buffers kept (256 MiB).
const KEPT: usize = 4096;

/// A page buffer, from the pool if it has one.
fn page_buffer() -> Box<[u8]> {
let kept = PAGES.lock().unwrap_or_else(|e| e.into_inner()).pop();
kept.unwrap_or_else(|| vec![0; PAGE].into_boxed_slice())
}

/// Returns page buffers to the pool.
fn give_back(buffers: impl IntoIterator<Item = Box<[u8]>>) {
let mut pool = PAGES.lock().unwrap_or_else(|e| e.into_inner());
for b in buffers {
if pool.len() >= KEPT {
break;
}
pool.push(b);
}
}

Expand Down Expand Up @@ -144,40 +158,72 @@ impl Shadow {

/// At submission, after the range's refresh: a submitted list's shaders
/// write this range. Its bytes are kept to tell later what the GPU wrote:
/// one snapshot per copy and submission, grown to cover every range the
/// submission declares (the world declares overlapping views of its
/// 174 MB heap dozens of times), in reused memory (fresh snapshots cost
/// ~2.3 million page faults per world frame).
/// per title page and submission, each page's part grown to cover every
/// range the submission declares in it (the world declares overlapping
/// views of its 174 MB heap dozens of times), parts newly covered taken
/// from the copy as it is now, in reused page buffers.
pub(crate) fn writing(&self, address: usize, len: usize) {
self.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((address, address + len));
let (from, to) = self.inside(address, len);
// SAFETY: inside the mapping.
let host = |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) };
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
let (start, end) = match &*before {
Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)),
None => (from, to),
let start = self.start as usize;
// In-page offsets `[a, b)` of `page`, from the copy.
// SAFETY: inside the mapping (the caller passes offsets in the buffer).
let host = |page: usize, a: usize, b: usize| unsafe {
std::slice::from_raw_parts(self.data.add(page * PAGE + a - start), b - a)
};
if let Some((at, bytes)) = &*before
&& (*at, at + bytes.len()) == (start, end)
{
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
let before = &mut *before;
if from >= to || before.spans.iter().any(|&(a, b)| a <= from && to <= b) {
return;
}
// Parts newly covered from the copy, the rest as it was taken.
let mut grown = pooled(end - start);
match before.take() {
Some((at, bytes)) => {
grown.extend_from_slice(host(start, at));
grown.extend_from_slice(&bytes);
grown.extend_from_slice(host(at + bytes.len(), end));
give_back(bytes);
// An earlier snapshot can span a gap that was not declared yet.
// Capture its refresh now, rather than treat it as a later GPU write.
let fresh = outside(from, to, before.spans.clone());
let (mut a, mut b) = (from, to);
before.spans.retain(|&(x, y)| {
let meets = x <= b && a <= y;
if meets {
(a, b) = (a.min(x), b.max(y));
}
!meets
});
before.spans.push((a, b));
let mut at = from;
while at < to {
let (page, lo) = ((start + at) / PAGE, (start + at) % PAGE);
let hi = lo + (PAGE - lo).min(to - at);
let snap = before.pages.entry(page).or_insert_with(|| Snap {
lo,
hi: lo,
bytes: page_buffer(),
});
let previous = (snap.lo, snap.hi);
if lo < snap.lo {
snap.bytes[lo..snap.lo].copy_from_slice(host(page, lo, snap.lo));
snap.lo = lo;
}
None => grown.extend_from_slice(host(start, end)),
if hi > snap.hi {
let from = snap.hi.max(snap.lo);
snap.bytes[from..hi].copy_from_slice(host(page, from, hi));
snap.hi = hi;
}
// Newly covered edges were copied above. Refresh only fresh
// portions inside the old extent; previously declared bytes
// must keep the original snapshot across overlapping ranges.
let page_start = page * PAGE;
for &(a, b) in &fresh {
let a = (start + a).max(page_start + previous.0);
let b = (start + b).min(page_start + previous.1);
if a < b {
let (a, b) = (a - page_start, b - page_start);
snap.bytes[a..b].copy_from_slice(host(page, a, b));
}
}
at += hi - lo;
}
*before = Some((start, grown));
}

/// After the submission ran: copies the bytes its shaders wrote back
Expand All @@ -192,25 +238,28 @@ impl Shadow {
let mut written = 0;
let (from, to) = self.inside(address, len);
let start = self.start as usize;
if let Some((taken, before)) = &*snapshot
&& *taken <= from
&& to <= taken + before.len()
&& from < to
{
let before = &before[from - taken..to - taken];
// By 64 KiB piece: the copy compared with its bytes before the
if from < to {
// By title page: the copy compared with its bytes before the
// submission, title memory read only where the GPU wrote.
const PIECE: usize = 64 << 10;
let mut title = vec![0u8; PIECE];
let mut scratch = page_buffer();
let mut synced = Vec::new();
let mut at = from;
while at < to {
let n = (PIECE - (start + at) % PIECE).min(to - at);
let (page, lo) = ((start + at) / PAGE, (start + at) % PAGE);
let n = (PAGE - lo).min(to - at);
let Some(snap) = snapshot
.pages
.get(&page)
.filter(|s| s.lo <= lo && lo + n <= s.hi)
else {
at += n;
continue;
};
// SAFETY: inside the mapping; only the submitting thread
// writes it.
let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
let old = &before[at - from..at - from + n];
let title = &mut title[..n];
let old = &snap.bytes[lo..lo + n];
let title = &mut scratch[..n];
if host != old && crate::host::read_into((start + at) as *const u8, title) {
// Title memory with the GPU's bytes put in; the copy
// takes the title's bytes in turn.
Expand All @@ -231,6 +280,7 @@ impl Shadow {
}
at += n;
}
give_back([scratch]);
// Pages made equal to title memory are current in the copy, so
// our own write is not taken for the title's; others keep what
// they had (a title write there shows at the next refresh).
Expand All @@ -251,10 +301,9 @@ impl Shadow {
// submission runs at a time), and the snapshot with the last range.
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
pending.retain(|&r| r != (address, address + len));
if pending.is_empty()
&& let Some((_, bytes)) = snapshot.take()
{
give_back(bytes);
if pending.is_empty() {
let taken = std::mem::take(&mut *snapshot);
give_back(taken.pages.into_values().map(|s| s.bytes));
}
written
}
Expand Down Expand Up @@ -365,6 +414,20 @@ impl Shadow {
}
}

/// Portions not yet declared by this submission, in copy-relative offsets.
fn outside(from: usize, to: usize, mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
ranges.sort_unstable();
let (mut at, mut parts) = (from, Vec::new());
for (a, b) in ranges {
if at < to && a > at {
parts.push((at, a.min(to)));
}
at = at.max(b);
}
if at < to { parts.push((at, to)); }
parts
}

struct Entry {
end: u64,
shadow: Option<Arc<Shadow>>,
Expand Down Expand Up @@ -497,3 +560,122 @@ pub(crate) fn near(va: u64) -> String {
}
text
}

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

/// A copy of title memory `[at, at + len)` holding the same bytes, if
/// there is a host device.
fn shadow_of(at: usize, len: usize) -> Option<Shadow> {
let (buffer, data) = host()?.shared_buffer((len as u64).next_multiple_of(PAGE as u64))?;
// SAFETY: the mapping holds `len` bytes; the title memory is ours.
unsafe { std::ptr::copy_nonoverlapping(at as *const u8, data, len) };
// SAFETY: a live buffer.
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
Some(Shadow::new(buffer, data, gpu, at as u64, len as u64))
}

/// Two overlapping ranges shaders write, declared with a refresh in
/// between: only the bytes the GPU changed go back, the title's own
/// writes meanwhile stay, and the page buffers return to the pool.
#[test]
fn copy_back_takes_only_what_the_gpu_wrote() {
let mut memory = vec![1u8; 4 * PAGE];
// Off a page boundary, over three title pages.
let base = (memory.as_mut_ptr() as usize).next_multiple_of(PAGE) + 100;
let len = 2 * PAGE + 500;
let Some(shadow) = shadow_of(base, len) else {
return;
};
// SAFETY: offsets inside the title range and the copy.
let title = |at: usize| unsafe { (base as *mut u8).add(at) };
// SAFETY: as above.
let host = |at: usize| unsafe { shadow.data.add(at) };
// SAFETY: (all writes below) bytes of the title range and the copy,
// which nothing else uses.
unsafe {
shadow.writing(base + 10, PAGE + 10);
// A refresh next to the first range, in its last page.
title(PAGE + 100).write(7);
host(PAGE + 100).write(7);
shadow.writing(base + PAGE + 50, PAGE + 50);
// The GPU writes in both ranges; the title writes meanwhile.
host(20).write(0xaa);
host(PAGE + 200).write(0xbb);
title(30).write(0xcc);
}
assert!(shadow.copy_back(base + 10, PAGE + 10) > 0);
assert!(shadow.copy_back(base + PAGE + 50, PAGE + 50) > 0);
// SAFETY: as above.
unsafe {
assert_eq!(title(20).read(), 0xaa);
assert_eq!(title(PAGE + 200).read(), 0xbb);
assert_eq!(title(30).read(), 0xcc, "the title's own write stays");
assert_eq!(host(30).read(), 0xcc, "and the copy takes it");
assert_eq!(title(PAGE + 100).read(), 7);
assert_eq!(title(40).read(), 1);
}
assert!(shadow.before.lock().unwrap().pages.is_empty());
assert!(PAGES.lock().unwrap().len() >= 3);
drop(memory);
}

/// A range declared again, or inside one declared, takes nothing new.
#[test]
fn declaring_a_range_again_keeps_its_snapshot() {
let memory = vec![3u8; 3 * PAGE];
let base = memory.as_ptr() as usize;
let Some(shadow) = shadow_of(base, 3 * PAGE) else {
return;
};
shadow.writing(base, 2 * PAGE);
// SAFETY: a byte of the copy, which nothing else uses: a GPU write
// between two dispatches declaring the range.
unsafe { shadow.data.add(5).write(9) };
shadow.writing(base, 2 * PAGE);
shadow.writing(base + 4, 100);
{
let before = shadow.before.lock().unwrap();
assert_eq!(before.spans, [(0, 2 * PAGE)]);
let at = base + 5;
assert_eq!(before.pages[&(at / PAGE)].bytes[at % PAGE], 3);
}
shadow.copy_back(base, 2 * PAGE);
shadow.copy_back(base + 4, 100);
// SAFETY: title memory of ours.
assert_eq!(unsafe { (base as *const u8).add(5).read() }, 9);
assert!(shadow.before.lock().unwrap().pages.is_empty());
drop(memory);
}

/// Refreshing an undeclared gap inside one snapshot page must not be
/// mistaken for a GPU write and overwrite a later CPU write.
#[test]
fn refreshed_gap_inside_a_page_keeps_the_titles_newer_byte() {
let mut memory = vec![0u8; 3 * PAGE];
let base = (memory.as_mut_ptr() as usize).next_multiple_of(PAGE);
let Some(shadow) = shadow_of(base, PAGE) else { return };
shadow.writing(base, 16);
shadow.writing(base + 128, 16);
// SAFETY: these bytes belong to the test and its mapped copy.
unsafe {
(base as *mut u8).add(64).write(1);
shadow.data.add(64).write(1); // mimic the middle range's refresh
}
shadow.writing(base + 64, 16);
// SAFETY: the CPU changes the middle byte after the snapshot; an
// actual GPU change is mimicked in the first range.
unsafe {
(base as *mut u8).add(64).write(2);
shadow.data.add(3).write(9);
}
for at in [base, base + 128, base + 64] { shadow.copy_back(at, 16); }
// SAFETY: still inside memory, which remains live for this test.
unsafe {
assert_eq!((base as *const u8).add(64).read(), 2, "CPU's newer byte");
assert_eq!((base as *const u8).add(3).read(), 9, "GPU's actual write");
}
}

}
Loading