From 73a39337f5df7cb2adfa91d1f5ca6ee7f8d88023 Mon Sep 17 00:00:00 2001 From: joeypercia Date: Wed, 25 Nov 2026 22:35:43 -0800 Subject: [PATCH 1/8] D3D12.X: a memory line by owner, against DXGI's budget What the video memory in use is made of could not be told from the XCL_ACTIVITY memory line: it gives no budget, and three of XCL's owners (#2688, workstream 1). memory_report::snapshot() takes the process's commit, and DXGI's local and non-local usage with their budgets, and XCL's parts of each: - commit: the UMA coherent window, and the CPU copy of mapped sparse tiles (a title page in a sparse window is committed on the CPU too); - video memory: target pages and the free part of their pools, arenas, mapped sparse tiles, free sparse pools, retired sparse pools (counted now: sparse::retired_bytes), and title textures that are committed resources of their own (title_textures::committed_bytes, console size). What each total holds besides them is its own part, "other". XCL_ACTIVITY logs it as a line of its own after the memory line, which stays as it was (scripts/smoke.ps1 and the integration branches' tools read it). Part of #2688. Assisted-by: Claude Code (Claude Opus 5.5) --- crates/xcl/src/hle/d3d12x/memory_report.rs | 241 ++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 7 + crates/xcl/src/hle/d3d12x/sparse.rs | 21 ++ crates/xcl/src/hle/d3d12x/title_textures.rs | 8 + crates/xcl/src/host.rs | 2 + 6 files changed, 280 insertions(+) create mode 100644 crates/xcl/src/hle/d3d12x/memory_report.rs diff --git a/crates/xcl/src/hle/d3d12x/memory_report.rs b/crates/xcl/src/hle/d3d12x/memory_report.rs new file mode 100644 index 0000000000..baa1e91f7b --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -0,0 +1,241 @@ +//! Where XCL's memory goes: the parts it knows of, against what Windows and DXGI report (#2688, +//! workstream 1). One snapshot holds the process's commit, the adapter's local (video) and +//! non-local (system) memory in use against their budgets, and XCL's owners of each. What the +//! owners don't cover is shown as its own part: the title's own resources, the driver, and +//! whatever XCL doesn't count yet. + +/// Which memory a part takes. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Kind { + /// the adapter's own memory (DXGI local segment) + Video, + /// system memory the GPU reads (DXGI non-local segment: upload and readback heaps) + NonLocal, + /// the process's commit + Commit, +} + +/// One owner's bytes. +#[derive(Clone, Debug, PartialEq)] +pub struct Part { + pub owner: &'static str, + pub kind: Kind, + pub bytes: u64, +} + +/// What DXGI reports for one segment group. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Segment { + pub usage: u64, + pub budget: u64, +} + +#[derive(Clone, Debug, Default)] +pub struct Snapshot { + /// the process's committed bytes (`PrivateUsage`; None where it reads 0: Wine leaves it so) + pub commit: Option, + /// None: no device or DXGI did not answer + pub local: Option, + pub non_local: Option, + pub parts: Vec, +} + +impl Snapshot { + /// The bytes of the parts of `kind`. + pub fn counted(&self, kind: Kind) -> u64 { + self.parts.iter().filter(|p| p.kind == kind).map(|p| p.bytes).sum() + } + + /// What the total of `kind` holds besides the parts XCL counts (negative when the parts are + /// more than the total: a part counted on the wrong side, or memory not made yet). + pub fn other(&self, kind: Kind) -> Option { + let total = match kind { + Kind::Video => self.local?.usage, + Kind::NonLocal => self.non_local?.usage, + Kind::Commit => self.commit?, + }; + Some(total as i64 - self.counted(kind) as i64) + } + + /// One log line: each total, its budget, its parts and what is left (MB). + pub fn line(&self) -> String { + let mb = |b: u64| b >> 20; + let smb = |b: i64| b >> 20; + let parts = |kind: Kind| { + let mut s: Vec = self.parts.iter().filter(|p| p.kind == kind).map(|p| format!("{} {}", p.owner, mb(p.bytes))).collect(); + if let Some(o) = self.other(kind) { + s.push(format!("other {}", smb(o))); + } + s.join(", ") + }; + let segment = |name: &str, seg: Option, kind: Kind| match seg { + Some(g) => format!("{name} {} of a {} budget ({})", mb(g.usage), mb(g.budget), parts(kind)), + None => format!("{name} unknown ({})", parts(kind)), + }; + format!( + // (not "memory: N MB committed": the line `scripts/smoke.ps1` reads stays as it is) + "memory by owner (MB): commit {} ({}); {}; {}", + self.commit.map_or("unknown".into(), |c| mb(c).to_string()), + parts(Kind::Commit), + segment("video memory", self.local, Kind::Video), + segment("non-local", self.non_local, Kind::NonLocal) + ) + } +} + +/// The process's committed bytes, or None where `PrivateUsage` reads 0 (Wine leaves it so; #1097 +/// and #2362 read the commit there another way). +fn process_commit() -> Option { + unsafe { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; + let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); + c.cb = std::mem::size_of_val(&c) as u32; + K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb); + Some(c.PrivateUsage as u64).filter(|&n| n != 0) + } +} + +/// What DXGI reports for the device's adapter: (local, non-local), or None without a device. +fn video_memory() -> Option<(Segment, Segment)> { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::ID3D12Device; + use windows::Win32::Graphics::Dxgi::*; + let raw = super::real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }?; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter3 = factory.EnumAdapterByLuid(dev.GetAdapterLuid()).ok()?; + let query = |group| { + let mut i = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + adapter.QueryVideoMemoryInfo(0, group, &mut i).ok().map(|_| Segment { usage: i.CurrentUsage, budget: i.Budget }) + }; + Some((query(DXGI_MEMORY_SEGMENT_GROUP_LOCAL)?, query(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)?)) + } +} + +/// The commit Windows charges for the process's D3D12 heaps: what DXGI counts in both segments, +/// less the coherent window D3D12 imported (`imported`: CPU memory, already committed as such); +/// 0 when unknown. +fn heap_charge(local: Option, non_local: Option, imported: u64) -> u64 { + match (local, non_local) { + (Some(l), Some(n)) => (l.usage + n.usage).saturating_sub(imported), + _ => 0, + } +} + +/// Where DXGI counts memory the GPU reads from system memory: the non-local segment, or on an +/// adapter with one segment (no non-local budget: an integrated GPU) the local one. +fn uma_segment(non_local: Option) -> Kind { + if non_local.is_some_and(|n| n.budget > 0) { + Kind::NonLocal + } else { + Kind::Video + } +} + +/// Now. +pub fn snapshot() -> Snapshot { + let (pages, page_pools) = super::vram::page_bytes(); + let (arenas, _) = super::vram::arena_bytes(); + let (pools, mapped) = super::sparse::pool_bytes(); + let (_, committed_textures) = super::title_textures::committed_bytes(); + let (local, non_local) = video_memory().map_or((None, None), |(l, n)| (Some(l), Some(n))); + let uma = crate::gpu::uma::get().map_or(0, |u| u.size() as u64); + // (what of it D3D12 has imported, which DXGI counts: none if the import failed) + let imported = super::real::uma_imported_bytes(); + let b = |n: usize| n as u64; + let parts = vec![ + // the title's memory in the coherent window: committed once, the GPU reads it there + Part { owner: "UMA window", kind: Kind::Commit, bytes: uma }, + // a title page in a sparse window is committed on the CPU as well as mapped to a tile + Part { owner: "sparse CPU copy", kind: Kind::Commit, bytes: b(super::sparse::committed_bytes()) }, + // Windows charges the process's D3D12 heaps to its commit as well, local and non-local + // alike (1 GiB heap: +1 GiB of commit, on an RTX 4070 Ti and an RDNA2 iGPU) – all DXGI + // counts but the coherent window, which is CPU memory imported and committed once + Part { owner: "D3D12 heaps", kind: Kind::Commit, bytes: heap_charge(local, non_local, imported) }, + Part { owner: "placed texture pages", kind: Kind::Video, bytes: b(pages) }, + Part { owner: "placed texture pools free", kind: Kind::Video, bytes: b(page_pools.saturating_sub(pages)) }, + Part { owner: "arenas", kind: Kind::Video, bytes: b(arenas) }, + Part { owner: "sparse tiles", kind: Kind::Video, bytes: b(mapped) }, + Part { owner: "sparse pools free", kind: Kind::Video, bytes: b(pools.saturating_sub(mapped)) }, + Part { owner: "sparse pools retired", kind: Kind::Video, bytes: b(super::sparse::retired_bytes()) }, + Part { owner: "committed textures", kind: Kind::Video, bytes: committed_textures }, + // the GPU reads the coherent window (imported, `OpenExistingHeapFromAddress`) as system + // memory: DXGI counts it in the non-local segment of a card (an RTX 4070 Ti and an + // RX 7800 XT), and in the local one of an integrated GPU, whose only segment that is + // (no non-local budget) + Part { owner: "UMA window", kind: uma_segment(non_local), bytes: imported }, + ]; + Snapshot { commit: process_commit(), local, non_local, parts } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The rest of each total is its total less its parts, a part is counted on its side only, + /// and the line shows every part, each total against its budget, and the rest. + #[test] + fn the_rest_is_the_total_less_the_parts() { + const M: u64 = 1 << 20; + let s = Snapshot { + commit: Some(10_000 * M), + local: Some(Segment { usage: 9_000 * M, budget: 11_000 * M }), + non_local: Some(Segment { usage: 300 * M, budget: 16_000 * M }), + parts: vec![ + Part { owner: "UMA window", kind: Kind::Commit, bytes: 4_096 * M }, + Part { owner: "placed texture pages", kind: Kind::Video, bytes: 5_000 * M }, + Part { owner: "arenas", kind: Kind::Video, bytes: 1_000 * M }, + Part { owner: "upload staging", kind: Kind::NonLocal, bytes: 400 * M }, + ], + }; + assert_eq!(s.counted(Kind::Video), 6_000 * M); + assert_eq!(s.other(Kind::Video), Some((3_000 * M) as i64)); + assert_eq!(s.other(Kind::Commit), Some((5_904 * M) as i64)); + // more counted than DXGI reports: a negative rest, not a wrap + assert_eq!(s.other(Kind::NonLocal), Some(-((100 * M) as i64))); + assert_eq!( + s.line(), + "memory by owner (MB): commit 10000 (UMA window 4096, other 5904); video memory 9000 of a 11000 budget (placed texture pages 5000, arenas 1000, other 3000); non-local 300 of a 16000 budget (upload staging 400, other -100)" + ); + // the coherent window: non-local on a card, local on a GPU of one segment + assert_eq!(uma_segment(Some(Segment { usage: 0, budget: 16_000 * M })), Kind::NonLocal); + assert_eq!(uma_segment(Some(Segment { usage: 0, budget: 0 })), Kind::Video); + assert_eq!(uma_segment(None), Kind::Video); + // the heaps' charge to the commit: both segments less the coherent window + let (l, n) = (Some(Segment { usage: 9_000 * M, budget: 1 }), Some(Segment { usage: 4_500 * M, budget: 1 })); + assert_eq!(heap_charge(l, n, 4_096 * M), 9_404 * M); + assert_eq!(heap_charge(l, None, 4_096 * M), 0); + assert_eq!(heap_charge(Some(Segment { usage: 100 * M, budget: 1 }), n, 8_000 * M), 0, "never below 0"); + // a window whose import failed is not in DXGI's usage: nothing of it is taken off + assert_eq!(heap_charge(Some(Segment { usage: 3_000 * M, budget: 1 }), Some(Segment { usage: 0, budget: 1 }), 0), 3_000 * M); + let unknown = Snapshot { commit: None, local: None, non_local: None, ..s }; + assert_eq!(unknown.other(Kind::Video), None); + // a commit that reads 0 (Wine) is unknown, not 0 with a negative rest + assert_eq!(unknown.other(Kind::Commit), None); + assert!(unknown.line().starts_with("memory by owner (MB): commit unknown (UMA window 4096)"), "{}", unknown.line()); + assert!(unknown.line().contains("video memory unknown (placed texture pages 5000, arenas 1000)"), "{}", unknown.line()); + } + + /// On a device the snapshot has DXGI's totals with a budget, the process's commit, and every + /// owner. + #[test] + fn a_snapshot_on_the_device_has_its_budget_and_owners() { + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let s = snapshot(); + // (an integrated GPU has one segment: its non-local budget is 0) + assert!(s.non_local.is_some(), "{}", s.line()); + assert!(s.local.expect("local video memory").budget > 0, "{}", s.line()); + // (`PrivateUsage` reads 0 under Wine: the commit is unknown there, and the line says so) + match s.commit { + Some(c) => assert!(c > 0), + None => assert!(s.line().contains("commit unknown"), "{}", s.line()), + } + for owner in ["UMA window", "sparse CPU copy", "D3D12 heaps", "placed texture pages", "placed texture pools free", "arenas", "sparse tiles", "sparse pools free", "sparse pools retired", "committed textures"] { + assert!(s.parts.iter().any(|p| p.owner == owner), "{owner} missing: {}", s.line()); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index bbfa841051..7cddaae6fb 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -34,6 +34,7 @@ pub mod layout; pub mod list_x; mod look_stats; mod lut3d; +pub mod memory_report; pub mod null; mod placements; pub mod present; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9c618fa178..ed03bdb577 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -186,6 +186,13 @@ pub fn abi_root_signature() -> Option { static UMA_BUFFER: Mutex> = Mutex::new(Vec::new()); /// the committed UMA windows opened as D3D12 heaps (indexed by window `k`; `None` for sparse windows) static UMA_HEAPS: Mutex>> = 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); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b52ee4ce25..0489915f60 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -944,6 +944,18 @@ pub fn pool_bytes() -> (usize, usize) { let quarantined: usize = s.quarantined.iter().map(|b| b.tiles.len()).sum(); (pools, pools.saturating_sub((s.free.len() + s.cooling.len() + quarantined) * 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 @@ -1277,6 +1289,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::() * PAGE + } + /// Pools whose every tile is free again (cooled, `COOL`) 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. @@ -5737,10 +5756,12 @@ mod tests { assert!(s.pending.is_empty()); 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"); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 990dc67f05..dbad053a83 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -456,6 +456,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 { diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 9904da067f..bdc323504c 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -190,6 +190,8 @@ pub fn host_main(boot_path: &Path) -> i32 { if let Some(over) = crate::hle::d3d12x::real::over_video_budget(local, budget) { crate::xlog_warn!("video memory: {} MB in use, {} MB over the budget of {} MB Windows gives this process", mb(local), mb(over), mb(budget)); } + // the same against DXGI's budget, by owner, with what XCL does not count (#2688) + crate::xlog_info!("{}", crate::hle::d3d12x::memory_report::snapshot().line()); last = now; } }); From 2c4a79e3b794d97561e5ad02be8ec18ec8b3df55 Mon Sep 17 00:00:00 2001 From: joeypercia Date: Thu, 26 Nov 2026 01:09:38 -0800 Subject: [PATCH 2/8] D3D12.X: count the resources XCL makes for itself, by where it makes them XCL's buffers sized per list or per submit (copy scratch, fill patterns, readbacks, upload staging, ...) were not in the memory line, so memory that grows with the title's submits could not be told apart from the title's own (#2688, workstream 1). resource_census::track gives a resource XCL made a small COM object as private data; D3D12 releases it with the resource, which takes it off its place's count. The eleven places XCL makes committed resources at run time are tracked. Each place's bytes are a part of the memory line, and a line of its own gives how many of each are alive and made. Part of #2688. Stacked on #2697. Assisted-by: Claude Code (Claude Opus 5.5) --- crates/xcl/src/gpu/texture.rs | 2 +- crates/xcl/src/hle/d3d12x/bind.rs | 2 +- crates/xcl/src/hle/d3d12x/list_x.rs | 8 +- crates/xcl/src/hle/d3d12x/memory_report.rs | 26 +++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/present.rs | 2 +- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 2 +- crates/xcl/src/hle/d3d12x/resource_census.rs | 197 ++++++++++++++++++ crates/xcl/src/hle/d3d12x/sparse.rs | 6 +- crates/xcl/src/host.rs | 3 + 10 files changed, 238 insertions(+), 11 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/resource_census.rs diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index a1e0531ce4..081b8c48dc 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -334,7 +334,7 @@ unsafe fn buffer(dev: &ID3D12Device, size: u64) -> Result = 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 { diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index f2a771ee06..c6c0b622c5 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -2482,7 +2482,7 @@ unsafe fn argument_order_buffer(list: &ID3D12GraphicsCommandList) -> Option Option Option { @@ -2808,7 +2808,7 @@ unsafe fn pattern_buffer(list: *mut c_void, pat: [u8; 16], n: u64) -> Option = 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() { @@ -3636,7 +3636,7 @@ unsafe fn predication_buffer(list: *mut c_void) -> Option { }; let mut buf: Option = 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(); diff --git a/crates/xcl/src/hle/d3d12x/memory_report.rs b/crates/xcl/src/hle/d3d12x/memory_report.rs index baa1e91f7b..ea7868e31a 100644 --- a/crates/xcl/src/hle/d3d12x/memory_report.rs +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -133,6 +133,11 @@ fn uma_segment(non_local: Option) -> Kind { } } +/// Where DXGI counts a census part: system memory as `uma_segment` puts it, the rest local. +fn census_kind(kind: Kind, non_local: Option) -> Kind { + if kind == Kind::NonLocal { uma_segment(non_local) } else { kind } +} + /// Now. pub fn snapshot() -> Snapshot { let (pages, page_pools) = super::vram::page_bytes(); @@ -166,9 +171,24 @@ pub fn snapshot() -> Snapshot { // (no non-local budget) Part { owner: "UMA window", kind: uma_segment(non_local), bytes: imported }, ]; + let mut parts = parts; + // the resources XCL makes for itself, by where (`resource_census`) + // (in system memory – upload, readback – is non-local only where the adapter has such a + // segment: on an integrated GPU it is local, as the coherent window) + parts.extend(super::resource_census::counts().into_iter().filter(|(_, _, c)| c.bytes > 0).map(|(site, kind, c)| Part { owner: site, kind: census_kind(kind, non_local), bytes: c.bytes })); Snapshot { commit: process_commit(), local, non_local, parts } } +/// The resources XCL makes for itself, by where: alive / made, and MB; None before any. +pub fn census_line() -> Option { + let counts = super::resource_census::counts(); + if counts.is_empty() { + return None; + } + let parts: Vec = counts.iter().map(|(site, _, c)| format!("{site} {} of {} made, {} MB", c.live, c.made, c.bytes >> 20)).collect(); + Some(format!("memory: XCL's own resources (alive): {}", parts.join("; "))) +} + #[cfg(test)] mod tests { use super::*; @@ -209,6 +229,12 @@ mod tests { assert_eq!(heap_charge(Some(Segment { usage: 100 * M, budget: 1 }), n, 8_000 * M), 0, "never below 0"); // a window whose import failed is not in DXGI's usage: nothing of it is taken off assert_eq!(heap_charge(Some(Segment { usage: 3_000 * M, budget: 1 }), Some(Segment { usage: 0, budget: 1 }), 0), 3_000 * M); + // a census part in system memory follows it; one in video memory stays there + let card = Some(Segment { usage: 0, budget: 16_000 * M }); + let one_segment = Some(Segment { usage: 0, budget: 0 }); + assert_eq!(census_kind(Kind::NonLocal, card), Kind::NonLocal); + assert_eq!(census_kind(Kind::NonLocal, one_segment), Kind::Video); + assert_eq!(census_kind(Kind::Video, card), Kind::Video); let unknown = Snapshot { commit: None, local: None, non_local: None, ..s }; assert_eq!(unknown.other(Kind::Video), None); // a commit that reads 0 (Wine) is unknown, not 0 with a negative rest diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 7cddaae6fb..fb30dece74 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -38,6 +38,7 @@ 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; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d6daec1221..e4a39c4f9b 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -1399,7 +1399,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); diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 57428482ae..bf8ebdf311 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -263,7 +263,7 @@ unsafe fn scratch_buffer(dev: &ID3D12Device, bytes: u64) -> Option> = 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 = 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, site: &'static str) -> Option { + 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 = 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); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 0489915f60..f964a788af 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1739,7 +1739,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)); @@ -1766,7 +1766,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; @@ -1793,7 +1793,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)); diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index bdc323504c..61c2a8d8bf 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -192,6 +192,9 @@ pub fn host_main(boot_path: &Path) -> i32 { } // the same against DXGI's budget, by owner, with what XCL does not count (#2688) crate::xlog_info!("{}", crate::hle::d3d12x::memory_report::snapshot().line()); + if let Some(line) = crate::hle::d3d12x::memory_report::census_line() { + crate::xlog_info!("{line}"); + } last = now; } }); From 2f7b2210509ee4b2562c59af90665f457724f102 Mon Sep 17 00:00:00 2001 From: joeypercia Date: Thu, 26 Nov 2026 03:24:37 -0800 Subject: [PATCH 3/8] D3D12.X: report.json keeps the memory by owner at its peak and at the end The XCL_ACTIVITY line by owner was only in the log, so comparing runs meant reading logs (#2688, workstream 1: an end-of-run table). The activity thread keeps each snapshot it logs (memory_report::note): the last one, and the one where video memory in use was highest. report.json gets them as memory_by_owner (MB: totals, budgets, XCL's parts and the rest of each total, with the second of the run). The report takes what was kept and makes no DXGI call, which a crash report may make from any thread. Without XCL_ACTIVITY there is no table. Part of #2688. Stacked on #2750. Assisted-by: Claude Code (Claude Opus 5.5) --- crates/xcl/src/hle/d3d12x/memory_report.rs | 114 +++++++++++++++++++++ crates/xcl/src/host.rs | 5 +- crates/xcl/src/report.rs | 5 + 3 files changed, 123 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/memory_report.rs b/crates/xcl/src/hle/d3d12x/memory_report.rs index ea7868e31a..704b06c1b3 100644 --- a/crates/xcl/src/hle/d3d12x/memory_report.rs +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -83,6 +83,75 @@ impl Snapshot { } } +/// A snapshot as `report.json` keeps it (MB), with the second of the run it was taken at. +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Record { + pub seconds: f64, + pub commit_mb: Option, + pub video_mb: Option, + pub video_budget_mb: Option, + pub non_local_mb: Option, + pub non_local_budget_mb: Option, + /// XCL's parts: (owner, "commit" / "video" / "non-local", MB) + pub parts: Vec<(String, String, u64)>, + /// what each total holds besides the parts (MB; absent where the total is unknown) + pub other_mb: std::collections::BTreeMap, +} + +impl Snapshot { + /// This snapshot, taken at `seconds`, as `report.json` keeps it. + pub fn record(&self, seconds: f64) -> Record { + let mb = |b: u64| b >> 20; + let name = |k: Kind| match k { + Kind::Commit => "commit", + Kind::Video => "video", + Kind::NonLocal => "non-local", + }; + Record { + seconds, + commit_mb: self.commit.map(mb), + video_mb: self.local.map(|s| mb(s.usage)), + video_budget_mb: self.local.map(|s| mb(s.budget)), + non_local_mb: self.non_local.map(|s| mb(s.usage)), + non_local_budget_mb: self.non_local.map(|s| mb(s.budget)), + parts: self.parts.iter().map(|p| (p.owner.to_string(), name(p.kind).to_string(), mb(p.bytes))).collect(), + other_mb: [Kind::Commit, Kind::Video, Kind::NonLocal].into_iter().filter_map(|k| self.other(k).map(|o| (name(k).to_string(), o >> 20))).collect(), + } + } +} + +/// The end-of-run table of `report.json`: the last snapshot the run took and the one where video +/// memory in use was highest (`XCL_ACTIVITY` takes one every 2 s; without it there are none). +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Table { + pub last: Option, + pub peak_video: Option, + /// the video memory in use of `peak_video`, in bytes as DXGI read it (None where unknown): + /// the peak is chosen on these, not on the MB, and a known reading ranks above an unknown one + #[serde(skip)] + peak_video_bytes: Option, +} + +static TABLE: std::sync::Mutex = std::sync::Mutex::new(Table { last: None, peak_video: None, peak_video_bytes: None }); + +/// Keep `s`, taken at `seconds`, for the end-of-run table. +pub fn note(s: &Snapshot, seconds: f64) { + let r = s.record(seconds); + let mut t = TABLE.lock().unwrap_or_else(|e| e.into_inner()); + let bytes = s.local.map(|g| g.usage); + if t.peak_video.is_none() || bytes > t.peak_video_bytes { + t.peak_video = Some(r.clone()); + t.peak_video_bytes = bytes; + } + t.last = Some(r); +} + +/// The table for `report.json` (taken from what `note` kept: no DXGI call here, which a crash +/// report may make from any thread). +pub fn table() -> Table { + TABLE.try_lock().map(|t| t.clone()).unwrap_or_default() +} + /// The process's committed bytes, or None where `PrivateUsage` reads 0 (Wine leaves it so; #1097 /// and #2362 read the commit there another way). fn process_commit() -> Option { @@ -264,4 +333,49 @@ mod tests { assert!(s.parts.iter().any(|p| p.owner == owner), "{owner} missing: {}", s.line()); } } + + /// A snapshot's record keeps its totals, budgets, parts and rests in MB; the table keeps the + /// last one and the one of most video memory; a record survives a JSON round trip. + #[test] + fn the_table_keeps_the_last_snapshot_and_the_peak_of_video_memory() { + const M: u64 = 1 << 20; + let snap = |video: u64, commit: u64| Snapshot { + commit: Some(commit * M), + local: Some(Segment { usage: video * M, budget: 10_000 * M }), + non_local: Some(Segment { usage: 500 * M, budget: 16_000 * M }), + parts: vec![Part { owner: "placed texture pages", kind: Kind::Video, bytes: 3_000 * M }, Part { owner: "UMA window", kind: Kind::Commit, bytes: 4_096 * M }], + }; + let r = snap(9_000, 20_000).record(12.5); + assert_eq!((r.seconds, r.commit_mb, r.video_mb, r.video_budget_mb, r.non_local_mb), (12.5, Some(20_000), Some(9_000), Some(10_000), Some(500))); + assert_eq!(r.parts, vec![("placed texture pages".into(), "video".into(), 3_000), ("UMA window".into(), "commit".into(), 4_096)]); + assert_eq!(r.other_mb.get("video"), Some(&6_000)); + assert_eq!(r.other_mb.get("commit"), Some(&15_904)); + assert_eq!(r.other_mb.get("non-local"), Some(&500)); + let back: Record = serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap(); + assert_eq!(back, r); + // (the module's table: its own, as `note` fills it) + *TABLE.lock().unwrap() = Table::default(); + note(&snap(9_000, 20_000), 10.0); + note(&snap(12_000, 25_000), 20.0); + note(&snap(11_000, 26_000), 30.0); + let t = table(); + assert_eq!(t.peak_video.as_ref().map(|r| (r.seconds, r.video_mb)), Some((20.0, Some(12_000)))); + assert_eq!(t.last.as_ref().map(|r| (r.seconds, r.commit_mb)), Some((30.0, Some(26_000)))); + // two readings within one MB: the peak is the higher one in bytes, with its own parts + *TABLE.lock().unwrap() = Table::default(); + let with_usage = |usage: u64, commit: u64| Snapshot { local: Some(Segment { usage, budget: 10_000 * M }), ..snap(0, commit) }; + note(&with_usage(100 * M, 20_000), 10.0); + note(&with_usage(100 * M + 1_023, 21_000), 20.0); + note(&with_usage(100 * M + 1_000, 22_000), 30.0); + let t = table(); + assert_eq!(t.peak_video.as_ref().map(|r| (r.seconds, r.video_mb, r.commit_mb)), Some((20.0, Some(100), Some(21_000)))); + // a known reading, even under 1 MB, ranks above an earlier unknown one + *TABLE.lock().unwrap() = Table::default(); + note(&Snapshot { local: None, ..snap(0, 20_000) }, 10.0); + note(&with_usage(512 * 1_024, 21_000), 20.0); + note(&Snapshot { local: None, ..snap(0, 22_000) }, 30.0); + let t = table(); + assert_eq!(t.peak_video.as_ref().map(|r| (r.seconds, r.video_mb)), Some((20.0, Some(0)))); + *TABLE.lock().unwrap() = Table::default(); + } } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 61c2a8d8bf..56c3686ca4 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -191,7 +191,10 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::xlog_warn!("video memory: {} MB in use, {} MB over the budget of {} MB Windows gives this process", mb(local), mb(over), mb(budget)); } // the same against DXGI's budget, by owner, with what XCL does not count (#2688) - crate::xlog_info!("{}", crate::hle::d3d12x::memory_report::snapshot().line()); + 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}"); } diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 45b886e103..5491bfe50f 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -79,6 +79,10 @@ pub struct Report { /// `XCL_DSTORAGE_BCPACK_FILL` #[serde(default)] pub dstorage: crate::hle::dstorage::DStorageStats, + /// memory by owner against DXGI's budget, as the `XCL_ACTIVITY` line gives it: the last + /// snapshot of the run and the one of most video memory (#2688) + #[serde(default)] + pub memory_by_owner: crate::hle::d3d12x::memory_report::Table, pub notes: Vec, } @@ -146,6 +150,7 @@ pub fn build() -> Report { audio: crate::hle::xaudio2::stats(), xgameruntime: crate::hle::xgameruntime::api::stats(), dstorage: crate::hle::dstorage::stats(), + memory_by_owner: crate::hle::d3d12x::memory_report::table(), notes: vec![ "D3D12.X methods missing on PC show up in called_stubs as '::#slot (not on PC)'.".into(), "Console-format shaders are replaced (fallback_pipelines) until the RDNA2 recompiler is finished.".into(), From fda797314bef994e7b9d0cc1f881c52c769b1d97 Mon Sep 17 00:00:00 2001 From: pr1sm-dev <29008292+pr1sm-dev@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:57:51 -0800 Subject: [PATCH 4/8] D3D12.X: the memory line by owner has the two-pass buffers The mesh draws' two-pass buffers are committed UAV buffers XCL makes for itself, up to XCL_TWO_PASS_MB alive (1024 MiB by default). The line by owner (#2688) left them in other. The row reads the count the buffers' own cap already keeps. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/bind.rs | 6 ++++++ crates/xcl/src/hle/d3d12x/memory_report.rs | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index c6c0b622c5..afbb971218 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -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) { diff --git a/crates/xcl/src/hle/d3d12x/memory_report.rs b/crates/xcl/src/hle/d3d12x/memory_report.rs index 704b06c1b3..6c4ab5c2b9 100644 --- a/crates/xcl/src/hle/d3d12x/memory_report.rs +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -234,6 +234,9 @@ pub fn snapshot() -> Snapshot { Part { owner: "sparse pools free", kind: Kind::Video, bytes: b(pools.saturating_sub(mapped)) }, Part { owner: "sparse pools retired", kind: Kind::Video, bytes: b(super::sparse::retired_bytes()) }, Part { owner: "committed textures", kind: Kind::Video, bytes: committed_textures }, + // the mesh draws' two-pass buffers: committed UAV buffers of XCL's own, up to + // `XCL_TWO_PASS_MB` of them alive (in use, kept for reuse, waiting for allocator resets) + Part { owner: "two-pass buffers", kind: Kind::Video, bytes: super::bind::two_pass_bytes() }, // the GPU reads the coherent window (imported, `OpenExistingHeapFromAddress`) as system // memory: DXGI counts it in the non-local segment of a card (an RTX 4070 Ti and an // RX 7800 XT), and in the local one of an integrated GPU, whose only segment that is @@ -329,7 +332,7 @@ mod tests { Some(c) => assert!(c > 0), None => assert!(s.line().contains("commit unknown"), "{}", s.line()), } - for owner in ["UMA window", "sparse CPU copy", "D3D12 heaps", "placed texture pages", "placed texture pools free", "arenas", "sparse tiles", "sparse pools free", "sparse pools retired", "committed textures"] { + for owner in ["UMA window", "sparse CPU copy", "D3D12 heaps", "placed texture pages", "placed texture pools free", "arenas", "sparse tiles", "sparse pools free", "sparse pools retired", "committed textures", "two-pass buffers"] { assert!(s.parts.iter().any(|p| p.owner == owner), "{owner} missing: {}", s.line()); } } From 744c14196a6eaeaf8dc1aff7fe5f593f16b17d02 Mon Sep 17 00:00:00 2001 From: pr1sm-dev <29008292+pr1sm-dev@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:48:25 -0800 Subject: [PATCH 5/8] D3D12.X: the census counts sparse readback jobs and texture upload jobs Two pooled kinds of buffers XCL makes for itself were not among the census's places (#2688): the readback buffers of the sparse windows' copy-back jobs and the upload buffers of the texture upload jobs (up to 512 MB of them kept free). Both are made on a pool miss only. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/sparse.rs | 2 +- crates/xcl/src/hle/d3d12x/texture_upload.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index f964a788af..42bb0d4ee3 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1945,7 +1945,7 @@ impl State { self.dev .CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut r) .ok()?; - let buf = r?; + let buf = crate::hle::d3d12x::resource_census::tracked(r, "sparse readback jobs")?; let mut p: *mut c_void = std::ptr::null_mut(); buf.Map(0, None, Some(&mut p)).ok()?; Some(RbJob { alloc, list, buf, ptr: p as *mut u8, cap, rb_v: 0, done_v: 0, copies: Vec::new(), ty, fences: None, seq: 0 }) diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index 16e06fd028..95b1efb51d 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -822,7 +822,7 @@ unsafe fn take(dev: &ID3D12Device, bytes: u64) -> Result { &mut buf, ) .map_err(e)?; - let buf = buf.ok_or("texture upload buffer")?; + let buf = crate::hle::d3d12x::resource_census::tracked(buf, "texture upload jobs").ok_or("texture upload buffer")?; let mut p: *mut c_void = std::ptr::null_mut(); buf.Map(0, None, Some(&mut p)).map_err(e)?; Ok(Job { dev: key, alloc, list, buf, ptr: p as *mut u8, bytes: cap }) From ec24e60772d61f33776e867b45c14efd91efa915 Mon Sep 17 00:00:00 2001 From: pr1sm-dev <29008292+pr1sm-dev@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:57:52 -0800 Subject: [PATCH 6/8] D3D12.X: the memory line by owner has the GPU-view tiles apart The mapped pool tiles are the sparse windows' own and those GPU views of the title's memory hold; the line by owner (#2688) had both as sparse tiles. The views' share is the count their cap already keeps: a view tile parked since the last submit, or kept with XCL_VIEW_KEEP, is not in it and stays with the windows' own. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/memory_report.rs | 9 +++++++-- crates/xcl/src/hle/d3d12x/sparse.rs | 11 +++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/memory_report.rs b/crates/xcl/src/hle/d3d12x/memory_report.rs index 6c4ab5c2b9..67e7d797bd 100644 --- a/crates/xcl/src/hle/d3d12x/memory_report.rs +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -212,6 +212,7 @@ pub fn snapshot() -> Snapshot { let (pages, page_pools) = super::vram::page_bytes(); let (arenas, _) = super::vram::arena_bytes(); let (pools, mapped) = super::sparse::pool_bytes(); + let view_tiles = super::sparse::view_tile_bytes(); let (_, committed_textures) = super::title_textures::committed_bytes(); let (local, non_local) = video_memory().map_or((None, None), |(l, n)| (Some(l), Some(n))); let uma = crate::gpu::uma::get().map_or(0, |u| u.size() as u64); @@ -230,7 +231,11 @@ pub fn snapshot() -> Snapshot { Part { owner: "placed texture pages", kind: Kind::Video, bytes: b(pages) }, Part { owner: "placed texture pools free", kind: Kind::Video, bytes: b(page_pools.saturating_sub(pages)) }, Part { owner: "arenas", kind: Kind::Video, bytes: b(arenas) }, - Part { owner: "sparse tiles", kind: Kind::Video, bytes: b(mapped) }, + // the mapped pool tiles: the sparse windows' own, and those GPU views of the title's + // memory hold (read a moment apart: the split can be off by the tiles of one submit; + // a view tile parked since the last submit, or kept, counts with the windows' own) + Part { owner: "sparse tiles", kind: Kind::Video, bytes: b(mapped.saturating_sub(view_tiles)) }, + Part { owner: "GPU-view tiles", kind: Kind::Video, bytes: b(view_tiles.min(mapped)) }, Part { owner: "sparse pools free", kind: Kind::Video, bytes: b(pools.saturating_sub(mapped)) }, Part { owner: "sparse pools retired", kind: Kind::Video, bytes: b(super::sparse::retired_bytes()) }, Part { owner: "committed textures", kind: Kind::Video, bytes: committed_textures }, @@ -332,7 +337,7 @@ mod tests { Some(c) => assert!(c > 0), None => assert!(s.line().contains("commit unknown"), "{}", s.line()), } - for owner in ["UMA window", "sparse CPU copy", "D3D12 heaps", "placed texture pages", "placed texture pools free", "arenas", "sparse tiles", "sparse pools free", "sparse pools retired", "committed textures", "two-pass buffers"] { + for owner in ["UMA window", "sparse CPU copy", "D3D12 heaps", "placed texture pages", "placed texture pools free", "arenas", "sparse tiles", "sparse pools free", "sparse pools retired", "committed textures", "two-pass buffers", "GPU-view tiles"] { assert!(s.parts.iter().any(|p| p.owner == owner), "{owner} missing: {}", s.line()); } } diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 42bb0d4ee3..e33808b00c 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -956,6 +956,17 @@ pub fn retired_bytes() -> usize { pub fn committed_bytes() -> usize { lock_state().as_ref().map_or(0, |s| s.committed_bytes()) } + +/// Bytes of the pool tiles that GPU views of the title's memory hold now (`mirrored`): a part of +/// `pool_bytes`' mapped bytes (memory accounting, #2688). The rest is the windows' own tiles, +/// and the view tiles `mirrored` no longer counts while they still hold a pool tile: those +/// parked since the last submit, and those kept with `XCL_VIEW_KEEP`. +pub fn view_tile_bytes() -> usize { + let g = lock_state(); + let _held = holding(Holder::Other); + g.as_ref().map_or(0, |s| s.mirrored * TILE) +} + /// 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 From fa74f7d091a8d80b424c2fcc741f1cb79d119e58 Mon Sep 17 00:00:00 2001 From: pr1sm-dev <29008292+pr1sm-dev@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:57:52 -0800 Subject: [PATCH 7/8] D3D12.X: XCL_ACTIVITY logs the swap chain's size and the pipeline builds What the line by owner (#2688) leaves in other has no count in XCL. Two figures help to read it: the swap chain's back buffers (DXGI makes them; their bytes are computed from their size) and pso_async's pipeline builds so far (finished, failed, pending: counts of the run, not the pipelines alive). One more XCL_ACTIVITY line has them. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/memory_report.rs | 35 ++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/present.rs | 22 ++++++++++++++ crates/xcl/src/host.rs | 3 ++ 3 files changed, 60 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/memory_report.rs b/crates/xcl/src/hle/d3d12x/memory_report.rs index 67e7d797bd..6f37115c88 100644 --- a/crates/xcl/src/hle/d3d12x/memory_report.rs +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -266,6 +266,27 @@ pub fn census_line() -> Option { Some(format!("memory: XCL's own resources (alive): {}", parts.join("; "))) } +/// Two things to read beside "other", which no row holds: the swap chain's back buffers (DXGI +/// makes them, so their bytes are computed from their size, not counted) and `pso_async`'s +/// pipeline builds so far – finished, failed and not finished yet; counts of the run, not the +/// pipelines alive, whose code is the driver's memory. None before there is either. +pub fn beside_line() -> Option { + beside_text(super::present::swap_chain_buffers(), super::pso_async::counts()) +} + +/// `beside_line` of a swap chain (buffers, width, height, bytes a pixel) and the builds' counts +/// (finished, failed, not finished yet). +fn beside_text(swap: Option<(u32, u32, u32, u32)>, (finished, failed, pending): (usize, usize, usize)) -> Option { + if swap.is_none() && finished + failed + pending == 0 { + return None; + } + let swap = match swap { + Some((n, w, h, pixel)) => format!("swap chain {n} buffers of {w}x{h}, about {} MB", (n as u64 * w as u64 * h as u64 * pixel as u64) >> 20), + None => "no swap chain yet".into(), + }; + Some(format!("memory: not in the rows: {swap}; pipeline builds so far: {finished} finished, {failed} failed, {pending} pending")) +} + #[cfg(test)] mod tests { use super::*; @@ -320,6 +341,20 @@ mod tests { assert!(unknown.line().contains("video memory unknown (placed texture pages 5000, arenas 1000)"), "{}", unknown.line()); } + /// The line beside "other": the swap chain's computed bytes and the background builds' + /// counts; nothing before there is either. + #[test] + fn the_line_beside_other_has_the_swap_chain_and_the_builds() { + assert_eq!(beside_text(None, (0, 0, 0)), None); + assert_eq!( + beside_text(Some((3, 3840, 2160, 4)), (1200, 2, 15)).as_deref(), + Some("memory: not in the rows: swap chain 3 buffers of 3840x2160, about 94 MB; pipeline builds so far: 1200 finished, 2 failed, 15 pending") + ); + // an fp16 swap chain takes 8 bytes a pixel + assert!(beside_text(Some((3, 1920, 1080, 8)), (0, 0, 0)).unwrap().contains("about 47 MB")); + assert!(beside_text(None, (1, 0, 0)).unwrap().contains("no swap chain yet; pipeline builds so far: 1 finished,")); + } + /// On a device the snapshot has DXGI's totals with a budget, the process's commit, and every /// owner. #[test] diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index e4a39c4f9b..de51476e66 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -946,6 +946,24 @@ unsafe impl Send for Presenter {} static PRESENTER: Mutex> = 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) } @@ -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; } @@ -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() diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 56c3686ca4..a67135b2f7 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -198,6 +198,9 @@ pub fn host_main(boot_path: &Path) -> i32 { if let Some(line) = crate::hle::d3d12x::memory_report::census_line() { crate::xlog_info!("{line}"); } + if let Some(line) = crate::hle::d3d12x::memory_report::beside_line() { + crate::xlog_info!("{line}"); + } last = now; } }); From 71dad56b13e366dd36a64b14af8defa448a82ed3 Mon Sep 17 00:00:00 2001 From: pr1sm-dev <29008292+pr1sm-dev@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:58:07 -0800 Subject: [PATCH 8/8] README: XCL_ACTIVITY's memory lines by owner Co-Authored-By: Claude Fable 5.2 --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 973a027e86..ce3173bea5 100644 --- a/README.md +++ b/README.md @@ -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