From ebbf3779791aff8988c4b742ba629c561928333c Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:11:45 -0500 Subject: [PATCH] Memory: a freed sparse block is decommitted before its address is reused d3d12x::sparse::free gave the block's address back to the sparse windows (sparse_release) and only then decommitted it. In between another thread could get the same address, commit it and write there; the late decommit then took the pages away under it: write access violations at the first title addresses of sparse window 0 (0x42001xxxx), which ended cargo test -p xcl --lib now and then (FreeTitlePhysicalPages frees homes this way while other tests allocate graphics memory). The block is now decommitted first and released last, as VirtualFree's own sparse path already does. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/xcl/src/hle/d3d12x/sparse.rs | 34 ++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 22c5a22f..b7561bbd 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1153,10 +1153,12 @@ pub unsafe fn free(p: usize) -> bool { if !u.is_sparse(p) { return false; } - let Some(len) = u.sparse_release(p) else { return false }; - decommitted(p, len); + // decommitted before the address goes back: once released, another thread may get it, + // commit it and write there + 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); - true + u.sparse_release(p).is_some() } /// After `queue.ExecuteCommandLists`: copy GPU-written sparse ranges (e.g. `Write32/64`, @@ -1488,6 +1490,32 @@ pub fn forget_buffer(res: usize) { mod tests { use super::*; + /// A block freed on one thread while another allocates: its address goes back to the + /// windows only once it is decommitted (released first, the decommit came after another + /// thread had the same address again: that thread's writes faulted). + #[test] + fn a_freed_block_is_decommitted_before_its_address_is_reused() { + if crate::gpu::uma::get().is_none_or(|u| !u.has_sparse()) { + return; + } + let threads: Vec<_> = (0..4) + .map(|_| { + std::thread::spawn(|| unsafe { + for i in 0..2000u64 { + let Some((p, n)) = alloc(TILE, TILE) else { continue }; + std::ptr::write_volatile(p as *mut u64, i); + std::ptr::write_volatile((p + n - 8) as *mut u64, i); + assert_eq!(std::ptr::read_volatile(p as *const u64), i); + assert!(free(p)); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + } + #[test] fn aligned_tile_addresses_spread_across_hash_buckets() { use std::hash::BuildHasher;