From 4913af0075f4ae57efa840eb4f3f2efb26ebb67f Mon Sep 17 00:00:00 2001 From: Utkarsh Bhatnagar Date: Tue, 24 Nov 2026 11:33:23 +0530 Subject: [PATCH] Memory: serialize sparse commits and decommits with uploads Keep host page transitions and sparse tile state under the same lock. Cover fixed-address bounds, reset rejection, and the upload/decommit ordering regression. Assisted-by: OpenAI Codex (GPT-6) --- crates/xcl/src/hle/d3d12x/sparse.rs | 282 ++++++++++++++++----- crates/xcl/src/hle/kernelx.rs | 137 +++++----- crates/xcl/src/hle/kernelx/placeholders.rs | 10 +- 3 files changed, 303 insertions(+), 126 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 0731890bf..b45efe67b 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -26,6 +26,7 @@ use windows::core::Interface; use windows::Win32::Foundation::{CloseHandle, HANDLE}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; +use windows_sys::Win32::Foundation::{SetLastError, ERROR_INVALID_ADDRESS, ERROR_INVALID_PARAMETER}; use windows_sys::Win32::System::Memory::{ VirtualAlloc, VirtualFree, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_DECOMMIT, PAGE_GUARD, PAGE_NOACCESS, PAGE_READWRITE, @@ -414,13 +415,17 @@ pub fn pool_bytes() -> (usize, usize) { } /// commits before the device existed: the pages committed, as disjoint page ranges (start → /// end) merged with their neighbours, so a commit or decommit costs O(log n) and not a scan of -/// every page committed so far. Like `committed` / `decommitted` with a state, a range counts +/// every page committed so far. Like `commit` / `decommit` with a state, a range counts /// every page it touches; `init` commits them once the windows exist. static EARLY: Mutex> = Mutex::new(BTreeMap::new()); -/// The pages `[a, a + n)` touches, as `[start, end)`. -fn page_span(a: usize, n: usize) -> (usize, usize) { - (a & !(PAGE - 1), a.saturating_add(n).saturating_add(PAGE - 1) & !(PAGE - 1)) +/// The pages touched by a nonempty byte range, as `[start, end)`. +fn page_span(a: usize, n: usize) -> Option<(usize, usize)> { + if n == 0 { + return None; + } + let end = a.checked_add(n)?.checked_next_multiple_of(PAGE)?; + Some((a & !(PAGE - 1), end)) } /// Add the pages `[a, b)` to `early`, merged with the ranges they overlap or touch. @@ -566,18 +571,20 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { }) })(); match made { - Ok(s) => { + Ok(mut s) => { crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len()); - // a state this replaces (the windows set up again) goes after the lock: the release of - // its last buffers reaches `forget_buffer`, which takes the lock (#344) - // (the queue first: `queue()` never answers with one older than the state's) let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); - let old = STATE.lock().unwrap().replace(s); + let old = { + let mut state = STATE.lock().unwrap(); + let early = std::mem::take(&mut *EARLY.lock().unwrap()); + for (a, b) in early { + mark_committed(&mut s, a, b - a); + } + state.replace(s) + }; + // Releasing the old state's buffers can call `forget_buffer`, which takes STATE. drop(old); drop(old_queue); - for (a, b) in std::mem::take(&mut *EARLY.lock().unwrap()) { - committed(a, b - a); - } out } Err(e) => { @@ -1187,11 +1194,10 @@ impl State { pub unsafe fn alloc(size: usize, align: usize) -> Option<(usize, usize)> { let u = crate::gpu::uma::get()?; let (addr, rounded) = u.sparse_alloc(size, align)?; - if VirtualAlloc(addr as *const c_void, rounded, MEM_COMMIT, PAGE_READWRITE).is_null() { + if commit(addr, rounded, PAGE_READWRITE).is_null() { u.sparse_release(addr); return None; } - committed(addr, rounded); Some((addr, rounded)) } @@ -1200,26 +1206,16 @@ pub unsafe fn alloc(size: usize, align: usize) -> Option<(usize, usize)> { pub unsafe fn alloc_in(window: usize, size: usize, align: usize) -> Option<(usize, usize)> { let u = crate::gpu::uma::get()?; let (addr, rounded) = u.sparse_alloc_in(window, size, align)?; - if VirtualAlloc(addr as *const c_void, rounded, MEM_COMMIT, PAGE_READWRITE).is_null() { + if commit(addr, rounded, PAGE_READWRITE).is_null() { u.sparse_release(addr); return None; } - committed(addr, rounded); Some((addr, rounded)) } -/// Release a sparse allocation from `alloc` / `alloc_in` (false: not a sparse allocation). +/// Release a sparse allocation from `alloc` / `alloc_in`. pub unsafe fn free(p: usize) -> bool { - let Some(u) = crate::gpu::uma::get() else { return false }; - if !u.is_sparse(p) { - return false; - } - // 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); - u.sparse_release(p).is_some() + crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p)) && free_reserved(p, 0, true) } /// After `queue.ExecuteCommandLists`: copy GPU-written sparse ranges (e.g. `Write32/64`, @@ -1306,35 +1302,144 @@ pub unsafe fn readback_now(va: usize, len: usize) { s.readback_ranges(&[(va, len)]); } -/// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that -/// lie outside the range are not committed (holes); the range's pages are. -pub unsafe fn committed(a: usize, n: usize) { - if n == 0 { - return; - } - let mut g = STATE.lock().unwrap(); - let Some(s) = g.as_mut() else { - let (start, end) = page_span(a, n); - early_add(&mut EARLY.lock().unwrap(), start, end); - return; +/// Commit CPU pages and publish their GPU mappings as one operation. +pub unsafe fn commit(a: usize, n: usize, protect: u32) -> *mut c_void { + commit_initialized(a, n, protect, || {}) +} + +/// Copy or initialize a physical mapping before making its pages available to the upload scan. +/// The initializer runs under STATE and must not call back into sparse memory operations. +pub unsafe fn commit_initialized(a: usize, n: usize, protect: u32, initialize: impl FnOnce()) -> *mut c_void { + let Some((start, end)) = page_span(a, n) else { + SetLastError(ERROR_INVALID_PARAMETER); + return std::ptr::null_mut(); }; - s.commit_range(a, n); + let mut state = STATE.lock().unwrap(); + commit_locked(&mut state, start, end, protect, initialize) +} + +/// A title commit must fit a single live reservation. Hold STATE through the ownership check, +/// host commit and bookkeeping so a simultaneous release cannot invalidate the check. +pub unsafe fn commit_reserved(a: usize, n: usize, protect: u32) -> *mut c_void { + let mut state = STATE.lock().unwrap(); + let Some((start, end)) = page_span(a, n).filter(|&(start, end)| { + crate::gpu::uma::get().and_then(|u| u.sparse_reservation(start)) + .is_some_and(|(base, len)| end <= base + len) + }) else { + SetLastError(ERROR_INVALID_ADDRESS); + return std::ptr::null_mut(); + }; + commit_locked(&mut state, start, end, protect, || {}) +} + +unsafe fn commit_locked( + state: &mut Option, start: usize, end: usize, protect: u32, initialize: impl FnOnce(), +) -> *mut c_void { + let n = end - start; + let q = VirtualAlloc(start as *const c_void, n, MEM_COMMIT, protect); + if q.is_null() { + return q; + } + initialize(); + if let Some(state) = state { + mark_committed(state, start, n); + } else { + early_add(&mut EARLY.lock().unwrap(), start, end); + } + q +} + +unsafe fn mark_committed(s: &mut State, a: usize, n: usize) { + s.ensure_mapped(a, n, |_| 0xFFFF); + let mut pg = a & !(PAGE - 1); + let end = a.saturating_add(n); + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = t.saturating_add(TILE).min(end); + if let Some(entry) = s.mapped.get_mut(&t) { + let mut p = pg; + while p < tile_end { + entry.holes &= !(1u16 << ((p - t) / PAGE)); + p += PAGE; + } + } + if tile_end <= pg { + break; + } + pg = tile_end; + } +} + +/// Decommit `[a, a + n)`: decommits host CPU pages under the sparse state lock (preventing races +/// with the upload thread in `before_execute`), and on success updates GPU tile mappings / bookkeeping. +pub unsafe fn decommit(a: usize, n: usize) -> bool { + decommit_with_lock(a, n, || STATE.lock().unwrap()) +} + +unsafe fn decommit_with_lock<'a>( + a: usize, n: usize, lock: impl FnOnce() -> std::sync::MutexGuard<'a, Option>, +) -> bool { + let mut state = lock(); + decommit_locked(&mut state, a, n) } -/// The title decommitted `[a, a + n)`: tiles whose pages are all uncommitted (whether in one -/// full-tile decommit or incrementally via sub-tile decommits) give their video memory back -/// (unless a placed buffer still pins the pool tile). -pub unsafe fn decommitted(a: usize, n: usize) { +unsafe fn decommit_locked(state: &mut Option, a: usize, n: usize) -> bool { if n == 0 { - return; + return true; } - let mut g = STATE.lock().unwrap(); - let Some(s) = g.as_mut() else { - let (start, end) = page_span(a, n); - early_remove(&mut EARLY.lock().unwrap(), start, end); - return; + let Some((start, page_end)) = page_span(a, n) else { + SetLastError(ERROR_INVALID_PARAMETER); + return false; }; - s.decommit_range(a, n); + let n = page_end - start; + if VirtualFree(start as *mut c_void, n, MEM_DECOMMIT) == 0 { + return false; + } + let Some(s) = state.as_mut() else { + early_remove(&mut EARLY.lock().unwrap(), start, page_end); + return true; + }; + let tiles = decommit_tiles(&mut s.mapped, &s.pinned, &mut s.free, &mut s.to_zero, start, n); + if !tiles.is_empty() { + s.runs = None; + let mut by_window: FxHashMap> = FxHashMap::default(); + for &t in &tiles { + if let Some(wi) = s.window_index(t) { + by_window.entry(wi).or_default().push(t); + } + } + for (wi, ts) in by_window { + let (b, r) = (s.windows[wi].0, s.windows[wi].1.clone()); + s.unmap_tiles(&r, b, &ts); + } + MAPPED_GEN.fetch_add(1, Ordering::Release); + s.signal(); + s.retire_free_pools(); + } + true +} + +/// Decommit or release a live reservation. Ownership stays protected through the host call +/// and, for release, until the range is available to the sparse allocator again. +pub unsafe fn free_reserved(a: usize, n: usize, release: bool) -> bool { + let mut state = STATE.lock().unwrap(); + let Some(u) = crate::gpu::uma::get() else { return false }; + let Some((base, len)) = u.sparse_reservation(a) else { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + }; + let whole = release || n == 0; + if (whole && base != a) || (!whole && a.checked_add(n).is_none_or(|end| end > base + len)) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + if !decommit_locked(&mut state, a, if whole { len } else { n }) { + return false; + } + if release { + u.sparse_release(a); + } + true } impl State { @@ -1621,6 +1726,64 @@ mod tests { assert!(answered, "queue() waited for the sparse state's lock"); } + #[test] + fn upload_scan_excludes_host_decommit() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + + struct HostPage(*mut c_void); + impl Drop for HostPage { + fn drop(&mut self) { + unsafe { VirtualFree(self.0, 0, MEM_RELEASE) }; + } + } + + unsafe { + let page = VirtualAlloc(std::ptr::null(), PAGE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + assert!(!page.is_null()); + let page = HostPage(page); + let a = page.0 as usize; + let page_state = || { + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery(a as *const c_void, &mut info, std::mem::size_of_val(&info)), 0); + info.State + }; + // Model before_execute's guard without creating a GPU device or changing global STATE. + let state = &Mutex::new(None); + std::thread::scope(|scope| { + let _scan = state.lock().unwrap(); + let raw = scope.spawn(|| VirtualFree(a as *mut c_void, PAGE, MEM_DECOMMIT)); + assert_ne!(raw.join().unwrap(), 0); + // An unguarded host decommit wins even while a scan is holding the mutex. + assert_eq!(page_state(), MEM_RESERVE); + }); + + assert!(!VirtualAlloc(page.0, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + page.0.cast::().write(0x5A); + let (at_lock, dirty) = std::thread::scope(|scope| { + let scan = state.lock().unwrap(); + let (ready, observed) = std::sync::mpsc::sync_channel(0); + let worker = scope.spawn(move || decommit_with_lock(a, PAGE, || { + // Observe the page at the lock boundary so an early decommit fails without + // a timing assumption or a read of an inaccessible page. + ready.send(page_state()).unwrap(); + state.lock().unwrap() + })); + let at_lock = observed.recv().unwrap(); + let mut dirty = Vec::new(); + if at_lock == MEM_COMMIT { + let bytes = std::slice::from_raw_parts(a as *const u8, PAGE); + scan_page(bytes, a, &mut None, &mut dirty); + } + drop(scan); + assert!(worker.join().unwrap()); + (at_lock, dirty) + }); + assert_eq!(at_lock, MEM_COMMIT); + assert_eq!(dirty, vec![(a, CHUNK)]); + assert_eq!(page_state(), MEM_RESERVE); + } + } + /// 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). @@ -2155,7 +2318,7 @@ mod tests { 1 => 1 + (next(&mut x) % 64) as usize, _ => 1 + (next(&mut x) % (24 * PAGE as u64)) as usize, }; - let (start, end) = page_span(a, n); + let (start, end) = page_span(a, n).unwrap(); let pages = (start..end).step_by(PAGE); if next(&mut x) % 3 == 0 { early_remove(&mut early, start, end); @@ -2206,29 +2369,30 @@ mod tests { assert_eq!(early.into_iter().collect::>(), vec![(a, a + TILE), (a + 2 * TILE, a + 4 * TILE)]); } - /// Time for n 64 KiB pages committed one at a time and decommitted one at a time in - /// reverse, before the device exists (`cargo test --release -p xcl --lib -- + /// Time for the early bookkeeping of n 64 KiB pages added one at a time and removed + /// one at a time in reverse (`cargo test --release -p xcl --lib -- /// --ignored --exact hle::d3d12x::sparse::tests::early_commit_timing --nocapture`, - /// `XCL_EARLY_PAGES=16384,32768`). Run it alone: a test that made the device keeps a state. + /// `XCL_EARLY_PAGES=16384,32768`). #[test] #[ignore] fn early_commit_timing() { - if STATE.lock().unwrap().is_some() { - return eprintln!("early_commit_timing: a sparse state exists – run it alone"); - } let sizes: Vec = std::env::var("XCL_EARLY_PAGES").ok().map_or(vec![4096, 8192, 16384, 32768], |v| v.split(',').map(|s| s.trim().parse().unwrap()).collect()); let base = 0x4_2000_0000usize; for n in sizes { + let mut early = BTreeMap::new(); let t = std::time::Instant::now(); for i in 0..n { - unsafe { committed(base + i * TILE, TILE) }; + let start = base + i * TILE; + early_add(&mut early, start, start + TILE); } let commit = t.elapsed(); let t = std::time::Instant::now(); for i in (0..n).rev() { - unsafe { decommitted(base + i * TILE, TILE) }; + let start = base + i * TILE; + early_remove(&mut early, start, start + TILE); } let decommit = t.elapsed(); + assert!(early.is_empty()); println!("early: {n} pages: commit {:.1} ms, decommit {:.1} ms", commit.as_secs_f64() * 1e3, decommit.as_secs_f64() * 1e3); } } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 8aa3bc200..589aff89f 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -225,11 +225,7 @@ const MEM_64K_PAGES: u32 = 0x2040_0000; /// Commit `[a, a + n)` of a sparse window (the title's reservations there) and give it video /// memory (`d3d12x::sparse`). unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { - let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, sanitize_protect(p)); - if !q.is_null() { - crate::hle::d3d12x::sparse::committed(q as usize, n); - } - q + crate::hle::d3d12x::sparse::commit(a, n, sanitize_protect(p)) } pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { @@ -239,8 +235,13 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: } let uma = crate::gpu::uma::get(); // committing inside one of the title's reservations in a sparse window - if !addr.is_null() && t & 0x1000 != 0 && uma.is_some_and(|u| u.is_sparse(addr as usize)) { - let q = commit_sparse(addr as usize, size, p); + if !addr.is_null() && uma.is_some_and(|u| u.is_sparse(addr as usize)) { + // Reset and other non-commit operations cannot bypass sparse page bookkeeping. + if t & mem::MEM_COMMIT == 0 { + fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); + return std::ptr::null_mut(); + } + let q = crate::hle::d3d12x::sparse::commit_reserved(addr as usize, size, sanitize_protect(p)); trace_mem("VirtualAlloc (sparse commit)", addr as usize, size, t as u64, p, q as usize); return q; } @@ -395,43 +396,14 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 } // the title's reservations in a sparse window: decommit (and on release give the address // space back); their video memory goes with it - if let Some(u) = crate::gpu::uma::get().filter(|u| u.is_sparse(addr as usize)) { - let a = addr as usize; + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(addr as usize)) { let release = t & mem::MEM_RELEASE != 0; let decommit = t & mem::MEM_DECOMMIT != 0; if release == decommit || (release && size != 0) { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } - let n = if release || size == 0 { - match u.sparse_reservation(a) { - Some((start, len)) if start == a => len, - _ => { - fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); - return 0; - } - } - } else { - match u.sparse_reservation(a) { - Some((start, len)) if a.checked_add(size).is_some_and(|end| end <= start + len) => size, - _ => { - fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); - return 0; - } - } - }; - if n > 0 { - // sparse first: under its lock, so no copy of CPU writes to video memory reads the - // pages while they go (the submit thread's copy faulted on them) - crate::hle::d3d12x::sparse::decommitted(a, n); - if mem::VirtualFree(addr, n, mem::MEM_DECOMMIT) == 0 { - return 0; - } - } - if release { - u.sparse_release(a); - } - return 1; + return crate::hle::d3d12x::sparse::free_reserved(addr as usize, size, release) as BOOL; } if let Some(u) = crate::gpu::uma::get().filter(|u| u.contains(addr as usize)) { if t & 0x8000 != 0 { @@ -560,8 +532,13 @@ pub unsafe extern "system" fn XMemFreeDefault(p: *mut c_void, attrs: u64) { } if XAllocAttrs::decode(attrs).memory_type == 0 { aligned_heap_free(p); - } else if !crate::hle::d3d12x::sparse::free(p as usize) && !crate::gpu::uma::get().is_some_and(|u| u.free(p as usize)) { - mem::VirtualFree(p, 0, mem::MEM_RELEASE); + } else { + let uma = crate::gpu::uma::get(); + if uma.is_some_and(|u| u.is_sparse(p as usize)) { + crate::hle::d3d12x::sparse::free(p as usize); + } else if !uma.is_some_and(|u| u.free(p as usize)) { + mem::VirtualFree(p, 0, mem::MEM_RELEASE); + } } } @@ -954,22 +931,25 @@ unsafe fn give_back_homes(away: &mut Away) { i += 1; } if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(start)) { - crate::hle::d3d12x::sparse::decommitted(start, end - start); + crate::hle::d3d12x::sparse::decommit(start, end - start); + } else { + mem::VirtualFree(start as *mut c_void, end - start, mem::MEM_DECOMMIT); } - mem::VirtualFree(start as *mut c_void, end - start, mem::MEM_DECOMMIT); } } /// The page's home, committed again if `move_home_away` gave it back (None: it could not be). unsafe fn home_again(home: usize) -> Option { if lazy_home(home) && !committed_page(home) { - if mem::VirtualAlloc(home as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { + let q = if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(home)) { + commit_sparse(home, PHYS_PAGE, mem::PAGE_READWRITE) + } else { + mem::VirtualAlloc(home as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE) + }; + if q.is_null() { crate::xlog_warn!("physical page: its home {home:#x} could not be committed again"); return None; } - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(home)) { - crate::hle::d3d12x::sparse::committed(home, PHYS_PAGE); - } } Some(home) } @@ -984,13 +964,15 @@ unsafe fn commit_homes(home: usize, n: usize) -> bool { if committed_range(home, len) { return true; } - if mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { + let q = if u.is_sparse(home) { + commit_sparse(home, len, mem::PAGE_READWRITE) + } else { + mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE) + }; + if q.is_null() { crate::xlog_warn!("physical pages: {n} at their home {home:#x} could not be committed"); return false; } - if u.is_sparse(home) { - crate::hle::d3d12x::sparse::committed(home, len); - } true } @@ -1091,9 +1073,10 @@ unsafe fn release_at(at: usize) { return; } if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { - crate::hle::d3d12x::sparse::decommitted(at, PHYS_PAGE); + crate::hle::d3d12x::sparse::decommit(at, PHYS_PAGE); + } else { + mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT); } - mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT); } /// A page mapped away from home (at `old`) that the title maps at `at`: what `old` holds copied @@ -1287,20 +1270,31 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) away.page.insert(p, at); continue; } - if !in_uma(at) && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { + let mut copied_home = false; + let mut initialize = || { + if committed_page(home) { + std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PHYS_PAGE); + copied_home = true; + } else if !fresh { + std::ptr::write_bytes(at as *mut u8, 0, PHYS_PAGE); + } + }; + let mapped = if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { + !crate::hle::d3d12x::sparse::commit_initialized(at, PHYS_PAGE, mem::PAGE_READWRITE, initialize).is_null() + } else if in_uma(at) || !mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { + initialize(); + true + } else { + false + }; + if !mapped { fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); } - if committed_page(home) { - std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PHYS_PAGE); + if copied_home { if move_home_away(away, home) { (at_run, home_run) = Default::default(); } - } else if !fresh { - std::ptr::write_bytes(at as *mut u8, 0, PHYS_PAGE); // a page never used: zeros - } - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { - crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); } away.at.insert(at, p); away.page.insert(p, at); @@ -2725,6 +2719,29 @@ mod tests { } } + #[test] + fn sparse_virtual_alloc_rejects_out_of_bounds_and_reset() { + let u = crate::gpu::uma::get().filter(|u| u.has_sparse()).expect("sparse UMA"); + let size = crate::gpu::uma::GRAIN; + let base = u.sparse_reserve(size).expect("sparse reservation"); + unsafe { + assert_eq!(VirtualAlloc(base as *const c_void, 0x1000, mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize, base); + // The last byte belongs to this reservation regardless of adjacent allocations. + for (at, len, flags) in [ + (base, 0, mem::MEM_COMMIT), + (base + size - 1, 2, mem::MEM_COMMIT), + (base, 0x1000, 0x0008_0000), // MEM_RESET + (base, 0x1000, 0x0100_0000), // MEM_RESET_UNDO + ] { + fnd::SetLastError(0); + let q = VirtualAlloc(at as *const c_void, len, flags, mem::PAGE_READWRITE); + assert!(q.is_null(), "VirtualAlloc accepted flags {flags:#x} at offset {:#x}", at - base); + assert_eq!(fnd::GetLastError(), fnd::ERROR_INVALID_ADDRESS, "flags {flags:#x}"); + } + assert_eq!(VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE), 1); + } + } + #[test] fn virtual_free_ex_and_sparse_validation() { unsafe { diff --git a/crates/xcl/src/hle/kernelx/placeholders.rs b/crates/xcl/src/hle/kernelx/placeholders.rs index 218a9bb3b..5bcf16f79 100644 --- a/crates/xcl/src/hle/kernelx/placeholders.rs +++ b/crates/xcl/src/hle/kernelx/placeholders.rs @@ -126,19 +126,15 @@ pub(super) unsafe fn free(addr: *mut c_void, size: usize, flags: u32) -> Option< return fail(); } let len = if size == 0 { r.end - base } else { size }; - super::super::d3d12x::sparse::decommitted(base, len); - return Some(mem::VirtualFree(addr, len, mem::MEM_DECOMMIT)); + return Some(super::super::d3d12x::sparse::decommit(base, len) as i32); } if start != base || (flags != PRESERVE && flags != mem::MEM_RELEASE) || (flags == mem::MEM_RELEASE && size != 0) || (flags == PRESERVE && size != 0 && size != r.end - base) { return fail(); } - if !r.placeholder { - super::super::d3d12x::sparse::decommitted(base, r.end - base); - if mem::VirtualFree(addr, r.end - base, mem::MEM_DECOMMIT) == 0 { - return Some(0); - } + if !r.placeholder && !super::super::d3d12x::sparse::decommit(base, r.end - base) { + return Some(0); } if flags == PRESERVE { regions.get_mut(&base).unwrap().placeholder = true;