diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index cde3561492..f56c01357d 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -454,7 +454,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 3f31c48b43..bbe34738ea 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -415,7 +415,7 @@ unsafe fn argument_order_buffer(list: &ID3D12GraphicsCommandList) -> Option Option Option { @@ -2385,7 +2385,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() { @@ -3116,7 +3116,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 = LISTS.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 new file mode 100644 index 0000000000..704b06c1b3 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -0,0 +1,381 @@ +//! 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) + ) + } +} + +/// 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 { + 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 + } +} + +/// 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(); + 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 }, + ]; + 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::*; + + /// 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); + // 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 + 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()); + } + } + + /// 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/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 8886624632..635fc193dc 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -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; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d47e67841e..bd69fcee59 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -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); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..f05cf9928e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -172,6 +172,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/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6fa76b4cbf..b900ef75f8 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -196,7 +196,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 b7560f861e..01de714874 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -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 @@ -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::() * 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. @@ -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)); @@ -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; @@ -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)); @@ -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"); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6d97bc6e4e..8843906448 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -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 { diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 444333d891..8c3c22494a 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -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; } }); 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(),