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
187 changes: 176 additions & 11 deletions crates/victory-gpu/src/shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//! indexed heaps keep what their first use copied.

use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use windows::Win32::Graphics::Direct3D12::ID3D12Resource;
Expand Down Expand Up @@ -377,12 +377,19 @@ fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> {
BUFFERS.lock().unwrap_or_else(|e| e.into_inner())
}

/// The longest title buffer registered so far (it stays after the buffer is
/// released): a buffer starting further below an address than this cannot
/// hold it. Changed under `BUFFERS`' lock.
static MAX_SPAN: AtomicU64 = AtomicU64::new(0);

/// A title buffer exists at `start` (`len` bytes).
pub(crate) fn register(resource: usize, start: u64, len: u64) {
buffers().insert(
let mut map = buffers();
MAX_SPAN.fetch_max(len, Ordering::Relaxed);
map.insert(
(start, resource),
Entry {
end: start + len,
end: start.saturating_add(len),
shadow: None,
},
);
Expand All @@ -393,17 +400,28 @@ pub(crate) fn unregister(resource: usize, start: u64) {
buffers().remove(&(start, resource));
}

/// The innermost entry holding `[address, end)`: the one starting closest
/// below `address` that reaches `end`, among those starting at most `span`
/// (the longest entry's length) below `end`. Big buffers hold many smaller
/// ones (a heap's placed buffers), so the one holding an address past
/// those can be any number of entries back.
fn enclosing(map: &BTreeMap<(u64, usize), Entry>, span: u64, address: u64, end: u64) -> Option<(u64, usize)> {
let lowest = end.saturating_sub(span);
if lowest > address {
return None;
}
map.range((lowest, 0)..=(address, usize::MAX))
.rev()
.find(|(_, e)| e.end >= end)
.map(|(k, _)| *k)
}

/// The copy of the innermost title buffer holding `[address, address +
/// len)`, made on first use.
pub(crate) fn find(address: u64, len: u64) -> Option<Arc<Shadow>> {
let end = address.checked_add(len.max(1))?;
let mut map = buffers();
let key = map
.range(..=(address, usize::MAX))
.rev()
.take(64)
.find(|(_, e)| e.end >= end)
.map(|(k, _)| *k);
let key = enclosing(&map, MAX_SPAN.load(Ordering::Relaxed), address, end);
let Some(key) = key else {
drop(map);
return loose(address, end);
Expand Down Expand Up @@ -445,13 +463,43 @@ const WINDOW: u64 = 4 << 20;
/// Copies of title memory outside buffers, by (start, length).
static LOOSE: Mutex<BTreeMap<(u64, u64), Arc<Shadow>>> = Mutex::new(BTreeMap::new());

/// The longest window in `LOOSE`. Changed under its lock.
static LOOSE_SPAN: AtomicU64 = AtomicU64::new(0);

/// Below this nothing is ever mapped (the null page and its guard area).
const LOWEST_MAPPED: u64 = 0x10000;

/// The window copy holding `[address, end)` among `windows` (by start and
/// length, none longer than `span`), the innermost if several do.
fn enclosing_window<V>(windows: &BTreeMap<(u64, u64), V>, span: u64, address: u64, end: u64) -> Option<&V> {
let lowest = end.saturating_sub(span);
if lowest > address {
return None;
}
windows
.range((lowest, 0)..=(address, u64::MAX))
.rev()
.find(|&(&(s, l), _)| s.saturating_add(l) >= end)
.map(|(_, v)| v)
}

/// The window copy for `[address, end)` outside buffers: one already made
/// that holds it (a range spanning two windows has one of its own, which
/// later ranges in it share), else a new one. None for memory that is not
/// committed (a stale or null address): 4 MiB of zeros would not help.
fn loose(address: u64, end: u64) -> Option<Arc<Shadow>> {
if address < LOWEST_MAPPED {
return None;
}
let start = address & !(WINDOW - 1);
let len = end.next_multiple_of(WINDOW) - start;
let len = end.checked_next_multiple_of(WINDOW)? - start;
let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner());
if let Some(shadow) = map.get(&(start, len)) {
if let Some(shadow) = enclosing_window(&map, LOOSE_SPAN.load(Ordering::Relaxed), address, end) {
return Some(shadow.clone());
}
if !crate::texture::committed(address as *const u8, 1) {
return None;
}
let (buffer, data) = host()?.shared_buffer(len)?;
crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}"));
// SAFETY: a live buffer.
Expand All @@ -462,6 +510,7 @@ fn loose(address: u64, end: u64) -> Option<Arc<Shadow>> {
"loose memory copied to the host"
);
let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len));
LOOSE_SPAN.fetch_max(len, Ordering::Relaxed);
map.insert((start, len), shadow.clone());
Some(shadow)
}
Expand Down Expand Up @@ -497,3 +546,119 @@ pub(crate) fn near(va: u64) -> String {
}
text
}

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

const MIB: u64 = 1 << 20;

fn entry(start: u64, len: u64) -> Entry {
Entry {
end: start + len,
shadow: None,
}
}

/// A 256 MiB parent with `children` 64 KiB buffers placed in its first
/// part, as a heap's placed buffers.
fn heap(base: u64, children: u64) -> BTreeMap<(u64, usize), Entry> {
let mut map = BTreeMap::new();
map.insert((base, 1), entry(base, 256 * MIB));
for i in 0..children {
map.insert((base + i * 0x10000, 100 + i as usize), entry(base + i * 0x10000, 0x10000));
}
map
}

#[test]
fn a_parent_is_found_past_many_children() {
let base = 0x10_0000_0000;
let map = heap(base, 200);
let span = 256 * MIB;
// Past all 200 children (and the 64 entries looked at before).
let at = base + 200 * 0x10000 + 0x100;
assert_eq!(enclosing(&map, span, at, at + 16), Some((base, 1)));
let first_64 = map.range(..=(at, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= at + 16);
assert!(first_64.is_none(), "the parent is more than 64 entries back");
// Near the parent's end.
let at = base + 256 * MIB - 16;
assert_eq!(enclosing(&map, span, at, at + 16), Some((base, 1)));
// Inside a child: the child, the innermost.
let at = base + 150 * 0x10000 + 8;
assert_eq!(enclosing(&map, span, at, at + 8), Some((base + 150 * 0x10000, 250)));
// Across two children: only the parent holds it.
let at = base + 151 * 0x10000 - 8;
assert_eq!(enclosing(&map, span, at, at + 16), Some((base, 1)));
// Past the parent, and before it.
let at = base + 256 * MIB;
assert_eq!(enclosing(&map, span, at, at + 1), None);
assert_eq!(enclosing(&map, span, base - 16, base + 16), None);
// Longer than any buffer: none, without looking.
assert_eq!(enclosing(&map, span, base, base + span + 1), None);
assert_eq!(enclosing(&map, 0, base, base + 1), None);
}

#[test]
fn registered_buffers_widen_the_search() {
// High above anything a test maps; resource numbers no live
// resource has.
let base = 0x7f00_0000_0000;
let len = 512 * MIB;
register(1, base, len);
for i in 0..100u64 {
register(2 + i as usize, base + i * 0x1000, 0x1000);
}
assert!(MAX_SPAN.load(Ordering::Relaxed) >= len);
let at = base + len - 64;
let found = enclosing(&buffers(), MAX_SPAN.load(Ordering::Relaxed), at, at + 64);
for i in 0..100u64 {
unregister(2 + i as usize, base + i * 0x1000);
}
unregister(1, base);
assert_eq!(found, Some((base, 1)));
assert!(buffers().range((base, 0)..=(base + len, usize::MAX)).next().is_none());
}

#[test]
fn loose_windows_are_reused_for_ranges_inside_them() {
let w = WINDOW;
let base = 0x20_0000_0000;
let mut windows = BTreeMap::new();
windows.insert((base, w), "first");
// A range across the next two windows got one of its own.
windows.insert((base + w, 2 * w), "spanning");
let span = 2 * w;
let find = |address: u64, len: u64| enclosing_window(&windows, span, address, address + len).copied();
assert_eq!(find(base, 1), Some("first"));
assert_eq!(find(base + w - 16, 16), Some("first"));
// Inside the spanning window, also in its second half.
assert_eq!(find(base + w + 8, 64), Some("spanning"));
assert_eq!(find(base + 2 * w + 8, 64), Some("spanning"));
assert_eq!(find(base + 3 * w - 8, 8), Some("spanning"));
// Across the first window's end: none holds it whole.
assert_eq!(find(base + w - 8, 16), None);
// Past every window, before them, longer than any.
assert_eq!(find(base + 3 * w, 1), None);
assert_eq!(find(base - 8, 4), None);
assert_eq!(find(base, 3 * w), None);
}

#[test]
fn loose_memory_must_be_committed() {
use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree};
// The null page and its guard area.
assert!(loose(0, 16).is_none());
assert!(loose(0x1000, 0x1010).is_none());
assert!(loose(LOWEST_MAPPED - 1, LOWEST_MAPPED + 1).is_none());
// Reserved, not committed.
// SAFETY: a fresh reservation, released below.
let p = unsafe { VirtualAlloc(std::ptr::null(), WINDOW as usize, MEM_RESERVE, PAGE_READWRITE) } as u64;
assert_ne!(p, 0);
assert!(loose(p + 64, p + 128).is_none());
// SAFETY: our reservation.
unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
// Too close to the top to round up to a window.
assert!(loose(u64::MAX - 8, u64::MAX).is_none());
}
}