Skip to content
Open
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
155 changes: 155 additions & 0 deletions crates/xcl/src/gpu/effects.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
//! What a console compute program can change outside itself, read from its code alone.
//!
//! A dispatch XCL does not run (its pipeline is still being built) leaves undone what the
//! program would have written. For memory that is dangerous: a culling pass writes the
//! counts and the arguments an `ExecuteIndirect` reads next, and without them the GPU is
//! given unbounded work. A program that writes nothing but images leaves a stale picture
//! and nothing else, so its dispatches can go on without it while the driver compiles it
//! (`hle::d3d12x::pso_async`).

use super::{rdna2, recomp, xbox};

/// The writes a program can make.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Effects {
/// memory other programs, the CPU or indirect arguments may read: buffer / flat / global /
/// scratch stores and atomics, and the global data share (append / consume counters, GWS)
pub memory: bool,
/// image stores and image atomics
pub images: bool,
/// instructions in the program
pub instructions: usize,
}

/// The writes of the RDNA2 program `code` (one program, as `xbox::Fssm::programs` cuts it).
/// None: an instruction that does not decode, so nothing can be said about what follows it.
pub fn of(code: &[u8]) -> Option<Effects> {
let mut e = Effects::default();
let mut off = 0;
// the whole program: code can follow an early S_ENDPGM (a branch to it, or past it); what
// does not decode after one is taken for trailing data, before one it says nothing
let mut ended = false;
while off + 4 <= code.len() {
let Ok(d) = rdna2::decode(&code[off..], off as u64) else {
if ended {
break;
}
return None;
};
off += d.len;
e.instructions += 1;
let n = d.inst.name;
let writes = n.contains("_STORE") || n.contains("_ATOMIC");
match d.enc.name {
"ENC_MIMG" => e.images |= writes,
"ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_SMEM" => e.memory |= writes,
// LDS is the group's own and gone after it; the global data share is not
"ENC_DS" => {
let gds = rdna2::field_value(d.enc, &d.words, "GDS").is_some_and(|v| v != 0);
e.memory |= gds || n == "DS_APPEND" || n == "DS_CONSUME" || n == "DS_ORDERED_COUNT" || n.starts_with("DS_GWS_");
}
_ => {}
}
ended |= n == "S_ENDPGM";
}
Some(e)
}

/// The compute program of a console shader container (the hardware CS variant of an FSSM, or
/// an FSPX driver container), as the translators take it.
fn compute_code(blob: &[u8]) -> Option<Vec<u8>> {
if let Some(f) = recomp::pso::fspx(blob) {
return Some(f.code.to_vec());
}
let sh = xbox::parse(blob)?;
let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?;
let p = f.programs.first()?;
Some(f.data.get(p.offset..p.offset.checked_add(p.len)?)?.to_vec())
}

/// Console code a compute program needs to be `big`: 16 KiB, about 4 000 instructions. The
/// programs a retail title's world start waits on longest are 73 – 118 KiB each (22 – 172 s
/// apiece in an RDNA2 driver); what it runs every frame from its first one is far smaller.
pub const BIG_CODE: usize = 16 << 10;

/// Whether the compute shader `blob` is a big program whose only writes are to images: one a
/// title can do without for the frames its pipeline takes to build. False for anything that
/// cannot be read.
pub fn big_and_image_only(blob: &[u8]) -> bool {
let Some(code) = compute_code(blob) else { return false };
code.len() >= BIG_CODE && of(&code).is_some_and(|e| !e.memory)
}

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

fn asm(insts: &[(&str, &str, &[(&str, u64)])]) -> Vec<u8> {
insts.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap_or_else(|e| panic!("{n}: {e}"))).collect()
}

const END: (&str, &str, &[(&str, u64)]) = ("S_ENDPGM", "ENC_SOPP", &[]);
const MOV: (&str, &str, &[(&str, u64)]) = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 129)]);
const IMAGE_STORE: (&str, &str, &[(&str, u64)]) = ("IMAGE_STORE", "ENC_MIMG", &[("DMASK", 15), ("VADDR", 0), ("VDATA", 4), ("SRSRC", 2)]);
const IMAGE_LOAD: (&str, &str, &[(&str, u64)]) = ("IMAGE_LOAD", "ENC_MIMG", &[("DMASK", 15), ("VADDR", 0), ("VDATA", 4), ("SRSRC", 2)]);

#[test]
fn images_and_memory_are_told_apart() {
// loads of either kind write nothing
let load: (&str, &str, &[(&str, u64)]) = ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]);
assert_eq!(of(&asm(&[MOV, IMAGE_LOAD, load, END])), Some(Effects { memory: false, images: false, instructions: 4 }));
assert_eq!(of(&asm(&[MOV, IMAGE_STORE, END])), Some(Effects { memory: false, images: true, instructions: 3 }));
let image_atomic: (&str, &str, &[(&str, u64)]) = ("IMAGE_ATOMIC_ADD", "ENC_MIMG", &[("DMASK", 1), ("VADDR", 0), ("VDATA", 4), ("SRSRC", 2)]);
assert_eq!(of(&asm(&[image_atomic, END])).map(|e| (e.memory, e.images)), Some((false, true)));
// every way into memory another pass or an indirect call reads
let writers: [(&str, &str, &[(&str, u64)]); 7] = [
("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]),
("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]),
("TBUFFER_STORE_FORMAT_XYZW", "ENC_MTBUF", &[("VDATA", 1), ("SRSRC", 2)]),
("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 2)]),
("FLAT_ATOMIC_ADD", "ENC_FLAT", &[("ADDR", 0), ("DATA", 2)]),
("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", 0), ("DATA", 2)]),
("DS_APPEND", "ENC_DS", &[("VDST", 1)]),
];
for w in writers {
assert_eq!(of(&asm(&[IMAGE_STORE, w, END])).map(|e| (e.memory, e.images)), Some((true, true)), "{}", w.0);
}
// the group's own LDS is not memory anyone else reads
let lds: (&str, &str, &[(&str, u64)]) = ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)]);
assert_eq!(of(&asm(&[lds, IMAGE_STORE, END])).map(|e| (e.memory, e.images)), Some((false, true)));
}

#[test]
fn code_after_an_early_end_counts() {
// a branch can jump past an early s_endpgm: a store after it is the program's (were it
// constant data instead, taking it for a store only makes binds wait, as before)
let store: (&str, &str, &[(&str, u64)]) = ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]);
assert_eq!(of(&asm(&[IMAGE_STORE, END, store, END])), Some(Effects { memory: true, images: true, instructions: 4 }));
// what does not decode after the end is trailing data
let mut code = asm(&[IMAGE_STORE, END]);
code.extend_from_slice(&[0xff; 8]);
if rdna2::decode(&[0xff; 8], 0).is_err() {
assert_eq!(of(&code), Some(Effects { memory: false, images: true, instructions: 2 }));
}
}

#[test]
fn the_global_data_share_is_memory() {
// the same LDS add, once with GDS set: other groups and the CPU can see that one
let lds: (&str, &str, &[(&str, u64)]) = ("DS_ADD_U32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)]);
let gds: (&str, &str, &[(&str, u64)]) = ("DS_ADD_U32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1), ("GDS", 1)]);
assert_eq!(of(&asm(&[lds, IMAGE_STORE, END])).map(|e| e.memory), Some(false));
assert_eq!(of(&asm(&[gds, IMAGE_STORE, END])).map(|e| e.memory), Some(true));
}

#[test]
fn code_that_does_not_decode_says_nothing() {
let mut code = asm(&[IMAGE_STORE]);
code.extend_from_slice(&[0xff; 8]);
code.extend(asm(&[END]));
// (only where the decoder really refuses the dwords: otherwise the test states nothing)
if rdna2::decode(&[0xff; 8], 0).is_err() {
assert_eq!(of(&code), None);
}
}
}
1 change: 1 addition & 0 deletions crates/xcl/src/gpu/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod bvh;
pub mod desc;
pub mod dxbc;
pub mod dxil;
pub mod effects;
pub(crate) mod fence;
pub mod pack;
pub mod rdna2;
Expand Down
92 changes: 92 additions & 0 deletions crates/xcl/src/hle/d3d12x/pso_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ struct Pending {
orphan: std::sync::atomic::AtomicBool,
/// a bind waited for it longer than `wait_budget`: binds go on without it until it is built
late: std::sync::atomic::AtomicBool,
/// its dispatches may be left out while it is built (`image_only`): binds do not wait for it
spared: std::sync::atomic::AtomicBool,
demand: Mutex<Demand>,
}

Expand Down Expand Up @@ -232,6 +234,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) {
used: Default::default(),
orphan: Default::default(),
late: Default::default(),
spared: Default::default(),
demand: Default::default(),
});
PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone());
Expand Down Expand Up @@ -411,6 +414,49 @@ mod used_tests {
let _ = released(standin);
}

/// A bind does not wait for a compute pipeline that writes only images: it gets the stand-in
/// at once, with no budget, the build goes to the workers
/// unwanted, and once built the bind gets the real one. Without `image_only` the same bind
/// waits until the pipeline is built.
#[test]
fn a_bind_does_not_wait_for_a_pipeline_that_writes_only_images() {
let (spared, waited) = (0x7E57_B0A1usize, 0x7E57_B0A2usize);
let (go, finish) = mpsc::channel::<()>();
let (tx, rx) = mpsc::channel();
submit_lazy(spared, true, Box::new(move || {
let _ = tx.send(wanted_here()());
let _ = finish.recv();
0x5A5A
}), 0);
image_only(spared);
// (on a thread: a bind that waits would wait for `go`, below)
let (bound_tx, bound) = mpsc::channel();
std::thread::spawn(move || {
let _ = bound_tx.send((resolve_wait_for(spared, None), resolve_wait_for(spared, None)));
});
let binds = bound.recv_timeout(std::time::Duration::from_secs(5));
if binds.is_err() {
let _ = go.send(());
}
assert_eq!(binds.expect("the binds waited for the build"), (spared, spared), "still being built: the stand-in");
assert!(is_pending(spared));
assert!(!rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker builds it"), "nobody waits: the build is not wanted");
go.send(()).unwrap();
let start = std::time::Instant::now();
while is_pending(spared) && start.elapsed() < std::time::Duration::from_secs(10) {
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert_eq!(resolve_wait_for(spared, None), 0x5A5A, "built by a worker");
// the same build without the mark: the bind waits for it
submit_lazy(waited, true, Box::new(|| {
std::thread::sleep(std::time::Duration::from_millis(100));
0x5B5B
}), 0);
assert_eq!(resolve_wait_for(waited, None), 0x5B5B);
let _ = released(spared);
let _ = released(waited);
}

/// A bind waits for a pipeline still being built no longer than its budget and goes on with
/// the stand-in; later binds do not wait for it again; once built it is the real one.
#[test]
Expand Down Expand Up @@ -539,6 +585,9 @@ pub fn resolve_wait(pso: usize) -> usize {
fn resolve_wait_for(pso: usize, budget: Option<std::time::Duration>) -> usize {
let Some(p) = entry(pso) else { return pso };
p.note_use();
if p.spared.load(Ordering::Acquire) {
return resolve_spared(&p, pso);
}
// (the title's thread is held from here until the pipeline is built or the budget is over)
let _held = (!*p.done.lock().unwrap()).then(Held::new);
if let Some(budget) = budget {
Expand Down Expand Up @@ -600,6 +649,49 @@ fn resolve_within(p: &Arc<Pending>, pso: usize, budget: std::time::Duration) ->
pso
}

/// `XCL_PSO_IMAGE_SKIP=1`: a bind does not wait for a big compute program that writes nothing
/// but images (`gpu::effects::big_and_image_only`); its dispatches are left out until a worker
/// has built it. Off by default: what such a program draws is missing for that long.
///
/// A retail title's world start binds one ray-tracing resolve program per material (73 – 118
/// KiB of console code, about 1 MB of DXIL each): an RDNA2 driver takes 22 – 172 s for each,
/// one bind at a time, and the title stands still for all of them. `XCL_PSO_WAIT_MS` goes on without every late
/// program, also the culling passes whose counts an `ExecuteIndirect` reads next – a GPU hang.
pub fn image_skip() -> bool {
static S: OnceLock<bool> = OnceLock::new();
*S.get_or_init(|| std::env::var("XCL_PSO_IMAGE_SKIP").is_ok_and(|v| v.trim() == "1"))
}

/// The compute pipeline behind stand-in `standin` writes nothing but images: binds go on
/// without it while it is built (`resolve_spared`). Told before the title has the stand-in.
pub fn image_only(standin: usize) {
if let Some(p) = entry(standin) {
p.spared.store(true, Ordering::Release);
}
}

/// `resolve_wait` for a pipeline binds do not wait for (`image_only`): the real one once built,
/// else the stand-in, with the build sent to the workers. Nobody waits, so the build is not
/// `wanted`: a big one takes its turn among the driver's compiles and waits for free commit.
fn resolve_spared(p: &Arc<Pending>, pso: usize) -> usize {
match p.real.load(Ordering::Acquire) {
0 => {
if !p.sent.swap(true, Ordering::AcqRel) {
let _ = queue().lock().unwrap().send(p.clone());
}
if !*p.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) {
static N: AtomicUsize = AtomicUsize::new(0);
let n = N.fetch_add(1, Ordering::Relaxed);
if n < 16 || n.is_power_of_two() {
crate::xlog_info!("D3D12.X: a compute program that writes only images is still being built: its dispatches are left out until it is ({} so far)", n + 1);
}
}
pso
}
r => r,
}
}

/// For binding: compute pipelines are waited for, graphics ones are not.
pub fn resolve_for_bind(pso: usize) -> usize {
match entry(pso) {
Expand Down
5 changes: 5 additions & 0 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4788,6 +4788,8 @@ unsafe fn go_background(
}
let dev = Dev(this as usize, f as usize);
let key = owned.shaders_key();
// a big compute program that writes nothing but images: binds can go on without it
let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b)));
let job: super::pso_async::Job = Box::new(move || {
let mut out: *mut c_void = std::ptr::null_mut();
if unsafe { build(dev, &owned, &mut out) } && !out.is_null() {
Expand All @@ -4801,6 +4803,9 @@ unsafe fn go_background(
} else {
super::pso_async::submit(*ppv as usize, compute, job);
}
if image_only {
super::pso_async::image_only(*ppv as usize);
}
Some(hr)
}

Expand Down
Loading