diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 49db594d0f..4ee012e6db 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -30,7 +30,6 @@ workspace = true windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", - "Win32_Graphics_Direct3D_Fxc", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 46cf638c05..783de8b233 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -242,11 +242,6 @@ fn create() -> windows::core::Result { })?; let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); tracing::info!("host D3D12 device ready"); - // DXC's first compile, while nothing is guarded yet (see there). - #[cfg(not(windows))] - if std::env::var_os("VICTORY_DXCOMPILER").is_some() { - let _ = crate::indirect::compiled(); - } Ok(Host { device, queue, diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 7bf77aaab9..c6c5810a69 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -3,13 +3,13 @@ //! translate wrongly leaves whatever the memory held, and a draw of four //! billion vertices or a dispatch past the host's limits runs until the //! host resets the display driver. So every record is clamped on the GPU, -//! just before its execution, by a compute shader of ours (HLSL compiled by -//! the system's compiler; a 5.1 shader with its root signature inside. On -//! Linux DXC compiles it, as 6.0, if `VICTORY_DXCOMPILER` names one). +//! just before its execution, by a compute shader of ours +//! (`victory_shader::emit::clamp`, built as the translations are: no HLSL +//! compiler on any host). //! -//! Each list also has a budget (2^27 vertex instances or threads, groups -//! counted as 64 threads, mesh groups as 128): records past it run empty, -//! so a list of thousands of garbage records cannot run for seconds +//! Each list also has a budget ([`LIMITS`]: vertex instances or threads, +//! groups counted as 64 threads, mesh groups as 128): records past it run +//! empty, so a list of thousands of garbage records cannot run for seconds //! either. //! //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 @@ -17,61 +17,21 @@ //! dispatches, the budget) cut legitimate work beyond them; raise them if //! the title needs more. -#[cfg(windows)] -use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -#[cfg(windows)] -use windows::Win32::Graphics::Direct3D::ID3DBlob; +use victory_shader::emit::clamp::{self, Limits}; +use victory_shader::emit::{ROOT_CBV_SPACE, USER_DATA_SPACE}; use windows::Win32::Graphics::Direct3D12::*; -#[cfg(windows)] -use windows::core::s; use crate::host::{HostList, host, transition}; -const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)" -cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; -RWByteAddressBuffer args : register(u0); -// The list's work so far (vertex instances, threads): past the budget, -// records run empty. -RWByteAddressBuffer budget : register(u1); -static const uint BUDGET = 1u << 27; -// Groups of one dispatch; more run empty. -static const uint GROUPS = 1u << 20; -[RootSignature(RS)] -[numthreads(64, 1, 1)] -void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= records) return; - uint at = id.x * stride; - uint cost; - if (kind <= 1) { - // Draws: vertex or index count, then instances. - uint count = min(args.Load(at), 1u << 24); - uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); - cost = count * instances; - args.Store2(at, uint2(count, instances)); - } else if (kind == 2) { - uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); - // x * y fits 32 bits; the whole count may not. - if (g.z != 0 && g.x * g.y > GROUPS / g.z) { - g = uint3(0, 0, 0); - } - cost = g.x * g.y * g.z * 64; - args.Store3(at, g); - } else { - // Mesh dispatches: the console's are one-dimensional. - uint3 g = args.Load3(at); - g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); - cost = g.x * g.y * g.z * 128; - args.Store3(at, g); - } - uint before; - budget.InterlockedAdd(0, cost, before); - if (before >= BUDGET || before + cost > BUDGET) { - // Draws keep their layout with no vertices; groups become zero. - args.Store(at, 0); - } -} -"#; +const LIMITS: Limits = Limits { + vertices: 1 << 24, + vertex_instances: 1 << 26, + groups_per_dimension: 65535, + groups: 1 << 20, + group_cost: 64, + mesh_group_cost: 128, + budget: 1 << 27, +}; struct Clamp { root: ID3D12RootSignature, @@ -83,7 +43,7 @@ unsafe impl Send for Clamp {} // SAFETY: as above. unsafe impl Sync for Clamp {} -fn clamp() -> Option<&'static Clamp> { +fn pipeline() -> Option<&'static Clamp> { static CLAMP: std::sync::OnceLock> = std::sync::OnceLock::new(); CLAMP .get_or_init(|| match make() { @@ -96,77 +56,50 @@ fn clamp() -> Option<&'static Clamp> { .as_ref() } -/// The clamp's DXIL, with its root signature, compiled once. DXC's LLVM -/// replaces our fault handlers at its first compile (it registers its own -/// once per process), so they are taken back right after; the device's -/// creation compiles it, before any copy guards title memory. -#[cfg(not(windows))] -pub(crate) fn compiled() -> windows::core::Result> { - static DXIL: std::sync::OnceLock>> = std::sync::OnceLock::new(); - DXIL.get_or_init(|| { - let dxil = victory_shader::hostlib::compile_hlsl(SOURCE, "main", "cs_6_0"); - victory_loader::linux::signals::reclaim(); - dxil.inspect_err(|e| tracing::warn!("argument clamp: {e}")).ok() - }) - .clone() - .ok_or_else(|| windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)) -} - -/// The clamp's DXBC, with its root signature. -#[cfg(windows)] -fn compiled() -> windows::core::Result> { - let mut code: Option = None; - let mut errors: Option = None; - // SAFETY: the source and names live through the call; out pointers ours. - let compiled = unsafe { - D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), - s!("clamp"), - None, - None, - s!("main"), - s!("cs_5_1"), - 0, - 0, - &mut code, - Some(&mut errors), - ) - }; - if let Err(e) = compiled { - if let Some(errors) = errors { - // SAFETY: the blob's own bytes. - let text = unsafe { - std::slice::from_raw_parts(errors.GetBufferPointer().cast::(), errors.GetBufferSize()) - }; - tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text)); - } - return Err(e); - } - let code = code.ok_or_else(windows::core::Error::empty)?; - // SAFETY: the blob's own bytes. - Ok(unsafe { - std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) - } - .to_vec()) -} - fn make() -> windows::core::Result { let device = &host().ok_or_else(windows::core::Error::empty)?.device; - let bytes = &compiled()?[..]; - // SAFETY: the root signature is inside the shader. - unsafe { - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; - let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + let uav = |slot: u8| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + // In the order `bound` sets them: the constants, then the buffers at + // the root parameter indices the shader names. + let params = [ + D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Num32BitValues: 4, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + uav(clamp::ARGUMENTS), + uav(clamp::BUDGET), + ]; + let (root, _) = crate::pipeline::host::root_signature(device, ¶ms, &[], true)?; + let bytes = clamp::argument_clamp(&LIMITS); + // SAFETY: the description points at live data. + let pso = unsafe { + device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len(), }, ..Default::default() - })?; - Ok(Clamp { root, pso }) - } + })? + }; + Ok(Clamp { root, pso }) } /// Records, in `list`, the clamp of `records` records of `kind` (PC @@ -180,7 +113,7 @@ pub(crate) fn bound( gpu: u64, (kind, stride, records): (u32, u32, u32), ) -> bool { - let (Some(c), Some(budget)) = (clamp(), list.budget()) else { + let (Some(c), Some(budget)) = (pipeline(), list.budget()) else { return false; }; if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { @@ -196,9 +129,9 @@ pub(crate) fn bound( l.SetComputeRootSignature(&c.root); l.SetPipelineState(&c.pso); l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - l.SetComputeRootUnorderedAccessView(1, gpu); - l.SetComputeRootUnorderedAccessView(2, budget); - l.Dispatch(records.div_ceil(64), 1, 1); + l.SetComputeRootUnorderedAccessView(clamp::ARGUMENTS.into(), gpu); + l.SetComputeRootUnorderedAccessView(clamp::BUDGET.into(), budget); + l.Dispatch(records.div_ceil(clamp::GROUP), 1, 1); l.ResourceBarrier(&[ uav_barrier(), transition( @@ -236,30 +169,85 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { #[cfg(test)] mod tests { - /// The clamp compiles with the system's compiler and the host takes it. + use victory_shader::emit::clamp::{DISPATCH, DRAW, DRAW_INDEXED, MESH, clamped}; + + use super::*; + + /// Runs the clamp over `records` (three dwords each, `stride` bytes + /// apart) in a list of its own and returns them; None without a host. + fn run(kind: u32, stride: u32, records: &[[u32; 3]]) -> Option> { + let host = host()?; + let step = (stride / 4) as usize; + let (buffer, data) = host.shared_buffer(u64::from(stride) * records.len() as u64)?; + // SAFETY: the buffer's own mapped dwords, `step` to a record. + let dwords = unsafe { std::slice::from_raw_parts_mut(data.cast::(), step * records.len()) }; + // Dwords past the third are the record's other arguments: untouched. + dwords.fill(0xdead_beef); + for (to, from) in dwords.chunks_mut(step).zip(records) { + to[..3].copy_from_slice(from); + } + let list = host.new_list().unwrap(); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + assert!(bound(&list, &buffer, gpu, (kind, stride, records.len() as u32))); + done(&list, &buffer); + list.close(); + host.execute(&[&list]); + assert!(dwords.chunks(step).all(|r| r[3..].iter().all(|&d| d == 0xdead_beef))); + Some(dwords.chunks(step).map(|r| [r[0], r[1], r[2]]).collect()) + } + + /// The host takes the shader we build and runs it as the arithmetic in + /// `clamped` says, for every kind of record. #[test] - fn argument_clamp_builds() { - if super::host().is_none() { - return; // no host GPU here + fn the_host_clamps_as_the_model_does() { + const BIG: u32 = u32::MAX; + let cases: [(u32, u32, &[[u32; 3]]); 4] = [ + (DRAW, 16, &[[3, 1, 7], [BIG, 1, 7], [6, 1000, 7], [0, BIG, 7], [1 << 24, 5, 7]]), + (DRAW_INDEXED, 20, &[[36, 2, 9], [BIG, BIG, 9], [0, 0, 9]]), + ( + DISPATCH, + 12, + &[[8, 8, 1], [BIG, 1, 1], [1024, 1024, 1], [1024, 1025, 1], [2, 2, BIG], [5, 0, 5], [1, 1, 0]], + ), + (MESH, 12, &[[40, 1, 1], [BIG, BIG, BIG], [9, 0, 1], [0, 1, 1]]), + ]; + for (kind, stride, records) in cases { + // Under the budget together, so the order the threads ran in + // does not show. + let spent: u64 = records.iter().map(|&r| u64::from(clamped(&LIMITS, kind, r, 0).1)).sum(); + assert!(spent <= u64::from(LIMITS.budget)); + let Some(got) = run(kind, stride, records) else { + eprintln!("no host D3D12 device; skipped"); + return; + }; + for (i, (&record, got)) in records.iter().zip(got).enumerate() { + let want = clamped(&LIMITS, kind, record, 0).0; + assert_eq!(got, want, "kind {kind} record {i} {record:x?}"); + } } - if cfg!(not(windows)) && std::env::var_os("VICTORY_DXCOMPILER").is_none() { - return; // no HLSL compiler named + // More records than one thread group, with their own values. + let many: Vec<[u32; 3]> = (0..200).map(|i| [i, i % 7, BIG - i]).collect(); + let got = run(DRAW, 16, &many).unwrap(); + for (&record, got) in many.iter().zip(got) { + assert_eq!(got, clamped(&LIMITS, DRAW, record, 0).0); } - #[cfg(not(windows))] - let handler = || { - victory_loader::linux::signals::install(); - // SAFETY: a query into a zeroed action of ours. - unsafe { - let mut action: libc::sigaction = std::mem::zeroed(); - libc::sigaction(libc::SIGSEGV, std::ptr::null(), &mut action); - action.sa_sigaction - } + } + + /// Records past the list's budget run empty: a draw keeps its layout + /// with no vertices. + #[test] + fn records_past_the_budget_run_empty() { + // Each draw clamps to the most one may ask for; two fill the budget. + let most = LIMITS.vertex_instances; + assert_eq!(LIMITS.budget, 2 * most); + let Some(got) = run(DRAW, 16, &[[1 << 24, u32::MAX, 0]; 6]) else { + eprintln!("no host D3D12 device; skipped"); + return; }; - #[cfg(not(windows))] - let ours = handler(); - assert!(super::clamp().is_some()); - // DXC's LLVM took the fault handler at its first compile; ours is back. - #[cfg(not(windows))] - assert_eq!(handler(), ours); + let instances = most >> 24; + // Which two ran is the threads' order. + assert_eq!(got.iter().filter(|r| **r == [1 << 24, instances, 0]).count(), 2, "{got:x?}"); + assert_eq!(got.iter().filter(|r| **r == [0, instances, 0]).count(), 4, "{got:x?}"); } } diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 25465bdc41..804952a29b 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -619,7 +619,7 @@ fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec { unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) }.to_vec() } -fn root_signature( +pub(crate) fn root_signature( device: &ID3D12Device, params: &[D3D12_ROOT_PARAMETER1], samplers: &[D3D12_STATIC_SAMPLER_DESC], diff --git a/crates/victory-loader/src/linux/signals.rs b/crates/victory-loader/src/linux/signals.rs index cb15f3e265..f73ff685ab 100644 --- a/crates/victory-loader/src/linux/signals.rs +++ b/crates/victory-loader/src/linux/signals.rs @@ -62,20 +62,6 @@ fn ours() -> libc::sigaction { action } -/// Puts our handler back where a library replaced it: DXC's LLVM installs -/// its own (`SA_RESETHAND`) at its first compile, after which the next -/// fault in title code, or write to a block the GPU side guards, ended the -/// process. What was there before ours stays the fallback. -pub fn reclaim() { - if !INSTALL.is_completed() { - return; - } - for &signal in &SIGNALS { - // SAFETY: our action, as `install` set it. - unsafe { libc::sigaction(signal, &ours(), std::ptr::null_mut()) }; - } -} - /// Gives the calling thread a 64 KiB alternate signal stack unless it has /// one that large (std gives its threads a smaller one), freed when the /// thread ends. Guest threads diff --git a/crates/victory-shader/src/emit/clamp.rs b/crates/victory-shader/src/emit/clamp.rs new file mode 100644 index 0000000000..aa0c0b352a --- /dev/null +++ b/crates/victory-shader/src/emit/clamp.rs @@ -0,0 +1,320 @@ +//! A compute shader of ours, not a translation: it bounds the arguments of +//! indirect execution on the GPU, just before they are read. Built with the +//! module builder the translations use, so the host needs no HLSL compiler. +//! +//! What the host binds ([`argument_clamp`]): +//! +//! * root constants `b0, space 0`: the record kind ([`DRAW`]..[`MESH`]), the +//! bytes from one record to the next, the number of records; +//! * the arguments as a root UAV, `u` in [`ROOT_CBV_SPACE`], at +//! the address of the first record; +//! * the list's budget as a root UAV, `u` there: one dword, the +//! work the list's records have asked for so far. +//! +//! One thread per record, 64 to a group: `ceil(records / 64)` groups. +//! +//! [`ROOT_CBV_SPACE`]: super::ROOT_CBV_SPACE + +use super::bitcode::{Attr, Bin, Term, Ty, V, pred}; +use super::shader::Shader; + +/// Record kinds: the first dword is a vertex count, an index count, or +/// the first of three group counts. +pub const DRAW: u32 = 0; +pub const DRAW_INDEXED: u32 = 1; +pub const DISPATCH: u32 = 2; +pub const MESH: u32 = 3; + +/// Root parameter indices of the two buffers (the constants are 0). +pub const ARGUMENTS: u8 = 1; +pub const BUDGET: u8 = 2; + +/// Threads in a group of the clamp itself. +pub const GROUP: u32 = 64; + +/// What a record may ask for. A count above its limit is lowered to it; a +/// record over the list's budget runs empty. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// Vertices (or indices) of a draw. + pub vertices: u32, + /// Vertices times instances of a draw. + pub vertex_instances: u32, + /// Thread groups of a dispatch in one dimension. + pub groups_per_dimension: u32, + /// Thread groups of a dispatch; one asking for more runs empty. + pub groups: u32, + /// What a compute group and a mesh group cost, in the budget's unit + /// (a vertex instance or a thread). + pub group_cost: u32, + pub mesh_group_cost: u32, + /// The work of one list. + pub budget: u32, +} + +struct Clamp { + s: Shader, + ret: Ty, + args: V, + budget: V, +} + +impl Clamp { + /// Dwords `at..` of the arguments. + fn load(&mut self, block: usize, at: V, n: u32) -> Vec { + let (undef, mask, align) = ( + self.s.m.undef(self.s.t.i32), + self.s.m.i8((1u8 << n) - 1), + self.s.m.i32(4), + ); + let r = self.s.op( + block, + "rawBufferLoad.i32", + Attr::ReadOnly, + self.ret, + 139, + &[self.args, at, undef, mask, align], + ); + (0..n).map(|k| self.s.m.extract(block, r, k)).collect() + } + + /// Writes `values` at dword `at` of the arguments. + fn store(&mut self, block: usize, at: V, values: &[V]) { + let undef = self.s.m.undef(self.s.t.i32); + let mut args = vec![self.args, at, undef]; + args.extend(values); + args.resize(3 + 4, undef); + args.push(self.s.m.i8((1u8 << values.len()) - 1)); + args.push(self.s.m.i32(4)); + let void = self.s.t.void; + self.s + .op(block, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args); + } + + fn min(&mut self, block: usize, a: V, limit: u32) -> V { + let limit = self.s.m.i32(limit); + let less = self.s.m.cmp(block, pred::IULT, a, limit); + self.s.m.select(block, less, a, limit) + } + + fn mul(&mut self, block: usize, a: V, b: V) -> V { + self.s.m.bin(block, Bin::Mul, a, b) + } +} + +/// The clamp for `limits`, as a DXIL container without a root signature. +pub fn argument_clamp(limits: &Limits) -> Vec { + let mut s = Shader::new(false); + s.threads = Some([GROUP, 1, 1]); + s.user_data = 3; + let i32t = s.t.i32; + let ret = s + .m + .named_struct("dx.types.ResRet.i32", vec![i32t, i32t, i32t, i32t, i32t]); + let entry = s.entry; + let constants = s.user_data_handle(); + let (args, budget) = (s.root_uav_handle(ARGUMENTS), s.root_uav_handle(BUDGET)); + let mut c = Clamp { + s, + ret, + args, + budget, + }; + let [first, draws, groups, dispatch, mesh, spend, empty, done] = + std::array::from_fn(|_| c.s.m.new_block()); + + // One thread per record; the last group's spare threads do nothing. + let zero = c.s.m.i32(0); + let row = c.s.op( + entry, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + c.s.t.cbuf_ret, + 59, + &[constants, zero], + ); + let [kind, stride, records] = [0, 1, 2].map(|k| c.s.m.extract(entry, row, k)); + let id = c + .s + .op(entry, "threadId.i32", Attr::ReadNone, i32t, 93, &[zero]); + let at = c.mul(entry, id, stride); + let one = c.s.m.i32(1); + let last_draw = c.s.m.i32(DRAW_INDEXED); + let is_draw = c.s.m.cmp(entry, pred::IULE, kind, last_draw); + let live = c.s.m.cmp(entry, pred::IULT, id, records); + c.s.m.terminate(entry, Term::CondBr(live, first, done)); + c.s.m.terminate(first, Term::CondBr(is_draw, draws, groups)); + + // Draws: the vertex or index count, then the instances. + let v = c.load(draws, at, 2); + let count = c.min(draws, v[0], limits.vertices); + let some = c.s.m.cmp(draws, pred::IUGT, count, zero); + let divisor = c.s.m.select(draws, some, count, one); + let total = c.s.m.i32(limits.vertex_instances); + let room = c.s.m.bin(draws, Bin::UDiv, total, divisor); + let fits = c.s.m.cmp(draws, pred::IULT, v[1], room); + let instances = c.s.m.select(draws, fits, v[1], room); + let draw_cost = c.mul(draws, count, instances); + c.store(draws, at, &[count, instances]); + c.s.m.terminate(draws, Term::Br(spend)); + + // Groups: three counts. The console's mesh dispatches are + // one-dimensional. + let g = c.load(groups, at, 3); + let is_dispatch = { + let k = c.s.m.i32(DISPATCH); + c.s.m.cmp(groups, pred::EQ, kind, k) + }; + c.s.m.terminate(groups, Term::CondBr(is_dispatch, dispatch, mesh)); + + let d: Vec = g + .iter() + .map(|&x| c.min(dispatch, x, limits.groups_per_dimension)) + .collect(); + // x * y fits 32 bits when both are limited to 16; the whole count may + // not, so it is compared by division. + let xy = c.mul(dispatch, d[0], d[1]); + let deep = c.s.m.cmp(dispatch, pred::IUGT, d[2], zero); + let divisor = c.s.m.select(dispatch, deep, d[2], one); + let total = c.s.m.i32(limits.groups); + let room = c.s.m.bin(dispatch, Bin::UDiv, total, divisor); + let over = c.s.m.cmp(dispatch, pred::IUGT, xy, room); + let over = c.s.m.bin(dispatch, Bin::And, over, deep); + let d: Vec = d + .iter() + .map(|&x| c.s.m.select(dispatch, over, zero, x)) + .collect(); + let dispatch_cost = { + let xy = c.mul(dispatch, d[0], d[1]); + let xyz = c.mul(dispatch, xy, d[2]); + let each = c.s.m.i32(limits.group_cost); + c.mul(dispatch, xyz, each) + }; + c.store(dispatch, at, &d); + c.s.m.terminate(dispatch, Term::Br(spend)); + + let m = [ + c.min(mesh, g[0], limits.groups_per_dimension), + c.min(mesh, g[1], 1), + c.min(mesh, g[2], 1), + ]; + let mesh_cost = { + let xy = c.mul(mesh, m[0], m[1]); + let xyz = c.mul(mesh, xy, m[2]); + let each = c.s.m.i32(limits.mesh_group_cost); + c.mul(mesh, xyz, each) + }; + c.store(mesh, at, &m); + c.s.m.terminate(mesh, Term::Br(spend)); + + // The list's budget: a record that starts past it, or ends past it, + // runs empty. Draws keep their layout with no vertices; groups become + // zero in x. + let cost = c.s.m.phi(spend, i32t); + c.s.m.set_phi( + cost, + vec![ + (draw_cost, draws), + (dispatch_cost, dispatch), + (mesh_cost, mesh), + ], + ); + let undef = c.s.m.undef(i32t); + let before = c.s.op( + spend, + "atomicBinOp.i32", + Attr::NoUnwind, + i32t, + 78, + &[c.budget, zero, zero, undef, undef, cost], + ); + let limit = c.s.m.i32(limits.budget); + let spent = c.s.m.cmp(spend, pred::IUGE, before, limit); + let after = c.s.m.bin(spend, Bin::Add, before, cost); + let past = c.s.m.cmp(spend, pred::IUGT, after, limit); + let out = c.s.m.bin(spend, Bin::Or, spent, past); + c.s.m.terminate(spend, Term::CondBr(out, empty, done)); + c.store(empty, at, &[zero]); + c.s.m.terminate(empty, Term::Br(done)); + c.s.m.terminate(done, Term::Ret); + c.s.finish() +} + +/// What the clamp makes of one record (`dwords` are its first three) with +/// `spent` of the budget used: the record, and what it adds to the budget. +/// The shader's arithmetic, for tests and for readers. +pub fn clamped(limits: &Limits, kind: u32, dwords: [u32; 3], spent: u32) -> ([u32; 3], u32) { + let [x, y, z] = dwords; + let (mut out, cost) = if kind <= DRAW_INDEXED { + let count = x.min(limits.vertices); + let instances = y.min(limits.vertex_instances / count.max(1)); + ([count, instances, z], count.wrapping_mul(instances)) + } else if kind == DISPATCH { + let d = dwords.map(|v| v.min(limits.groups_per_dimension)); + let over = d[2] != 0 && d[0].wrapping_mul(d[1]) > limits.groups / d[2]; + let d = if over { [0; 3] } else { d }; + let groups = d[0].wrapping_mul(d[1]).wrapping_mul(d[2]); + (d, groups.wrapping_mul(limits.group_cost)) + } else { + let m = [x.min(limits.groups_per_dimension), y.min(1), z.min(1)]; + let groups = m[0] * m[1] * m[2]; + (m, groups.wrapping_mul(limits.mesh_group_cost)) + }; + if spent >= limits.budget || spent.wrapping_add(cost) > limits.budget { + out[0] = 0; + } + (out, cost) +} + +#[cfg(test)] +mod tests { + use super::*; + + const LIMITS: Limits = Limits { + vertices: 1 << 24, + vertex_instances: 1 << 26, + groups_per_dimension: 65535, + groups: 1 << 20, + group_cost: 64, + mesh_group_cost: 128, + budget: 1 << 27, + }; + + #[test] + fn the_container_is_a_compute_shader_with_its_bindings() { + let dxil = argument_clamp(&LIMITS); + assert_eq!(dxil, argument_clamp(&LIMITS), "not deterministic"); + let c = crate::dxbc::Container::parse(&dxil).unwrap(); + let has = |name: &[u8; 4]| c.part(crate::dxbc::FourCC(*name)).is_some(); + assert!(has(b"DXIL") && has(b"PSV0") && !has(b"RTS0")); + // The validator, where one is installed, takes it too. + if let Ok(mut v) = crate::emit::validator::Validator::load( + crate::emit::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut dxil.clone()).unwrap(); + } + } + + #[test] + fn the_model_bounds_every_kind() { + let l = &LIMITS; + let big = u32::MAX; + // Draws: the count, then instances by what the count leaves. + assert_eq!(clamped(l, DRAW, [3, 2, 9], 0), ([3, 2, 9], 6)); + assert_eq!(clamped(l, DRAW, [big, big, 9], 0), ([1 << 24, 4, 9], 1 << 26)); + assert_eq!(clamped(l, DRAW_INDEXED, [0, big, 9], 0), ([0, 1 << 26, 9], 0)); + // Dispatches: each dimension, then the whole count or nothing. + assert_eq!(clamped(l, DISPATCH, [8, 8, 1], 0), ([8, 8, 1], 64 * 64)); + assert_eq!(clamped(l, DISPATCH, [big, 1, 1], 0), ([65535, 1, 1], 65535 * 64)); + assert_eq!(clamped(l, DISPATCH, [1024, 1024, 1], 0), ([1024, 1024, 1], 1 << 26)); + assert_eq!(clamped(l, DISPATCH, [1024, 1025, 1], 0), ([0; 3], 0)); + assert_eq!(clamped(l, DISPATCH, [5, 0, 5], 0), ([5, 0, 5], 0)); + assert_eq!(clamped(l, DISPATCH, [1, 1, 0], 0), ([1, 1, 0], 0)); + // Mesh dispatches are one-dimensional. + assert_eq!(clamped(l, MESH, [big, big, big], 0), ([65535, 1, 1], 65535 * 128)); + // The budget: a record that starts or ends past it runs empty. + assert_eq!(clamped(l, DRAW, [3, 2, 9], l.budget - 6).0, [3, 2, 9]); + assert_eq!(clamped(l, DRAW, [3, 2, 9], l.budget - 5).0, [0, 2, 9]); + assert_eq!(clamped(l, DISPATCH, [8, 8, 1], l.budget).0, [0, 8, 1]); + } +} diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index b0d30f9188..6452e098d3 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -117,7 +117,7 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { /// A resource bound by register, as `PSV0` lists it. #[derive(Debug, Clone, Copy)] pub(crate) struct Binding { - /// PSV resource type: 1 sampler, 2 CBV. + /// PSV resource type: 1 sampler, 2 CBV, 4 raw SRV, 7 raw UAV. pub kind: u32, pub space: u32, pub register: u32, diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 48e0a7cb66..c2890dd2b4 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -76,6 +76,7 @@ //! console never exports them). mod bitcode; +pub mod clamp; mod container; #[cfg(test)] mod diff_tests; diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 1bcbe5ebf1..e7f6f1ef87 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -9,8 +9,8 @@ use super::container::{self, Binding, Psv, SigElement}; pub const USER_DATA_SPACE: u32 = 0; /// Where immediate samplers are bound: `s` in this space. pub const SAMPLER_SPACE: u32 = 0; -/// Where root CBVs and SRVs are bound: `b` and -/// `t` in this space. +/// Where root CBVs, SRVs and UAVs are bound: `b`, +/// `t` and `u` in this space. pub const ROOT_CBV_SPACE: u32 = 1; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. @@ -67,6 +67,8 @@ pub(crate) struct Shader { pub root_cbvs: Vec<(u8, V)>, /// Root SRVs (raw buffers) read, likewise. pub root_srvs: Vec<(u8, V)>, + /// Root UAVs (raw buffers) read and written, likewise. + pub root_uavs: Vec<(u8, V)>, pub flags: u64, /// A compute shader with this thread-group size. pub threads: Option<[u32; 3]>, @@ -122,6 +124,7 @@ impl Shader { cmp_samplers: 0, root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), flags: 0, threads: None, wave_size: None, @@ -237,6 +240,30 @@ impl Shader { h } + /// The handle of the root UAV (a raw buffer) of root parameter `slot`. + pub fn root_uav_handle(&mut self, slot: u8) -> V { + if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) { + return h; + } + let r = self.m.i32(u32::from(slot)); + let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(1)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 11 | 0x1000, 0); + self.flags |= flags::RAW_BUFFERS; + self.root_uavs.push((slot, h)); + h + } + /// The handle of immediate sampler `n` (a comparison sampler when its /// bit in `cmp_samplers` is set). pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { @@ -312,6 +339,7 @@ impl Shader { || self.samplers > 0 || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() + || !self.root_uavs.is_empty() { let empty = self.m.md_str(""); let mut cbvs = None; @@ -395,6 +423,41 @@ impl Shader { } srvs = Some(self.m.md_node(list)); } + let mut uavs = None; + if !self.root_uavs.is_empty() { + let ty = self + .m + .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let no = self.m.bool(false); + let mut list = Vec::new(); + for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() { + // After the kind: globally coherent, a counter, a + // rasterizer-ordered view. + let ops = vec![ + Some(i32c(&mut self, n as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(self.m.md_value(no)), + Some(self.m.md_value(no)), + Some(self.m.md_value(no)), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 7, + space: ROOT_CBV_SPACE, + register: u32::from(slot), + dxil_kind: 11, + }); + } + uavs = Some(self.m.md_node(list)); + } let mut samplers = None; if self.samplers > 0 { let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]); @@ -424,12 +487,13 @@ impl Shader { } samplers = Some(self.m.md_node(list)); } - resources = Some(self.m.md_node(vec![srvs, None, cbvs, samplers])); - // PSV0 lists them as the module does: CBVs, samplers, SRVs. + resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers])); + // PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs. bindings.sort_by_key(|b| match b.kind { 2 => 0, 1 => 1, - _ => 2, + 4 => 2, + _ => 3, }); } if let Some(r) = resources { diff --git a/crates/victory-shader/src/hostlib.rs b/crates/victory-shader/src/hostlib.rs index 4b22c7ad2c..1c0952aa03 100644 --- a/crates/victory-shader/src/hostlib.rs +++ b/crates/victory-shader/src/hostlib.rs @@ -122,146 +122,3 @@ pub unsafe fn serialize_versioned_root_signature( // SAFETY: the export has this signature; the caller's pointers. Ok(unsafe { std::mem::transmute::<*mut c_void, Serialize>(f)(desc, blob, error) }) } - -/// DXC's `libdxcompiler.so`, only at `VICTORY_DXCOMPILER` (Arch's -/// 1.10.2605 build asserts on every shader, so none is found unasked), -/// opened once. -fn dxcompiler() -> Result { - static LIBRARY: OnceLock> = OnceLock::new(); - LIBRARY - .get_or_init(|| { - let path = std::env::var_os("VICTORY_DXCOMPILER") - .ok_or("no HLSL compiler: set VICTORY_DXCOMPILER to DXC's libdxcompiler.so")?; - Library::open(Path::new(&path)).map_err(|e| { - format!( - "no HLSL compiler: cannot load {} ({e})", - Path::new(&path).display() - ) - }) - }) - .as_ref() - .copied() - .map_err(String::as_str) -} - -/// Compiles HLSL `source` with DXC (`dxc -E entry -T target -Vd`): the -/// DXIL container, or the compiler's messages. DXC's COM is SysV here and -/// its wide strings are 32-bit (`wchar_t`). -pub fn compile_hlsl(source: &str, entry: &str, target: &str) -> Result, String> { - type Object = *mut *const usize; - type Create = unsafe extern "system" fn(*const [u8; 16], *const [u8; 16], *mut Object) -> i32; - type Compile = unsafe extern "system" fn( - Object, - *const [usize; 3], - *const *const u32, - u32, - *mut c_void, - *const [u8; 16], - *mut Object, - ) -> i32; - type Get = unsafe extern "system" fn(Object, *mut i32) -> i32; - type Blob = unsafe extern "system" fn(Object, *mut Object) -> i32; - type Bytes = unsafe extern "system" fn(Object) -> *const u8; - type Size = unsafe extern "system" fn(Object) -> usize; - type Release = unsafe extern "system" fn(Object) -> u32; - const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u8; 16] { - let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes()); - [ - a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], - d[6], d[7], - ] - } - const CLSID_COMPILER: [u8; 16] = guid( - 0x73e2_2d93, - 0xe6ce, - 0x47f3, - [0xb5, 0xbf, 0xf0, 0x66, 0x4f, 0x39, 0xc1, 0xb0], - ); - const IID_COMPILER3: [u8; 16] = guid( - 0x228b_4687, - 0x5a6a, - 0x4730, - [0x90, 0x0c, 0x97, 0x02, 0xb2, 0x20, 0x3f, 0x54], - ); - const IID_RESULT: [u8; 16] = guid( - 0x5834_6cda, - 0xdde7, - 0x4497, - [0x94, 0x61, 0x6f, 0x87, 0xaf, 0x5e, 0x06, 0x59], - ); - /// The method in `slot` of `object`. - unsafe fn method(object: Object, slot: usize) -> F { - // SAFETY: the caller names a slot of the object's interface. - unsafe { std::mem::transmute_copy(&*(*object).add(slot)) } - } - let library = dxcompiler()?; - // SAFETY: the export has this signature. - let create: Create = unsafe { std::mem::transmute(library.symbol(c"DxcCreateInstance")?) }; - let wide = |s: &str| s.chars().map(u32::from).chain([0]).collect::>(); - let args: Vec> = ["-E", entry, "-T", target, "-Vd"].map(wide).into(); - let pointers: Vec<*const u32> = args.iter().map(|a| a.as_ptr()).collect(); - // `DxcBuffer`: pointer, size, encoding (`DXC_CP_UTF8`). - let buffer = [source.as_ptr() as usize, source.len(), 65001]; - // SAFETY: IDxcCompiler3::Compile (slot 3) with live arguments; then - // IDxcResult's GetStatus (3), GetResult (4) and GetErrorBuffer (5), and - // IDxcBlob's GetBufferPointer (3) and GetBufferSize (4). Every object - // we get is released. - unsafe { - let mut compiler: Object = std::ptr::null_mut(); - if create(&CLSID_COMPILER, &IID_COMPILER3, &mut compiler) < 0 || compiler.is_null() { - return Err("DxcCreateInstance(compiler) failed".into()); - } - let mut result: Object = std::ptr::null_mut(); - let hr = method::(compiler, 3)( - compiler, - &buffer, - pointers.as_ptr(), - pointers.len() as u32, - std::ptr::null_mut(), - &IID_RESULT, - &mut result, - ); - method::(compiler, 2)(compiler); - if hr < 0 || result.is_null() { - return Err(format!("DXC Compile failed: {hr:#x}")); - } - let mut status = 0; - method::(result, 3)(result, &mut status); - let mut blob: Object = std::ptr::null_mut(); - let slot = if status < 0 { 5 } else { 4 }; - method::(result, slot)(result, &mut blob); - method::(result, 2)(result); - let bytes = if blob.is_null() { - Vec::new() - } else { - let at = method::(blob, 3)(blob); - let len = method::(blob, 4)(blob); - let bytes = std::slice::from_raw_parts(at, len).to_vec(); - method::(blob, 2)(blob); - bytes - }; - if status < 0 { - return Err(String::from_utf8_lossy(&bytes) - .trim_end_matches('\0') - .trim() - .into()); - } - Ok(bytes) - } -} - -#[cfg(test)] -mod tests { - #[test] - fn hlsl_compiles_to_dxil() { - let source = "RWByteAddressBuffer o : register(u0);\n\ - [RootSignature(\"UAV(u0)\")] [numthreads(1, 1, 1)]\n\ - void main() { o.Store(0, 7); }"; - match super::compile_hlsl(source, "main", "cs_6_0") { - Ok(dxil) => assert_eq!(&dxil[..4], b"DXBC"), - Err(e) if e.starts_with("no HLSL compiler") => eprintln!("{e}; skipped"), - Err(e) => panic!("{e}"), - } - assert!(super::compile_hlsl("not hlsl", "main", "cs_6_0").is_err_and(|e| !e.is_empty())); - } -} diff --git a/docs/linux.md b/docs/linux.md index 7ae7fdb25d..77993da3bd 100644 --- a/docs/linux.md +++ b/docs/linux.md @@ -115,8 +115,7 @@ translator stay shared. `victory_gpu::kernel_will_write` first (the file layer and UCRT reads, DirectStorage), and writes into the physical pool outside the views call `vm::pool_written`. -- **Not yet:** the DXIL validator and the indirect argument clamp's compiler by default - (below), fence events until the handle table registers its `SetEvent` +- **Not yet:** the DXIL validator by default (below), fence events until the handle table registers its `SetEvent` (`victory_gpu::fence::on_set_event`), the debug layer and WARP. Building vkd3d-proton (meson, ninja, glslang; Vulkan headers come with @@ -135,18 +134,17 @@ libraries); Arch's `vkd3d` is upstream vkd3d, a different library. vkd3d-proton writes `vkd3d-proton.cache` into the working directory (`VKD3D_SHADER_CACHE_PATH` moves it). -DXC is optional and opt-in on Linux: `VICTORY_DXIL` names `libdxil.so` -for `victory translate --validate`, `VICTORY_DXCOMPILER` names -`libdxcompiler.so` for the indirect argument clamp (without it indirect -execution is dropped, as when the clamp fails on Windows). Arch's -`directx-shader-compiler` 1.10.2605 asserts on every shader it compiles -and its validator traps on some of ours, so neither is loaded unasked. -Microsoft's own Linux release works (tested: v1.9.2609): +DXC's validator is optional and opt-in on Linux: `VICTORY_DXIL` names +`libdxil.so` for `victory translate --validate`. Arch's +`directx-shader-compiler` 1.10.2605 validator traps on some of our +shaders, so it is not loaded unasked. Microsoft's own Linux release works +(tested: v1.9.2609). Nothing needs an HLSL compiler: the indirect argument +clamp is built by our own emitter. ```sh gh release download v1.9.2609 -R microsoft/DirectXShaderCompiler -p 'linux_dxc_*.tar.gz' mkdir -p ~/.local/dxc && tar xzf linux_dxc_*.tar.gz -C ~/.local/dxc -export VICTORY_DXIL=~/.local/dxc/lib/libdxil.so VICTORY_DXCOMPILER=~/.local/dxc/lib/libdxcompiler.so +export VICTORY_DXIL=~/.local/dxc/lib/libdxil.so ``` Tests with a device: `VICTORY_VKD3D=... cargo test -p victory-shader