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
262 changes: 252 additions & 10 deletions crates/xcl/src/hle/d3d12x/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,61 @@ impl FreePools {
}
}

/// `XCL_SPARSE_SYSMEM=1`: sparse-window tiles outside the
/// title's GPU heaps (`note_hot`) get pool tiles in system memory (custom heaps in L0, read by
/// the GPU over PCIe) instead of video memory; the GPU heaps' tiles keep video memory. A pool
/// tile of these heaps has `SYS` set in its pool index.
const SYS: u32 = 1 << 31;

#[derive(Default)]
struct SysPools {
heaps: Vec<ID3D12Heap>,
/// (by the heap's index without `SYS`: `FreePools` sizes its table by it)
free: FreePools,
cooling: VecDeque<((u32, u32), std::time::Instant)>,
}

// D3D12 heaps are free-threaded
unsafe impl Send for SysPools {}

static SYS_POOLS: Mutex<Option<SysPools>> = Mutex::new(None);
/// the title's GPU heaps in the sparse windows (`XCL_COHERENT_HEAPS=sparse`): (start, bytes)
static HOT: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());

/// `[a, a + n)` is a GPU heap of the title: its tiles keep video memory under `XCL_SPARSE_SYSMEM`.
pub fn note_hot(a: usize, n: usize) {
HOT.lock().unwrap().push((a, n));
}

/// The reservation at `a` is released: a later one there is placed by its own kind.
pub fn forget_hot(a: usize) {
HOT.lock().unwrap().retain(|&(s, _)| s != a);
}

#[cfg_attr(test, allow(unreachable_code))]
fn sysmem_tiles() -> bool {
// (a test's own thread decides: the environment of a test run does not)
#[cfg(test)]
return tests::SYSMEM_FOR_TEST.with(|c| c.get());
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| {
let on = std::env::var("XCL_SPARSE_SYSMEM").is_ok_and(|v| v.trim() == "1");
if on {
crate::xlog_info!("sparse windows: XCL_SPARSE_SYSMEM=1 - tiles outside the title's GPU heaps in system memory");
}
on
})
}

fn is_hot(a: usize) -> bool {
HOT.lock().unwrap().iter().any(|&(s, n)| a >= s && a < s + n)
}

/// Bytes of the system-memory pool heaps.
pub fn sys_pool_bytes() -> usize {
SYS_POOLS.lock().unwrap().as_ref().map_or(0, |p| p.heaps.len() * POOL_TILES as usize * TILE)
}

/// Whether the oldest tile of `cooling` was freed `COOL` ago or more at `now`
fn cooled(cooling: &VecDeque<((u32, u32), std::time::Instant)>, now: std::time::Instant) -> bool {
cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL)
Expand Down Expand Up @@ -3127,7 +3182,8 @@ pub fn pool_bytes() -> (usize, usize) {
let _held = holding(Holder::Other);
let Some(s) = g.as_ref() else { return (0, 0) };
let pools = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize * TILE;
let quarantined: usize = s.quarantined.iter().map(|b| b.tiles.len()).sum();
// (tiles of the system-memory pools, `SYS`, are none of these bytes)
let quarantined: usize = s.quarantined.iter().map(|b| b.tiles.iter().filter(|t| t.0 & SYS == 0).count()).sum();
(pools, pools.saturating_sub((s.free.len() + s.cooling.len() + quarantined) * TILE))
}

Expand Down Expand Up @@ -3508,6 +3564,68 @@ impl State {
Some(UploadPageObservation { page, pool: entry.pool, hole, sent, source })
}

/// `take_tile` from the system-memory pools (`XCL_SPARSE_SYSMEM`).
unsafe fn take_sys_tile(&mut self) -> Option<((u32, u32), bool)> {
self.drain_quarantined();
let mut g = SYS_POOLS.lock().unwrap();
let p = g.get_or_insert_with(SysPools::default);
if let Some((h, t)) = reuse_tile(&mut p.free, &mut p.cooling, std::time::Instant::now()) {
return Some(((SYS | h, t), true));
}
let desc = D3D12_HEAP_DESC {
SizeInBytes: POOL_TILES as u64 * TILE as u64,
Properties: D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_CUSTOM,
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
..Default::default()
},
Alignment: 0,
Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES,
};
let mut heap: Option<ID3D12Heap> = None;
if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)) {
crate::xlog_warn!("sparse windows: no system-memory pool heap ({e}) - video memory instead");
drop(g);
return self.take_tile();
}
let heap = heap?;
let _ = heap.SetName(windows::core::w!("xcl sparse system-memory pool"));
p.heaps.push(heap);

@gut0to gut0to Dec 1, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each 64 MiB heap added to SYS_POOLS.heaps remains there for the process lifetime; unlike the video pools, the system-memory pools have no all-free retirement path. A workload that temporarily grows this pool can therefore retain its peak L0 allocation after all tiles are cooled and freed. Could empty system heaps be retired once their tiles are unmapped and the sparse-queue fence has passed, with a test that sys_pool_bytes() decreases? AI-assisted static review: I used an AI assistant to inspect the allocation and release paths.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed from the diff: SYS_POOLS.heaps only grows (sys_pool_bytes() is heaps.len() * POOL_TILES * TILE, and nothing removes a heap), while the video pools have their retired path. Our world runs show the size it reaches: with XCL_SPARSE_SYSMEM=1 the process's non-local (system) video memory went from 3.9 GB at the start to 8.7 GB at the end of a 900 s run (run 398), against 3.6 → 4.9 GB without it (run 397), RTX 4080, same build. So about 3.8 GB of system-memory pool, which with this code stays for the rest of the process even if the tiles cool. Since the switch is off by default it does not affect the default path (that is what our merge check above covers), but retirement of all-free system heaps after the sparse-queue fence, with a test that sys_pool_bytes() drops, would be needed before it could ever be turned on by default. @treybertram06

AI use: Claude Code (Claude Opus 5.5) read the diff and the run logs.

let h = p.heaps.len() as u32 - 1;
p.free.add_heap(h);
let n = p.heaps.len();
if n.is_power_of_two() {
crate::xlog_info!("sparse windows: {} MB of system-memory pool heaps", n * POOL_TILES as usize * TILE >> 20);
}
Some(((SYS | h, 0), false))
}

/// A pool tile for window tile `t`: from the system-memory pools under `XCL_SPARSE_SYSMEM`
/// unless `t` is in a GPU heap of the title.
unsafe fn take_tile_for(&mut self, t: usize) -> Option<((u32, u32), bool)> {
if sysmem_tiles() && !is_hot(t) { self.take_sys_tile() } else { self.take_tile() }
}

/// The heap of pool index `h` (video memory, or a system-memory pool with `SYS`).
fn pool_heap(&self, h: u32) -> ID3D12Heap {
if h & SYS != 0 {
return SYS_POOLS.lock().unwrap().as_ref().expect("system-memory pools").heaps[(h & !SYS) as usize].clone();
}
self.pools[h as usize].clone().expect("a pool tile of a live pool")
}

/// A freed pool tile cools in its own pools' queue.
fn cool(&mut self, tile: (u32, u32), at: std::time::Instant) {
if tile.0 & SYS != 0 {
if let Some(p) = SYS_POOLS.lock().unwrap().as_mut() {
p.cooling.push_back(((tile.0 & !SYS, tile.1), at));
}
} else {
self.cooling.push_back((tile, at));
}
}

/// A pool tile (true: used before, to be cleared). One freed less than `COOL` ago, or one
/// still `quarantined`, is not taken: a retired pool is taken back or a heap made instead.
/// (Parked tiles are not flushed for it: freed now, they would wait and cool all the same.)
Expand Down Expand Up @@ -3633,7 +3751,7 @@ impl State {
coords.len() as u32,
Some(coords.as_ptr()),
Some(regions.as_ptr()),
self.pools[h as usize].as_ref().expect("a pool tile of a live pool"),
&self.pool_heap(h),
flags.len() as u32,
Some(flags.as_ptr()),
Some(offsets.as_ptr()),
Expand Down Expand Up @@ -3799,8 +3917,10 @@ impl State {
while t < end {
if self.mapped.get(&t).is_some_and(|e| e.pool == LAZY) {
let at_hand = !self.free.is_empty() || cooled(&self.cooling, std::time::Instant::now()) || !self.retired.is_empty();
let wait = left > 0 || (!force && self.short_of_memory() && !at_hand);
match if wait { None } else { self.take_tile() } {
// (short of video memory: a tile of the system-memory pools does not wait for it)
let sys = sysmem_tiles() && !is_hot(t);
let wait = left > 0 || (!force && !sys && self.short_of_memory() && !at_hand);
match if wait { None } else { self.take_tile_for(t) } {
Some((tile, used)) => {
if let Some(e) = self.mapped.get_mut(&t) {
e.pool = tile;
Expand Down Expand Up @@ -3848,11 +3968,29 @@ impl State {
let end = a.saturating_add(n);
let mut new = false;
let mut unparked = false;
// parked system-memory tiles at addresses of a GPU heap now (`XCL_SPARSE_SYSMEM`)
let mut replaced = Vec::new();
let mut t = first;
while t < end {
if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() {
// still mapped there: no new mapping, what it held is cleared
if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) {
// a tile parked here from before is in system memory and a GPU heap of the title
// is here now: a video-memory tile takes its place, mapped over it at once, and it
// goes once the GPU is past that (one a placed buffer uses stays; none found: it stays)
let swap = self.parked.get(&t).is_some_and(|tile| tile.0 & SYS != 0 && !self.pinned.contains_key(tile)) && is_hot(t);
if let Some((tile, reused)) = if swap { self.take_tile() } else { None } {
replaced.extend(self.parked.remove(&t));
let (holes, not_rw) = initial_state(t);
let mut entry = TileEntry::with_holes(tile, holes);
entry.not_rw = not_rw;
self.mapped.insert(t, entry);
early_add(&mut self.runs, t, t + TILE);
if reused {
self.to_zero.insert((t, TILE));
}
self.pending.push(t);
new = true;
} else if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) {
// still mapped there: no new mapping, what it held is cleared
let (holes, not_rw) = initial_state(t);
let mut entry = TileEntry::with_holes(tile, holes);
entry.not_rw = not_rw;
Expand All @@ -3861,7 +3999,7 @@ impl State {
self.to_zero.insert((t, TILE));
unparked = true;
} else {
let Some((tile, reused)) = self.take_tile() else { break };
let Some((tile, reused)) = self.take_tile_for(t) else { break };
let (holes, not_rw) = initial_state(t);
let mut entry = TileEntry::with_holes(tile, holes);
entry.not_rw = not_rw;
Expand All @@ -3882,7 +4020,12 @@ impl State {
if new || unparked {
MAPPED_GEN.fetch_add(1, Ordering::Release);
}
if self.pending.len() >= PENDING_MAX {
if !replaced.is_empty() {
// (their new mappings sent first: the old tiles go behind the fence of that)
self.flush_pending();
let completion = super::present::queue_completion_snapshot();
self.quarantine_tiles_for(replaced, &completion.active, &completion.retiring, completion.blocked);
} else if self.pending.len() >= PENDING_MAX {
self.flush_pending();
} else if !self.pending.is_empty() {
pending_soon();
Expand Down Expand Up @@ -4886,9 +5029,19 @@ fn uav_to_copy(r: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER {
/// 4 GiB window boundary when `size <= 4 GiB`). Commits the CPU pages and maps VRAM tiles
/// (or queues them until the D3D12 device exists). Returns `(address, rounded_size)`.
pub unsafe fn alloc(size: usize, align: usize) -> Option<(usize, usize)> {
alloc_as(size, align, false)
}

/// `alloc` of a title GPU heap (`hot`: its tiles keep video memory under `XCL_SPARSE_SYSMEM`,
/// known before its commit maps them).
pub unsafe fn alloc_as(size: usize, align: usize, hot: bool) -> Option<(usize, usize)> {
let u = crate::gpu::uma::get()?;
let (addr, rounded) = u.sparse_alloc(size, align)?;
if hot {
note_hot(addr, rounded);
}
if VirtualAlloc(addr as *const c_void, rounded, MEM_COMMIT, PAGE_READWRITE).is_null() {
forget_hot(addr);
u.sparse_release(addr);
return None;
}
Expand Down Expand Up @@ -4920,6 +5073,7 @@ pub unsafe fn free(p: usize) -> bool {
let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false };
decommitted(start, len);
VirtualFree(p as *mut c_void, len, MEM_DECOMMIT);
forget_hot(start);
u.sparse_release(p).is_some()
}

Expand Down Expand Up @@ -5894,7 +6048,7 @@ impl State {
&& self.parked.get(&t) != Some(&tile)
&& !self.quarantined.iter().any(|b| b.tiles.contains(&tile))
{
self.cooling.push_back((tile, std::time::Instant::now()));
self.cool(tile, std::time::Instant::now());
}
}

Expand Down Expand Up @@ -5980,7 +6134,7 @@ impl State {
let at = batch.at;
for tile in batch.tiles {
if !self.pinned.contains_key(&tile) {
self.cooling.push_back((tile, at));
self.cool(tile, at);
freed = true;
}
}
Expand Down Expand Up @@ -8455,6 +8609,8 @@ mod tests {
pub(super) static LAZY_COMMITS_FOR_TEST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
/// `take_tile` finds no video memory on this thread
pub(super) static NO_TILES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// `sysmem_tiles` (`XCL_SPARSE_SYSMEM`) for the test on this thread (`Lazy::sysmem`)
pub(super) static SYSMEM_FOR_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// The runs of the tiles mapped, made from all of them (but those over a CPU view: their
Expand Down Expand Up @@ -10316,6 +10472,23 @@ mod tests {
}
}

#[test]
fn the_title_gpu_heaps_are_hot_and_nothing_around_them() {
// (addresses no other test uses: `HOT` is global)
let (a, n) = (0x7f12_3400_0000usize, 3 * TILE);
assert!(!is_hot(a));
note_hot(a, n);
assert!(is_hot(a) && is_hot(a + TILE) && is_hot(a + n - 1));
assert!(!is_hot(a - 1) && !is_hot(a + n));
// a pool tile of the system-memory pools is told apart by its pool index
let (video, system) = ((7u32, 3u32), (SYS | 7, 3u32));
assert!(video.0 & SYS == 0 && system.0 & SYS != 0);
assert_eq!(system.0 & !SYS, video.0);
// released: a reservation there later is placed by its own kind
forget_hot(a);
assert!(!is_hot(a) && !is_hot(a + TILE));
}

#[test]
fn aligned_tile_addresses_spread_across_hash_buckets() {
use std::hash::BuildHasher;
Expand Down Expand Up @@ -11260,11 +11433,16 @@ mod tests {
fn no_tiles(&self, none: bool) {
NO_TILES.with(|c| c.set(none));
}
/// `XCL_SPARSE_SYSMEM` on for this thread
fn sysmem(&self, on: bool) {
SYSMEM_FOR_TEST.with(|c| c.set(on));
}
}
impl Drop for Lazy {
fn drop(&mut self) {
LAZY_COMMITS_FOR_TEST.with(|c| c.set(None));
NO_TILES.with(|c| c.set(false));
SYSMEM_FOR_TEST.with(|c| c.set(false));
}
}

Expand Down Expand Up @@ -11343,6 +11521,70 @@ mod tests {
drop(lazy);
}

/// Under `XCL_SPARSE_SYSMEM` a lazy tile outside the title's GPU heaps gets its memory from the
/// system-memory pools at its first bytes, as an eager one does, and the bytes reach the GPU.
#[test]
fn a_lazy_tile_outside_the_gpu_heaps_gets_system_memory() {
let lazy = Lazy::on(true);
lazy.sysmem(true);
unsafe {
let Some((base, mut s, queue)) = lazy_state(2) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") };
let eager = base + TILE;
s.ensure_mapped(eager, TILE, |_| (0, 0));
if s.mapped[&eager].pool.0 & SYS == 0 {
return crate::gpu::recomp::runner::skip_test("no system-memory pool heap");
}
s.commit_range(base, TILE);
assert_eq!(s.mapped[&base].pool, LAZY);
let dirty = write_tile(base, 11);
s.before_execute_on(&queue, &dirty, PAGE);
assert_ne!(s.mapped[&base].pool.0 & SYS, 0, "its first bytes gave it a system-memory tile");
let cpu = std::slice::from_raw_parts(base as *const u8, TILE).to_vec();
assert!(window_bytes(&mut s, base, TILE) == cpu, "the bytes reached the GPU");
}
drop(lazy);
}

/// A system-memory tile parked at an address that is a GPU heap of the title by its next commit
/// gives way to a video-memory tile, mapped there before the old one goes (behind the fences),
/// and the heap's bytes reach the GPU through the new one.
#[test]
fn a_parked_system_memory_tile_gives_way_to_a_gpu_heap() {
let eager = Lazy::on(false);
eager.sysmem(true);
unsafe {
let Some((base, mut s, queue)) = lazy_state(1) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") };
s.ensure_mapped(base, TILE, |_| (0, 0));
let old = s.mapped[&base].pool;
if old.0 & SYS == 0 {
return crate::gpu::recomp::runner::skip_test("no system-memory pool heap");
}
s.flush_pending();
s.decommit_range(base, TILE);
assert_eq!(s.parked.get(&base), Some(&old));
note_hot(base, TILE);
s.ensure_mapped(base, TILE, |_| (0, 0));
let now = s.mapped[&base].pool;
assert_eq!(now.0 & SYS, 0, "a GPU heap's tile is in video memory");
assert!(!s.parked.contains_key(&base) && s.pending.is_empty(), "the new mapping went out");
assert!(s.quarantined.iter().any(|b| b.tiles.contains(&old)), "the old tile waits for the GPU");
let dirty = write_tile(base, 13);
s.before_execute_on(&queue, &dirty, PAGE);
let cpu = std::slice::from_raw_parts(base as *const u8, TILE).to_vec();
assert!(window_bytes(&mut s, base, TILE) == cpu, "the bytes reached the GPU");
// once the GPU is past it, the old tile cools among the system-memory pools: the
// video-memory pools' free table is indexed by heap number, and `SYS` is none
settle_quarantined(&mut s);
assert!(s.quarantined.is_empty(), "the GPU is past the old tile");
assert!(!s.cooling.iter().any(|&(t, _)| t == old), "not in the video-memory pools' queue");
assert!(s.free.by_heap.len() <= s.pools.len(), "the video-memory free table keeps its size");
let sys = (old.0 & !SYS, old.1);
assert!(SYS_POOLS.lock().unwrap().as_ref().is_some_and(|p| p.cooling.iter().any(|&(t, _)| t == sys)), "it cools among the system-memory pools");
forget_hot(base);
}
drop(eager);
}

/// Bytes that found no video memory at an upload are owed and go up whole once there is some.
#[test]
fn bytes_that_found_no_memory_go_up_once_there_is_some() {
Expand Down
Loading
Loading