Skip to content
Merged
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
5 changes: 5 additions & 0 deletions crates/xcl/src/gpu/uma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -987,6 +987,11 @@ impl Arena {

static GLOBAL: OnceLock<Option<Uma>> = OnceLock::new();

/// The region, if a caller has already initialized it. Observability must not allocate it.
pub fn existing() -> Option<&'static Uma> {
GLOBAL.get().and_then(Option::as_ref)
}

/// A process that holds no title memory (a shader preparation worker): `get` is None from here
/// on, and nothing is reserved or committed for it (a run's region commits its coherent window).
/// Before any `get`.
Expand Down
79 changes: 76 additions & 3 deletions crates/xcl/src/hle/d3d12x/memory_report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,26 @@ pub fn local_segment() -> Option<Segment> {
video_memory(super::real::device_raw()).0
}

/// The commit Windows charges for the process's D3D12 heaps: both DXGI segments less the coherent
/// UMA windows that DXGI already counts alongside `"UMA window"` on `Kind::Commit`; 0 when either
/// DXGI segment is unknown.
fn heap_charge(local: Option<Segment>, non_local: Option<Segment>, uma_dxgi_shared: u64) -> u64 {
match (local, non_local) {
(Some(l), Some(n)) => l.usage.saturating_add(n.usage).saturating_sub(uma_dxgi_shared),
_ => 0,
}
}

/// Where DXGI counts coherent system-memory UMA windows: non-local on a discrete GPU, or local on
/// a single-segment adapter (no non-local budget: an integrated GPU).
fn uma_segment(non_local: Option<Segment>) -> Kind {
if non_local.is_some_and(|n| n.budget > 0) {
Kind::NonLocal
} else {
Kind::Video
}
}

pub fn snapshot() -> Snapshot {
let raw = super::real::device_raw();
let device = raw as usize;
Expand All @@ -114,19 +134,26 @@ pub fn snapshot() -> Snapshot {
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 uma = crate::gpu::uma::existing().map_or(0, |u| u64::try_from(u.size()).unwrap_or(u64::MAX));
let (uma_non_local, uma_local) = super::real::uma_dxgi_bytes_for(device);
let uma_dxgi_shared = uma_non_local.saturating_add(uma_local);
let b = |n: usize| u64::try_from(n).unwrap_or(u64::MAX);
let parts = vec![
let mut 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: "D3D12 heaps", kind: Kind::Commit, bytes: heap_charge(local, non_local, uma_dxgi_shared) },
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 },
Part { owner: "UMA window", kind: uma_segment(non_local), bytes: uma_non_local },
];
if uma_local > 0 {
parts.push(Part { owner: "UMA window (local)", kind: Kind::Video, bytes: uma_local });
}
Snapshot { commit: process_commit(), local, non_local, parts }
}

Expand Down Expand Up @@ -187,6 +214,50 @@ mod tests {
assert_eq!(large.other(Kind::Commit), Some(i64::MIN));
}

#[test]
fn heap_charge_and_uma_segment_avoid_double_counting() {
const M: u64 = 1 << 20;
let local = Some(Segment { usage: 6_000 * M, budget: 7_200 * M });
let non_local = Some(Segment { usage: 4_500 * M, budget: 16_000 * M });
// Discrete GPU: coherent UMA window lives in non-local, and is subtracted once from D3D12 heaps commit.
assert_eq!(uma_segment(non_local), Kind::NonLocal);
assert_eq!(heap_charge(local, non_local, 4_096 * M), 6_404 * M);
// Mixed UMA window (e.g. 512 MiB GPU_UPLOAD + 3584 MiB CUSTOM L0): total shared = 4096 MiB subtracted once.
assert_eq!(heap_charge(local, non_local, 512 * M + 3_584 * M), 6_404 * M);
// Shadowed or unimported window (shared = 0): full local + non-local charged to D3D12 heaps.
assert_eq!(heap_charge(local, non_local, 0), 10_500 * M);
// Never underflows when shared exceeds stale/smaller DXGI totals, and 0 when either segment is unknown.
assert_eq!(heap_charge(Some(Segment { usage: 100 * M, budget: 1 }), non_local, 8_000 * M), 0);
assert_eq!(heap_charge(local, None, 4_096 * M), 0);
assert_eq!(heap_charge(None, non_local, 4_096 * M), 0);
// Single-segment adapter (integrated GPU, non-local budget 0) or unknown non-local: UMA lives on local.
assert_eq!(uma_segment(Some(Segment { usage: 0, budget: 0 })), Kind::Video);
assert_eq!(uma_segment(None), Kind::Video);
}

#[test]
fn snapshot_does_not_initialize_uma() {
const CHILD: &str = "XCL_TEST_MEMORY_SNAPSHOT_CHILD";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "hle::d3d12x::memory_report::tests::snapshot_does_not_initialize_uma", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
return;
}
assert!(crate::gpu::uma::existing().is_none());
let s = snapshot();
assert!(crate::gpu::uma::existing().is_none(), "a memory snapshot allocated the UMA window");
assert_eq!(s.parts.iter().find(|p| p.kind == Kind::Commit && p.owner == "UMA window").unwrap().bytes, 0);
}

#[test]
fn device_snapshot_has_budget_and_all_owners() {
if super::super::backend() != super::super::Backend::Real {
Expand All @@ -195,8 +266,10 @@ mod tests {
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"] {
for owner in ["UMA window", "sparse CPU copy", "D3D12 heaps", "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());
}
let dxgi_uma_kind = uma_segment(s.non_local);
assert!(s.parts.iter().any(|p| p.kind == dxgi_uma_kind && p.owner == "UMA window"), "DXGI UMA window missing: {}", s.line());
}
}
23 changes: 21 additions & 2 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,16 @@ static UMA_BUFFER: Mutex<Vec<(usize, u64)>> = Mutex::new(Vec::new());
/// contiguous `(seg_offset, seg_len, heap_raw)` segments (1 entry for single-heap windows, N for
/// `XCL_UMA_DRIVER=mixed:...`).
static UMA_HEAPS: Mutex<Vec<Vec<(usize, usize, usize)>>> = Mutex::new(Vec::new());
/// Coherent UMA bytes counted by DXGI for the device that opened them: `(device_raw, non_local, local)`.
/// Shadowed windows are omitted because their CPU and GPU allocations are separate.
static UMA_DXGI_BYTES: Mutex<(usize, u64, u64)> = Mutex::new((0, 0, 0));

/// Coherent UMA bytes counted by DXGI for `device`: `(non_local, local)`.
/// Never initializes the UMA region.
pub(super) fn uma_dxgi_bytes_for(device: usize) -> (u64, u64) {
let &(dev, non_local, local) = &*UMA_DXGI_BYTES.lock().unwrap();
if dev == device && device != 0 { (non_local, local) } else { (0, 0) }
}

fn uma_heap_for(k: usize, offset: usize, len: usize) -> Option<(usize, usize)> {
let g = UMA_HEAPS.lock().unwrap();
Expand Down Expand Up @@ -694,6 +704,7 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) {
let mut bufs: Vec<(usize, u64)> = vec![(0, 0); n];
let mut heaps: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); n];
let mut shadows: Vec<(usize, ID3D12Resource)> = Vec::new();
let (mut uma_non_local, mut uma_local) = (0u64, 0u64);
for k in 0..n {
if !u.is_committed_window(k) {
continue;
Expand All @@ -705,6 +716,10 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) {
match super::uma_driver::remake_window(device, base, size, u.committed_window() == Some(k)) {
Ok(remade) => {
u.set_driver_window(k);
let l0 = remade.watched_regions.as_ref().map_or(size, |segs| segs.iter().map(|&(_, l)| l).sum()) as u64;
let l1 = (size as u64).saturating_sub(l0);
uma_non_local = uma_non_local.saturating_add(l0);
uma_local = uma_local.saturating_add(l1);
if let Some(segs) = remade.watched_regions {
crate::gpu::uma::set_driver_watch_segments(k, segs);
}
Expand All @@ -729,12 +744,15 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) {
shadows.push((k, buf.clone()));
}
let va = buf.GetGPUVirtualAddress();
Ok((buf.into_raw() as usize, va, heap.into_raw() as usize))
Ok((buf.into_raw() as usize, va, heap.into_raw() as usize, shadowed))
});
match made {
Ok((buf_raw, va, heap_raw)) => {
Ok((buf_raw, va, heap_raw, shadowed)) => {
bufs[k] = (buf_raw, va);
heaps[k] = vec![(0, u.window(k).1, heap_raw)];
if !shadowed {
uma_non_local = uma_non_local.saturating_add(u.window(k).1 as u64);
}
}
Err(e) => {
crate::xlog_warn!("D3D12.X: UMA not available to the GPU: {e}");
Expand Down Expand Up @@ -769,6 +787,7 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) {
w0_va
);
*UMA_HEAPS.lock().unwrap() = heaps;
*UMA_DXGI_BYTES.lock().unwrap() = (device.as_raw() as usize, uma_non_local, uma_local);
for (k, buf) in &shadows {
let (base, size) = u.window(*k);
u.set_shadowed();
Expand Down
Loading