diff --git a/apps/larp/src/run.rs b/apps/larp/src/run.rs index 9271f12..219af8b 100644 --- a/apps/larp/src/run.rs +++ b/apps/larp/src/run.rs @@ -30,8 +30,20 @@ pub fn run( None => println!("build unknown ({hash})"), } + let title_dir = exe.parent().unwrap_or(Path::new(".")); + // A missing manifest leaves id 0 and no storage quota. + let manifest = + std::fs::read_to_string(title_dir.join("MicrosoftGame.config")).unwrap_or_default(); + let title = larp_hle::runtime::Title::from_manifest(&manifest); + let settings = cfg.data_dir.join(format!("{:08X}", title.id)).join("settings.ini"); + let keep = larp_hle::settings::layer_value(&settings, "keep_graphics_pipelines"); + let keep_env = std::env::var_os("LARP_KEEP_GRAPHICS_PIPELINES"); + larp_hle::modules::d3d12x::configure_graphics_pipeline_residency(keep_graphics_pipelines( + keep_env.as_deref(), + keep.as_deref(), + )); let images = cfg.cache_subdir("images")?; - larp_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?, pipelines_dir(&cfg, exe)?); + larp_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?, pipelines_dir(&cfg, &settings)?); // Our replacement shaders, before the title starts. larp_hle::modules::d3d12x::shader_replace::open().map_err(anyhow::Error::msg)?; // DirectStorage's decoded results, beside the translations. @@ -62,11 +74,6 @@ pub fn run( HostPolicy::default() }); let wanted = |dll: &str| title_dll(&resolver.host, dll); - let title_dir = exe.parent().unwrap_or(Path::new(".")); - // A missing manifest leaves id 0 and no storage quota. - let manifest = - std::fs::read_to_string(title_dir.join("MicrosoftGame.config")).unwrap_or_default(); - let title = larp_hle::runtime::Title::from_manifest(&manifest); let storage = cfg.data_subdir(&format!("{:08X}/storage", title.id))?; println!( "title {:08X}, storage {} ({} MB)", @@ -280,14 +287,9 @@ pub fn run( /// the title starts), else the cache's `pipelines`. A folder asked for that /// is inside the source tree or cannot be made is said once, and the /// cache's is used. -fn pipelines_dir(cfg: &larp_core::Config, exe: &Path) -> Result { +fn pipelines_dir(cfg: &larp_core::Config, settings: &Path) -> Result { use larp_core::config::{PipelinesFrom, cache_dir_at, pipelines_override}; - // The settings file by the manifest's title id, where `run` finds it later. - let title_dir = exe.parent().unwrap_or(Path::new(".")); - let manifest = std::fs::read_to_string(title_dir.join("MicrosoftGame.config")).unwrap_or_default(); - let title = larp_hle::runtime::Title::from_manifest(&manifest); - let settings = cfg.data_dir.join(format!("{:08X}", title.id)).join("settings.ini"); - let setting = larp_hle::settings::layer_value(&settings, "pipeline_cache_dir"); + let setting = larp_hle::settings::layer_value(settings, "pipeline_cache_dir"); let env = std::env::var_os("LARP_PIPELINE_CACHE_DIR"); if let Some((dir, from)) = pipelines_override(env.as_deref(), setting.as_deref()) { let by = match from { @@ -313,6 +315,27 @@ fn pipelines_dir(cfg: &larp_core::Config, exe: &Path) -> Result, setting: Option<&str>) -> bool { + env.map_or(setting == Some("on"), |value| value == "1") +} + +#[cfg(test)] +mod pipeline_residency_tests { + use super::keep_graphics_pipelines; + use std::ffi::OsStr; + + #[test] + fn residency_is_opt_in_and_environment_overrides_the_settings_file() { + assert!(!keep_graphics_pipelines(None, None)); + assert!(!keep_graphics_pipelines(None, Some("default"))); + assert!(!keep_graphics_pipelines(None, Some("off"))); + assert!(keep_graphics_pipelines(None, Some("on"))); + assert!(keep_graphics_pipelines(Some(OsStr::new("1")), Some("off"))); + assert!(!keep_graphics_pipelines(Some(OsStr::new("0")), Some("on"))); + assert!(!keep_graphics_pipelines(Some(OsStr::new("invalid")), Some("on"))); + } +} + /// The title's calls into the console's ray-tracing structure builder /// (`XboxBvhBuilder.dll`) go to `larp_gpu::bvh`, which answers the prebuild with the host's /// sizes and the build, rehydrate and copy calls with host structures alone (the prebuild with diff --git a/crates/larp-gpu/src/pipeline.rs b/crates/larp-gpu/src/pipeline.rs index 752093a..38a879d 100644 --- a/crates/larp-gpu/src/pipeline.rs +++ b/crates/larp-gpu/src/pipeline.rs @@ -971,6 +971,8 @@ pub fn stacks_at_stall(dump: fn()) { crate::stall::stacks_with(dump); } +pub use make::configure_graphics_pipeline_residency; + /// Keeps compiled host pipelines, and the list of the pipelines the title /// creates, in `dir` (a folder of the cache) across runs. pub fn use_pipeline_cache(dir: std::path::PathBuf) { diff --git a/crates/larp-gpu/src/pipeline/blobs/tests.rs b/crates/larp-gpu/src/pipeline/blobs/tests.rs index e1e8181..8b70a69 100644 --- a/crates/larp-gpu/src/pipeline/blobs/tests.rs +++ b/crates/larp-gpu/src/pipeline/blobs/tests.rs @@ -116,6 +116,30 @@ fn await_persistence(store: &Store, blob: &[u8]) { } } +#[test] +fn resident_warmup_materializes_a_graphics_blob_that_default_warmup_skips() { + use super::super::make::Pending; + + let scratch = Scratch::new(); + let driver = Driver::default(); + let first_run = disk(&scratch.0, A); + assert!(!driver.request(&first_run, BLOB_A, true)); + driver.assert_calls(&[Call::Compiled]); + await_persistence(&first_run, BLOB_A); + drop(first_run); + + let store = disk(&scratch.0, A); + let default = Pending::new(Vec::new(), None); + assert!(driver.request(&store, BLOB_A, default.needs_blob_only(false))); + driver.assert_calls(&[]); + assert!(default.release_if_unasked(false)); + + let resident = Pending::new(Vec::new(), None); + assert!(!driver.request(&store, BLOB_A, resident.needs_blob_only(true))); + driver.assert_calls(&[Call::Accepted(BLOB_A)]); + assert!(!resident.release_if_unasked(true)); +} + fn a_b_a(identity_b: WindowsIdentity) { let scratch = Scratch::new(); let driver = Driver::default(); diff --git a/crates/larp-gpu/src/pipeline/make.rs b/crates/larp-gpu/src/pipeline/make.rs index 721ef12..21d79c3 100644 --- a/crates/larp-gpu/src/pipeline/make.rs +++ b/crates/larp-gpu/src/pipeline/make.rs @@ -13,7 +13,7 @@ //! list, and the title creates its second batch 23 s before its world) //! asks for it ahead of the queue and waits ([`ready`]). //! -//! A graphics pipeline made before any draw asked for it is released as +//! By default, a graphics pipeline made before any draw asked for it is released as //! soon as it is made ([`Pending::make`]): what its making leaves is its //! cached blob on disk (`super::blobs`), compiled if the host had none or //! refused the one it had, and the first draw with it makes it again from @@ -21,7 +21,8 @@ //! alive, each of the 95,000 held its own cache of the driver's code and //! its SPIR-V in the host's memory for the whole run (11.7 GB resident in //! one run, the size of the blobs on disk), for the few thousand a -//! session draws with. +//! session draws with. Set `keep_graphics_pipelines = on` or +//! `LARP_KEEP_GRAPHICS_PIPELINES=1` to retain those pipelines through first use. //! //! A compute pipeline is kept from its making on, as the title holds its //! own: it creates each of its few thousand before its world. They are the @@ -151,19 +152,14 @@ impl Pending { // and released again, 102,687 in 43 to 47 s of the menu's hold // (two runs: 17 GB of blobs read). A draw asking for it // since makes it now; one asking later finds it released. - let warming = !self.computes() && self.asked.load(Ordering::Relaxed) == u64::MAX; + // In resident mode an existing blob must still become a live D3D12 + // object during warmup, including for a quad-mask variant. + let compute = self.computes(); + let keep_resident = compute || keep_graphics_pipelines(); + let warming = self.needs_blob_only(keep_resident); let (mut made, passed) = super::blobs::unless_on_disk(warming, host); if passed { - let released = { - let _queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); - let asked = self.asked.load(Ordering::Relaxed) != u64::MAX; - if !asked { - self.warmed.store(true, Ordering::Relaxed); - self.queue_state.store(NOT_QUEUED, Ordering::Relaxed); - } - !asked - }; - if released { + if self.release_if_unasked(keep_resident) { let (lock, done) = &DONE; let _held = lock.lock().unwrap_or_else(|e| e.into_inner()); done.notify_all(); @@ -171,17 +167,7 @@ impl Pending { } made = host(); } - let compute = made.is_some() && self.computes(); - let keep = made.is_none() || compute || { - let _queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); - let asked = self.asked.load(Ordering::Relaxed) != u64::MAX; - if !asked { - self.warmed.store(true, Ordering::Relaxed); - self.queue_state.store(NOT_QUEUED, Ordering::Relaxed); - } - asked - }; - if keep { + if made.is_none() || !self.release_if_unasked(keep_resident) { let kept = if compute { &KEPT_COMPUTE } else { &KEPT_FOR_DRAWS }; kept.fetch_add(u64::from(made.is_some()), Ordering::Relaxed); let _ = self.made.set(made); @@ -206,6 +192,25 @@ impl Pending { } } + /// Leaves a disk-warmed pipeline available to be queued by its first + /// draw. An ask racing the warmup observes this change under QUEUE. + pub(super) fn release_if_unasked(&self, keep_resident: bool) -> bool { + if keep_resident { + return false; + } + let _queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); + if self.asked.load(Ordering::Relaxed) != u64::MAX { + return false; + } + self.warmed.store(true, Ordering::Relaxed); + self.queue_state.store(NOT_QUEUED, Ordering::Relaxed); + true + } + + pub(super) fn needs_blob_only(&self, keep_resident: bool) -> bool { + !keep_resident && self.asked.load(Ordering::Relaxed) == u64::MAX + } + /// Whether it is a compute pipeline. fn computes(&self) -> bool { matches!(self.shaders.as_slice(), [only] if only.stage == "compute") @@ -305,7 +310,76 @@ pub(crate) fn missing(p: &Pending) -> Option { } } -/// Graphics pipelines kept for the draws that asked for them, compute +static KEEP_GRAPHICS_PIPELINES: OnceLock = OnceLock::new(); + +// The resident gameplay run reached about 65 GiB of process private commit. +// Warn about comparable workloads at startup without imposing a hard limit. +const STARTUP_COMMIT_HEADROOM_BYTES: u64 = 64 << 30; +const LOW_COMMIT_HEADROOM_BYTES: u64 = 8 << 30; +const COMMIT_SAMPLE_INTERVAL: Duration = Duration::from_secs(30); + +/// Sets the startup policy before any host pipelines are created. +pub fn configure_graphics_pipeline_residency(keep: bool) { + if KEEP_GRAPHICS_PIPELINES.set(keep).is_ok() { + tracing::info!(keep_graphics_pipelines = keep, "pipelines: graphics pipeline residency"); + if keep { + if let Some(commit) = SystemCommit::sample() { + commit.report(STARTUP_COMMIT_HEADROOM_BYTES, "startup"); + } else { + tracing::warn!("resident graphics pipelines: could not read Windows system commit"); + } + } + } +} + +fn keep_graphics_pipelines() -> bool { + KEEP_GRAPHICS_PIPELINES.get().copied().unwrap_or(false) +} + +struct SystemCommit { + used: u64, + limit: u64, +} + +impl SystemCommit { + fn sample() -> Option { + use windows_sys::Win32::System::ProcessStatus::{K32GetPerformanceInfo, PERFORMANCE_INFORMATION}; + let size = size_of::() as u32; + let mut info = PERFORMANCE_INFORMATION { + cb: size, + ..Default::default() + }; + // SAFETY: the buffer and its size describe a writable PERFORMANCE_INFORMATION. + if unsafe { K32GetPerformanceInfo(&mut info, size) } == 0 || info.PageSize == 0 || info.CommitLimit == 0 { + return None; + } + Some(Self { + used: (info.CommitTotal as u64).saturating_mul(info.PageSize as u64), + limit: (info.CommitLimit as u64).saturating_mul(info.PageSize as u64), + }) + } + + fn headroom(&self) -> u64 { + self.limit.saturating_sub(self.used) + } + + fn report(&self, threshold: u64, phase: &str) { + let used_mib = self.used >> 20; + let limit_mib = self.limit >> 20; + let headroom_mib = self.headroom() >> 20; + if self.headroom() < threshold { + tracing::warn!( + phase, used_mib, limit_mib, headroom_mib, + warning_below_mib = threshold >> 20, + "resident graphics pipelines: Windows commit headroom is low. Close other apps, check the Windows page file, or disable pipeline retention and restart." + ); + } else { + tracing::info!(phase, used_mib, limit_mib, headroom_mib, "resident graphics pipelines: Windows system commit"); + } + } +} + +/// Graphics pipelines kept for draws, including those retained at warmup, compute /// pipelines (all kept), and the graphics pipelines released as soon as /// made because nothing had asked ([`Pending::make`]). static KEPT_FOR_DRAWS: AtomicU64 = AtomicU64::new(0); @@ -1026,8 +1100,20 @@ fn progress() { let mut batch_loaded_from = super::blobs::LOADED.load(Ordering::Relaxed); let mut empty_since: Option = None; let mut shown: Option<(u64, u64, bool)> = None; + let mut last_commit_sample = Instant::now(); + let mut commit_warning_active = false; loop { std::thread::sleep(Duration::from_millis(250)); + if keep_graphics_pipelines() && last_commit_sample.elapsed() >= COMMIT_SAMPLE_INTERVAL { + last_commit_sample = Instant::now(); + if let Some(commit) = SystemCommit::sample() { + let low = commit.headroom() < LOW_COMMIT_HEADROOM_BYTES; + if low && !commit_warning_active { + commit.report(LOW_COMMIT_HEADROOM_BYTES, "running"); + } + commit_warning_active = low; + } + } let waiting = WAITING.load(Ordering::Relaxed); let made = FINISHED.load(Ordering::Relaxed).saturating_sub(batch_from); let of = made + waiting; @@ -1041,6 +1127,7 @@ fn progress() { HOLD.store(false, Ordering::Relaxed); tracing::info!( made, + resident_graphics = KEPT_FOR_DRAWS.load(Ordering::Relaxed), loaded_with_blob = super::blobs::LOADED.load(Ordering::Relaxed), skipped_with_blob = super::blobs::PASSED_OVER.load(Ordering::Relaxed), created_without_blob = super::blobs::MADE.load(Ordering::Relaxed), @@ -1572,6 +1659,35 @@ fn flushed(queued: u64, waited: Duration, limit: Duration) -> bool { mod tests { use super::*; + #[test] + fn commit_headroom_saturates_at_zero() { + let commit = SystemCommit { used: 60 << 30, limit: 64 << 30 }; + assert_eq!(commit.headroom(), 4 << 30); + let over_limit = SystemCommit { used: 65 << 30, ..commit }; + assert_eq!(over_limit.headroom(), 0); + } + + #[test] + fn only_disk_warmed_unasked_pipelines_become_eligible_for_recreation() { + let base = Arc::new(Pending::new(Vec::new(), None)); + let quad = Pending::quad_of(&base); + for pipeline in [&*base, &quad] { + pipeline.queue_state.store(MAKING, Ordering::Relaxed); + assert!(!pipeline.release_if_unasked(true)); + assert!(!pipeline.warmed.load(Ordering::Relaxed)); + assert_eq!(pipeline.queue_state.load(Ordering::Relaxed), MAKING); + + pipeline.asked.store(0, Ordering::Relaxed); + assert!(!pipeline.release_if_unasked(false)); + assert_eq!(pipeline.queue_state.load(Ordering::Relaxed), MAKING); + + pipeline.asked.store(u64::MAX, Ordering::Relaxed); + assert!(pipeline.release_if_unasked(false)); + assert!(pipeline.warmed.load(Ordering::Relaxed)); + assert_eq!(pipeline.queue_state.load(Ordering::Relaxed), NOT_QUEUED); + } + } + #[test] fn parse_wait_budget_handles_opt_in_values() { assert_eq!(parse_wait_budget(None), None); diff --git a/crates/larp-hle/src/modules/d3d12x.rs b/crates/larp-hle/src/modules/d3d12x.rs index c6217c4..af891aa 100644 --- a/crates/larp-hle/src/modules/d3d12x.rs +++ b/crates/larp-hle/src/modules/d3d12x.rs @@ -42,7 +42,9 @@ pub fn use_shader_cache(dir: std::path::PathBuf, pipelines: std::path::PathBuf) larp_gpu::shader_cache::use_shader_cache(dir); } -pub use larp_gpu::pipeline::{save_pipeline_cache, stacks_at_stall, wait_until_all_made}; +pub use larp_gpu::pipeline::{ + configure_graphics_pipeline_residency, save_pipeline_cache, stacks_at_stall, wait_until_all_made, +}; /// Our own compiled shaders in place of translations, for the run's start and the offline /// translator. pub use larp_gpu::shader_replace; diff --git a/crates/larp-hle/src/settings.rs b/crates/larp-hle/src/settings.rs index bfcfc46..c686b69 100644 --- a/crates/larp-hle/src/settings.rs +++ b/crates/larp-hle/src/settings.rs @@ -385,7 +385,7 @@ pub fn menu_value(settings: &Path, key: &str) -> Option { /// The settings file's keys that are the layer's own and no option of the /// menu: `larp run` reads them before the title starts ([`layer_value`]). -pub const LAYER_KEYS: &[&str] = &["pipeline_cache_dir"]; +pub const LAYER_KEYS: &[&str] = &["pipeline_cache_dir", "keep_graphics_pipelines"]; /// The value of one of the layer's own keys ([`LAYER_KEYS`]) in the /// settings file at `settings`, as written (its last line); none without diff --git a/crates/larp-hle/src/settings/file.rs b/crates/larp-hle/src/settings/file.rs index e2b3904..9d27f02 100644 --- a/crates/larp-hle/src/settings/file.rs +++ b/crates/larp-hle/src/settings/file.rs @@ -199,14 +199,19 @@ pub(super) fn default_text() -> String { } // The layer's own keys (`super::LAYER_KEYS`), not in the menu. out.push_str( - "\n; The layer's own folders, read at the start. Not in the menu.\n\ + "\n; Layer settings read at startup.\n\ [layer]\n\ \n\ ; Pipeline cache folder. Where compiled pipelines (the driver's blobs) and the lists of the title's\n\ ; pipelines are kept, in place of the `pipelines` folder of the cache. A path with `;` or `#` in it\n\ ; cannot be written here (the variable takes any).\n\ ; Values: default, a folder's path. Takes effect at the next start. LARP_PIPELINE_CACHE_DIR wins over it.\n\ - pipeline_cache_dir = default\n", + pipeline_cache_dir = default\n\ + \n\ + ; Keep warmed graphics pipelines resident in system RAM. Enable only on PCs with 64 GB\n\ + ; or more of installed system RAM and sufficient commit headroom.\n\ + ; Values: default (off), off, on. Takes effect at the next start. LARP_KEEP_GRAPHICS_PIPELINES wins.\n\ + keep_graphics_pipelines = default\n", ); out } diff --git a/docs/environment-variables.md b/docs/environment-variables.md index a2a22e9..4f63795 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -83,6 +83,7 @@ Set these in `Larp\bin\launch.ps1` (or in your shell before running `larp.exe ru | `LARP_PIPELINE_CACHE_DIR` | `` | unset (`pipelines\` under `LARP_CACHE_DIR`) | Folder for the compiled pipeline cache only (`blobs-windows-v1-*`, `created-pipelines.bin`, `created-shaders.bin`, `quad-pipelines.txt`), e.g. on another drive; everything else stays under `LARP_CACHE_DIR`. Created if missing. Also `pipeline_cache_dir = ` in `data\\settings.ini`; the variable wins over the file. A folder that cannot be created (or is inside the larp source tree) is reported with one warning and the default is used. Moving the folder does not move existing files: copy them, or the pipelines are compiled again. | | `LARP_PIPELINE_BLOBS` | `0`, `1` | `1` | `0` keeps no compiled pipelines on disk (`pipelines\blobs-*`) and loads none from there: every pipeline is compiled anew each run, while the lists of earlier runs' pipelines are kept. A workaround for corruption from cached blobs under Wine with Mesa RADV (#732). | | `LARP_PIPELINE_WAIT_MS` | `<ms>` (e.g. `8`) | `0` (off) | Opt-in per-frame wait budget (ms) for non-lasting graphics pipelines to eliminate shader-compilation hitches while driving. | +| `LARP_KEEP_GRAPHICS_PIPELINES` | `0`, `1` | `0` (off) | Keeps warmed graphics pipelines in system RAM to reduce first-use hitches. Enable only with **64 GB or more of installed system RAM** and sufficient Windows commit headroom. The page file and memory committed by other processes affect that headroom. The log reports current commit and the limit at startup, warns below 64 GiB of startup headroom, and checks every 30 seconds for headroom below 8 GiB during play. Set `keep_graphics_pipelines = on` under `[layer]` in `data\<title id>\settings.ini` for a persistent setting. The environment variable takes precedence when set. Restart to apply. | | `LARP_LANGUAGE` | `auto`, `en`, `de`, `fr`, `es`, `pl`, `pt-BR`, `tr`, `zh-CN`, `zh-TW` | `auto` (OS UI) | UI/overlay/CLI language (also switchable live in the `F10` menu or via `--lang`). | | `LARP_DSTORAGE_WORKERS` | `<1..64>` | logical cores | Worker thread count for DirectStorage decompression. | | `LARP_DSTORAGE_STAGING_MB` | `<16..512>` | `32` | DirectStorage staging buffer size in MiB for fast NVMe drives. |