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
15 changes: 0 additions & 15 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1832,21 +1832,6 @@ pub(crate) fn chain_command_signature(dev: &ID3D12Device, rs: &ID3D12RootSignatu
Ok(sig)
}

pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result<ID3D12CommandSignature, String> {
static MADE: Mutex<Option<(usize, ID3D12CommandSignature)>> = Mutex::new(None);
let mut made = MADE.lock().unwrap();
if let Some((_, sig)) = made.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) {
return Ok(sig.clone());
}
let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() };
let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 };
let mut sig = None;
unsafe { dev.CreateCommandSignature(&desc, None, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?;
let sig: ID3D12CommandSignature = sig.ok_or("CreateCommandSignature")?;
*made = Some((windows::core::Interface::as_raw(dev) as usize, sig.clone()));
Ok(sig)
}

const INDIRECT_SLICER: &str = r#"
#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)"
cbuffer C : register(b0) { uint rounds; uint most; };
Expand Down
78 changes: 55 additions & 23 deletions crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ fn queue_whole(chain: &Arc<Chain>) -> bool {
// dispatch queue it again after `WHOLE_RETRY`
Err(_) if guard.job.0.whole.ready().is_none() => drop(guard),
Err(e) => {
crate::xlog_warn!("D3D12.X: the whole form of a split compute program was not built ({e}): its indirect dispatches stay left out");
crate::xlog_warn!("D3D12.X: the whole form of a split compute program was not built ({e}): its Dispatch-only indirect dispatches run its chain, others stay left out");
guard.finish();
}
}
Expand Down Expand Up @@ -578,15 +578,23 @@ fn indirect_rounds() -> u32 {
pub(in crate::hle::d3d12x) enum Indirect {
/// its chain ran
Ran,
/// not a split program, or one whose chain cannot run here: the whole form (`whole_ready`)
/// not a split program, its whole form is already built, or its chain cannot run here:
/// hand off to the whole form (`whole_ready`)
Whole,
}

/// Run one Dispatch-only indirect command through an existing split chain: the pieces a direct
/// dispatch runs, each round's root constants and groups from the slicer's commands
/// (`pso::chain_command_signature`), so it waits for no other build. The slicer writes either
/// bounded piece commands or the whole-form command, never a partial chain; the latter is left out
/// while the whole form is not there (queued as for `whole_ready`, never waited for).
/// Prefer the single whole-form `ExecuteIndirect` over the multi-round split chain once the
/// whole form has finished building (`Ok`). While still building (`None`) or after a driver
/// refusal (`Err`), stay on the split chain.
fn indirect_prefers_whole<T>(ready: Option<Result<T, HRESULT>>) -> bool {
matches!(ready, Some(Ok(_)))
}

/// Run one Dispatch-only indirect command through an existing split chain while its whole form is
/// still building or refused: the pieces a direct dispatch runs, each round's root constants and
/// groups from the slicer's commands (`pso::chain_command_signature`), so it waits for no other
/// build. Once the whole form is ready, return [`Indirect::Whole`] so the caller dispatches it
/// directly without claiming split scratch or recording multi-round piece chains.
/// `around_slicer(true)` and `(false)` bracket the one pass that reads `args`, only when it is
/// recorded.
pub(in crate::hle::d3d12x) unsafe fn execute_indirect(
Expand All @@ -595,6 +603,9 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(
) -> Result<Indirect, String> {
let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(Indirect::Whole) };
note_indirect_use(&chain);
if indirect_prefers_whole(chain.whole.ready()) {
return Ok(Indirect::Whole);
}
let allocator = if super::super::alloc_pool::enabled() {
super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0)
} else { allocator };
Expand All @@ -604,15 +615,15 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(
return Ok(Indirect::Whole);
};
let signature = pso::chain_command_signature(&chain.builder.device, &chain.builder.signature)?;
let tail_signature = pso::dispatch_command_signature(&chain.builder.device)?;
// for a dispatch whose groups do not fit the slicer's rounds
let whole = match chain.whole.ready() {
Some(result) => result.ok(),
// Queue the background whole-form build if not yet started, and hand off if it finished while
// preparing scratch or the command signature.
match chain.whole.ready() {
Some(Ok(_)) => return Ok(Indirect::Whole),
Some(Err(_)) => {}
None => {
queue_whole(&chain);
None
}
};
}
let rounds = indirect_rounds();
let command_bytes = pso::chain_tail_offset(rounds) + 12;
let commands = commands_for(
Expand All @@ -628,11 +639,6 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(
sliced?;
let bound = bind(chain.builder.signature.as_raw() as usize);
if bound.is_ok() {
if let Some(whole) = &whole {
super::bind_pipeline_exact(list.as_raw(), original, whole.as_raw() as usize);
list.ExecuteIndirect(&tail_signature, 1, &commands.buffer,
pso::chain_tail_offset(rounds), None::<&ID3D12Resource>, 0);
}
pso::record_dispatch_chain_indirect(
list, &signature, &commands.buffer, rounds, &scratch.buffer, std::iter::once(&first).chain(&chain.tail),
|piece| super::bind_pipeline_exact(list.as_raw(), original, piece.as_raw() as usize),
Expand Down Expand Up @@ -785,13 +791,12 @@ mod tests {
let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() };
let first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap();
let whole = WholeBuild::new();
whole.get_or_build(std::time::Instant::now(), || Ok(first.clone())).unwrap();
let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), samplers: Vec::new(),
flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0, mode: ComputeBuild::DirectChain });
let key = first.as_raw() as usize;
// Whole form not yet built (and marked queued so no background build runs here).
CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4,
whole_code: Vec::new(), whole, indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) }));
whole_code: Vec::new(), whole: WholeBuild::new(), indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(true) }));
let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE;
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap();
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap();
Expand Down Expand Up @@ -819,8 +824,8 @@ mod tests {
}

/// An indirect dispatch of a split program runs the chain's own pieces under its root signature
/// at once, with no other build and no whole form there: it never waits for the whole form
/// (only queues it, for the slicer's overflow tail).
/// while the whole form is still building (queueing it without waiting), and hands back to the
/// whole form once it has finished building.
#[test]
fn an_indirect_dispatch_runs_its_chain_without_any_whole_form() {
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
Expand Down Expand Up @@ -868,6 +873,17 @@ mod tests {
assert_eq!(around, [true, false], "the slicer bracketed once");
let ran = CHAINS.lock().unwrap().get(&key).cloned().unwrap();
assert!(ran.whole.ready().is_none(), "the whole form was not built");
// Once the whole form finishes building, indirect dispatches hand back to it instead of
// re-running the slicer + multi-round split chain.
ran.whole.get_or_build(std::time::Instant::now(), || Ok(first.clone())).unwrap();
assert_eq!(
execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), |_| {
panic!("whole-ready indirect dispatch must not bind the split chain")
}, |_| {
panic!("whole-ready indirect dispatch must not run the slicer")
}),
Ok(Indirect::Whole)
);
type Close = unsafe extern "system" fn(*mut c_void) -> HRESULT;
let close: Close = std::mem::transmute(super::super::orig_fn(list.as_raw(), 9));
assert!(close(list.as_raw()) >= 0, "the recorded chain closes");
Expand Down Expand Up @@ -1103,4 +1119,20 @@ mod tests {
let tid3 = done3_rx.recv_timeout(Duration::from_secs(5)).expect("job 3 ran after panic");
assert_eq!(tid3, worker_tid);
}

#[test]
fn indirect_prefers_whole_only_once_built_ok() {
let build: WholeBuild<u32> = WholeBuild::new();
assert!(!indirect_prefers_whole(build.ready()));
let at = std::time::Instant::now();
let oom: HRESULT = 0x8007_000Eu32 as i32;
let _ = build.get_or_build(at, || Err(oom));
assert!(!indirect_prefers_whole(build.ready()));
assert_eq!(build.get_or_build(at + WHOLE_RETRY, || Ok(42)), Ok(42));
assert!(indirect_prefers_whole(build.ready()));

let failed: WholeBuild<u32> = WholeBuild::new();
let _ = failed.get_or_build(at, || Err(crate::util::E_INVALIDARG));
assert!(!indirect_prefers_whole(failed.ready()));
}
}
Loading