diff --git a/README.md b/README.md index 2d85d6e0bf..ce8eed5255 100644 --- a/README.md +++ b/README.md @@ -324,8 +324,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder is not a whole number is ignored. - `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. + waits, DirectStorage requests), a `memory:` line with the process's commit and video memory in + use, and a `memory by owner` line splitting the known XCL allocations from `other`. A negative + `other` exposes an overlapping or stale sample; unavailable adapter segments say `unknown`. + 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 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..c80f950b41 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -0,0 +1,197 @@ +//! Process and adapter memory against their budgets, split into XCL-owned parts (#2697). + +pub fn enabled() -> bool { + static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); + *ENABLED.get_or_init(|| std::env::var_os("XCL_ACTIVITY").is_some()) +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Kind { + Video, + NonLocal, + Commit, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Part { + pub owner: &'static str, + pub kind: Kind, + pub bytes: u64, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Segment { + pub usage: u64, + pub budget: u64, +} + +#[derive(Clone, Debug, Default)] +pub struct Snapshot { + pub commit: Option, + pub local: Option, + pub non_local: Option, + pub parts: Vec, +} + +impl Snapshot { + pub fn counted(&self, kind: Kind) -> u64 { + self.parts.iter().filter(|p| p.kind == kind).fold(0, |bytes, p| bytes.saturating_add(p.bytes)) + } + + /// A negative remainder exposes aliasing, a stale sample, or a part charged to the wrong side. + 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?, + }; + let difference = i128::from(total) - i128::from(self.counted(kind)); + Some(difference.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64) + } + + pub fn line(&self) -> String { + let mb = |b: u64| b >> 20; + let smb = |b: i64| b / (1 << 20); + let parts = |kind: Kind| { + let mut out: Vec = self.parts.iter().filter(|p| p.kind == kind) + .map(|p| format!("{} {}", p.owner, mb(p.bytes))).collect(); + if let Some(other) = self.other(kind) { + out.push(format!("other {}", smb(other))); + } + out.join(", ") + }; + let segment = |name: &str, value: Option, kind: Kind| match value { + Some(s) => format!("{name} {} of a {} budget ({})", mb(s.usage), mb(s.budget), parts(kind)), + None => format!("{name} unknown ({})", parts(kind)), + }; + let commit = match self.commit { + Some(bytes) => format!("commit {} ({})", mb(bytes), parts(Kind::Commit)), + None => format!("commit unknown ({})", parts(Kind::Commit)), + }; + format!("memory by owner (MB): {commit}; {}; {}", + segment("video memory", self.local, Kind::Video), + segment("non-local", self.non_local, Kind::NonLocal)) + } +} + +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) != 0) + .then(|| u64::try_from(c.PrivateUsage).unwrap_or(u64::MAX)) + } +} + +fn video_memory(raw: *mut std::ffi::c_void) -> (Option, Option) { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::ID3D12Device; + use windows::Win32::Graphics::Dxgi::*; + let Some(dev) = (unsafe { ID3D12Device::from_raw_borrowed(&raw) }) else { return (None, None) }; + unsafe { + let Ok(factory) = CreateDXGIFactory1::() else { return (None, None) }; + let Ok(adapter) = factory.EnumAdapterByLuid::(dev.GetAdapterLuid()) else { return (None, None) }; + 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 }) + }; + (query(DXGI_MEMORY_SEGMENT_GROUP_LOCAL), query(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)) + } +} + +pub fn snapshot() -> Snapshot { + let raw = super::real::device_raw(); + let device = raw as usize; + let (pages, page_pools) = super::vram::page_bytes_for(device); + let arenas = super::vram::arena_bytes_for(device); + let (pools, mapped, retired, sparse_commit) = super::sparse::memory_bytes_for(device); + let (_, committed_textures) = super::title_textures::committed_bytes_for(device); + let (local, non_local) = video_memory(raw); + let uma = crate::gpu::uma::get().map_or(0, |u| u64::try_from(u.size()).unwrap_or(u64::MAX)); + let b = |n: usize| u64::try_from(n).unwrap_or(u64::MAX); + let parts = vec![ + Part { owner: "UMA window", kind: Kind::Commit, bytes: uma }, + Part { owner: "sparse CPU copy", kind: Kind::Commit, bytes: b(sparse_commit) }, + Part { owner: "target pages", kind: Kind::Video, bytes: b(pages) }, + Part { owner: "target 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(retired) }, + Part { owner: "tracked committed sampled textures", kind: Kind::Video, bytes: committed_textures }, + ]; + Snapshot { commit: process_commit(), local, non_local, parts } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn remainder_and_partial_query_failure_are_explicit() { + 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: None, + parts: vec![ + Part { owner: "UMA window", kind: Kind::Commit, bytes: 4_096 * M }, + Part { owner: "target pages", kind: Kind::Video, bytes: 5_000 * M }, + Part { owner: "upload staging", kind: Kind::NonLocal, bytes: 400 * M }, + ], + }; + assert_eq!(s.other(Kind::Video), Some(4_000 * M as i64)); + assert_eq!(s.other(Kind::NonLocal), None); + assert_eq!(s.line(), "memory by owner (MB): commit 10000 (UMA window 4096, other 5904); video memory 9000 of a 11000 budget (target pages 5000, other 4000); non-local unknown (upload staging 400)"); + let over = Snapshot { non_local: Some(Segment { usage: 300 * M, budget: 16_000 * M }), ..s }; + assert_eq!(over.other(Kind::NonLocal), Some(-(100 * M as i64))); + let unknown = Snapshot { commit: None, ..over }; + assert!(unknown.line().contains("commit unknown (UMA window 4096)")); + + let reverse = Snapshot { + local: None, + non_local: Some(Segment { usage: 700 * M, budget: 2_000 * M }), + ..unknown + }; + let line = reverse.line(); + assert!(line.contains("video memory unknown (target pages 5000)"), "{line}"); + assert!(line.contains("non-local 700 of a 2000 budget (upload staging 400, other 300)"), "{line}"); + } + + #[test] + fn signed_remainders_truncate_and_saturate() { + let tiny = Snapshot { + local: Some(Segment { usage: (1 << 20) - 1, budget: 1 << 20 }), + parts: vec![Part { owner: "one MiB", kind: Kind::Video, bytes: 1 << 20 }], + ..Default::default() + }; + assert_eq!(tiny.other(Kind::Video), Some(-1)); + assert!(tiny.line().contains("other 0"), "{}", tiny.line()); + + let large = Snapshot { + commit: Some(0), + parts: vec![ + Part { owner: "large", kind: Kind::Commit, bytes: u64::MAX }, + Part { owner: "saturated", kind: Kind::Commit, bytes: 1 }, + ], + ..Default::default() + }; + assert_eq!(large.counted(Kind::Commit), u64::MAX); + assert_eq!(large.other(Kind::Commit), Some(i64::MIN)); + } + + #[test] + fn device_snapshot_has_budget_and_all_owners() { + if super::super::backend() != super::super::Backend::Real { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let s = snapshot(); + assert!(s.local.expect("local video memory").budget > 0, "{}", s.line()); + assert!(s.commit.is_some()); + for owner in ["UMA window", "sparse CPU copy", "target pages", "target pools free", "arenas", "sparse tiles", "sparse pools free", "sparse pools retired", "tracked committed sampled 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 07fdb94224..9851e31b9a 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -25,6 +25,7 @@ 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 pso_async; diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index bec8a1bcf3..25925c1262 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -447,6 +447,43 @@ 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)) } + +/// Active pool bytes, occupied tile bytes, retired pool bytes, and committed CPU page bytes for +/// `device`, from one state lock so a pool moving to the retired list cannot be counted twice. +pub(super) fn memory_bytes_for(device: usize) -> (usize, usize, usize, usize) { + let g = lock_state(); + let Some(s) = g.as_ref() else { return (0, 0, 0, 0) }; + memory_byte_counts( + device, + s.dev.as_raw() as usize, + s.pools.iter().filter(|p| p.is_some()).count(), + s.free.len(), + s.retired.len(), + s.mapped.values().map(|e| e.holes), + ) +} + +fn memory_byte_counts( + device: usize, + owner: usize, + active_pools: usize, + free_tiles: usize, + retired_pools: usize, + mapped_holes: impl Iterator, +) -> (usize, usize, usize, usize) { + if device != owner { + return (0, 0, 0, 0); + } + let pool_bytes = (POOL_TILES as usize).saturating_mul(TILE); + let pools = active_pools.saturating_mul(pool_bytes); + let occupied = pools.saturating_sub(free_tiles.saturating_mul(TILE)); + let retired = retired_pools.saturating_mul(pool_bytes); + let committed = mapped_holes.fold(0usize, |bytes, holes| { + let pages = PAGES_PER_TILE.saturating_sub(holes.count_ones() as usize); + bytes.saturating_add(pages.saturating_mul(PAGE)) + }); + (pools, occupied, retired, committed) +} /// 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 @@ -1774,6 +1811,17 @@ fn forget_in(s: &mut State, res: usize) { mod tests { use super::*; + #[test] + fn memory_counts_committed_pages_and_separates_devices_and_retired_pools() { + let holes = [0xFFFE, 0xFFF0].into_iter(); // one committed page, then four + let (pools, occupied, retired, committed) = memory_byte_counts(7, 7, 1, 60, 1, holes); + assert_eq!(pools, POOL_TILES as usize * TILE); + assert_eq!(occupied, 4 * TILE, "occupied video tiles are independent of CPU page commitment"); + assert_eq!(retired, POOL_TILES as usize * TILE, "the retired pool is not also active"); + assert_eq!(committed, 5 * PAGE, "holes in a 64 KiB tile do not consume CPU commit"); + assert_eq!(memory_byte_counts(8, 7, 1, 60, 1, [0].into_iter()), (0, 0, 0, 0)); + } + /// `queue()` answers while the state's lock is held: a resource's last `Release` asks for /// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be /// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`). diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ddef51322f..a7f5b07401 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -65,6 +65,8 @@ struct GpuWriter { struct Entry { device: usize, + /// PC allocation size of a committed resource (zero for placed resources and test entries) + committed_bytes: u64, /// the title's address of the texture va: usize, /// where its bytes are read and its CPU writes watched: `va`, or – for a texture in a GPU @@ -310,6 +312,11 @@ impl Table { by_res.get_mut(&res).or_else(|| shadowed.get_mut(&res)) } + fn committed_bytes_for(&self, device: usize) -> (usize, u64) { + self.by_res.values().chain(self.shadowed.values()).filter(|e| e.device == device && !e.placed) + .fold((0usize, 0u64), |(n, bytes), e| (n.saturating_add(1), bytes.saturating_add(e.committed_bytes))) + } + fn overlapping(&self, va: usize, len: usize) -> Vec<(usize, usize)> { self.active_overlaps(va, va.saturating_add(len)).into_iter().take(4).map(|(ova, ores, _)| (ores, ova)).collect() } @@ -351,6 +358,21 @@ pub fn counts() -> (usize, u64) { (TEXTURES_LEN.load(Ordering::Relaxed), UPLOADS.load(Ordering::Relaxed)) } +/// Sampled textures tracked for CPU coherency on `device` that use committed resources: count and +/// their PC allocation bytes. This deliberately excludes untracked render/depth/UAV fallbacks. +/// Shadowed resources remain live and are included once until the title releases them. +pub(super) fn committed_bytes_for(device: usize) -> (usize, u64) { + TEXTURES.lock().unwrap().committed_bytes_for(device) +} + +unsafe fn committed_allocation_bytes(device: *mut c_void, resource: *mut c_void, placed: bool) -> u64 { + if placed || !super::memory_report::enabled() { return 0 } + let Some(dev) = ID3D12Device::from_raw_borrowed(&device) else { return 0 }; + let Some(res) = ID3D12Resource::from_raw_borrowed(&resource) else { return 0 }; + let bytes = dev.GetResourceAllocationInfo(0, &[res.GetDesc()]).SizeInBytes; + if bytes == u64::MAX { 0 } else { bytes } +} + fn update_lengths(t: &Table) { TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); CPU_TEXTURES_LEN.store(t.by_res.values().filter(|e| e.cpu_backed).count(), Ordering::Relaxed); @@ -410,8 +432,10 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, } } let in_gpu_view = crate::hle::kernelx::mirrors::source(va).is_some(); + let placed = super::vram::is_placed_texture(res as usize); let e = Entry { device: device as usize, + committed_bytes: committed_allocation_bytes(device, res, placed), va, src, in_gpu_view, @@ -421,7 +445,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, gpu_written: false, gpu_writers: Vec::new(), cpu_backed: true, - placed: super::vram::is_placed_texture(res as usize), + placed, unmapped: false, generation: 0, }; @@ -491,6 +515,7 @@ pub(super) unsafe fn register_gpu_owned( let src = mirror_source(va); let e = Entry { device: device as usize, + committed_bytes: 0, va, src, in_gpu_view: crate::hle::kernelx::mirrors::source(va).is_some(), @@ -2592,7 +2617,7 @@ mod tests { d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); let tex = Arc::new(xg::Texture::new(&d).unwrap()); - let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }; + let mut e = Entry { device: 0, committed_bytes: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }; assert_eq!(e.src, cpu + 0x2_0000); assert!(!recheck_source(&mut e), "nothing changed yet"); assert_eq!(kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at); @@ -2716,6 +2741,7 @@ mod tests { let res = 0x7E57_1000_1000usize; let entry = |tex: &Arc| Entry { device: 0, + committed_bytes: 0, va: 0x7E57_1000_0000, src: 0x7E57_1000_0000, in_gpu_view: false, @@ -2791,7 +2817,7 @@ mod tests { assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, committed_bytes: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); @@ -2983,6 +3009,39 @@ mod tests { d } + #[test] + fn committed_sampled_bytes_follow_device_shadowing_and_release() { + const M: u64 = 1 << 20; + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + let entry = |device, va, committed_bytes, placed| Entry { + device, + committed_bytes, + va, + src: va, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: false, + gpu_writers: Vec::new(), + cpu_backed: true, + placed, + unmapped: false, + generation: 0, + }; + let mut table = Table::new(); + table.insert(1, entry(7, 0x10_0000, 3 * M, false)); + table.insert(2, entry(7, 0x10_2000, 2 * M, false)); // shadows 1, which remains live + table.insert(3, entry(7, 0x20_0000, 8 * M, true)); // shared pages, not committed + table.insert(4, entry(8, 0x30_0000, 11 * M, false)); + assert_eq!(table.committed_bytes_for(7), (2, 5 * M)); + assert_eq!(table.committed_bytes_for(8), (1, 11 * M)); + assert!(table.remove(2).0); + assert_eq!(table.committed_bytes_for(7), (1, 3 * M), "the uncovered sampled texture is counted once"); + assert!(table.remove(1).0); + assert_eq!(table.committed_bytes_for(7), (0, 0), "logical release removes the partial diagnostic owner"); + } + fn readback_for(tex: &xg::Texture, format: u32, subresource: u32) -> (ReadbackFootprint, Vec, Vec) { let s = tex.texels().unwrap(); let mips = s.chain.levels.len(); @@ -3173,6 +3232,7 @@ mod tests { assert_eq!((tex_16k.size(), tex_64k.size()), (0x4000, 0x1_0000)); let entry = |va: usize, tex: &Arc, pending: bool, placed: bool| Entry { device: 0, + committed_bytes: 0, va, src: va, in_gpu_view: false, @@ -3578,6 +3638,7 @@ mod tests { let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); let entry = |cpu_backed: bool| Entry { device: 0, + committed_bytes: 0, va: 0x20_0000, src: 0x20_0000, in_gpu_view: false, @@ -3619,6 +3680,7 @@ mod tests { let e_stream = Entry { device: 0, + committed_bytes: 0, va, src: va, in_gpu_view: false, @@ -3634,6 +3696,7 @@ mod tests { }; let e_gpu = Entry { device: 0, + committed_bytes: 0, va: va + size, src: va, in_gpu_view: false, diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 8d39240c49..312262e4eb 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -108,6 +108,9 @@ impl Arenas { } fn bytes(&self) -> usize { self.list.iter().map(|a| a.size).sum() } + fn bytes_for(&self, dev: usize) -> usize { + self.list.iter().filter(|a| a.dev == dev).fold(0, |bytes, a| bytes.saturating_add(a.size)) + } } // D3D12 heaps are free-threaded @@ -123,6 +126,10 @@ static MADE_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsi pub fn arena_bytes() -> (usize, usize) { (ARENAS.lock().unwrap().bytes(), MADE_BYTES.load(std::sync::atomic::Ordering::Relaxed)) } + +pub(super) fn arena_bytes_for(device: usize) -> usize { + ARENAS.lock().unwrap().bytes_for(device) +} static PLACED_TEXTURES: Mutex>> = Mutex::new(None); /// A texture backed by one of the aliasable D3D12 heaps. @@ -1293,11 +1300,12 @@ pub(super) fn mapped_tiles_for(device: usize, resource: usize) -> Option<(Vec<(u (used.len() + extra.len() == target.total as usize).then_some((used, extra)) } -#[cfg(test)] pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { let g = PAGES.lock().unwrap(); let Some(Some(p)) = g.get(&device) else { return (0, 0) }; - ((p.pages.len() + p.extra_pages.len()) * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) + let pages = p.pages.len().saturating_add(p.extra_pages.len()).saturating_mul(PAGE); + let pools = p.pools.len().saturating_mul(POOL_PAGES as usize).saturating_mul(PAGE); + (pages, pools) } /// Pool/tile identities used by one mapped resource: title pages, then extra pages. diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 70e9475f04..b519c46aa4 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -50,7 +50,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::hle::d3d12x::real::log_dispatch_chain_counts(); }); // `XCL_ACTIVITY=1`: every 2 s what the title did since (a timeline of where it stops) - if std::env::var_os("XCL_ACTIVITY").is_some() { + if crate::hle::d3d12x::memory_report::enabled() { let _ = std::thread::Builder::new().name("xcl-activity".into()).spawn(|| { let snap = || { let (p, e) = crate::hle::d3d12x::present::activity(); @@ -69,21 +69,17 @@ pub fn host_main(boot_path: &Path) -> i32 { d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9], d[10] ); // where the memory is: the process's commit, video memory, and XCL's parts of it - let private = 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); - c.PrivateUsage - }; - let (local, non_local) = crate::hle::d3d12x::real::video_memory().unwrap_or((0, 0)); + let owner = crate::hle::d3d12x::memory_report::snapshot(); + let private = owner.commit.unwrap_or(0); + let local = owner.local.map_or(0, |s| s.usage); + let non_local = owner.non_local.map_or(0, |s| s.usage); let (arenas, arenas_made) = crate::hle::d3d12x::vram::arena_bytes(); let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); let (pages, page_pools) = crate::hle::d3d12x::vram::page_bytes(); let mb = |b: u64| b >> 20; crate::xlog_info!( "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped)", - mb(private as u64), + mb(private), mb(local), mb(non_local), mb(pages as u64), @@ -93,6 +89,7 @@ pub fn host_main(boot_path: &Path) -> i32 { mb(pools as u64), mb(pools_mapped as u64) ); + crate::xlog_info!("{}", owner.line()); last = now; } });