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
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/texture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,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
2 changes: 1 addition & 1 deletion crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,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 @@ -2341,7 +2341,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 @@ -2385,7 +2385,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 @@ -2495,7 +2495,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 @@ -3116,7 +3116,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 = LISTS.lock().unwrap();
let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default();
Expand Down
381 changes: 381 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 @@ -23,8 +23,10 @@ pub mod guard;
mod late_release;
pub mod layout;
pub mod list_x;
pub mod memory_report;
pub mod null;
pub mod present;
pub mod resource_census;
pub mod pso_async;
pub mod real;
mod shader_cache_session;
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1305,7 +1305,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 @@ -172,6 +172,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 @@ -196,7 +196,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")
}

/// Called with the original six ABI views bound. The extended signature is
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);
}
}
}
27 changes: 24 additions & 3 deletions crates/xcl/src/hle/d3d12x/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,18 @@ pub fn pool_bytes() -> (usize, usize) {
let pools = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize * TILE;
(pools, pools.saturating_sub(s.free.len() * TILE))
}

/// Bytes of the pool heaps given back but not released yet (titles' queues may still read
/// them): memory accounting, #2688.
pub fn retired_bytes() -> usize {
lock_state().as_ref().map_or(0, |s| s.retired.len() * POOL_TILES as usize * TILE)
}

/// Bytes of the title's pages committed in the sparse windows (their CPU side): memory
/// accounting, #2688.
pub fn committed_bytes() -> usize {
lock_state().as_ref().map_or(0, |s| s.committed_bytes())
}
/// 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
Expand Down Expand Up @@ -654,6 +666,13 @@ impl State {
h
}

/// Bytes of the title's pages committed in the windows: the pages of the mapped tiles that
/// are not holes. A tile the title decommitted whole is not mapped any more, though its pool
/// tile may still be parked (memory accounting, #2688).
fn committed_bytes(&self) -> usize {
self.mapped.values().map(|e| PAGES_PER_TILE - e.holes.count_ones() as usize).sum::<usize>() * PAGE
}

/// Pools whose every tile is free again go (64 MB of video memory each – and as much of the
/// system's commit: a retail game's homes of physical pages left 0.75 GB of pools for
/// 0.29 GB of tiles in use). Call after their tiles are unmapped and signalled.
Expand Down Expand Up @@ -907,7 +926,7 @@ impl State {
&mut r,
)
.ok()?;
let r = r?;
let r = crate::hle::d3d12x::resource_census::tracked(r, "sparse staging")?;
let mut p = std::ptr::null_mut();
r.Map(0, None, Some(&mut p)).ok()?;
self.staging = Some((r, p as *mut u8));
Expand All @@ -934,7 +953,7 @@ impl State {
{
return false;
}
let Some(r) = r else { return false };
let Some(r) = crate::hle::d3d12x::resource_census::tracked(r, "sparse zero buffer") else { return false };
let mut p = std::ptr::null_mut();
if r.Map(0, None, Some(&mut p)).is_err() {
return false;
Expand All @@ -961,7 +980,7 @@ impl State {
&mut r,
)
.ok()?;
let r = r?;
let r = crate::hle::d3d12x::resource_census::tracked(r, "sparse readback")?;
let mut p = std::ptr::null_mut();
r.Map(0, None, Some(&mut p)).ok()?;
self.readback = Some((r, p as *mut u8));
Expand Down Expand Up @@ -2177,10 +2196,12 @@ mod tests {
let tile = s.mapped[&base].pool;
let v = s.value;
assert!(v > 0, "a new tile is mapped");
assert_eq!(s.committed_bytes(), TILE, "its pages are committed");

// decommitted: parked, still mapped, nothing sent to the GPU
s.decommit_range(base, TILE);
assert!(!s.mapped.contains_key(&base));
assert_eq!(s.committed_bytes(), 0, "a parked tile's pages are not committed any more");
assert_eq!(s.parked.get(&base), Some(&tile));
assert!(!s.free.contains(&tile));
assert_eq!(s.value, v, "no tile mapping changed");
Expand Down
8 changes: 8 additions & 0 deletions crates/xcl/src/hle/d3d12x/title_textures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,14 @@ pub fn counts() -> (usize, u64) {
(TEXTURES.lock().unwrap().by_res.len(), UPLOADS.load(Ordering::Relaxed))
}

/// The title textures kept in step that are committed resources of their own (not on shared
/// `vram::Pages` tiles): how many, and their console size in bytes (memory accounting, #2688;
/// the PC resource can take somewhat more).
pub fn committed_bytes() -> (usize, u64) {
let t = TEXTURES.lock().unwrap();
t.by_res.values().chain(t.shadowed.values()).filter(|e| !e.placed).fold((0, 0), |(n, b), e| (n + 1, b + e.tex.size()))
}

/// Whether a non-depth render target / UAV texture is small enough to be a CPU-filled glyph or UI
/// atlas (`<= 1M` pixels, up to `2048` on either axis, e.g. a retail title's `2048x128` R8 glyph cache).
fn is_small_cpu_filled_target(w: u64, h: u32, samples: u32, flags: u32) -> bool {
Expand Down
8 changes: 8 additions & 0 deletions crates/xcl/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,14 @@ pub fn host_main(boot_path: &Path) -> i32 {
mb(pools as u64),
mb(pools_mapped as u64)
);
// the same against DXGI's budget, by owner, with what XCL does not count (#2688)
let snapshot = crate::hle::d3d12x::memory_report::snapshot();
crate::xlog_info!("{}", snapshot.line());
// (kept for the end-of-run table in report.json)
crate::hle::d3d12x::memory_report::note(&snapshot, crate::log::uptime());
if let Some(line) = crate::hle::d3d12x::memory_report::census_line() {
crate::xlog_info!("{line}");
}
last = now;
}
});
Expand Down
Loading
Loading