Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/texture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ unsafe fn buffer(dev: &ID3D12Device, size: u64) -> Result<ID3D12Resource, String
let mut r: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut r)
.map_err(|x| format!("texture upload buffer: {x}"))?;
r.ok_or_else(|| "texture upload buffer".into())
crate::hle::d3d12x::resource_census::tracked(r, "upload staging").ok_or_else(|| "texture upload buffer".into())
}

fn transition(r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ unsafe fn argument_order_buffer(list: &ID3D12GraphicsCommandList) -> Option<ID3D
}
return None;
}
let b = b?;
let b = crate::hle::d3d12x::resource_census::tracked(b, "ExecuteIndirect argument order")?;
*g = Some((dev.as_raw() as usize, b.clone()));
Some(b)
}
Expand Down
8 changes: 4 additions & 4 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2341,7 +2341,7 @@ unsafe fn make_copy_scratch(list: *mut c_void, bytes: u64) -> Option<ID3D12Resou
device_of(list)?
.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut b)
.ok()?;
b
crate::hle::d3d12x::resource_census::tracked(b, "copy scratch")
}

unsafe fn device_of(list: *mut c_void) -> Option<ID3D12Device> {
Expand Down Expand Up @@ -2385,7 +2385,7 @@ unsafe fn pattern_buffer(list: *mut c_void, pat: [u8; 16], n: u64) -> Option<usi
&mut b,
)
.ok()?;
let b = b?;
let b = crate::hle::d3d12x::resource_census::tracked(b, "fill pattern")?;
let mut p: *mut c_void = std::ptr::null_mut();
b.Map(0, None, Some(&mut p)).ok()?;
for chunk in std::slice::from_raw_parts_mut(p as *mut u8, len as usize).chunks_exact_mut(16) {
Expand Down Expand Up @@ -2495,7 +2495,7 @@ unsafe fn ensure_timestamp_readback(dev: &ID3D12Device, pool: &mut TimestampPool
};
let mut rb: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).ok()?;
let rb = rb?;
let rb = crate::hle::d3d12x::resource_census::tracked(rb, "timestamp readback")?;
let mut ptr: *mut c_void = std::ptr::null_mut();
rb.Map(0, None, Some(&mut ptr)).ok()?;
if ptr.is_null() {
Expand Down Expand Up @@ -3116,7 +3116,7 @@ unsafe fn predication_buffer(list: *mut c_void) -> Option<usize> {
};
let mut buf: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).ok()?;
let buf = buf?;
let buf = crate::hle::d3d12x::resource_census::tracked(buf, "predication")?;
let (raw, extra) = {
let mut g = LISTS.lock().unwrap();
let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default();
Expand Down
267 changes: 267 additions & 0 deletions crates/xcl/src/hle/d3d12x/memory_report.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
//! 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<u64>,
/// None: no device or DXGI did not answer
pub local: Option<Segment>,
pub non_local: Option<Segment>,
pub parts: Vec<Part>,
}

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<i64> {
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<String> = 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<Segment>, 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<u64> {
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<Segment>, non_local: Option<Segment>, 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<Segment>) -> 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<Segment>) -> 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<String> {
let counts = super::resource_census::counts();
if counts.is_empty() {
return None;
}
let parts: Vec<String> = 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());
}
}
}
2 changes: 2 additions & 0 deletions crates/xcl/src/hle/d3d12x/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ pub mod guard;
mod late_release;
pub mod layout;
pub mod list_x;
pub mod memory_report;
pub mod null;
pub mod present;
pub mod resource_census;
pub mod pso_async;
pub mod real;
mod shader_cache_session;
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1305,7 +1305,7 @@ unsafe fn readback_copy(list: &ID3D12GraphicsCommandList, src: &ID3D12Resource,
&mut rb,
)
.ok()?;
let rb = rb?;
let rb = crate::hle::d3d12x::resource_census::tracked(rb, "frame dump readback")?;
let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } };
let s = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(src), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } };
list.CopyTextureRegion(&dst, 0, 0, 0, &s, None);
Expand Down
7 changes: 7 additions & 0 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,13 @@ pub fn abi_root_signature() -> Option<ID3D12RootSignature> {
static UMA_BUFFER: Mutex<Vec<(usize, u64)>> = Mutex::new(Vec::new());
/// the committed UMA windows opened as D3D12 heaps (indexed by window `k`; `None` for sparse windows)
static UMA_HEAPS: Mutex<Vec<Option<usize>>> = Mutex::new(Vec::new());

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

/// Called with the original six ABI views bound. The extended signature is
Expand Down
Loading
Loading