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
130 changes: 118 additions & 12 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,11 @@ impl State {
}
}
}
// Not folded unless the dispatch says so.
if let Some(param) = stage.fold {
// SAFETY: an open list; the parameter is one root constant.
unsafe { l.SetComputeRoot32BitConstant(param, 0, 0) };
}
for (views, kind) in [(&stage.root_cbvs, 0), (&stage.root_srvs, 1), (&stage.root_uavs, 2)] {
for &(slot, param) in views {
if kind == 1 && slot == victory_shader::emit::VIEW_STRIDES {
Expand Down Expand Up @@ -951,8 +956,27 @@ impl State {
list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
#[cfg(feature = "diagnostics")]
self.probe_small(list, true);
// SAFETY: an open list with everything set.
unsafe { list.list.Dispatch(x, y, z) };
let row = victory_shader::emit::GROUP_FOLD_ROW;
match p.stages.first().and_then(|s| s.fold) {
// More groups than the host runs along x: in rows along z,
// then the rest (`GROUP_FOLD_ROW`).
Some(param) if x > row && y == 1 && z == 1 => {
let (rows, rest) = (x / row, x % row);
// SAFETY: an open list with everything set; the parameter
// is one root constant.
unsafe {
list.list.SetComputeRoot32BitConstant(param, 1, 0);
list.list.Dispatch(row, 1, rows);
if rest != 0 {
list.list.SetComputeRoot32BitConstant(param, rows * row + 1, 0);
list.list.Dispatch(rest, 1, 1);
}
list.list.SetComputeRoot32BitConstant(param, 0, 0);
}
}
// SAFETY: an open list with everything set.
_ => unsafe { list.list.Dispatch(x, y, z) },
}
#[cfg(feature = "diagnostics")]
self.probe_written(list);
DISPATCHED.fetch_add(1, Ordering::Relaxed);
Expand Down Expand Up @@ -1620,8 +1644,29 @@ impl State {
if let Some((s, at)) = &counter {
s.refresh(list, *at, 4);
}
// One uncounted dispatch of a compute program may run folded
// (`GROUP_FOLD_ROW`): the clamp writes its records to a region of
// the list's fold buffer, with the fold root constant.
let folded = (kind == DISPATCH && count.is_none() && max == 1)
.then(|| crate::pipeline::host_pipeline(self.pipeline as This))
.flatten()
.filter(|p| p.compute)
.and_then(|p| {
let param = p.stages.first()?.fold?;
let signature = fold_signature(&p.root, param)?;
Some((list.fold_region()?, signature))
});
// Bounded first: the clamp binds a compute pipeline of its own.
if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) {
let (threads, hash) = crate::pipeline::group_of(self.pipeline as This);
let tag = crate::indirect::tag(&hash);
if !crate::indirect::bound(
list,
&args.buffer,
args.gpu(arguments),
(kind, stride, max),
(threads, tag),
folded.as_ref().map(|((buffer, gpu, _), _)| (buffer, *gpu)),
) {
why("not bounded (no clamp, or arguments not 4-byte aligned)");
return false;
}
Expand All @@ -1643,6 +1688,9 @@ impl State {
};
if !ran {
crate::indirect::done(list, &args.buffer);
if let Some(((buffer, ..), _)) = &folded {
crate::indirect::done_fold(list, buffer);
}
#[cfg(feature = "diagnostics")]
match crate::pipeline::host_pipeline(self.pipeline as This) {
None => {
Expand All @@ -1666,17 +1714,26 @@ impl State {
)
});
// SAFETY: an open list with everything set; the buffers are host
// copies the list keeps alive (refresh), the signature is cached.
// copies the list keeps alive (refresh) or its own fold buffer, the
// signatures are cached.
unsafe {
list.list.ExecuteIndirect(
&signature,
max,
&args.buffer,
args.offset(arguments),
counter.as_ref().map(|(s, _)| &s.buffer),
counter.as_ref().map_or(0, |(s, at)| s.offset(*at)),
)
match &folded {
Some(((buffer, _, offset), signature)) => {
list.list.ExecuteIndirect(signature, 2, buffer, offset + 16, buffer, *offset)
}
None => list.list.ExecuteIndirect(
&signature,
max,
&args.buffer,
args.offset(arguments),
counter.as_ref().map(|(s, _)| &s.buffer),
counter.as_ref().map_or(0, |(s, at)| s.offset(*at)),
),
}
};
if let Some(((buffer, ..), _)) = &folded {
crate::indirect::done_fold(list, buffer);
}
// A listed frame: what the records held (after the clamp).
#[cfg(feature = "diagnostics")]
if crate::capture::dump_on() {
Expand All @@ -1694,6 +1751,55 @@ impl State {
}
}

/// The host command signature of folded dispatches for the root signature
/// `root`, whose root parameter `param` is the fold constant: records of
/// that constant and a dispatch, 16 bytes apart. Made once per root
/// signature (kept alive here).
fn fold_signature(root: &ID3D12RootSignature, param: u32) -> Option<ID3D12CommandSignature> {
static MADE: std::sync::Mutex<Vec<(ID3D12RootSignature, u32, ID3D12CommandSignature)>> =
std::sync::Mutex::new(Vec::new());
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
if let Some((.., s)) = made.iter().find(|(r, p, _)| r == root && *p == param) {
return Some(s.clone());
}
let arguments = [
D3D12_INDIRECT_ARGUMENT_DESC {
Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT,
Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 {
Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 {
RootParameterIndex: param,
DestOffsetIn32BitValues: 0,
Num32BitValuesToSet: 1,
},
},
},
D3D12_INDIRECT_ARGUMENT_DESC {
Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH,
..Default::default()
},
];
let desc = D3D12_COMMAND_SIGNATURE_DESC {
ByteStride: 16,
NumArgumentDescs: 2,
pArgumentDescs: arguments.as_ptr(),
NodeMask: 0,
};
let mut signature: Option<ID3D12CommandSignature> = None;
// SAFETY: a description of two arguments for a live root signature.
let result = unsafe {
crate::host::host()?
.device
.CreateCommandSignature(&desc, root, &mut signature)
};
if let Err(e) = result {
once!(error = %e, param, "host command signature for folded dispatches refused");
return None;
}
let signature = signature?;
made.push((root.clone(), param, signature.clone()));
Some(signature)
}

/// The host command signature for one argument of `kind` with records
/// `stride` bytes apart (no root arguments, so no root signature), made
/// once.
Expand Down
47 changes: 42 additions & 5 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,12 @@ mod tests {
}
}

/// Bytes of a list's fold buffer per indirect execution: the record count,
/// then up to two records of a root constant and three group counts.
pub(crate) const FOLD_REGION: u32 = 64;
/// Fold regions per list (folded indirect dispatches between resets).
const FOLD_REGIONS: u32 = 1024;

/// A host command list and its allocator, always used together.
pub(crate) struct HostList {
allocator: ID3D12CommandAllocator,
Expand Down Expand Up @@ -643,6 +649,9 @@ pub(crate) struct HostList {
/// The work its indirect executions may still do (`indirect`): a
/// shader-writable word, zeroed when the list is submitted.
budget: OnceLock<Option<(ID3D12Resource, usize)>>,
/// Where the argument clamp writes the records of folded dispatches
/// (`crate::indirect`), [`FOLD_REGION`] bytes per execution.
fold: OnceLock<Option<ID3D12Resource>>,
/// The texts of the markers `note_op` set, in order (for device-removed
/// data without marker texts), with the host GPU range a copy reads.
#[cfg(feature = "diagnostics")]
Expand Down Expand Up @@ -836,6 +845,8 @@ struct Deferred {
writes: Vec<(usize, crate::queue::Written, usize)>,
/// Whether a step zeroes the indirect-work budget.
budget_zeroed: bool,
/// Fold regions taken since the reset ([`HostList::fold_region`]).
fold_regions: u32,
/// Work done once the list has run, before the bottom-of-pipe writes
/// (title memory shaders wrote at addresses they computed goes back).
after: Vec<Box<dyn Fn() + Send>>,
Expand Down Expand Up @@ -951,6 +962,7 @@ impl Host {
pipelines: Mutex::default(),
id,
budget: OnceLock::new(),
fold: OnceLock::new(),
#[cfg(feature = "diagnostics")]
notes: Mutex::default(),
#[cfg(feature = "diagnostics")]
Expand Down Expand Up @@ -1921,23 +1933,48 @@ impl HostList {
let (buffer, data) = self
.budget
.get_or_init(|| {
let (b, d) = host()?.shared_buffer(256)?;
// The budget, then the log of reduced records (`crate::indirect`).
let (b, d) = host()?.shared_buffer(1024)?;
Some((b, d as usize))
})
.as_ref()?;
let mut deferred = self.deferred();
if !deferred.budget_zeroed {
deferred.budget_zeroed = true;
let at = *data;
// SAFETY: the list's own mapped word, written before it runs.
deferred
.copies
.push(Step::Host(Box::new(move || unsafe { (at as *mut u32).write_volatile(0) })));
// SAFETY: the list's own mapped words, read (what its last run
// logged) and zeroed before it runs.
deferred.copies.push(Step::Host(Box::new(move || unsafe {
let words = std::slice::from_raw_parts(at as *const u32, 256);
let read: Vec<u32> = words.iter().map(|w| std::ptr::read_volatile(w)).collect();
crate::indirect::take_log(&read);
(at as *mut u32).write_volatile(0);
(at as *mut u32).add(1).write_volatile(0);
})));
}
// SAFETY: a live buffer.
Some(unsafe { buffer.GetGPUVirtualAddress() })
}

/// A region of the list's fold buffer for one indirect execution until
/// the list is reset: the buffer, the region's host address and its
/// offset; none when the list has used them all.
pub(crate) fn fold_region(&self) -> Option<(ID3D12Resource, u64, u64)> {
let buffer = self
.fold
.get_or_init(|| Some(host()?.shared_buffer(u64::from(FOLD_REGION * FOLD_REGIONS))?.0))
.as_ref()?;
let mut deferred = self.deferred();
if deferred.fold_regions >= FOLD_REGIONS {
return None;
}
let offset = u64::from(deferred.fold_regions * FOLD_REGION);
deferred.fold_regions += 1;
// SAFETY: a live buffer.
let gpu = unsafe { buffer.GetGPUVirtualAddress() } + offset;
Some((buffer.clone(), gpu, offset))
}

/// Keeps `object` alive until the list is reset.
pub(crate) fn keep(&self, object: &impl Interface) {
if let Ok(object) = object.cast::<windows::core::IUnknown>() {
Expand Down
Loading
Loading