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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
ones with `record HASH`, the console record's hash that `--measure-pso` and
`--export-hlsl --record-hash` take), with whether it was gated and how long it waited;
`XCL_PSO_TRACE=1` logs every driver compile.
- `XCL_DEFER_PRIVATE_HOME_TILES=1` keeps sparse physical pages used only for storage I/O
in CPU memory. When the title maps those pages at their home address, XCL allocates their
GPU tiles and uploads the stored data before the next GPU submission. Off by default.
- 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.
Expand Down
59 changes: 59 additions & 0 deletions crates/xcl/src/hle/d3d12x/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1604,6 +1604,65 @@ pub fn forget_buffer(res: usize) {
mod tests {
use super::*;

#[test]
fn private_physical_pages_reach_the_gpu_on_mapping() {
// The option, device and sparse windows are process-wide.
const CHILD: &str = "XCL_TEST_PRIVATE_PHYSICAL_PAGES";
if std::env::var_os(CHILD).is_none() {
let status = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping", "--nocapture"])
.env(CHILD, "1")
.env("XCL_DEFER_PRIVATE_HOME_TILES", "1")
.status().unwrap();
assert!(status.success());
return;
}
use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, write_physical_pages};
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
unsafe {
let mut device = None;
if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut device).is_err() {
crate::gpu::recomp::runner::skip_test("no GPU");
return;
}
let device: ID3D12Device = device.unwrap();
let windows = init(&device);
if windows.is_empty() {
crate::gpu::recomp::runner::skip_test("no sparse windows");
return;
}
for (_, raw, _) in windows { drop(ID3D12Resource::from_raw(raw as *mut c_void)); }
let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap();
let mut pages = [0usize; 3];
let mut n = pages.len();
let null = std::ptr::null_mut();
assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1);
let first = vec![0xa7; TILE];
let last = vec![0x38; TILE];
let before = mapped_ranges();
assert!(write_physical_pages(&pages[..1], 0, &first));
assert!(write_physical_pages(&pages[2..], 0, &last));
assert_eq!(mapped_ranges(), before, "storage writes allocated GPU tiles");

// Expose one fully CPU-backed page first, then a mixed span of all three.
let first_home = MapTitlePhysicalPages(null, 1, 0, 4, pages.as_mut_ptr());
assert!(!first_home.is_null());
let home = MapTitlePhysicalPages(null, n, 0, 4, pages.as_mut_ptr()) as usize;
assert_eq!(home, first_home as usize);
assert!(mapped_ranges().iter().any(|&(a, b)| a <= home && home + n * TILE <= b));
// A prior write-watch scan may have consumed the writes before the first submit.
assert_eq!(windows_sys::Win32::System::Memory::ResetWriteWatch(home as *const c_void, n * TILE), 0);
super::super::title_textures::refresh(queue.as_raw());
std::ptr::write_bytes(home as *mut u8, 0xdd, n * TILE);
readback_after_execute(&queue, &[(home, n * TILE)]);
let result = std::slice::from_raw_parts(home as *const u8, n * TILE);
assert_eq!(&result[..TILE], &first);
assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0));
assert_eq!(&result[2 * TILE..], &last);
assert_eq!(FreeTitlePhysicalPages(null, n, pages.as_mut_ptr()), 1);
}
}

/// `queue()` answers while the state's lock is held: a resource's last `Release` asks for
/// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be
/// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`).
Expand Down
16 changes: 16 additions & 0 deletions crates/xcl/src/hle/d3d12x/title_textures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,12 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty:
}
}

static INITIAL_CPU_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());

pub(crate) fn rescan_cpu_backing(start: usize, bytes: usize) {
INITIAL_CPU_RANGES.lock().unwrap().push((start, bytes));
}

unsafe fn refresh_once(queue: *mut c_void) {
let Some(u) = crate::gpu::uma::get() else { return };
let sparse = u.has_sparse();
Expand All @@ -705,7 +711,17 @@ unsafe fn refresh_once(queue: *mut c_void) {
take_written(base, size, &mut buf, &mut dirty, &mut page);
}
});
let watched = dirty.len();
if *crate::hle::kernelx::DEFER_PRIVATE_HOME_TILES {
let mut initial = INITIAL_CPU_RANGES.lock().unwrap();
for (start, size) in initial.drain(..) {
dirty.extend((start..start + size).step_by(page as usize));
}
}
dirty.sort_unstable();
if dirty.len() > watched {
dirty.dedup();
}
dirty.len()
});
super::sparse::note_watch(watch_t0.elapsed(), dirty_len);
Expand Down
66 changes: 48 additions & 18 deletions crates/xcl/src/hle/kernelx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -803,9 +803,14 @@ static PHYS_BLOCKS: std::sync::Mutex<std::collections::BTreeMap<usize, (usize, u
/// sparse window, the coherent one, or – without room there – plain reserved memory)
static NEXT_PAGE_INDEX: AtomicUsize = AtomicUsize::new(0);

#[derive(Clone, Copy, PartialEq, Eq)]
enum SparseHome { CpuOnly, Exposed }

/// Pages mapped away from home: address → page, and page → address.
#[derive(Default)]
struct Away {
/// CPU-only backing needs an upload when the title first maps it at home.
sparse_homes: std::collections::HashMap<usize, SparseHome>,
at: std::collections::BTreeMap<usize, usize>,
page: std::collections::HashMap<usize, usize>,
/// homes in a sparse window whose pages went away in this call, given back at its end in
Expand Down Expand Up @@ -864,7 +869,7 @@ fn lazy_home(home: usize) -> bool {

/// Resolve the live virtual addresses of the physical pages covering `offset..offset+len`.
/// Caller must hold `AWAY`.
unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: usize, len: usize) -> Option<Vec<usize>> {
unsafe fn resolve_physical_pages(away: &mut Away, pages: &[usize], offset: usize, len: usize) -> Option<Vec<usize>> {
if offset >= PHYS_PAGE {
return None;
}
Expand All @@ -876,9 +881,9 @@ unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: u
let mut addrs = Vec::with_capacity(need);
for &p in &pages[..need] {
let home = page_home(p)?;
let addr = match away.and_then(|a| a.page.get(&p).copied()) {
let addr = match away.page.get(&p).copied() {
Some(at) => at,
None => home_again(home)?,
None => home_again(home, p, away)?,
};
addrs.push(addr);
}
Expand All @@ -892,8 +897,8 @@ pub unsafe fn read_physical_pages(pages: &[usize], offset: usize, dst: &mut [u8]
if dst.is_empty() {
return offset < PHYS_PAGE;
}
let g = AWAY.lock().unwrap();
let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, dst.len()) else { return false };
let mut g = AWAY.lock().unwrap();
let Some(addrs) = resolve_physical_pages(g.get_or_insert_with(Away::default), pages, offset, dst.len()) else { return false };
let mut done = 0;
let mut page_off = offset;
for addr in addrs {
Expand All @@ -911,8 +916,8 @@ pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) -
if src.is_empty() {
return offset < PHYS_PAGE;
}
let g = AWAY.lock().unwrap();
let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, src.len()) else { return false };
let mut g = AWAY.lock().unwrap();
let Some(addrs) = resolve_physical_pages(g.get_or_insert_with(Away::default), pages, offset, src.len()) else { return false };
let mut done = 0;
let mut page_off = offset;
for addr in addrs {
Expand Down Expand Up @@ -961,36 +966,60 @@ unsafe fn give_back_homes(away: &mut Away) {
}
}

pub(crate) static DEFER_PRIVATE_HOME_TILES: std::sync::LazyLock<bool> =
std::sync::LazyLock::new(|| std::env::var("XCL_DEFER_PRIVATE_HOME_TILES").is_ok_and(|v| v == "1"));

/// 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<usize> {
unsafe fn home_again(home: usize, page: usize, away: &mut Away) -> Option<usize> {
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() {
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);
if *DEFER_PRIVATE_HOME_TILES && away.sparse_homes.get(&page) != Some(&SparseHome::Exposed) {
away.sparse_homes.insert(page, SparseHome::CpuOnly);
} else {
crate::hle::d3d12x::sparse::committed(home, PHYS_PAGE);
}
}
}
Some(home)
}

/// `n` pages from `home` committed (a sparse home is only reserved until it is used).
unsafe fn commit_homes(home: usize, n: usize) -> bool {
unsafe fn commit_homes(home: usize, pages: &[usize], away: &mut Away) -> bool {
let n = pages.len();
let Some(u) = crate::gpu::uma::get() else { return false };
if !lazy_home(home) {
return true;
}
let len = n * PHYS_PAGE;
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 ready = committed_range(home, len);
if !ready && mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).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);
let private = |page: &usize| away.sparse_homes.get(page) == Some(&SparseHome::CpuOnly);
let has_private = *DEFER_PRIVATE_HOME_TILES && pages.iter().any(private);
if !ready || has_private {
crate::hle::d3d12x::sparse::committed(home, len);
}
if has_private {
// A write-watch scan can consume a storage write before its GPU tile exists.
let mut addr = home;
for run in pages.chunk_by(|a, b| private(a) == private(b)) {
let bytes = run.len() * PHYS_PAGE;
if private(&run[0]) {
crate::hle::d3d12x::title_textures::rescan_cpu_backing(addr, bytes);
}
addr += bytes;
}
}
if *DEFER_PRIVATE_HOME_TILES {
away.sparse_homes.extend(pages.iter().map(|&p| (p, SparseHome::Exposed)));
}
}
true
}
Expand Down Expand Up @@ -1069,7 +1098,7 @@ unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range<usi
let own = page_home(page);
let pending = away.gone.len();
away.gone.retain(|&h| Some(h) != own);
let home = if away.gone.len() < pending || own.is_some_and(|h| committed.contains(&h)) { own } else { own.and_then(|h| home_again(h)) };
let home = if away.gone.len() < pending || own.is_some_and(|h| committed.contains(&h)) { own } else { own.and_then(|h| home_again(h, page, away)) };
if let Some(home) = home {
std::ptr::copy_nonoverlapping(at as *const u8, home as *mut u8, PHYS_PAGE);
#[cfg(test)]
Expand Down Expand Up @@ -1169,6 +1198,7 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr:
// freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes
if let Some(away) = AWAY.lock().unwrap().as_mut() {
for i in 0..n {
away.sparse_homes.remove(&*arr.add(i));
if let Some(at) = away.page.remove(&*arr.add(i)) {
away.at.remove(&at);
note_mapping_at(at);
Expand Down Expand Up @@ -1228,7 +1258,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize)
fnd::SetLastError(fnd::ERROR_NOT_SUPPORTED); // scattered pages need an address
return std::ptr::null_mut();
};
if !commit_homes(home, n) {
if !commit_homes(home, &pages, away) {
fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY);
return std::ptr::null_mut();
}
Expand Down Expand Up @@ -2568,7 +2598,7 @@ mod tests {
let at = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize;
mem::VirtualFree(at as *mut c_void, 0, mem::MEM_RELEASE);
let page = 0x7E57_0000usize;
let mut away = Away { at: Default::default(), page: Default::default(), gone: Vec::new() };
let mut away = Away::default();
away.at.insert(old, page);
away.page.insert(page, old);
assert!(move_away(&mut away, old, at, page, false).is_err());
Expand Down
Loading