diff --git a/README.md b/README.md index 1f67ee7a60..6cf89b82ad 100644 --- a/README.md +++ b/README.md @@ -427,7 +427,9 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. 4 KiB placements (`XCL_SMALL_TEXTURES=0`: a committed resource each), and 64 MB of idle texture upload buffers are kept (`XCL_UPLOAD_KEEP_MB`). Shader preparation starts no more workers than the RAM available holds (2 GB each, 4 GB left over) and the commit left (3 GB each); - `XCL_PREPARE_WORKERS=N` sets the number. + `XCL_PREPARE_WORKERS=N` sets the number. On AMD, `XCL_PREPARE_DRIVER_CACHE=1` starts no more + than 8 (fewer while other copies of `xcl.exe` run), each building several pipelines at once, so + everything they build lands in the driver's shader cache later runs read (off by default). - Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime classes asked for, shader statistics, audio formats, crash). `d3d12.presents` counts presentations, not visible content. With `XCL_FRAME_DUMP=N` (`N > 1`), diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index be3304d8d0..cb91e3bfbd 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -3381,7 +3381,7 @@ fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation, corpus: Optio if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS | if recomp::pso::heap_flat() { recomp::HEAP_FLAT } else { 0 }; } - let workers = prepare_workers(); + let (workers, threads) = driver_cache_split(prepare_workers(), &progress.adapter); for input in &inputs { let coverage = corpus.filter(|c| c.compute_directory().is_some()) .map(|corpus| ComputeCoverage::Published(corpus, Mutex::default(), AtomicUsize::new(0))); @@ -3394,7 +3394,7 @@ fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation, corpus: Optio std::time::Instant::now(), Some(progress), coverage.as_ref())?; if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } if coverage.as_ref().is_some_and(ComputeCoverage::all_staged) { continue; } - pipelines_in_workers(&pack, windows, workers, n, progress, coverage.as_ref())?; + pipelines_in_workers(&pack, windows, workers, threads, n, progress, coverage.as_ref())?; continue; } precompile(input, usize::MAX, windows, None, None, true, None, None, None, @@ -3402,7 +3402,7 @@ fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation, corpus: Optio } if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } if std::env::var("XCL_PREPARE_GRAPHICS").is_ok_and(|v| v.trim() == "0") { return Ok(()); } - graphics_in_workers(&inputs, windows, workers, progress, corpus.and_then(|c| c.graphics_path())) + graphics_in_workers(&inputs, windows, workers, threads, progress, corpus.and_then(|c| c.graphics_path())) } /// Only records verified byte-for-byte against the discovered corpus may leave their native @@ -3505,6 +3505,71 @@ fn workers_for(cores: usize, free_mb: u64, ram_mb: u64) -> usize { cores.saturating_sub(4).min(32).min((free_mb / 3072) as usize).min((ram_mb.saturating_sub(4096) / 2048) as usize).max(1) } +/// `XCL_PREPARE_DRIVER_CACHE=1` (off by default): on an AMD adapter, no more worker processes +/// than AMD's DX12 driver keeps its shader cache for. It keeps it in `%LOCALAPPDATA%\AMD\DxcCache` +/// in 10 parts for each executable file name: a process takes the first free part and keeps it, +/// and one more process of the same file name gets a cache of its own that no later run reads (on +/// an RX 9070 XT, a 21-process warm left 4.5 GB there and 20 of 117 slow pipelines were compiled +/// again at run time, 0.2–3.9 s each; ReVIctory, `crates/victory-gpu/src/pipeline/known.rs`). XCL's +/// own driver-blob cache is off on AMD, so the driver's is the one later runs read. The workers +/// (`prepare_workers`) and the pipelines each builds at once (`XCL_PIPELINE_THREADS`, 1 unless +/// set): `processes_for_driver_cache`, logged once. `XCL_PREPARE_WORKERS` still sets the number. +fn driver_cache_split(workers: usize, adapter: &str) -> (usize, usize) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var("XCL_PREPARE_DRIVER_CACHE").is_ok_and(|v| v.trim() == "1")) + || std::env::var_os("XCL_PREPARE_WORKERS").is_some() || adapter_vendor(adapter) != 0x1002 { + return (workers, 1); + } + let others = others_of_this_executable(); + let (processes, threads) = processes_for_driver_cache(workers, others); + crate::xlog_info!("Shader preparation: AMD driver cache: {processes} worker processes, {} pipelines at once in each (for {workers}; {others} other processes of this program running)", + std::env::var("XCL_PIPELINE_THREADS").unwrap_or_else(|_| threads.to_string())); + (processes, threads) +} + +/// The worker processes and the pipelines each builds at once for `workers` when `others` other +/// processes of this program run: at most 8, and of the driver's 10 cache parts one left for this +/// process (which hosts the title) and one for each other; no more pipelines at once in all than +/// `workers` (the RAM and commit `workers_for` left room for). +fn processes_for_driver_cache(workers: usize, others: usize) -> (usize, usize) { + let processes = workers.min(8).min(9usize.saturating_sub(others)).max(1); + (processes, (workers / processes).max(1)) +} + +/// The PCI vendor of the adapter preparation builds for, as `Pipelines::for_adapter` chooses it +/// (`XCL_ADAPTER`, then `adapter`); 0 for WARP or when there is none. +fn adapter_vendor(adapter: &str) -> u32 { + use windows::Win32::Graphics::Dxgi::*; + let sel = crate::gpu::adapter::Selector::from_env_or(adapter); + if sel == crate::gpu::adapter::Selector::Warp { return 0; } + let Ok(factory) = (unsafe { CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) }) else { return 0 }; + crate::gpu::adapter::candidates(&factory, &sel).first().map_or(0, |(_, desc)| desc.VendorId) +} + +/// The other running processes with this program's file name (the driver's cache parts are per +/// file name). +fn others_of_this_executable() -> usize { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS}; + let Some(name) = std::env::current_exe().ok().and_then(|p| Some(p.file_name()?.to_string_lossy().to_lowercase())) else { return 0 }; + let me = std::process::id(); + let mut n = 0; + unsafe { + let snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if snap == INVALID_HANDLE_VALUE { return 0; } + let mut pe: PROCESSENTRY32W = std::mem::zeroed(); + pe.dwSize = std::mem::size_of::() as u32; + let mut ok = Process32FirstW(snap, &mut pe) != 0; + while ok { + let len = pe.szExeFile.iter().position(|&c| c == 0).unwrap_or(pe.szExeFile.len()); + if pe.th32ProcessID != me && String::from_utf16_lossy(&pe.szExeFile[..len]).to_lowercase() == name { n += 1; } + ok = Process32NextW(snap, &mut pe) != 0; + } + CloseHandle(snap); + } + n +} + /// The record count of a builder's progress line (` 400/26503 (12 s)`). fn progress_count(line: &str) -> Option { let (d, rest) = line.trim().split_once('/')?; @@ -3516,7 +3581,7 @@ fn progress_count(line: &str) -> Option { /// The compute pipelines of `pack` built by `workers` processes of this program, each on its own /// slice of the records (`XCL_PRECOMPILE_SLICE`). A failed worker prevents guest entry. -fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation, +fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, threads: usize, records: usize, progress: &LaunchPreparation, coverage: Option<&ComputeCoverage>) -> Result<(), String> { let me = std::env::current_exe().map_err(|e| e.to_string())?; let series_s = crate::hle::d3d12x::pso_async::profile_is_series_s(); @@ -3530,6 +3595,7 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz let (cancelled, failed, _) = in_workers(workers, records, progress, |i| { let mut c = pipeline_worker_command(&me, pack, windows, used_only, &format!("{i}/{workers}"), series_s); if let Some((file, dir)) = &map { c.env(COVERAGE_MAP, &file.0).env(COVERAGE_DIR, dir); } + if threads > 1 && std::env::var_os("XCL_PIPELINE_THREADS").is_none() { c.env("XCL_PIPELINE_THREADS", threads.to_string()); } if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } c }); @@ -3710,7 +3776,7 @@ fn prepare_history_graphics( Ok(()) } -fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation, staged_graphics: Option<&Path>) -> Result<(), String> { +fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, threads: usize, progress: &LaunchPreparation, staged_graphics: Option<&Path>) -> Result<(), String> { let t0 = std::time::Instant::now(); let path = gfx_records::path(); let local = if path.try_exists().map_err(|e| e.to_string())? { gfx_records::read_history_payloads(&path)? } else { Vec::new() }; @@ -3786,6 +3852,7 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: c.arg("shaders").arg(&jobs[i].0).args(["--graphics-records", "--windows"]).arg((windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT)).to_string()); // (the title's adapter: its blobs are the ones it takes) if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } + if threads > 1 && std::env::var_os("XCL_PIPELINE_THREADS").is_none() { c.env("XCL_PIPELINE_THREADS", threads.to_string()); } c }); progress.graphics.store(false, Ordering::Relaxed); @@ -4767,6 +4834,29 @@ mod tests { assert_eq!(workers_for_commit(16, 0, 64 * GIB, 10 * GIB), 3); } + /// With `XCL_PREPARE_DRIVER_CACHE=1` on AMD: at most 8 processes, one cache part of the 10 left + /// for this process and one for each other process of this program, and no more pipelines at + /// once in all than the workers asked for. + #[test] + fn driver_cache_processes_leave_parts_for_this_and_other_processes() { + assert_eq!(processes_for_driver_cache(28, 0), (8, 3)); + assert_eq!(processes_for_driver_cache(28, 2), (7, 4)); + assert_eq!(processes_for_driver_cache(21, 0), (8, 2)); + assert_eq!(processes_for_driver_cache(9, 0), (8, 1)); + assert_eq!(processes_for_driver_cache(6, 0), (6, 1)); + assert_eq!(processes_for_driver_cache(12, 5), (4, 3)); + assert_eq!(processes_for_driver_cache(12, 8), (1, 12)); + assert_eq!(processes_for_driver_cache(12, 20), (1, 12)); + assert_eq!(processes_for_driver_cache(1, 0), (1, 1)); + for workers in 1..=32 { + for others in 0..12 { + let (processes, threads) = processes_for_driver_cache(workers, others); + assert!(processes <= 8 && (processes + others <= 9 || processes == 1)); + assert!(processes * threads <= workers && processes * (threads + 1) > workers); + } + } + } + /// A builder's progress line gives its record count; its other lines give none. #[test] fn a_builders_progress_line_gives_its_count() {