Skip to content
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,10 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper.
- `XCL_ACTIVITY=1` (any value turns it on): every 2 seconds `xcl.log` gets an `activity (2 s)`
line with what the title did in that time (presents, submits, draws, dispatches, frame-event
waits, DirectStorage requests), and a `memory:` line with the process's commit and the video
memory in use. Where the lines stop changing is where the title stopped.
memory in use. A `memory by owner (MB)` line splits the commit, the video memory and the
non-local memory by what in XCL holds them, against DXGI's budgets, with the rest as `other`;
two more `memory:` lines list the buffers XCL makes for itself and the swap chain's size with
the pipeline builds so far. Where the lines stop changing is where the title stopped.
- `XCL_THREAD_DUMP_AT=s1,s2,…`: at each of those seconds after the start, the state of every
thread of the title goes into `xcl.log`, for a title that stalls.
- `XCL_TRACE_FAULTS=1` (any value): the first 32 access violations are logged as they are raised
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/texture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ unsafe fn buffer(dev: &ID3D12Device, size: u64) -> Result<ID3D12Resource, String
let mut r: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut r)
.map_err(|x| format!("texture upload buffer: {x}"))?;
r.ok_or_else(|| "texture upload buffer".into())
crate::hle::d3d12x::resource_census::tracked(r, "upload staging").ok_or_else(|| "texture upload buffer".into())
}

fn transition(r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
Expand Down
8 changes: 7 additions & 1 deletion crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,12 @@ const TP_GONE: usize = 2;
const TP_ALIVE: usize = 3;
const TP_REFUSED: usize = 4;

/// Bytes of the two-pass buffers alive: in use, kept for reuse and waiting for allocator resets
/// (memory accounting, #2688). Each is a committed buffer in video memory.
pub fn two_pass_bytes() -> u64 {
TWO_PASS[TP_ALIVE].load(Ordering::Relaxed)
}

/// One more of `TWO_PASS[k]`. Logged at most every 2 s while they change (always: each buffer
/// made or let go is the driver's memory manager at work, in video memory that may be short).
fn note_two_pass(k: usize) {
Expand Down Expand Up @@ -2482,7 +2488,7 @@ unsafe fn argument_order_buffer(list: &ID3D12GraphicsCommandList) -> Option<ID3D
}
return None;
}
let b = b?;
let b = crate::hle::d3d12x::resource_census::tracked(b, "ExecuteIndirect argument order")?;
*g = Some((dev.as_raw() as usize, b.clone()));
Some(b)
}
Expand Down
8 changes: 4 additions & 4 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2764,7 +2764,7 @@ unsafe fn make_copy_scratch(list: *mut c_void, bytes: u64) -> Option<ID3D12Resou
device_of(list)?
.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut b)
.ok()?;
b
crate::hle::d3d12x::resource_census::tracked(b, "copy scratch")
}

unsafe fn device_of(list: *mut c_void) -> Option<ID3D12Device> {
Expand Down Expand Up @@ -2808,7 +2808,7 @@ unsafe fn pattern_buffer(list: *mut c_void, pat: [u8; 16], n: u64) -> Option<usi
&mut b,
)
.ok()?;
let b = b?;
let b = crate::hle::d3d12x::resource_census::tracked(b, "fill pattern")?;
let mut p: *mut c_void = std::ptr::null_mut();
b.Map(0, None, Some(&mut p)).ok()?;
for chunk in std::slice::from_raw_parts_mut(p as *mut u8, len as usize).chunks_exact_mut(16) {
Expand Down Expand Up @@ -2942,7 +2942,7 @@ unsafe fn ensure_timestamp_readback(dev: &ID3D12Device, pool: &mut TimestampPool
};
let mut rb: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).ok()?;
let rb = rb?;
let rb = crate::hle::d3d12x::resource_census::tracked(rb, "timestamp readback")?;
let mut ptr: *mut c_void = std::ptr::null_mut();
rb.Map(0, None, Some(&mut ptr)).ok()?;
if ptr.is_null() {
Expand Down Expand Up @@ -3636,7 +3636,7 @@ unsafe fn predication_buffer(list: *mut c_void) -> Option<usize> {
};
let mut buf: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).ok()?;
let buf = buf?;
let buf = crate::hle::d3d12x::resource_census::tracked(buf, "predication")?;
let (raw, extra) = {
let mut g = recording(list as usize).lock().unwrap();
let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default();
Expand Down
424 changes: 424 additions & 0 deletions crates/xcl/src/hle/d3d12x/memory_report.rs

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions crates/xcl/src/hle/d3d12x/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,11 @@ pub mod layout;
pub mod list_x;
mod look_stats;
mod lut3d;
pub mod memory_report;
pub mod null;
mod placements;
pub mod present;
pub mod resource_census;
pub mod pso_async;
pub mod real;
mod scatter;
Expand Down
24 changes: 23 additions & 1 deletion crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -946,6 +946,24 @@ unsafe impl Send for Presenter {}

static PRESENTER: Mutex<Option<Presenter>> = Mutex::new(None);

/// The swap chain's width, height and bytes a pixel, as it was last made or resized (0: none
/// yet). Kept apart from `PRESENTER`, which a present holds for as long as it takes.
static SWAP_SIZE: [std::sync::atomic::AtomicU32; 3] = [const { std::sync::atomic::AtomicU32::new(0) }; 3];

fn note_swap_chain(w: u32, h: u32, fmt: DXGI_FORMAT) {
let pixel = if fmt == DXGI_FORMAT_R16G16B16A16_FLOAT { 8 } else { 4 };
for (slot, v) in SWAP_SIZE.iter().zip([w, h, pixel]) {
slot.store(v, Ordering::Relaxed);
}
}

/// The swap chain's back buffers: how many, their width and height, and the bytes of a pixel
/// (memory accounting, #2688). None before there is a swap chain.
pub fn swap_chain_buffers() -> Option<(u32, u32, u32, u32)> {
let [w, h, pixel] = std::array::from_fn(|i| SWAP_SIZE[i].load(Ordering::Relaxed));
(w != 0 && h != 0).then_some((SWAP_BUFFERS, w, h, pixel))
}

unsafe fn transition(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
transition_sub(res, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after)
}
Expand Down Expand Up @@ -1007,6 +1025,7 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D
p.w = w;
p.h = h;
p.fmt = fmt;
note_swap_chain(w, h, fmt);
crate::xlog_info!("present: swap chain {w}x{h} {:?}", fmt);
return true;
}
Expand Down Expand Up @@ -1034,6 +1053,9 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D
p.w = w;
p.h = h;
p.fmt = fmt;
if p.sc.is_some() {
note_swap_chain(w, h, fmt);
}
crate::xlog_info!("present: swap chain {w}x{h} {:?} – the game image will appear in the XCL window", fmt);
crate::xlog_info!("present: swap chain window {:#x}", hwnd.0 as usize);
p.sc.is_some()
Expand Down Expand Up @@ -1399,7 +1421,7 @@ unsafe fn readback_copy(list: &ID3D12GraphicsCommandList, src: &ID3D12Resource,
&mut rb,
)
.ok()?;
let rb = rb?;
let rb = crate::hle::d3d12x::resource_census::tracked(rb, "frame dump readback")?;
let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } };
let s = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(src), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } };
list.CopyTextureRegion(&dst, 0, 0, 0, &s, None);
Expand Down
7 changes: 7 additions & 0 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,13 @@ pub fn abi_root_signature() -> Option<ID3D12RootSignature> {
static UMA_BUFFER: Mutex<Vec<(usize, u64)>> = Mutex::new(Vec::new());
/// the committed UMA windows opened as D3D12 heaps (indexed by window `k`; `None` for sparse windows)
static UMA_HEAPS: Mutex<Vec<Option<usize>>> = Mutex::new(Vec::new());

/// Bytes of the coherent windows imported into D3D12 (`OpenExistingHeapFromAddress`): those DXGI
/// counts. 0 before, or when the import failed (the windows are then CPU memory only).
pub fn uma_imported_bytes() -> u64 {
let Some(u) = crate::gpu::uma::get() else { return 0 };
UMA_HEAPS.lock().unwrap().iter().enumerate().filter(|(_, h)| h.is_some()).map(|(k, _)| u.window(k).1 as u64).sum()
}
/// console buffers placed in unified memory: resource → (address, bytes)
/// address, bytes, whether XCL allocated the memory (not: the title's own, CreatePlacedResourceX)
type UmaBuffer = (usize, usize, bool);
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ unsafe fn scratch_buffer(dev: &ID3D12Device, bytes: u64) -> Option<ID3D12Resourc
let mut resource = None;
dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, CreationNodeMask: 1, VisibleNodeMask: 1, ..Default::default() },
D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut resource).ok()?;
resource
crate::hle::d3d12x::resource_census::tracked(resource, "dispatch chain scratch")
}

/// A piece or the whole form on `list`: on a list XCL adopted (a title's) past the hook of a
Expand Down
197 changes: 197 additions & 0 deletions crates/xcl/src/hle/d3d12x/resource_census.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
//! The D3D12 resources XCL makes for itself (not the title's), by where it makes them: how many
//! are alive and their bytes (#2688, workstream 1). A resource is counted when it is made
//! (`track`) and taken off when D3D12 destroys it: `track` gives it a small COM object as private
//! data, which D3D12 releases with the resource. Growth that follows the title's submits shows up
//! as one place whose count keeps climbing.

use std::collections::BTreeMap;
use std::ffi::c_void;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Mutex;

use windows::core::{Interface, GUID, HRESULT, IUnknown};
use windows::Win32::Graphics::Direct3D12::*;

use super::memory_report::Kind;

/// What a place has made: alive now, their bytes, made in all.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Count {
pub live: u64,
pub bytes: u64,
pub made: u64,
}

/// (place, which memory) → its count
static SITES: Mutex<BTreeMap<(&'static str, KindKey), Count>> = Mutex::new(BTreeMap::new());

/// `Kind` as a map key
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
enum KindKey {
Video,
NonLocal,
}

/// The private data a tracked resource holds (its id is XCL's own).
const TRACKER: GUID = GUID::from_u128(0x5c1d_7e2a_8b44_4f0e_9a61_3d2c_7b1e_0a95);

/// The COM object D3D12 keeps as a tracked resource's private data: its release takes the
/// resource off its place's count.
#[repr(C)]
struct Tracker {
vtbl: *const Vtbl,
refs: AtomicU32,
site: &'static str,
kind: KindKey,
bytes: u64,
}

/// IUnknown's three methods
#[repr(C)]
struct Vtbl {
query_interface: unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT,
add_ref: unsafe extern "system" fn(*mut c_void) -> u32,
release: unsafe extern "system" fn(*mut c_void) -> u32,
}

static VTBL: Vtbl = Vtbl { query_interface, add_ref, release };

unsafe extern "system" fn query_interface(this: *mut c_void, iid: *const GUID, out: *mut *mut c_void) -> HRESULT {
if !out.is_null() && !iid.is_null() && *iid == IUnknown::IID {
add_ref(this);
*out = this;
return HRESULT(0);
}
if !out.is_null() {
*out = std::ptr::null_mut();
}
HRESULT(0x8000_4002_u32 as i32) // E_NOINTERFACE
}

unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 {
(*(this as *const Tracker)).refs.fetch_add(1, Ordering::AcqRel) + 1
}

unsafe extern "system" fn release(this: *mut c_void) -> u32 {
let t = this as *mut Tracker;
let n = (*t).refs.fetch_sub(1, Ordering::AcqRel) - 1;
if n == 0 {
let t = Box::from_raw(t);
if let Some(c) = SITES.lock().unwrap_or_else(|e| e.into_inner()).get_mut(&(t.site, t.kind)) {
c.live = c.live.saturating_sub(1);
c.bytes = c.bytes.saturating_sub(t.bytes);
}
}
n
}

/// Count `res`, which XCL made at `site` (a short name: "copy scratch", "upload staging"), until
/// D3D12 destroys it. Its bytes are its allocation's size. One in an upload or readback heap is
/// in system memory (`Kind::NonLocal` here; `memory_report` puts it where the adapter's DXGI
/// segments count it), the rest in video memory.
pub unsafe fn track(res: &ID3D12Resource, site: &'static str) {
let desc = res.GetDesc();
let mut dev: Option<ID3D12Device> = None;
let bytes = match res.GetDevice(&mut dev).ok().and(dev) {
Some(dev) => dev.GetResourceAllocationInfo(0, &[desc]).SizeInBytes,
None => 0,
};
let bytes = if bytes == u64::MAX { 0 } else { bytes };
let mut heap = D3D12_HEAP_PROPERTIES::default();
let kind = match res.GetHeapProperties(Some(&mut heap), None) {
Ok(()) if matches!(heap.Type, D3D12_HEAP_TYPE_UPLOAD | D3D12_HEAP_TYPE_READBACK) => KindKey::NonLocal,
_ => KindKey::Video,
};
let t = Box::into_raw(Box::new(Tracker { vtbl: &VTBL, refs: AtomicU32::new(1), site, kind, bytes }));
// (ours: the one reference `Box::into_raw` made; D3D12 takes its own)
let unknown = IUnknown::from_raw(t as *mut c_void);
{
let mut g = SITES.lock().unwrap_or_else(|e| e.into_inner());
let c = g.entry((site, kind)).or_default();
c.live += 1;
c.bytes += bytes;
c.made += 1;
}
if res.SetPrivateDataInterface(&TRACKER, &unknown).is_err() {
// (not kept: the count it made goes again when `unknown` is dropped below)
}
drop(unknown);
}

/// `track` of the resource in `r`, if any; `r` back.
pub fn tracked(r: Option<ID3D12Resource>, site: &'static str) -> Option<ID3D12Resource> {
if let Some(res) = &r {
// SAFETY: a live resource of XCL's own
unsafe { track(res, site) };
}
r
}

/// Every place's count now, with the memory it takes.
pub fn counts() -> Vec<(&'static str, Kind, Count)> {
SITES
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.map(|(&(site, k), &c)| (site, if k == KindKey::NonLocal { Kind::NonLocal } else { Kind::Video }, c))
.collect()
}

#[cfg(test)]
mod tests {
use super::*;

/// A tracked resource counts at its place while it lives (its bytes, upload heaps as
/// non-local) and goes off the count when D3D12 destroys it; `made` stays.
#[test]
fn a_tracked_resource_counts_until_it_is_destroyed() {
if super::super::backend() != super::super::Backend::Real {
crate::gpu::recomp::runner::skip_test("no GPU");
return;
}
let count = |site: &str| counts().into_iter().find(|(s, _, _)| *s == site).map(|(_, k, c)| (k, c));
unsafe {
let raw = super::super::real::device_raw();
let dev = ID3D12Device::from_raw_borrowed(&raw).unwrap();
let buffer = |heap: D3D12_HEAP_TYPE, size: u64| -> ID3D12Resource {
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size,
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,
..Default::default()
};
let state = if heap == D3D12_HEAP_TYPE_UPLOAD { D3D12_RESOURCE_STATE_GENERIC_READ } else { D3D12_RESOURCE_STATE_COMMON };
let mut r: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap();
r.unwrap()
};
let a = buffer(D3D12_HEAP_TYPE_DEFAULT, 1 << 20);
let b = buffer(D3D12_HEAP_TYPE_DEFAULT, 1 << 20);
track(&a, "census test video");
track(&b, "census test video");
let up = buffer(D3D12_HEAP_TYPE_UPLOAD, 3 << 20);
track(&up, "census test upload");
let (k, c) = count("census test video").unwrap();
assert_eq!((k, c.live, c.made), (Kind::Video, 2, 2));
assert!(c.bytes >= 2 << 20, "{c:?}");
let (k, c) = count("census test upload").unwrap();
assert_eq!((k, c.live), (Kind::NonLocal, 1));
assert!(c.bytes >= 3 << 20, "{c:?}");
// a reference elsewhere keeps it alive and counted
let a2 = a.clone();
drop(a);
assert_eq!(count("census test video").unwrap().1.live, 2);
drop(a2);
let (_, c) = count("census test video").unwrap();
assert_eq!((c.live, c.made), (1, 2), "destroyed: off the count");
drop(b);
drop(up);
assert_eq!(count("census test video").unwrap().1, Count { live: 0, bytes: 0, made: 2 });
assert_eq!(count("census test upload").unwrap().1.live, 0);
}
}
}
Loading
Loading