diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 9c03999491..1c79f6cc85 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -776,9 +776,45 @@ pub fn memory_reserve() -> u64 { RESERVE_GB.load(Ordering::Relaxed) << 30 } -/// Available page-file commit bytes from Windows, or `None` if the query fails. +/// Commit as Windows reports it: `now`, free against the page files' current size, `growth`, +/// what they can still grow by, and `job_limited`, whether a job caps this process's commit +/// (a limit that does not rise when a page file grows). +pub(crate) struct CommitSource { + pub(crate) now: N, + pub(crate) growth: G, + pub(crate) job_limited: J, +} + +impl Option, G: Fn() -> u64, J: Fn() -> bool> CommitSource { + /// What can be committed now. Compile admission reads this: Windows grows a page file only + /// when a commit needs it, and allocations made side by side can fail before it has grown. + pub(crate) fn free(&self) -> Option { + (self.now)() + } + + /// [`Self::free`] plus the page files' growth, for planning heaps that live the whole run; + /// [`Self::free`] alone under a job's commit limit. + pub(crate) fn capacity(&self) -> Option { + (self.now)().map(|now| if (self.job_limited)() { now } else { now.saturating_add((self.growth)()) }) + } +} + +type SystemCommit = CommitSource Option, fn() -> u64, fn() -> bool>; +static COMMIT: SystemCommit = CommitSource { now: avail_page_file, growth: page_file_growth, job_limited: job_commit_limit }; + +/// Commit free now ([`avail_page_file`]), or `None` if the query fails. The compile gates admit +/// against it. pub fn commit_free() -> Option { - avail_page_file() + COMMIT.free() +} + +/// Commit that can be had once the page files have grown ([`page_file_growth`]), or `None` if the +/// query fails: for the coherent window's long-lived GPU heaps (`uma`). With page files that start +/// small (the default, or a 2 GB start with a 16 GB maximum) [`commit_free`] reads a few GB on a +/// 32 GB PC while over 20 GB more can be had, and the heaps stayed out of the window. Under a +/// job's commit limit ([`job_commit_limit`]) it is [`commit_free`] alone. +pub fn commit_capacity() -> Option { + COMMIT.capacity() } /// Compiles running on the DXC workers (`wait_for_memory` lets them in). @@ -830,7 +866,8 @@ impl Drop for MemorySlot { } } -/// Available page-file commit bytes from Windows, or `None` if the query fails. +/// Available page-file commit bytes from Windows at the page files' current size +/// (`ullAvailPageFile`), or `None` if the query fails. fn avail_page_file() -> Option { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; @@ -838,6 +875,119 @@ fn avail_page_file() -> Option { (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPageFile) } +/// A page file as the kernel has it now, in bytes: its size, the most it may grow to, and the +/// free space of its volume (`None`: not known). +#[derive(Clone, Copy, Debug)] +struct PageFile { + size: u64, + max: u64, + volume_free: Option, +} + +/// What the page files can still grow by: each up to its maximum, and no further than its +/// volume's free space (nothing when that is not known). +fn growth_of(files: &[PageFile]) -> u64 { + files.iter().map(|f| f.max.saturating_sub(f.size).min(f.volume_free.unwrap_or(0))).fold(0, u64::saturating_add) +} + +/// [`growth_of`] the page files the kernel has now (0 when they cannot be read). Logged once. +fn page_file_growth() -> u64 { + let files = page_files(); + let growth = growth_of(&files); + static LOGGED: AtomicBool = AtomicBool::new(false); + if !LOGGED.swap(true, Ordering::Relaxed) { + crate::xlog_info!( + "commit: the page files can grow by {} MB more than their size now ({} page file(s): {})", + growth >> 20, + files.len(), + files.iter().map(|f| format!("{} of {} MB", f.size >> 20, f.max >> 20)).collect::>().join(", ") + ); + } + growth +} + +/// Whether the job this process is in caps its commit (`JOB_OBJECT_LIMIT_PROCESS_MEMORY` or +/// `JOB_OBJECT_LIMIT_JOB_MEMORY`). Such a limit does not rise when a page file grows, and +/// `ullAvailPageFile` does not show it: on Windows 11 build 26200 a process in an 8 GB job read +/// the system's free commit (42 GB). Only the process's immediate job: a limit set on an outer +/// job of nested jobs cannot be read from inside. Read at each call (a job can be assigned +/// while the process runs), logged the first time it is found. +fn job_commit_limit() -> bool { + use windows_sys::Win32::Foundation::HANDLE; + use windows_sys::Win32::System::JobObjects::{ + JobObjectExtendedLimitInformation, QueryInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_JOB_MEMORY, + JOB_OBJECT_LIMIT_PROCESS_MEMORY, + }; + let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() }; + // a null job handle names the job this process is in; the query fails when it is in none + let none: HANDLE = unsafe { std::mem::zeroed() }; + let size = std::mem::size_of_val(&info) as u32; + let ok = unsafe { QueryInformationJobObject(none, JobObjectExtendedLimitInformation, (&mut info as *mut JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(), size, std::ptr::null_mut()) } != 0; + let limited = ok && info.BasicLimitInformation.LimitFlags & (JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_JOB_MEMORY) != 0; + static LOGGED: AtomicBool = AtomicBool::new(false); + if limited && !LOGGED.swap(true, Ordering::Relaxed) { + crate::xlog_info!( + "commit: this process's job caps its commit (process {} MB, job {} MB): the page files' growth is not counted for the GPU heaps", + info.ProcessMemoryLimit >> 20, + info.JobMemoryLimit >> 20 + ); + } + limited +} + +/// The page files from `NtQuerySystemInformation(SystemPageFileInformationEx)`: unlike the +/// registry, the sizes in force now (a change made in System Properties applies at once when it +/// grows a page file). +fn page_files() -> Vec { + #[repr(C)] + struct PageFileInformationEx { + next_entry_offset: u32, + total_size: u32, + total_in_use: u32, + peak_usage: u32, + name_length: u16, + name_maximum_length: u16, + name_buffer: *const u16, + minimum_size: u32, + maximum_size: u32, + } + #[link(name = "ntdll", kind = "raw-dylib")] + extern "system" { + fn NtQuerySystemInformation(class: u32, info: *mut c_void, len: u32, ret: *mut u32) -> i32; + } + const SYSTEM_PAGE_FILE_INFORMATION_EX: u32 = 144; + const PAGE: u64 = 4096; + let mut buf = vec![0u64; 512]; + let mut ret = 0u32; + let status = unsafe { NtQuerySystemInformation(SYSTEM_PAGE_FILE_INFORMATION_EX, buf.as_mut_ptr().cast(), (buf.len() * 8) as u32, &mut ret) }; + // no page file: success with nothing written (`ret` 0) + if status != 0 || ret == 0 { + return Vec::new(); + } + let base = buf.as_ptr() as *const u8; + let mut files = Vec::new(); + let mut off = 0usize; + while off + std::mem::size_of::() <= ret as usize { + let e = unsafe { &*(base.add(off) as *const PageFileInformationEx) }; + let name = if e.name_buffer.is_null() { String::new() } else { String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(e.name_buffer, e.name_length as usize / 2) }) }; + files.push(PageFile { size: e.total_size as u64 * PAGE, max: e.maximum_size as u64 * PAGE, volume_free: volume_free(&name) }); + if e.next_entry_offset == 0 { + break; + } + off += e.next_entry_offset as usize; + } + files +} + +/// Free bytes on the volume of a page file the kernel names `\??\C:\pagefile.sys`. +fn volume_free(nt_name: &str) -> Option { + use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW; + let path = nt_name.strip_prefix(r"\??\")?; + let root = path.get(..3).filter(|r| r.as_bytes()[1] == b':' && r.as_bytes()[2] == b'\\')?; + let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64); + (unsafe { GetDiskFreeSpaceExW(crate::util::wide(root).as_ptr(), &mut avail, &mut total, &mut free) } != 0).then_some(free) +} + /// Before a compile: with 6 GB of commit left or more, plus 1 GB for every compile already /// running (each can still grow to ~0.7 GB), at once; with less, one compile at a /// time – it goes when no other is running (and after a minute in any case). Each compile used @@ -847,10 +997,15 @@ fn avail_page_file() -> Option { /// of its threads waited for cold compiles, four of which stood in this queue, until its watchdog /// ended it. pub fn wait_for_memory(wanted: &Wanted) -> MemorySlot { - MEMORY_GATE.wait_with(RESERVE_GB.load(Ordering::Relaxed) << 30, avail_page_file, std::time::Duration::from_secs(60), wanted); + wait_admitted(&MEMORY_GATE, &COMMIT, RESERVE_GB.load(Ordering::Relaxed) << 30, std::time::Duration::from_secs(60), wanted); MemorySlot } +/// [`wait_for_memory`]'s wait at `gate`, against the commit `source` has free now (not its growth). +fn wait_admitted Option, G: Fn() -> u64, J: Fn() -> bool>(gate: &MemoryGate, source: &CommitSource, reserve_bytes: u64, timeout: std::time::Duration, wanted: &Wanted) { + gate.wait_with(reserve_bytes, || source.free(), timeout, wanted); +} + /// DXC workers (`compile_threads`, each with its own compiler and a `DXC_STACK` stack), started /// on first use; callers wait for their job. fn pool() -> &'static Arc { @@ -2357,6 +2512,73 @@ mod memory_gate_tests { use std::sync::Barrier; use std::time::Duration; + const GB: u64 = 1 << 30; + + #[test] + fn page_files_that_start_small_count_what_they_can_grow_by() { + // the default a 32 GB PC had: three page files of 2–5 GB now, 16 or 32 GB at most, and + // room on every volume; `ullAvailPageFile` alone left all of it out + let files = [ + PageFile { size: 5 * GB, max: 16 * GB, volume_free: Some(100 * GB) }, + PageFile { size: 2 * GB, max: 16 * GB, volume_free: Some(200 * GB) }, + PageFile { size: 2 * GB, max: 32 * GB, volume_free: Some(255 * GB) }, + ]; + assert_eq!(growth_of(&files), 11 * GB + 14 * GB + 30 * GB); + } + + #[test] + fn page_file_growth_stops_at_its_volume_free_space_and_a_fixed_size() { + let files = [ + PageFile { size: 2 * GB, max: 16 * GB, volume_free: Some(3 * GB) }, + PageFile { size: 32 * GB, max: 32 * GB, volume_free: Some(255 * GB) }, + PageFile { size: 2 * GB, max: 16 * GB, volume_free: None }, + PageFile { size: 8 * GB, max: 4 * GB, volume_free: Some(255 * GB) }, + ]; + assert_eq!(growth_of(&files), 3 * GB, "the full volume, the fixed size, the unknown volume and a file over its maximum add only what can be had"); + assert_eq!(growth_of(&[]), 0, "no page file: nothing to grow"); + } + + #[test] + fn the_page_files_read_from_the_kernel_are_within_their_maximum() { + // whatever this machine has: each page file read has a maximum, and the growth counted is + // never more than the maxima together + let files = page_files(); + for f in &files { + assert!(f.max > 0, "{f:?}"); + } + assert!(growth_of(&files) <= files.iter().map(|f| f.max).sum::()); + } + + #[test] + fn a_background_compile_waits_for_commit_free_now_not_the_page_files_growth() { + // one background compile running, 2 GB free now and page files that can grow by 20 GB: + // the heaps' plan counts the growth, but a second background compile waits until the + // reserve and 1 GB for the one running (7 GB) are free now + use std::sync::atomic::AtomicU64; + let gate = MemoryGate::new(); + let reserve = 6 * GB; + let now = AtomicU64::new(2 * GB); + let source = CommitSource { now: || Some(now.load(Ordering::SeqCst)), growth: || 20 * GB, job_limited: || false }; + assert_eq!(source.capacity(), Some(22 * GB)); + let unwanted: Wanted = Box::new(|| false); + assert!(gate.try_admit(reserve, || source.free(), false, &unwanted), "the first compile goes in with none running"); + let admitted = AtomicBool::new(false); + let early = std::thread::scope(|s| { + s.spawn(|| { + let unwanted: Wanted = Box::new(|| false); + wait_admitted(&gate, &source, reserve, Duration::from_secs(60), &unwanted); + admitted.store(true, Ordering::SeqCst); + }); + std::thread::sleep(Duration::from_millis(300)); + let early = admitted.load(Ordering::SeqCst); + now.store(7 * GB, Ordering::SeqCst); + early + }); + assert!(!early, "a second background compile went in on page-file growth that had not happened"); + assert!(admitted.load(Ordering::SeqCst), "it goes in once 7 GB are free now"); + assert_eq!(gate.working.load(Ordering::SeqCst), 2); + } + #[test] fn tight_commit_headroom_bounds_concurrent_admissions() { let gate = MemoryGate::new(); diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 18b4024907..1633347719 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -1073,17 +1073,26 @@ pub fn coherent_hint_for(windows: usize) -> usize { let cap = auto_coherent_cap(total_physical()).map_or(cap, |c| c.clamp(GRAIN, cap)); let route = crate::hle::kernelx::coherent_heaps_route(); let title = std::fs::read_to_string(coherent_file(&route)).map_or(0, |s| stored_need(&s)); - // only with the commit for all of it: the title's ~13 GB, video memory for its render targets - // and textures (WDDM charges commit for each video-memory allocation too) and the window - // itself – a retail game took ~18 GB; with less free it runs without (its GPU heaps outside - // unified memory: no image) rather than taking the system's commit - if title > 0 && free_commit() < NEEDS_FOR_COHERENT_HEAPS { - crate::xlog_warn!( - "UMA: {} MB of commit free, under {} MB: the title's GPU heaps stay outside unified memory (a larger page file gives them the coherent window)", - free_commit() >> 20, - NEEDS_FOR_COHERENT_HEAPS >> 20 - ); - return RUNTIME_COMMITTED_CAP.min(cap); + heaps_window(title, cap, crate::gpu::recomp::dxc::commit_capacity) +} + +/// The coherent window for `title` bytes of the title's GPU heaps (its last run's), up to `cap`: +/// with them only with the commit for all of it (`capacity`: `dxc::commit_capacity`, `None` +/// when not known). That is the title's ~13 GB, video memory for its render targets and +/// textures (WDDM charges commit for each video-memory allocation too) and the window itself – a +/// retail game took ~18 GB; with less it runs without (its GPU heaps outside unified memory: no +/// image) rather than taking the system's commit. +fn heaps_window(title: usize, cap: usize, capacity: impl Fn() -> Option) -> usize { + if title > 0 { + let free = capacity().map_or(usize::MAX, |b| b as usize); + if free < NEEDS_FOR_COHERENT_HEAPS { + crate::xlog_warn!( + "UMA: {} MB of commit free, under {} MB: the title's GPU heaps stay outside unified memory (a larger page file gives them the coherent window)", + free >> 20, + NEEDS_FOR_COHERENT_HEAPS >> 20 + ); + return RUNTIME_COMMITTED_CAP.min(cap); + } } (title + RUNTIME_COMMITTED_CAP).min(cap) } @@ -1096,16 +1105,6 @@ pub fn coherent_hint() -> usize { /// Commit free before the title starts for its GPU heaps to go to the coherent window. const NEEDS_FOR_COHERENT_HEAPS: usize = 17 << 30; -fn free_commit() -> usize { - use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; - let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; - m.dwLength = std::mem::size_of::() as u32; - if unsafe { GlobalMemoryStatusEx(&mut m) } == 0 { - return usize::MAX; - } - m.ullAvailPageFile as usize -} - /// bytes of graphics memory the title asked the coherent window for in this run static NOTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// `coherent_file` is read and written under it @@ -1251,6 +1250,23 @@ pub fn get() -> Option<&'static Uma> { mod tests { use super::*; + /// From the commit query to the window: 4 GiB free now and page files that can grow by + /// 20 GiB. Outside a job the growth counts and the title's 13 GiB of heaps go to the coherent + /// window; under a job's commit limit (which does not grow with the page files) they stay + /// outside, as with 4 GiB. + #[test] + fn a_job_commit_limit_keeps_the_gpu_heaps_off_the_page_files_growth() { + use crate::gpu::recomp::dxc::CommitSource; + const GB: u64 = 1 << 30; + let (title, cap) = (13usize << 30, 4095usize << 20); + let outside = CommitSource { now: || Some(4 * GB), growth: || 20 * GB, job_limited: || false }; + let in_job = CommitSource { now: || Some(4 * GB), growth: || 20 * GB, job_limited: || true }; + assert_eq!(heaps_window(title, cap, || outside.capacity()), cap, "outside a job the page files' growth gives the heaps the window"); + assert_eq!(heaps_window(title, cap, || in_job.capacity()), RUNTIME_COMMITTED_CAP, "a job's commit limit does not grow with the page files"); + assert_eq!(heaps_window(title, cap, || Some(17 * GB)), cap, "17 GiB free now is enough without growth"); + assert_eq!(heaps_window(0, cap, || panic!("no stored heaps: no query")), RUNTIME_COMMITTED_CAP); + } + /// Arena blocks come from XCL's pool while the title holds the rest of window 0, and go /// back to it when freed. #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e70e3d9e85..a9e27b9499 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5712,12 +5712,9 @@ fn big_compile_headroom(dxil_len: usize) -> u64 { (3u64 << 30).max(dxil_len as u64 * 512) } -/// That much commit is free (true when that is not known). +/// That much commit is free now (true when that is not known). pub(super) fn big_compile_commit_free(need: u64) -> bool { - use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; - let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; - m.dwLength = std::mem::size_of::() as u32; - unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPageFile >= need } + crate::gpu::recomp::dxc::commit_free().is_none_or(|a| a >= need) } /// The driver compiles of a split program's pieces (`largest`: the biggest one's DXIL) that go