Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
- For compute shaders that XCL can split, the runtime first tries the saved driver blob for
the whole shader. A usable blob lets the GPU run it in one dispatch. If the blob is missing
or the driver rejects it, XCL builds the split pieces.
- **Compute driver cache**: programs with static samplers get cache filenames that include
their sampler state. The first run after upgrading can rebuild those blobs. Programs without
static samplers keep their existing filenames.
- **`--pipelines` size cap**: a compute program whose DXIL is over 8 MiB and that has no saved
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`
Expand Down
219 changes: 161 additions & 58 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,41 @@ fn graphics_wave32(device: *mut c_void) -> bool {
}
}

/// The debug layer (`d3d12_debug` / `XCL_D3D12_DEBUG`) and DRED (`XCL_DRED`), turned on before a
/// device is made: for the title's device (`init`) and the one `xcl shaders --pipelines` makes
/// its blobs on. The debug layer goes on once per process, and a device made before it is removed
/// then. Whether the debug layer was asked for.
pub(crate) fn enable_device_layers(cfg: &crate::config::Config) -> bool {
let debug = cfg.d3d12_debug || std::env::var_os("XCL_D3D12_DEBUG").is_some();
if debug {
match crate::gpu::agility::enable_debug_layer() {
Ok(()) => {
crate::xlog_info!("D3D12: debug layer enabled");
}
Err(e) => {
crate::xlog_warn!("D3D12: debug layer requested but unavailable: {e}");
}
}
}
// `XCL_DRED=1`: on a device removal the faulting address and the last GPU operations
// (logged by `log_device_removed`); no debug layer needed. Opt-in: with it XDefiant
// stalled in its first seconds twice.
if std::env::var_os("XCL_DRED").is_some() {
match crate::gpu::agility::configuration_interface::<ID3D12DeviceRemovedExtendedDataSettings>(
&CLSID_D3D12DeviceRemovedExtendedData,
) {
Ok(d) => unsafe {
d.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
d.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
},
Err(e) => {
crate::xlog_warn!("D3D12: DRED requested but unavailable: {e}");
}
}
}
debug
}

/// Create the process-wide D3D12 device (the adapter `d3d12_adapter` / `XCL_ADAPTER` chooses,
/// by default the high-performance GPU → WARP); once – later calls
/// return the existing device's adapter.
Expand All @@ -483,33 +518,7 @@ pub fn init() -> Result<String, String> {
}
crate::gpu::agility::State::NotFound => {}
}
let debug = cfg.d3d12_debug || std::env::var_os("XCL_D3D12_DEBUG").is_some();
if debug {
match crate::gpu::agility::enable_debug_layer() {
Ok(()) => {
crate::xlog_info!("D3D12: debug layer enabled");
}
Err(e) => {
crate::xlog_warn!("D3D12: debug layer requested but unavailable: {e}");
}
}
}
// `XCL_DRED=1`: on a device removal the faulting address and the last GPU operations
// (logged by `log_device_removed`); no debug layer needed. Opt-in: with it XDefiant
// stalled in its first seconds twice.
if std::env::var_os("XCL_DRED").is_some() {
match crate::gpu::agility::configuration_interface::<ID3D12DeviceRemovedExtendedDataSettings>(
&CLSID_D3D12DeviceRemovedExtendedData,
) {
Ok(d) => {
d.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
d.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
}
Err(e) => {
crate::xlog_warn!("D3D12: DRED requested but unavailable: {e}");
}
}
}
let debug = enable_device_layers(cfg);
let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?;
let mut device: Option<ID3D12Device> = None;
let mut name = String::new();
Expand Down Expand Up @@ -4344,7 +4353,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const
let record = crate::gpu::shader::fnv64(cs);
let warm = compiled.dispatch_chain.as_ref().and_then(|_| {
let rs = abi_rs_for(this, &compiled.samplers)?;
let result = compute_container(this, f, d, rs, &dxil, record, riid, ppv, ComputeBuild::CachedWhole);
let result = compute_container(this, f, d, rs, &compiled.samplers, &dxil, record, riid, ppv, ComputeBuild::CachedWhole);
(result.0 >= 0).then_some((rs, result))
});
if let Some(plan) = compiled.dispatch_chain.filter(|_| warm.is_none()) {
Expand All @@ -4364,7 +4373,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const
Some(hit) => hit,
None => {
let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) };
(rs, compute_container(this, f, d, rs, &dxil, record, riid, ppv, ComputeBuild::Whole))
(rs, compute_container(this, f, d, rs, &compiled.samplers, &dxil, record, riid, ppv, ComputeBuild::Whole))
}
};
LAST_COMPUTE_RS.with(|c| c.set(rs as usize));
Expand All @@ -4379,7 +4388,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const
crate::xlog_warn!(
"D3D12.X: the driver refused the compute PSO of record {record:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver: its dispatches are skipped",
dxil.len(),
driver_cache::name(&dxil, d.Flags.0),
driver_cache::name(&dxil, &compiled.samplers, d.Flags.0),
in_driver.as_millis()
);
}
Expand All @@ -4405,6 +4414,58 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const
pub(super) mod dispatch_chain;
pub(crate) use dispatch_chain::log_counts as log_dispatch_chain_counts;

/// The description the driver gets for the translated compute pipeline of `title`: `dxil` under
/// `rs` (not owned: it has to outlive the description), no blob yet, and of `title` only its
/// `Flags`, which are in the blob's file name (`driver_cache`). `xcl shaders --pipelines` makes
/// its pipelines from a default description with this, so its blobs are the ones a title's run
/// asks for.
///
/// `NodeMask` is 0 whatever the title's: XCL drives one adapter, where 0 and 1 are the same node,
/// and a driver may refuse a blob made under the other mask (vkd3d-proton does: #1368, #2453).
pub(crate) unsafe fn translated_compute_desc(title: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, dxil: &[u8]) -> D3D12_COMPUTE_PIPELINE_STATE_DESC {
D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop<Option<ID3D12RootSignature>>>(rs),
CS: bytecode(dxil),
NodeMask: 0,
CachedPSO: D3D12_CACHED_PIPELINE_STATE::default(),
Flags: title.Flags,
}
}

#[cfg(test)]
mod translated_compute_desc_tests {
use super::*;

fn fields(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> (Option<*mut c_void>, *const c_void, usize, u32, *const c_void, usize, i32) {
let rs = d.pRootSignature.as_ref().map(|r| r.as_raw());
(rs, d.CS.pShaderBytecode, d.CS.BytecodeLength, d.NodeMask, d.CachedPSO.pCachedBlob, d.CachedPSO.CachedBlobSizeInBytes, d.Flags.0)
}

#[test]
fn a_titles_pipeline_is_described_to_the_driver_as_the_offline_pass_describes_it() {
// (never used: the description does not own its root signature)
let rs = 0x1000 as *mut c_void;
let dxil = [1u8, 2, 3, 4];
// `xcl shaders --pipelines`: a default description
let offline = unsafe { translated_compute_desc(&D3D12_COMPUTE_PIPELINE_STATE_DESC::default(), rs, &dxil) };
assert_eq!(fields(&offline), (Some(rs), dxil.as_ptr().cast(), 4, 0, std::ptr::null(), 0, 0));
// a title's: node mask 1 (one adapter: the same node as 0), its console CS and a blob
let console = [5u8, 6];
let blob = [9u8; 8];
let title = D3D12_COMPUTE_PIPELINE_STATE_DESC {
CS: bytecode(&console),
NodeMask: 1,
CachedPSO: D3D12_CACHED_PIPELINE_STATE { pCachedBlob: blob.as_ptr().cast(), CachedBlobSizeInBytes: blob.len() },
..Default::default()
};
assert_eq!(fields(&unsafe { translated_compute_desc(&title, rs, &dxil) }), fields(&offline));
// the title's flags stay: the blob's file name has them
let debug = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: 1, Flags: D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG, ..Default::default() };
let d = unsafe { translated_compute_desc(&debug, rs, &dxil) };
assert_eq!((d.NodeMask, d.Flags), (0, D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG));
}
}

#[derive(Clone, Copy, PartialEq)]
enum ComputeBuild {
Whole,
Expand All @@ -4415,18 +4476,17 @@ enum ComputeBuild {
Chain,
}

/// `samplers` are the static samplers of `rs`.
unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void,
samplers: &[crate::gpu::recomp::pso::StaticSampler],
dxil: &[u8], record: u64, riid: *const GUID, ppv: *mut *mut c_void, mode: ComputeBuild) -> (HRESULT, std::time::Duration, bool) {
let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d);
copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop<Option<ID3D12RootSignature>>>(rs);
copy.CS = bytecode(dxil);
copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default();
let mut copy = translated_compute_desc(d, rs, dxil);
// A program built again gets the driver's own result of its first build: a retail title
// made 14 big compute pipelines twice while loading, 13 - 30 s each the second time.
let key = compute_blob_key(dxil, rs as usize, copy.Flags.0);
let mut cached = compute_blob(key);
// … and one built in an earlier run gets the blob kept on disk then (`driver_cache`)
let disk = driver_cache::path_for(dxil, copy.Flags.0, mode == ComputeBuild::Chain);
let disk = driver_cache::path_for(dxil, samplers, copy.Flags.0, mode == ComputeBuild::Chain);
let from_disk = cached.is_none();
if from_disk {
cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new);
Expand Down Expand Up @@ -4482,11 +4542,12 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL
/// run still goes through the driver's compiler. On an NVIDIA GPU that is 5 – 27 s for each of
/// a retail title's larger compute programs when its world loads: the title dispatches without
/// them meanwhile and is ended before all are built, so the next run starts the same compiles
/// again. A blob whose build took `KEEP` or longer is written under the hash of its DXIL and
/// its flags (`<DXIL cache>\driver\`) and read when a later run has none in memory; the
/// driver refuses the blob of another driver, adapter or root signature (the file is dropped
/// and the program compiled as before). `XCL_PSO_DISK_CACHE=0`: off.
/// again. A blob whose build took `KEEP` or longer is written under the hash of its DXIL, its
/// flags and its static samplers (`<DXIL cache>\driver\`) and read when a later run has none
/// in memory; the driver refuses the blob of another driver, adapter or root signature (the
/// file is dropped and the program compiled as before). `XCL_PSO_DISK_CACHE=0`: off.
pub(crate) mod driver_cache {
use crate::gpu::recomp::pso::StaticSampler;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

Expand All @@ -4496,16 +4557,28 @@ pub(crate) mod driver_cache {
static STALE: AtomicU64 = AtomicU64::new(0);
static STORED: AtomicU64 = AtomicU64::new(0);

/// The file of the pipeline made from `dxil` with `flags`.
pub fn name(dxil: &[u8], flags: i32) -> String {
name_for(dxil, flags, false)
/// The file of the pipeline made from `dxil` with `flags`, under a root signature with
/// `samplers` as its static samplers.
pub fn name(dxil: &[u8], samplers: &[StaticSampler], flags: i32) -> String {
name_for(dxil, samplers, flags, false)
}

/// Like [`name`], using `.chain.pso` for pipelines built with the dispatch chain's root
/// signature (`dispatch_chain`).
pub fn name_for(dxil: &[u8], flags: i32, chained: bool) -> String {
///
/// Static samplers are only in the root signature: the programs of two S# sets can have one
/// DXIL, and each one's blob is refused for the other (#2453). A program without static
/// samplers keeps the name of its blob of earlier runs.
pub fn name_for(dxil: &[u8], samplers: &[StaticSampler], flags: i32, chained: bool) -> String {
let ext = if chained { "chain.pso" } else { "pso" };
format!("{:016x}-{:x}-{:x}.{ext}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags)
let samplers = if samplers.is_empty() {
String::new()
} else {
let mut h = super::two_pass_identity::Fnv64::new();
super::two_pass_identity::samplers_hash_into(&mut h, samplers);
format!("-s{:016x}", h.finish())
};
format!("{:016x}-{:x}-{:x}{samplers}.{ext}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags)
}

/// The file of a translated graphics pipeline keyed by its full state + shader digest.
Expand All @@ -4518,12 +4591,12 @@ pub(crate) mod driver_cache {
*ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").map_or(true, |v| v.trim() != "0"))
}

pub fn path(dxil: &[u8], flags: i32) -> Option<PathBuf> {
path_for(dxil, flags, false)
pub fn path(dxil: &[u8], samplers: &[StaticSampler], flags: i32) -> Option<PathBuf> {
path_for(dxil, samplers, flags, false)
}

pub fn path_for(dxil: &[u8], flags: i32, chained: bool) -> Option<PathBuf> {
enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for(dxil, flags, chained)))
pub fn path_for(dxil: &[u8], samplers: &[StaticSampler], flags: i32, chained: bool) -> Option<PathBuf> {
enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for(dxil, samplers, flags, chained)))
}

pub fn graphics_path(hash: u64, bytes: usize) -> Option<PathBuf> {
Expand Down Expand Up @@ -4608,20 +4681,50 @@ pub(crate) mod driver_cache {

#[test]
fn a_file_is_named_after_its_dxil_and_flags() {
assert_eq!(name(b"abc", 0), name(b"abc", 0));
assert_ne!(name(b"abc", 0), name(b"abd", 0));
assert_ne!(name(b"abc", 0), name(b"abc", 1));
assert_eq!(name(b"abc", &[], 0), name(b"abc", &[], 0));
assert_ne!(name(b"abc", &[], 0), name(b"abd", &[], 0));
assert_ne!(name(b"abc", &[], 0), name(b"abc", &[], 1));
// (the length is in the name: two programs of one hash and different lengths differ)
assert!(name(&[0u8; 0x1234], 2).ends_with("-1234-2.pso"));
assert_eq!(name_for(b"abc", 0, false), name(b"abc", 0));
assert_ne!(name_for(b"abc", 0, true), name_for(b"abc", 0, false));
assert!(name_for(&[0u8; 0x1234], 2, true).ends_with("-1234-2.chain.pso"));
assert!(name(&[0u8; 0x1234], &[], 2).ends_with("-1234-2.pso"));
assert_eq!(name_for(b"abc", &[], 0, false), name(b"abc", &[], 0));
assert_ne!(name_for(b"abc", &[], 0, true), name_for(b"abc", &[], 0, false));
assert!(name_for(&[0u8; 0x1234], &[], 2, true).ends_with("-1234-2.chain.pso"));
}

#[test]
fn one_dxil_under_other_static_samplers_is_another_file() {
// S# words that differ in one word, and a comparison sampler of the first's words
let point: StaticSampler = ([0, 0, 0, 0], false);
let linear: StaticSampler = ([0, 0, 0x0050_0000, 0], false);
let compared: StaticSampler = (point.0, true);
let dxil = b"one program";
// a program without static samplers keeps the name of its earlier runs' blob
assert_eq!(name(dxil, &[], 0), format!("{:016x}-{:x}-0.pso", crate::gpu::shader::fnv64(dxil), dxil.len()));
let names = [
name(dxil, &[], 0),
name(dxil, &[point], 0),
name(dxil, &[linear], 0),
name(dxil, &[compared], 0),
name(dxil, &[point, linear], 0),
// (the order is the root signature's registers s0, s1…)
name(dxil, &[linear, point], 0),
name_for(dxil, &[point], 0, true),
];
for (i, a) in names.iter().enumerate() {
for b in &names[i + 1..] {
assert_ne!(a, b);
}
}
let copy = dxil.to_vec();
assert_eq!(name(dxil, &[point, linear], 0), name(&copy, &[point, linear], 0));
assert!(name(dxil, &[point], 2).starts_with(&name(dxil, &[], 2).replace(".pso", "-s")));
assert!(name_for(dxil, &[point], 0, true).ends_with(".chain.pso"));
}

#[test]
fn a_kept_blob_is_read_back_and_a_refused_one_is_dropped() {
let dir = std::env::temp_dir().join(format!("xcl-driver-cache-test-{}", std::process::id()));
let p = dir.join("driver").join(name(b"program", 0));
let p = dir.join("driver").join(name(b"program", &[], 0));
assert_eq!(load(&p), None, "nothing kept yet");
assert!(!write(&p, &[]), "an empty blob is not kept");
keep(&p, &[1, 2, 3], std::time::Duration::from_millis(10));
Expand Down Expand Up @@ -4718,7 +4821,7 @@ mod compute_blob_tests {
let code = std::fs::read(input).unwrap();
let c = console_to_dxil_for(&code, Stage::Compute, 0, wave32_only(raw)).unwrap();
assert!(c.dispatch_chain.is_some());
let path = driver_cache::path(&c.dxil, 0).unwrap();
let path = driver_cache::path(&c.dxil, &c.samplers, 0).unwrap();
assert!(path.starts_with(&cache));
assert_eq!(path.exists(), mode == "offline", "expected driver cache entry at {}", path.display());
unsafe {
Expand Down Expand Up @@ -6011,7 +6114,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu:
// share `tp.cs` (in memory and on disk), matching `translated_compute_pso_once`.
let ckey = compute_blob_key(&tp.cs, rs as usize, 0);
let mut ccached = compute_blob(ckey);
let cdisk = driver_cache::path(&tp.cs, 0);
let cdisk = driver_cache::path(&tp.cs, &tp.samplers, 0);
let cfrom_disk = ccached.is_none();
if cfrom_disk {
ccached = cdisk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new);
Expand Down
Loading
Loading