From e58293b01a1789c598525d8e6ee5c6836960dbf4 Mon Sep 17 00:00:00 2001 From: mokkamokacaffe <329663686+mokkamokacaffe@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:10:13 +0100 Subject: [PATCH 1/2] shaders: benchmark direct DXIL PSO compilation --- README.md | 12 +++- crates/xcl/src/gpu/recomp/pso.rs | 2 +- crates/xcl/src/main.rs | 5 +- crates/xcl/src/shaders.rs | 99 ++++++++++++++++++++++++-------- 4 files changed, 91 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index d9d151320..f2a9f601e 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,8 @@ xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compi xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build compute pipelines and save driver blobs for the next run xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines --used-only # only the compute pipelines an earlier run of the title used xcl shaders D:\data\shaders.rpf --export-hlsl out --record-hash HEX # exact compute HLSL for investigation -xcl shaders D:\data\shaders.rpf --measure-pso HEX --repeat 3 # cold driver PSO timing (cache disabled) +xcl shaders D:\data\shaders.rpf --measure-pso HEX --repeat 3 # driver PSO timing (cache-disable requested) +xcl shaders D:\data\shaders.rpf --measure-pso HEX --backend direct --repeat 3 --json xcl rpf D:\data\shaders.rpf --extract NAME --out folder ``` @@ -233,6 +234,15 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder blob is left to the runtime instead of being compiled in the pass — those compiles take tens of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB` sets the cap in KiB (0 turns it off). + +`--measure-pso --json` reports the exact shader hash and name, backend, selected DXGI +adapter, translation/DXC time, DXIL size, and every driver PSO time after D3D12 accepted a +cache-disable request. That API is a hint: a driver may still reuse an internal or on-disk +result, so a fast repeat is not proof of a cold compile. Record the driver version, OS build, +full command line, GPU power settings and any vendor-specific cache control beside the JSON; +compare interleaved HLSL/direct runs of the same hash and do not treat an in-game FPS +screenshot as a shader-compiler benchmark. + - **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a game…* (pick its exe or `MicrosoftGame.config`) or *Run again* (the last one). On an error the window stays open until Enter. diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index c9a50b72b..b23fefa15 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -812,7 +812,7 @@ fn direct_fallback(stage: &str, err: &str) { /// A console compute shader through the direct DXIL translator (`gpu::dxil::kernel`). /// FSPX (driver) containers are left to the HLSL path. -fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result { +pub(crate) fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result { let sh = xbox::parse(blob).ok_or("not a console shader container")?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)).ok_or("no hardware CS variant")?; let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) }; diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 6291b5dea..dc95916fe 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -36,8 +36,9 @@ Usage: --compile N: additionally compiles N complete translations with DXC. --export-hlsl DIR [--count N] [--min-kb N] [--record-hash HEX]: writes deterministic compute HLSL for investigation; an exact hash bypasses the size threshold. - --measure-pso HEX [--repeat N]: times cache-disabled driver compilation of one exact - compute record with XCL's real root signature and static samplers. + --measure-pso HEX [--repeat N] [--backend hlsl|direct] [--json]: + times cache-disabled driver compilation of one exact compute record. + The default backend is hlsl. Direct translation failures are reported. --direct [--sample N] [--seed S] [--validate] [--compare]: direct DXIL translator coverage over a seeded sample (default 200 programs, 0 = all); also --timeout, --max-bytes, --threads, --json, --hash H, --dump DIR. diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 68ee30332..5f54ed9a4 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -4,7 +4,7 @@ //! or an RPF9 shader pack (records found by scanning, see `gpu::pack`). `--recomp` //! translates every program to HLSL (kernel mode) and reports what is still missing; //! `--compile N` also compiles N of the complete translations with DXC. `--export-hlsl` -//! writes deterministic compute HLSL, and `--measure-pso` times one exact driver compile. +//! writes deterministic compute HLSL, and `--measure-pso` times one exact driver PSO creation. use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::{Path, PathBuf}; @@ -876,6 +876,19 @@ pub fn run(path: &Path, args: &[String]) -> i32 { ); } if let Some(hash) = measure { + let direct = match required("--backend") { + Ok(None) => false, + Ok(Some(v)) if v == "hlsl" => false, + Ok(Some(v)) if v == "direct" => true, + Ok(Some(_)) => { + eprintln!("xcl shaders: --backend must be hlsl or direct"); + return 2; + } + Err(e) => { + eprintln!("{e}"); + return 2; + } + }; let hash = match parse_record_hash(hash) { Ok(h) => h, Err(e) => { @@ -889,6 +902,8 @@ pub fn run(path: &Path, args: &[String]) -> i32 { opt("--repeat").unwrap_or(1).max(1), runtime_windows(), opt("--split").map(|v| v != 0), + direct, + json, ); } if args.iter().any(|a| a == "--precompile") { @@ -1029,12 +1044,11 @@ enum MeasureError { Failed(String), } -/// Compile one exact console compute shader through DXC, then time only the driver's -/// `CreateComputePipelineState`. The implicit D3D and driver caches must both be disabled; -/// refusing to do that is an error rather than a misleading warm-cache measurement. -/// This is the HLSL path the runtime uses by default (not `XCL_DIRECT_DXIL`). -fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option) -> i32 { - match measure_pso_result(input, hash, repeat, windows, split) { +/// Translate one exact console compute shader, then time only the driver's +/// `CreateComputePipelineState`. D3D12 must accept disabling its implicit cache kinds, but +/// that control is a driver hint and does not prove that a measured call compiled cold. +fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option, direct: bool, json: bool) -> i32 { + match measure_pso_result(input, hash, repeat, windows, split, direct, json) { Ok(()) => 0, Err(MeasureError::Unavailable(e) | MeasureError::Failed(e)) => { eprintln!("xcl shaders --measure-pso: {e}"); @@ -1043,7 +1057,7 @@ fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Opt } } -fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option) -> Result<(), MeasureError> { +fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option, direct: bool, json: bool) -> Result<(), MeasureError> { use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; use MeasureError::{Failed, Unavailable}; @@ -1052,7 +1066,9 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl if !is_compute_container(&blob) { return Err(Failed(format!("{name} is not a console compute shader"))); } - recomp::dxc::location().map_err(|e| Unavailable(format!("DXC: {e}")))?; + if !direct { + recomp::dxc::location().map_err(|e| Unavailable(format!("DXC: {e}")))?; + } let pipeline = Pipelines::new().map_err(|e| Unavailable(format!("no GPU device: {e}")))?; // before translating and compiling (tens of seconds for a big program): a machine that // cannot turn the caches off fails at once @@ -1061,11 +1077,20 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) } .map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?; let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::pso::wave32_only_for_device(&pipeline.dev)); - let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?; - let dxc_start = std::time::Instant::now(); - let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?; - let dxc_ms = dxc_start.elapsed().as_millis(); - let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, &translation.static_samplers).map_err(|e| Failed(format!("root signature: {e}")))?; + let start = std::time::Instant::now(); + let (dxil, samplers, translation_ms, hlsl_bytes, dxc_ms) = if direct { + let compiled = recomp::pso::direct_compute(&blob, 0, windows, split) + .map_err(|e| Failed(format!("{name}: direct DXIL: {e}")))?; + (compiled.dxil, compiled.samplers, start.elapsed().as_secs_f64() * 1000.0, None, None) + } else { + let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split) + .map_err(|e| Failed(format!("{name}: {e}")))?; + let translation_ms = start.elapsed().as_secs_f64() * 1000.0; + let dxc_start = std::time::Instant::now(); + let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?; + (dxil, translation.static_samplers, translation_ms, Some(translation.hlsl.len()), Some(dxc_start.elapsed().as_secs_f64() * 1000.0)) + }; + let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, &samplers).map_err(|e| Failed(format!("root signature: {e}")))?; let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::ManuallyDrop::new(Some(rs)), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, @@ -1084,7 +1109,9 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl break; } } - println!("PSO run {run}/{repeat}: {:.3} s", elapsed.as_secs_f64()); + if !json { + println!("PSO run {run}/{repeat}: {:.3} s", elapsed.as_secs_f64()); + } times.push(elapsed.as_secs_f64()); } // the root signature's reference, on every path @@ -1092,14 +1119,34 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl if let Some(e) = failure { return Err(e); } - times.sort_by(f64::total_cmp); - let median = if times.len() & 1 == 0 { (times[times.len() / 2 - 1] + times[times.len() / 2]) / 2.0 } else { times[times.len() / 2] }; + let mut sorted = times.clone(); + sorted.sort_by(f64::total_cmp); + let backend = if direct { "direct" } else { "hlsl" }; + let mid = sorted.len() / 2; + let median = if sorted.len() & 1 == 0 { (sorted[mid - 1] + sorted[mid]) / 2.0 } else { sorted[mid] }; + if json { + println!("{}", serde_json::json!({ + // Keep enough context in every result to reject the kind of unqualified FPS or + // compile-time claim that cannot be reproduced on another adapter. Driver version, + // OS build, and command line remain properties of the benchmark host/run manifest. + "record_hash": format!("{hash:016x}"), "record_name": name, + "backend": backend, "adapter": pipeline.adapter, + "windows": windows & !recomp::HEAP_WINDOWS, "heap_windows": windows & recomp::HEAP_WINDOWS != 0, + "split_wave64": split, "static_samplers": samplers, + "translation_ms": translation_ms, "hlsl_bytes": hlsl_bytes, "dxc_ms": dxc_ms, + "dxil_bytes": dxil.len(), "driver_seconds": times, "driver_median_seconds": median, + "cache_disable_requested": true, "cold_compile_verified": false + })); + return Ok(()); + } + let dxc = dxc_ms.map_or_else(String::new, |ms| format!(", {ms:.3} ms DXC")); println!( - "PSO {hash:016x}: {} bytes DXIL, {dxc_ms} ms DXC, {repeat} cache-off run(s), median {:.3} s, min {:.3} s, max {:.3} s, {name}", + "PSO {hash:016x} ({backend}, {}): {} bytes DXIL, {translation_ms:.3} ms translation{dxc}, {repeat} cache-disable-requested run(s), median {:.3} s, min {:.3} s, max {:.3} s, {name} (cold compilation is not verified)", + pipeline.adapter, dxil.len(), median, - times[0], - times[times.len() - 1] + sorted[0], + sorted[sorted.len() - 1] ); Ok(()) } @@ -1124,6 +1171,9 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl /// (the > 8 MB HLSL programs DXC compiles at `-O0`, #1269). struct Pipelines { dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, + /// DXGI adapter name recorded with cold-compile measurements. A timing without the + /// adapter (and the run manifest's driver version) is not a comparable benchmark. + adapter: String, signatures: Mutex, windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, made: AtomicUsize, refused: AtomicUsize, @@ -1212,11 +1262,12 @@ impl Pipelines { unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; let sel = crate::gpu::adapter::Selector::from_env_or("auto"); - let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + let adapter_name = crate::gpu::adapter::name(&desc); let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); - Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), capped: AtomicUsize::new(0), capped_bytes: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most, max_dxil }) + Ok(Pipelines { dev, adapter: adapter_name, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), capped: AtomicUsize::new(0), capped_bytes: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most, max_dxil }) } } @@ -1897,6 +1948,8 @@ mod tests { assert_eq!(run(&dir, &args(&["--export-hlsl", "--record-hash", "DEADBEEF"])), 2); assert!(!std::path::Path::new("--record-hash").exists(), "the next flag is not taken as the value"); assert_eq!(run(&dir, &args(&["--measure-pso"])), 2); + assert_eq!(run(&dir, &args(&["--measure-pso", "deadbeef", "--backend", "--json"])), 2); + assert_eq!(run(&dir, &args(&["--measure-pso", "deadbeef", "--backend", "auto"])), 2); assert_eq!(run(&dir, &args(&["--export-hlsl", "out", "--record-hash"])), 2); let _ = std::fs::remove_dir_all(&dir); } @@ -1917,7 +1970,7 @@ mod tests { let blob = compute_sample(); std::fs::write(&path.0, &blob).unwrap(); let hash = shader::fnv64(&blob); - match measure_pso_result(&Input::Files(vec![path.0.clone()]), hash, 1, 4, None) { + match measure_pso_result(&Input::Files(vec![path.0.clone()]), hash, 1, 4, None, false, false) { Ok(()) => {} // no DXC, a WARP-only or cacheless device, cache control without Developer Mode Err(MeasureError::Unavailable(e)) => recomp::runner::skip_test(&e), From 2cc2ba1ac89b53e3e025ea273e29e4c5d45f92c4 Mon Sep 17 00:00:00 2001 From: Daydream3r <25246982+Daydream3r@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:44:43 +0100 Subject: [PATCH 2/2] Scripts: measure NVIDIA PSOs with a temporary cache-off profile ShaderCacheControl succeeds on this RTX 5070 Ti but repeated PSO creation still reuses compiled results. Associate a unique sibling executable with a temporary NVIDIA cache-off profile, then remove both after success or failure. Part of #1269. Depends on the JSON/backend measurement support in #1802. Profile lifetime tests and real NVIDIA controls verify cleanup and eliminate the observed millisecond repeat timings. Assisted-by: Codex desktop (GPT-6; exact variant not exposed) --- README.md | 11 +++ THIRD_PARTY.md | 1 + scripts/measure-nvidia-pso.ps1 | 148 ++++++++++++++++++++++++++++ scripts/test-measure-nvidia-pso.ps1 | 26 +++++ 4 files changed, 186 insertions(+) create mode 100644 scripts/measure-nvidia-pso.ps1 create mode 100644 scripts/test-measure-nvidia-pso.ps1 diff --git a/README.md b/README.md index f2a9f601e..22fd61cfc 100644 --- a/README.md +++ b/README.md @@ -243,6 +243,17 @@ full command line, GPU power settings and any vendor-specific cache control besi compare interleaved HLSL/direct runs of the same hash and do not treat an in-game FPS screenshot as a shader-compiler benchmark. +On NVIDIA, successful `ShaderCacheControl` calls can still leave repeat measurements +cached. With the JSON/backend measurement support above, use +`scripts/measure-nvidia-pso.ps1 -Pack D:\data\shaders.rpf -Hash HEX -Backend direct`. +It copies the exe beside the original, registers a unique temporary NVIDIA profile +with the shader disk cache off, and removes both afterwards, including on measurement +failure. Other profiles and shared cache files are untouched. Run HLSL/direct +interleaved and check the individual timings; this is compilation time, not GPU +execution time. If the script is forcibly terminated, its printed `XCL cold PSO ...` +profile may need removal from NVIDIA settings. Requires Windows NVIDIA NVAPI and +permission to save an application profile; existing application matches cause an error. + - **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a game…* (pick its exe or `MicrosoftGame.config`) or *Run again* (the last one). On an error the window stays open until Enter. diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 9868e3454..9a4730714 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -14,6 +14,7 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | +| [NVIDIA NVAPI](https://github.com/NVIDIA/nvapi) | MIT | no SDK code; function signatures, IDs and structure layout facts in `scripts/measure-nvidia-pso.ps1` | independently written bindings; system driver DLL loaded at runtime, not distributed | | Windows XGameRuntime (`System32\xgameruntime.dll`) | system | class GUIDs and slot order of the GDK thunk protocol in `hle/xgameruntime/api.rs` (facts, determined by analysis); APIs XCL does not implement are forwarded to it at runtime | interoperability; not distributed | | docs.xbox.com | documentation | signatures, enums, structs written independently | reference | | Rust crates (`Cargo.lock`) | MIT / BSD-2 / Zlib / Unlicense (or with an MIT alternative) | build dependencies | statically linked | diff --git a/scripts/measure-nvidia-pso.ps1 b/scripts/measure-nvidia-pso.ps1 new file mode 100644 index 000000000..69a091444 --- /dev/null +++ b/scripts/measure-nvidia-pso.ps1 @@ -0,0 +1,148 @@ +# NVIDIA cold PSO measurements for #1269. Requires the JSON/backend support in #1802. +param( + [string]$Pack, + [string]$Hash, + [ValidateSet('hlsl', 'direct')][string]$Backend = 'hlsl', + [ValidateRange(1, 20)][int]$Repeat = 3, + [string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe') +) +$ErrorActionPreference = 'Stop' + +# Keep the profile lifetime testable without touching the driver. A failed creation +# has not saved anything; a failed measurement must still remove the saved profile. +function Invoke-ColdPsoScope { + param([scriptblock]$Create, [scriptblock]$Measure, [scriptblock]$Remove) + & $Create + try { & $Measure } finally { & $Remove } +} + +function Initialize-NvidiaPsoProfile { + if ('XclColdPso.Profile' -as [type]) { return } + # Independently written ABI bindings; signatures, IDs and layout facts from + # NVIDIA/nvapi nvapi.h, nvapi_interface.h, NvApiDriverSettings.h (MIT). + # https://github.com/NVIDIA/nvapi . No SDK files or driver binaries are bundled. + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +using System.Text; +namespace XclColdPso { + public static class Profile { + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + static extern IntPtr LoadLibraryExW(string name, IntPtr file, uint flags); + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] + static extern IntPtr GetProcAddress(IntPtr module, string name); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate IntPtr Query(uint id); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int Init(); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int NewSession(out IntPtr s); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int SessionCall(IntPtr s); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int Find(IntPtr s, IntPtr name, out IntPtr p); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int Pair(IntPtr s, IntPtr p); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int Triple(IntPtr s, IntPtr p, IntPtr data); + static readonly Query query; + static Profile() { + IntPtr dll = LoadLibraryExW("nvapi64.dll", IntPtr.Zero, 0x800); // System32 only + if (dll == IntPtr.Zero) throw new Exception("nvapi64.dll is unavailable"); + IntPtr entry = GetProcAddress(dll, "nvapi_QueryInterface"); + if (entry == IntPtr.Zero) throw new Exception("nvapi_QueryInterface is unavailable"); + query = (Query)Marshal.GetDelegateForFunctionPointer(entry, typeof(Query)); + Check("initialize", Fn(0x0150e828)()); + } + static T Fn(uint id) where T : class { + IntPtr p = query(id); + if (p == IntPtr.Zero) throw new Exception("NVAPI entry unavailable: " + id.ToString("x")); + return (T)(object)Marshal.GetDelegateForFunctionPointer(p, typeof(T)); + } + static void Check(string operation, int status) { + if (status != 0) throw new Exception("NVAPI " + operation + ": " + status); + } + sealed class Buffer : IDisposable { + public readonly IntPtr P; + public Buffer(int bytes, bool versioned) { + P = Marshal.AllocHGlobal(bytes); + Marshal.Copy(new byte[bytes], 0, P, bytes); + if (versioned) Marshal.WriteInt32(P, bytes | (1 << 16)); + } + public void Text(int offset, string value) { + if (value.Length >= 2048 || value.IndexOf('\0') >= 0) throw new ArgumentException("NVAPI string too long or contains NUL"); + byte[] bytes = Encoding.Unicode.GetBytes(value + "\0"); + Marshal.Copy(bytes, 0, IntPtr.Add(P, offset), bytes.Length); + } + public void Dispose() { Marshal.FreeHGlobal(P); } + } + public static void Change(string name, string exe, bool create) { + if (!System.Text.RegularExpressions.Regex.IsMatch(name, @"\AXCL cold PSO [0-9a-f]{32}\z")) + throw new ArgumentException("Not a temporary cold PSO profile name"); + IntPtr session; + Check("create session", Fn(0x0694d52e)(out session)); + try { + Check("load settings", Fn(0x375dbd6b)(session)); + using (var text = new Buffer(4096, false)) { + text.Text(0, name); + IntPtr profile; + int found = Fn(0x7e4a9a0b)(session, text.P, out profile); + if (!create) { + if (found == -163) return; // profile not found + Check("find temporary profile", found); + Check("delete temporary profile", Fn(0x17093206)(session, profile)); + } else { + if (found != -163) throw new Exception("Refusing to replace an existing profile"); + using (var info = new Buffer(4116, true)) { // NVDRS_PROFILE_V1 + info.Text(4, name); + Check("create temporary profile", Fn(0xcc176068)(session, info.P, out profile)); + } + using (var app = new Buffer(12296, true)) { // NVDRS_APPLICATION_V1 + app.Text(8, exe); + Check("register probe exe (existing matches are left unchanged)", Fn(0x4347a9de)(session, profile, app.P)); + } + using (var setting = new Buffer(12320, true)) { // NVDRS_SETTING_V1, pack 4 + Marshal.WriteInt32(setting.P, 4100, 0x00198fff); // PS_SHADERDISKCACHE_ID + // DWORD type = 0; current value at 8220 = 0 (OFF). + Check("disable probe disk cache", Fn(0x577dd202)(session, profile, setting.P)); + } + } + Check("save settings", Fn(0xfcbc7e14)(session)); + } + } finally { Check("destroy session", Fn(0xdad9cff8)(session)); } + } + } +} +'@ +} + +function Invoke-NvidiaColdPso { + if ($Hash -notmatch '\A[0-9a-fA-F]{16}\z') { throw 'Hash must be exactly 16 hexadecimal digits.' } + $packPath = (Resolve-Path -LiteralPath $Pack).ProviderPath + $source = (Resolve-Path -LiteralPath $Xcl).ProviderPath + $id = [guid]::NewGuid().ToString('N') + $profile = "XCL cold PSO $id" + # Avoid x*.exe: NVIDIA predefined wildcard profiles can match those names. + $probe = Join-Path (Split-Path $source -Parent) "coldpso$id.exe" + Initialize-NvidiaPsoProfile + Copy-Item -LiteralPath $source -Destination $probe + try { + Invoke-ColdPsoScope -Create { + [XclColdPso.Profile]::Change($profile, $probe, $true) + Write-Host "Temporary NVIDIA profile: $profile" + } -Measure { + $raw = & $probe shaders $packPath --measure-pso $Hash --backend $Backend --windows 4 --split 1 --repeat $Repeat --json + if ($LASTEXITCODE -ne 0) { throw "xcl measurement failed: $LASTEXITCODE" } + $result = ($raw -join "`n") | ConvertFrom-Json + if ($result.backend -ne $Backend -or $result.adapter -notlike '*NVIDIA*' -or $result.driver_seconds.Count -ne $Repeat) { + throw 'Expected NVIDIA/backend JSON from #1802; this result is not a supported measurement.' + } + $result | Add-Member -NotePropertyName cache_control -NotePropertyValue 'temporary_nvidia_profile_off' + $result | ConvertTo-Json -Depth 8 -Compress + } -Remove { + try { + [XclColdPso.Profile]::Change($profile, $probe, $false) + Write-Host "Removed temporary NVIDIA profile: $profile" + } + catch { throw "Could not remove temporary profile '$profile': $_" } + } + } finally { + # The only file removed is this invocation's new, exact sibling of xcl.exe. + Remove-Item -LiteralPath $probe + } +} + +if ($MyInvocation.InvocationName -ne '.') { Invoke-NvidiaColdPso } diff --git a/scripts/test-measure-nvidia-pso.ps1 b/scripts/test-measure-nvidia-pso.ps1 new file mode 100644 index 000000000..d2cfdf74e --- /dev/null +++ b/scripts/test-measure-nvidia-pso.ps1 @@ -0,0 +1,26 @@ +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'measure-nvidia-pso.ps1') + +foreach ($failure in 'none', 'create', 'measure', 'remove') { + $events = [System.Collections.Generic.List[string]]::new() + $caught = $null + try { + Invoke-ColdPsoScope -Create { + $events.Add('create') + if ($failure -eq 'create') { throw 'creation failed' } + } -Measure { + $events.Add('measure') + if ($failure -eq 'measure') { throw 'measurement failed' } + } -Remove { + $events.Add('remove') + if ($failure -eq 'remove') { throw 'cleanup failed' } + } + } catch { $caught = $_.Exception.Message } + $expected = if ($failure -eq 'create') { 'create' } else { 'create,measure,remove' } + if (($events -join ',') -ne $expected) { throw "Wrong profile lifetime for $failure`: $events" } + if ($failure -eq 'none' -and $caught) { throw $caught } + if ($failure -eq 'create' -and $caught -ne 'creation failed') { throw 'Creation failure lost.' } + if ($failure -eq 'measure' -and $caught -ne 'measurement failed') { throw 'Measurement failure lost.' } + if ($failure -eq 'remove' -and $caught -ne 'cleanup failed') { throw 'Cleanup failure lost.' } +} +Write-Output '4 profile lifetime checks passed (no driver settings touched).'