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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
- With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`.
XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with
those on which the GPU completed at least one operation.
- `XCL_SPARSE_DIRECT=1` commits each sparse unified-memory window whole, in one allocation the GPU
reads directly (`OpenExistingHeapFromAddress`), so buffers the title places there need no tiles
and no CPU→GPU copy. It charges the whole window at start; a layout the host cannot commit falls
back to the tiled windows.
- `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib
requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget
(`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order.
Expand Down
64 changes: 64 additions & 0 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4213,6 +4213,70 @@ fn gpu_arena_partial_commit_probe() {
}
}

/// A whole-committed write-watched window imports as a heap and buffers placed in it sit at the
/// window's GPU address plus their offset (`hle::d3d12x::sparse`, the direct sparse windows).
#[test]
fn gpu_buffers_placed_on_an_imported_window_heap_stay_at_the_window_offset() {
use windows::core::Interface;
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
use windows::Win32::Graphics::Direct3D12::*;
use windows_sys::Win32::System::Memory::*;
const MEM_WRITE_WATCH: u32 = 0x20_0000;
let mb = crate::gpu::uma::MAX_SIZE >> 20;
unsafe {
let mut dev: Option<ID3D12Device> = None;
if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() {
runner::skip_test("no GPU");
return;
}
let dev = dev.unwrap();
let Ok(dev3) = dev.cast::<ID3D12Device3>() else {
runner::skip_test("no ID3D12Device3");
return;
};
let p = VirtualAlloc(std::ptr::null(), crate::gpu::uma::MAX_SIZE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE);
assert!(!p.is_null(), "no {} MB of commit", mb);
let heap: ID3D12Heap = match dev3.OpenExistingHeapFromAddress(p) {
Ok(h) => h,
Err(e) => {
VirtualFree(p, 0, MEM_RELEASE);
panic!("OpenExistingHeapFromAddress of a {} MB write-watched window: {e}", mb);
}
};
assert_eq!(heap.GetDesc().SizeInBytes as usize, crate::gpu::uma::MAX_SIZE, "the heap is not the whole window");
let buf = |w: u64| D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: w,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER,
..Default::default()
};
let mut keep: Vec<ID3D12Resource> = Vec::new();
let mut placed = |offset: u64, w: u64| -> Result<u64, String> {
let mut r: Option<ID3D12Resource> = None;
match dev.CreatePlacedResource(&heap, offset, &buf(w), D3D12_RESOURCE_STATE_COMMON, None, &mut r) {
Ok(()) => {
let res = r.unwrap();
let va = res.GetGPUVirtualAddress();
keep.push(res);
Ok(va)
}
Err(e) => Err(format!("{e}")),
}
};
let base = placed(0, crate::gpu::uma::MAX_SIZE as u64).expect("a buffer over the whole window");
assert_eq!(placed(0x1_0000, 0x2_0000).unwrap(), base + 0x1_0000, "a placed buffer is not at its address in the window");
assert_eq!(placed(0x2_0000, 0x2_0000).unwrap(), base + 0x2_0000, "a placement may overlap one already there (the title aliases)");
assert!(placed(0x1_8000, 0x2_0000).is_err(), "a placed buffer needs a 64 KiB-aligned offset");
drop(heap);
VirtualFree(p, 0, MEM_RELEASE);
}
}

/// Decoded GFX10 T#s give resource descriptions the driver accepts.
#[test]
fn gpu_tsharp_to_d3d12_resources() {
Expand Down
107 changes: 93 additions & 14 deletions crates/xcl/src/gpu/uma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ fn slot_limit(windows: usize) -> usize {
if windows > MAX_WINDOWS { 1 << (40 - 32) } else { 512 }
}

/// Whether each sparse window is one whole-committed allocation, so `sparse.rs` can import it as a
/// heap and skip the CPU→GPU copy (`XCL_SPARSE_DIRECT=1`).
pub(crate) fn sparse_direct_wanted() -> bool {
std::env::var("XCL_SPARSE_DIRECT").ok().as_deref() == Some("1")
}

/// Requested runtime UMA window count (`XCL_UMA_WINDOWS=4|8|16`, default 4).
/// Layouts wider than 4 windows require `XCL_HEAP_WINDOWS=1`.
pub(crate) fn configured_runtime_windows() -> usize {
Expand Down Expand Up @@ -112,6 +118,8 @@ pub struct Uma {
inner: Mutex<Inner>,
/// free ranges of the sparse windows (address → length) and the reservations in them
sparse_free: Mutex<(BTreeMap<usize, usize>, BTreeMap<usize, usize>)>,
/// usable bytes in a sparse window: 4 GiB, or `MAX_SIZE` when each is whole-committed for import
sparse_len: usize,
/// XCL's own pool in window 0 for `Arena` blocks: (start, end, free blocks). The title
/// cannot take it – a title that commits all of unified memory at start (Unicorn
/// Overlord: 2046 of 2048 MB) left no room for draw arguments, and draws were skipped.
Expand Down Expand Up @@ -249,23 +257,57 @@ impl Uma {
Self::reserve_runtime(size, coherent, windows)
}

/// The runtime layout the environment asks for; a direct layout the host cannot commit falls
/// back to the tiled one.
fn reserve_runtime(size: usize, coherent: usize, windows: usize) -> Option<Uma> {
let direct = sparse_direct_wanted();
Self::reserve_runtime_layout(size, coherent, windows, direct)
.or_else(|| direct.then(|| Self::reserve_runtime_layout(size, coherent, windows, false)).flatten())
}

fn reserve_runtime_layout(size: usize, coherent: usize, windows: usize, direct: bool) -> Option<Uma> {
let coh_sizes = coherent_window_sizes(size, coherent, windows);
let coh_wins = coh_sizes.len();
let sparse_wins = (windows - coh_wins).min(MAX_RUNTIME_SPARSE_WINDOWS);
let sparse_len = sparse_wins * WINDOW;
let sparse_len = sparse_wins * if direct { MAX_SIZE } else { WINDOW };
for slot in (windows..slot_limit(windows)).step_by(windows) {
let base = slot << 32;
let sp = unsafe { VirtualAlloc(base as *const std::ffi::c_void, sparse_len, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) };
if sp as usize != base {
if !sp.is_null() {
unsafe { VirtualFree(sp, 0, MEM_RELEASE) };
let mut win_allocs = Vec::with_capacity(1 + coh_wins);
let mut sparse_free: (BTreeMap<usize, usize>, BTreeMap<usize, usize>) = Default::default();
let mut ok = true;
if direct {
// one whole-committed allocation per window: the 1 MiB left of each is not address space
for k in 0..sparse_wins {
let w = base + k * WINDOW;
let sp = unsafe { VirtualAlloc(w as *const std::ffi::c_void, MAX_SIZE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) };
if sp as usize != w {
if !sp.is_null() {
unsafe { VirtualFree(sp, 0, MEM_RELEASE) };
}
ok = false;
break;
}
win_allocs.push(w);
sparse_free.0.insert(w, MAX_SIZE);
}
} else if sparse_wins > 0 {
let sp = unsafe { VirtualAlloc(base as *const std::ffi::c_void, sparse_len, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) };
if sp as usize == base {
win_allocs.push(base);
sparse_free.0.insert(base, sparse_len);
} else {
if !sp.is_null() {
unsafe { VirtualFree(sp, 0, MEM_RELEASE) };
}
ok = false;
}
}
if !ok {
for p in win_allocs {
unsafe { VirtualFree(p as *mut std::ffi::c_void, 0, MEM_RELEASE) };
}
continue;
}
let mut win_allocs = Vec::with_capacity(1 + coh_wins);
win_allocs.push(base);
let mut ok = true;
for (c, &c_size) in coh_sizes.iter().enumerate() {
let c_base = base + (sparse_wins + c) * WINDOW;
let cp = unsafe { VirtualAlloc(c_base as *const std::ffi::c_void, c_size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) };
Expand All @@ -292,13 +334,12 @@ impl Uma {
inner.free.insert(k * WINDOW, c_size);
kinds[k] = WindowKind::Committed(c_size);
}
let mut sparse_free: (BTreeMap<usize, usize>, BTreeMap<usize, usize>) = Default::default();
sparse_free.0.insert(base, sparse_len);
let u = Uma {
base,
kinds,
win_allocs,
inner: Mutex::new(inner),
sparse_len: if direct { MAX_SIZE } else { WINDOW },
sparse_free: Mutex::new(sparse_free),
pool: Mutex::new((0, 0, Vec::new())),
};
Expand Down Expand Up @@ -510,6 +551,7 @@ impl Uma {
kinds,
win_allocs,
inner: Mutex::new(inner),
sparse_len: WINDOW,
sparse_free: Mutex::new(Default::default()),
pool: Mutex::new((0, 0, Vec::new())),
});
Expand Down Expand Up @@ -541,19 +583,24 @@ impl Uma {
self.kinds.iter().filter(|w| matches!(w, WindowKind::Committed(_))).count()
}

/// (address, bytes) of window `k` (a sparse window: all 4 GiB)
/// Whether the sparse windows are whole-committed allocations (`MAX_SIZE` each, not 4 GiB).
pub fn sparse_direct(&self) -> bool {
self.sparse_len < WINDOW
}

/// (address, bytes) of window `k` (a sparse window: all 4 GiB, or `MAX_SIZE` when direct)
pub fn window(&self, k: usize) -> (usize, usize) {
let len = match self.kinds.get(k).copied().unwrap_or(WindowKind::None) {
WindowKind::Committed(s) => s,
WindowKind::Sparse => WINDOW,
WindowKind::Sparse => self.sparse_len,
WindowKind::None => 0,
};
(self.base + k * WINDOW, len)
}

/// Underlying write-watched `VirtualAlloc` regions `(base, size)` for `GetWriteWatch`:
/// contiguous sparse windows belong to a single reservation, while each committed window
/// is its own allocation.
/// (and each whole-committed sparse one) is its own allocation.
pub fn watch_regions(&self) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = Vec::with_capacity(self.kinds.len());
let mut k = 0;
Expand All @@ -568,8 +615,11 @@ impl Uma {
let start = self.base + k * WINDOW;
let mut len = 0usize;
while k < self.kinds.len() && matches!(self.kinds[k], WindowKind::Sparse) {
len += WINDOW;
len += self.sparse_len;
k += 1;
if self.sparse_direct() {
break;
}
}
out.push((start, len));
}
Expand Down Expand Up @@ -1105,6 +1155,35 @@ mod tests {
assert_eq!(u.watch_regions(), vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)]);
}

#[test]
fn the_direct_layout_shortens_the_sparse_windows_and_gives_each_its_own_watch_region() {
let test = "the_direct_layout_shortens_the_sparse_windows_and_gives_each_its_own_watch_region";
let Some(d) = Uma::reserve_runtime_layout(16 << 20, 16 << 20, MAX_WINDOWS, true) else {
eprintln!("SKIPPED {test}: the host refused {} MiB of committed memory", 3 * MAX_SIZE / (1 << 20));
return;
};
let b = d.base();
assert!(d.sparse_direct());
for k in 0..MAX_RUNTIME_SPARSE_WINDOWS {
assert_eq!(d.window(k), (b + k * WINDOW, MAX_SIZE), "sparse window {k} is one whole-committed allocation");
assert!(d.is_sparse_window(k));
}
assert_eq!(d.window_of(b + MAX_RUNTIME_SPARSE_WINDOWS * WINDOW - 1), None, "the 1 MiB at a window's end is not address space");
let (a, la) = d.sparse_alloc_in(2, MAX_SIZE - GRAIN, GRAIN).expect("a direct window's whole length is allocatable");
assert_eq!(d.window_of(a), Some(2));
assert!(a + la <= b + 2 * WINDOW + MAX_SIZE, "an allocation stays inside its window");
assert_eq!(d.sparse_release(a), Some(la));
assert_eq!(
d.watch_regions(),
vec![(b, MAX_SIZE), (b + WINDOW, MAX_SIZE), (b + 2 * WINDOW, MAX_SIZE), (b + 3 * WINDOW, 16 << 20)],
"each whole-committed sparse window is its own write-watch region"
);
let t = Uma::reserve_runtime_layout(16 << 20, 16 << 20, MAX_WINDOWS, false).expect("tiled layout");
assert!(!t.sparse_direct());
assert_eq!(t.window(0).1, WINDOW);
assert_eq!(t.watch_regions(), vec![(t.base(), 3 * WINDOW), (t.base() + 3 * WINDOW, 16 << 20)]);
}

#[test]
fn runtime_layout_supports_eight_and_sixteen_heap_windows() {
for windows in [8usize, MAX_HEAP_WINDOWS] {
Expand Down
Loading
Loading