diff --git a/README.md b/README.md index 321cc03a9e..8a4819ce02 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,7 @@ xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines --used-only 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 rpf D:\data\shaders.rpf --extract NAME --out folder +xcl nvprofile install --mb 1024 # NVIDIA: a bigger shader heap for xcl.exe (elevated, once; #2403) ```
diff --git a/crates/xcl/src/gpu/mod.rs b/crates/xcl/src/gpu/mod.rs index 0264fdb555..2fcd4f6945 100644 --- a/crates/xcl/src/gpu/mod.rs +++ b/crates/xcl/src/gpu/mod.rs @@ -8,6 +8,7 @@ pub mod desc; pub mod dxbc; pub mod dxil; pub mod effects; +pub mod nvprofile; pub(crate) mod fence; pub mod pack; pub mod rdna2; diff --git a/crates/xcl/src/gpu/nvprofile.rs b/crates/xcl/src/gpu/nvprofile.rs new file mode 100644 index 0000000000..f868d04b19 --- /dev/null +++ b/crates/xcl/src/gpu/nvprofile.rs @@ -0,0 +1,415 @@ +//! An NVIDIA driver profile (DRS) for an executable, written through NVAPI (#2403). +//! +//! NVIDIA's D3D12 driver reserves 512 MB of VA for the machine code of the pipelines in use and +//! removes the device when a submission needs more. Setting `0x001ABC0F` ("the amount of VA space +//! in bytes reserved for the shader heap") in a profile for the executable raises it; NVIDIA's own +//! profiles use 1 or 2 GiB. This writes that one setting into a profile named [`PROFILE`] that +//! holds only XCL's executables, so [`remove`] takes it out again without touching anything else. + +use std::ffi::c_void; + +/// The setting: VA space in bytes reserved for the shader heap (a multiple of 64 KiB). +pub const SHADER_HEAP_VA: u32 = 0x001A_BC0F; +/// The profile XCL owns. +pub const PROFILE: &str = "XCL (xcl-dev)"; + +const UNICODE_LEN: usize = 2048; +type Wide = [u16; UNICODE_LEN]; +type Handle = *mut c_void; + +#[repr(C)] +struct Profile { + version: u32, + name: Wide, + gpu_support: u32, + is_predefined: u32, + num_apps: u32, + num_settings: u32, +} + +#[repr(C)] +struct Application { + version: u32, + is_predefined: u32, + app_name: Wide, + friendly_name: Wide, + launcher: Wide, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct Binary { + len: u32, + data: [u8; 4096], +} + +#[repr(C)] +#[derive(Clone, Copy)] +union Value { + u32: u32, + binary: Binary, + wide: Wide, +} + +#[repr(C)] +struct Setting { + version: u32, + name: Wide, + id: u32, + kind: u32, + location: u32, + is_current_predefined: u32, + is_predefined_valid: u32, + predefined: Value, + current: Value, +} + +const fn ver(v: u32) -> u32 { + std::mem::size_of::() as u32 | (v << 16) +} + +fn wide(s: &str) -> Wide { + let mut w = [0u16; UNICODE_LEN]; + for (d, c) in w.iter_mut().zip(s.encode_utf16().take(UNICODE_LEN - 1)) { + *d = c; + } + w +} + +fn zeroed() -> Box { + // SAFETY: every type here is plain integers / arrays, for which all-zero is valid. + unsafe { Box::new(std::mem::zeroed()) } +} + +type Status = i32; +const OK: Status = 0; +const INVALID_USER_PRIVILEGE: Status = -137; +const SETTING_NOT_FOUND: Status = -160; +const PROFILE_NOT_FOUND: Status = -163; +const EXECUTABLE_NOT_FOUND: Status = -166; // values from NVIDIA/nvapi nvapi_lite_common.h + +struct Api { + create_session: unsafe extern "C" fn(*mut Handle) -> Status, + destroy_session: unsafe extern "C" fn(Handle) -> Status, + load: unsafe extern "C" fn(Handle) -> Status, + save: unsafe extern "C" fn(Handle) -> Status, + find_app: unsafe extern "C" fn(Handle, *const u16, *mut Handle, *mut Application) -> Status, + find_profile: unsafe extern "C" fn(Handle, *const u16, *mut Handle) -> Status, + create_profile: unsafe extern "C" fn(Handle, *mut Profile, *mut Handle) -> Status, + delete_profile: unsafe extern "C" fn(Handle, Handle) -> Status, + create_app: unsafe extern "C" fn(Handle, Handle, *mut Application) -> Status, + set_setting: unsafe extern "C" fn(Handle, Handle, *mut Setting) -> Status, + get_setting: unsafe extern "C" fn(Handle, Handle, u32, *mut Setting) -> Status, + profile_info: unsafe extern "C" fn(Handle, Handle, *mut Profile) -> Status, + enum_apps: unsafe extern "C" fn(Handle, Handle, u32, *mut u32, *mut Application) -> Status, +} + +fn api() -> Result { + use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; + unsafe { + let lib = LoadLibraryW(windows::core::w!("nvapi64.dll")).map_err(|e| format!("no nvapi64.dll: {e}"))?; + let qi = GetProcAddress(lib, windows::core::s!("nvapi_QueryInterface")).ok_or("no nvapi_QueryInterface")?; + let qi: unsafe extern "C" fn(u32) -> *const c_void = std::mem::transmute(qi); + let get = |id: u32| { + let p = qi(id); + if p.is_null() { Err(format!("NVAPI has no function {id:#010x}")) } else { Ok(p) } + }; + let init: unsafe extern "C" fn() -> Status = std::mem::transmute(get(0x0150_E828)?); + let s = init(); + if s != OK { + return Err(format!("NvAPI_Initialize: {s}")); + } + Ok(Api { + create_session: std::mem::transmute(get(0x0694_D52E)?), + destroy_session: std::mem::transmute(get(0xDAD9_CFF8)?), + load: std::mem::transmute(get(0x375D_BD6B)?), + save: std::mem::transmute(get(0xFCBC_7E14)?), + find_app: std::mem::transmute(get(0xEEE5_66B2)?), + find_profile: std::mem::transmute(get(0x7E4A_9A0B)?), + create_profile: std::mem::transmute(get(0xCC17_6068)?), + delete_profile: std::mem::transmute(get(0x1709_3206)?), + create_app: std::mem::transmute(get(0x4347_A9DE)?), + set_setting: std::mem::transmute(get(0x577D_D202)?), + get_setting: std::mem::transmute(get(0x73BF_8338)?), + profile_info: std::mem::transmute(get(0x61CD_6FD6)?), + enum_apps: std::mem::transmute(get(0x7FA2_173A)?), + }) + } +} + +struct Session<'a> { + api: &'a Api, + h: Handle, +} + +impl<'a> Session<'a> { + fn open(api: &'a Api) -> Result { + let mut h = std::ptr::null_mut(); + unsafe { + check("CreateSession", (api.create_session)(&mut h))?; + let s = Session { api, h }; + check("LoadSettings", (api.load)(h))?; + Ok(s) + } + } +} + +impl Drop for Session<'_> { + fn drop(&mut self) { + unsafe { (self.api.destroy_session)(self.h) }; + } +} + +fn check(what: &str, s: Status) -> Result<(), String> { + if s == OK { Ok(()) } else { Err(format!("NvAPI_DRS_{what}: {s}")) } +} + +/// A lookup's result: `true` when found, `false` only for NVAPI's not-found codes, and an error for +/// anything else (an ambiguous executable path, a failed call), so a failure is not read as absence. +fn found(what: &str, s: Status) -> Result { + match s { + OK => Ok(true), + SETTING_NOT_FOUND | PROFILE_NOT_FOUND | EXECUTABLE_NOT_FOUND => Ok(false), + _ => Err(format!("NvAPI_DRS_{what}: {s}")), + } +} + +/// Whether a profile named [`PROFILE`] holds only what [`install`] puts there: none of NVIDIA's +/// predefined content, no application but `exes`, and no setting but the shader heap. A profile +/// someone else made under that name, or added to, is left alone by `install` and `remove`. +fn owned(predefined: bool, apps: &[String], settings: u32, has_heap: bool, exes: &[&str]) -> bool { + !predefined + && apps.iter().all(|a| exes.iter().any(|e| a.eq_ignore_ascii_case(e))) + && (settings == 0 || (settings == 1 && has_heap)) +} + +/// Errors unless `profile` is [`owned`] by XCL. +unsafe fn check_owned(api: &Api, s: Handle, profile: Handle, exes: &[&str]) -> Result<(), String> { + let mut p = zeroed::(); + p.version = ver::(1); + check("GetProfileInfo", (api.profile_info)(s, profile, &mut *p))?; + let mut apps = Vec::new(); + for i in 0..p.num_apps { + let mut a = zeroed::(); + a.version = ver::(1); + let mut n = 1; + check("EnumApplications", (api.enum_apps)(s, profile, i, &mut n, &mut *a))?; + let len = a.app_name.iter().position(|&c| c == 0).unwrap_or(UNICODE_LEN); + apps.push(String::from_utf16_lossy(&a.app_name[..len])); + } + let mut set = zeroed::(); + set.version = ver::(1); + let has_heap = found("GetSetting", (api.get_setting)(s, profile, SHADER_HEAP_VA, &mut *set))?; + if owned(p.is_predefined != 0, &apps, p.num_settings, has_heap, exes) { + return Ok(()); + } + Err(format!( + "a profile named \"{PROFILE}\" already holds other applications or settings ({} applications: {}; {} settings), so XCL leaves it alone; rename or delete it (e.g. in NVIDIA Profile Inspector) and run this again", + apps.len(), + apps.join(", "), + p.num_settings + )) +} + +/// The shader heap the driver will reserve for `exe` (a file name such as `xcl.exe`): `None` where +/// the exe is in no profile or its profile does not set it (then the driver's 512 MB applies). +pub fn status(exe: &str) -> Result, String> { + let api = api()?; + let s = Session::open(&api)?; + let name = wide(exe); + let mut profile = std::ptr::null_mut(); + let mut app = zeroed::(); + app.version = ver::(1); + unsafe { + if !found("FindApplicationByName", (api.find_app)(s.h, name.as_ptr(), &mut profile, &mut *app))? { + return Ok(None); + } + let mut set = zeroed::(); + set.version = ver::(1); + if !found("GetSetting", (api.get_setting)(s.h, profile, SHADER_HEAP_VA, &mut *set))? { + return Ok(None); + } + Ok(Some(set.current.u32)) + } +} + +/// Puts `exes` into [`PROFILE`] (made if missing) with the shader heap at `bytes`, and saves. +/// Writing the driver's settings may need an elevated process. +pub fn install(exes: &[&str], bytes: u32) -> Result<(), String> { + if bytes % 0x1_0000 != 0 { + return Err("the shader heap must be a multiple of 64 KiB".into()); + } + let api = api()?; + let s = Session::open(&api)?; + let pname = wide(PROFILE); + let mut profile = std::ptr::null_mut(); + unsafe { + if !found("FindProfileByName", (api.find_profile)(s.h, pname.as_ptr(), &mut profile))? { + let mut p = zeroed::(); + p.version = ver::(1); + p.name = pname; + check("CreateProfile", (api.create_profile)(s.h, &mut *p, &mut profile))?; + } else { + check_owned(&api, s.h, profile, exes)?; + } + for exe in exes { + let mut app_profile = std::ptr::null_mut(); + let mut a = zeroed::(); + a.version = ver::(1); + let name = wide(exe); + if found("FindApplicationByName", (api.find_app)(s.h, name.as_ptr(), &mut app_profile, &mut *a))? + && app_profile == profile + { + continue; + } + let mut a = zeroed::(); + a.version = ver::(1); + a.app_name = name; + a.friendly_name = wide(exe); + check("CreateApplication", (api.create_app)(s.h, profile, &mut *a))?; + } + let mut set = zeroed::(); + set.version = ver::(1); + set.id = SHADER_HEAP_VA; + set.kind = 0; // NVDRS_DWORD_TYPE + set.current.u32 = bytes; + let r = (api.set_setting)(s.h, profile, &mut *set); + if r == INVALID_USER_PRIVILEGE { + return Err("writing the driver's settings needs an elevated prompt (run as administrator)".into()); + } + check("SetSetting", r)?; + check("SaveSettings", (api.save)(s.h)) + } +} + +/// Deletes [`PROFILE`], if there is one and it holds only `exes` and the shader heap. +pub fn remove(exes: &[&str]) -> Result { + let api = api()?; + let s = Session::open(&api)?; + let pname = wide(PROFILE); + let mut profile = std::ptr::null_mut(); + unsafe { + if !found("FindProfileByName", (api.find_profile)(s.h, pname.as_ptr(), &mut profile))? { + return Ok(false); + } + check_owned(&api, s.h, profile, exes)?; + check("DeleteProfile", (api.delete_profile)(s.h, profile))?; + check("SaveSettings", (api.save)(s.h))?; + } + Ok(true) +} + +/// What `xcl nvprofile` is asked to do. +#[derive(Debug, PartialEq)] +enum Command { + Status, + Install(u32), + Remove, +} + +fn parse(args: &[String]) -> Result { + let mut p = crate::cli::Parser::new(args); + let cmd = match p.next_arg() { + None | Some("status") => Command::Status, + Some("remove") => Command::Remove, + Some("install") => { + let mut mb = 1024; + while let Some(a) = p.next_arg() { + match a { + "--mb" => mb = p.parse_usize("--mb")?, + _ => return Err(crate::cli::Parser::unexpected(a)), + } + } + // 4096 MB is 2^32 bytes, which does not fit in the setting's u32. + if !(512..=4095).contains(&mb) { + return Err(format!("--mb {mb}: expected 512 - 4095")); + } + return Ok(Command::Install((mb as u32) << 20)); + } + Some(a) => return Err(crate::cli::Parser::unexpected(a)), + }; + match p.next_arg() { + Some(a) => Err(crate::cli::Parser::unexpected(a)), + None => Ok(cmd), + } +} + +/// `xcl nvprofile [status | install [--mb N] | remove]`. +pub fn run(args: &[String]) -> i32 { + let cmd = match parse(args) { + Ok(c) => c, + Err(e) => { + eprintln!("xcl nvprofile: {e}"); + return 2; + } + }; + let done = match cmd { + Command::Status => Ok(()), + Command::Install(bytes) => install(&["xcl.exe"], bytes).map(|()| println!("xcl.exe is in the profile \"{PROFILE}\"")), + Command::Remove => remove(&["xcl.exe"]).map(|had| println!("{}", if had { "profile removed" } else { "no XCL profile" })), + }; + let shown = done.and_then(|()| status("xcl.exe")).map(|v| match v { + Some(b) => println!("xcl.exe: shader heap {} MB", b >> 20), + None => println!("xcl.exe: the driver's default shader heap (512 MB on D3D12)"), + }); + match shown { + Ok(()) => 0, + Err(e) => { + eprintln!("xcl nvprofile: {e}"); + 1 + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn struct_sizes_match_nvapi() { + assert_eq!(std::mem::size_of::(), 4 + 4096 + 16); + assert_eq!(std::mem::size_of::(), 8 + 3 * 4096); + assert_eq!(std::mem::size_of::(), 4 + 4096 + 20 + 2 * 4100); + } + + #[test] + fn the_command_line_is_checked() { + let a = |s: &[&str]| parse(&s.iter().map(|x| x.to_string()).collect::>()); + assert_eq!(a(&[]), Ok(Command::Status)); + assert_eq!(a(&["remove"]), Ok(Command::Remove)); + assert_eq!(a(&["install"]), Ok(Command::Install(1 << 30))); + assert_eq!(a(&["install", "--mb", "2048"]), Ok(Command::Install(1 << 31))); + assert_eq!(a(&["install", "--mb", "4095"]), Ok(Command::Install(4095 << 20))); + assert!(a(&["install", "--mb", "4096"]).is_err()); + assert!(a(&["install", "--mb", "100"]).is_err()); + assert!(a(&["install", "--mb"]).is_err()); + assert!(a(&["status", "x"]).is_err()); + assert!(a(&["frobnicate"]).is_err()); + } + + #[test] + fn only_not_found_reads_as_absent() { + assert_eq!(found("x", OK), Ok(true)); + assert_eq!(found("x", PROFILE_NOT_FOUND), Ok(false)); + assert_eq!(found("x", EXECUTABLE_NOT_FOUND), Ok(false)); + assert_eq!(found("x", SETTING_NOT_FOUND), Ok(false)); + assert!(found("x", -1).is_err()); // NVAPI_ERROR + assert!(found("x", -182).is_err()); // NVAPI_EXECUTABLE_PATH_IS_AMBIGUOUS + } + + #[test] + fn only_a_profile_xcl_could_have_made_is_changed() { + let apps = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); + let x = &["xcl.exe"]; + // What install leaves, a run interrupted before the setting, and an empty profile. + assert!(owned(false, &apps(&["xcl.exe"]), 1, true, x)); + assert!(owned(false, &apps(&["XCL.EXE"]), 0, false, x)); + assert!(owned(false, &[], 0, false, x)); + // Someone else's application, another setting, or NVIDIA's own profile. + assert!(!owned(false, &apps(&["xcl.exe", "other.exe"]), 1, true, x)); + assert!(!owned(false, &apps(&["other.exe"]), 0, false, x)); + assert!(!owned(false, &apps(&["xcl.exe"]), 2, true, x)); + assert!(!owned(false, &apps(&["xcl.exe"]), 1, false, x)); + assert!(!owned(true, &apps(&["xcl.exe"]), 1, true, x)); + } +} diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 4c45685711..4eb10061a1 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -48,6 +48,10 @@ Usage: Lists or extracts readable inline records. Archives larger than 1 GB use a bounded-memory header probe; --probe requests it explicitly and --full overrides it. Use --probe only for header summaries, without --find, --extract, --out or --full. + xcl nvprofile [status | install [--mb N] | remove] + NVIDIA only: the driver profile of xcl.exe. `install` raises the shader heap the driver + reserves for pipelines in use (512 MB by default, a removed device past it, #2403) to + N MB (1024); it needs an elevated prompt once. `remove` takes XCL's profile out again. xcl --version "; @@ -75,6 +79,7 @@ fn main() { } Some("disasm") if args.len() >= 2 => xcl::disasm::run(&PathBuf::from(&args[1]), &args[2..]), Some("shaders") if args.len() >= 2 => xcl::shaders::run(&PathBuf::from(&args[1]), &args[2..]), + Some("nvprofile") => xcl::gpu::nvprofile::run(&args[1..]), Some("rpf") if args.len() >= 2 => xcl::rpf::run(&PathBuf::from(&args[1]), &args[2..]), Some("--version") | Some("-V") => { println!("xcl {}", env!("CARGO_PKG_VERSION"));