indirect.rs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. //! Indirect execution's arguments, bounded before the GPU reads them. The
  2. //! title's own compute passes write most of them; a pass we drop or
  3. //! translate wrongly leaves whatever the memory held, and a draw of four
  4. //! billion vertices or a dispatch past the host's limits runs until the
  5. //! host resets the display driver. So active records are copied and clamped
  6. //! on the GPU into a device-local scratch buffer, just before execution, by a
  7. //! compute shader of ours (HLSL compiled by the system's compiler; a 5.1
  8. //! shader with its root signature inside), leaving the title's argument and
  9. //! count buffers untouched.
  10. //!
  11. //! When a count buffer is given, threads at or past `min(max, count)` return
  12. //! immediately without charging the list's budget or reading uninitialized
  13. //! tail slots. Each list has a budget (2^27 vertex instances or threads,
  14. //! groups counted as 64 threads, mesh groups as 128): active records past it
  15. //! run empty, saturating without 32-bit wraparound so a list of thousands of
  16. //! garbage records cannot run for seconds either.
  17. //!
  18. //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
  19. //! groups per dimension and 2^20 per dispatch, one-dimensional mesh
  20. //! dispatches, the budget) cut legitimate work beyond them; raise them if
  21. //! the title needs more.
  22. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  23. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  24. use windows::Win32::Graphics::Direct3D12::*;
  25. use windows::core::s;
  26. use crate::host::{HostList, host, transition};
  27. const SOURCE: &str = r#"
  28. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
  29. cbuffer Record : register(b0) {
  30. uint kind;
  31. uint stride;
  32. uint records;
  33. uint args_offset;
  34. // Bit 0: a count buffer bounds the records. Bit 1: the records are a
  35. // window clamped ahead of their draws: one that asks for more than can
  36. // run is left empty and costs nothing.
  37. uint has_count;
  38. uint count_offset;
  39. };
  40. ByteAddressBuffer src_args : register(t0);
  41. ByteAddressBuffer count_buf : register(t1);
  42. RWByteAddressBuffer dst_args : register(u0);
  43. // The list's work so far (vertex instances, threads): past the budget,
  44. // records run empty.
  45. RWByteAddressBuffer budget : register(u1);
  46. static const uint BUDGET = 1u << 27;
  47. // Groups of one dispatch; more run empty.
  48. static const uint GROUPS = 1u << 20;
  49. [RootSignature(RS)]
  50. [numthreads(64, 1, 1)]
  51. void main(uint3 id : SV_DispatchThreadID) {
  52. uint eff_count = records;
  53. bool ahead = (has_count & 2u) != 0;
  54. if ((has_count & 1u) != 0) {
  55. eff_count = min(eff_count, count_buf.Load(count_offset));
  56. }
  57. if (id.x >= eff_count) return;
  58. uint src_at = args_offset + id.x * stride;
  59. uint dst_at = id.x * stride;
  60. uint cost;
  61. uint2 draw_counts = uint2(0, 0);
  62. uint3 groups = uint3(0, 0, 0);
  63. if (kind <= 1) {
  64. // Draws: vertex or index count, then instances.
  65. uint2 asked = src_args.Load2(src_at);
  66. if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) {
  67. asked = uint2(0, 0);
  68. }
  69. uint count = min(asked.x, 1u << 24);
  70. uint instances = min(asked.y, (1u << 26) / max(count, 1u));
  71. cost = count * instances;
  72. draw_counts = uint2(count, instances);
  73. } else if (kind == 2) {
  74. uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u));
  75. // x * y fits 32 bits; the whole count may not.
  76. if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
  77. g = uint3(0, 0, 0);
  78. }
  79. cost = g.x * g.y * g.z * 64u;
  80. groups = g;
  81. } else {
  82. // Mesh dispatches: the console's are one-dimensional.
  83. uint3 g = src_args.Load3(src_at);
  84. // Ahead of its draw, a record over the most a dispatch runs is a
  85. // slot the title has not filled (the title leaves all
  86. // ones there): empty, and not counted below either.
  87. if (ahead && g.x > 65535u) {
  88. g = uint3(0, 0, 0);
  89. }
  90. // Diagnostics, in the budget buffer's next words: the largest
  91. // group count a mesh record asked for, and the groups asked in all.
  92. uint was;
  93. budget.InterlockedMax(4, g.x, was);
  94. budget.InterlockedAdd(8, min(g.x, 1u << 24), was);
  95. g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
  96. cost = g.x * g.y * g.z * 128u;
  97. groups = g;
  98. }
  99. bool over = false;
  100. if (cost > 0) {
  101. uint before;
  102. budget.InterlockedOr(0, 0, before);
  103. [allow_uav_condition]
  104. while (before < BUDGET) {
  105. uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost);
  106. uint prev;
  107. budget.InterlockedCompareExchange(0, before, next, prev);
  108. if (prev == before) break;
  109. before = prev;
  110. }
  111. over = before >= BUDGET || BUDGET - before < cost;
  112. }
  113. if (kind <= 1) {
  114. if (over) {
  115. draw_counts = uint2(0, 0);
  116. }
  117. dst_args.Store2(dst_at, draw_counts);
  118. for (uint off = 8; off < stride; off += 4) {
  119. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  120. }
  121. } else {
  122. if (over) {
  123. groups = uint3(0, 0, 0);
  124. }
  125. dst_args.Store3(dst_at, groups);
  126. for (uint off = 12; off < stride; off += 4) {
  127. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  128. }
  129. }
  130. }
  131. "#;
  132. struct Clamp {
  133. root: ID3D12RootSignature,
  134. pso: ID3D12PipelineState,
  135. }
  136. // SAFETY: D3D12 objects are free-threaded.
  137. unsafe impl Send for Clamp {}
  138. // SAFETY: as above.
  139. unsafe impl Sync for Clamp {}
  140. fn clamp() -> Option<&'static Clamp> {
  141. static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
  142. CLAMP
  143. .get_or_init(|| match make() {
  144. Ok(c) => Some(c),
  145. Err(e) => {
  146. tracing::warn!(error = %e, "no argument clamp: indirect execution dropped");
  147. None
  148. }
  149. })
  150. .as_ref()
  151. }
  152. fn make() -> windows::core::Result<Clamp> {
  153. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  154. make_for(device)
  155. }
  156. fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> {
  157. let mut code: Option<ID3DBlob> = None;
  158. let mut errors: Option<ID3DBlob> = None;
  159. // SAFETY: the source and names live through the call; out pointers ours.
  160. let compiled = unsafe {
  161. D3DCompile(
  162. SOURCE.as_ptr().cast(),
  163. SOURCE.len(),
  164. s!("clamp"),
  165. None,
  166. None,
  167. s!("main"),
  168. s!("cs_5_1"),
  169. 0,
  170. 0,
  171. &mut code,
  172. Some(&mut errors),
  173. )
  174. };
  175. if let Err(e) = compiled {
  176. if let Some(errors) = errors {
  177. // SAFETY: the blob's own bytes.
  178. let text = unsafe {
  179. std::slice::from_raw_parts(
  180. errors.GetBufferPointer().cast::<u8>(),
  181. errors.GetBufferSize(),
  182. )
  183. };
  184. tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text));
  185. }
  186. return Err(e);
  187. }
  188. let code = code.ok_or_else(windows::core::Error::empty)?;
  189. // SAFETY: the blob's own bytes; the root signature is inside the shader.
  190. unsafe {
  191. let bytes =
  192. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  193. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  194. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  195. pRootSignature: std::mem::transmute_copy(&root),
  196. CS: D3D12_SHADER_BYTECODE {
  197. pShaderBytecode: bytes.as_ptr().cast(),
  198. BytecodeLength: bytes.len(),
  199. },
  200. ..Default::default()
  201. })?;
  202. Ok(Clamp { root, pso })
  203. }
  204. }
  205. /// Minimum record byte stride for a supported PC indirect argument `kind`.
  206. fn min_stride(kind: u32) -> Option<u32> {
  207. match kind {
  208. 0 => Some(16),
  209. 1 => Some(20),
  210. 2 | 10 => Some(12),
  211. _ => None,
  212. }
  213. }
  214. /// Validates record alignment and returns the scratch byte size `stride * records`.
  215. fn validate_layout(
  216. (kind, stride, records): (u32, u32, u32),
  217. src_offset: u64,
  218. count_offset: Option<u64>,
  219. ) -> Option<u64> {
  220. let min = min_stride(kind)?;
  221. if stride < min || !stride.is_multiple_of(4) || !src_offset.is_multiple_of(4) {
  222. return None;
  223. }
  224. if count_offset.is_some_and(|off| !off.is_multiple_of(4)) {
  225. return None;
  226. }
  227. let bytes = u64::from(stride).checked_mul(u64::from(records))?;
  228. (bytes <= u64::from(u32::MAX)).then_some(bytes)
  229. }
  230. /// Records, in `list`, the non-destructive clamp of up to `records` records of
  231. /// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded
  232. /// by the 32-bit count in `count` when given) into a device-local scratch
  233. /// buffer, leaving that scratch buffer in `INDIRECT_ARGUMENT` at offset `0`.
  234. /// Replaces the list's compute root signature and pipeline (callers bind
  235. /// theirs after). `None` if the clamp or alignment is not available.
  236. pub(crate) fn bound(
  237. list: &HostList,
  238. src: (&ID3D12Resource, u64),
  239. count: Option<(&ID3D12Resource, u64)>,
  240. spec: (u32, u32, u32),
  241. ) -> Option<ID3D12Resource> {
  242. let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?;
  243. let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
  244. record_clamp(c, &list.list, &dst, budget, src, count, spec).then_some(dst)
  245. }
  246. /// [`bound`] for a window of records clamped ahead of the draws that will
  247. /// read them (`crate::draw`'s windows; no count buffer). The records past
  248. /// the ones the title filled are whatever the buffer holds, and each
  249. /// record clamped charges the list's budget when it is clamped: a slot of
  250. /// all ones, clamped to the most a mesh dispatch runs (65,535 groups),
  251. /// charged a sixteenth of the budget, so sixteen of them emptied every
  252. /// draw of the list after them (run 93: "the largest group count asked for
  253. /// 4294967295", 43 to 153 such records a frame). Here a record that asks
  254. /// for more than can run is left empty and charges nothing; a record
  255. /// clamped alone is clamped and charged as before.
  256. pub(crate) fn bound_ahead(
  257. list: &HostList,
  258. src: (&ID3D12Resource, u64),
  259. spec: (u32, u32, u32),
  260. ) -> Option<ID3D12Resource> {
  261. let bytes = validate_layout(spec, src.1, None)?;
  262. let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
  263. record_clamp_as(c, &list.list, &dst, budget, src, None, spec, true).then_some(dst)
  264. }
  265. fn record_clamp(
  266. c: &Clamp,
  267. l: &ID3D12GraphicsCommandList,
  268. dst: &ID3D12Resource,
  269. budget: u64,
  270. src: (&ID3D12Resource, u64),
  271. count: Option<(&ID3D12Resource, u64)>,
  272. spec: (u32, u32, u32),
  273. ) -> bool {
  274. record_clamp_as(c, l, dst, budget, src, count, spec, false)
  275. }
  276. /// [`record_clamp`]; `ahead`: the records are a window clamped ahead of
  277. /// their draws ([`bound_ahead`]).
  278. #[allow(clippy::too_many_arguments)]
  279. fn record_clamp_as(
  280. c: &Clamp,
  281. l: &ID3D12GraphicsCommandList,
  282. dst: &ID3D12Resource,
  283. budget: u64,
  284. (src, src_offset): (&ID3D12Resource, u64),
  285. count: Option<(&ID3D12Resource, u64)>,
  286. (kind, stride, records): (u32, u32, u32),
  287. ahead: bool,
  288. ) -> bool {
  289. let Some(bytes) = validate_layout(
  290. (kind, stride, records),
  291. src_offset,
  292. count.map(|(_, off)| off),
  293. ) else {
  294. return false;
  295. };
  296. // SAFETY: live D3D12 buffer resources.
  297. let (src_base, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) };
  298. if !src_base.is_multiple_of(4) || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) {
  299. return false;
  300. }
  301. let (src_gpu, args_offset) = match src_offset
  302. .checked_add(bytes)
  303. .filter(|&end| end <= u64::from(u32::MAX))
  304. {
  305. Some(_) => (src_base, src_offset as u32),
  306. None => {
  307. let Some(rebased) = src_base.checked_add(src_offset) else {
  308. return false;
  309. };
  310. (rebased, 0)
  311. }
  312. };
  313. let (count_gpu, has_count, count_offset) = match count {
  314. Some((buf, off)) => {
  315. // SAFETY: a live D3D12 buffer resource.
  316. let base = unsafe { buf.GetGPUVirtualAddress() };
  317. if !base.is_multiple_of(4) {
  318. return false;
  319. }
  320. match off.checked_add(4).filter(|&end| end <= u64::from(u32::MAX)) {
  321. Some(_) => (base, 1u32, off as u32),
  322. None => {
  323. let Some(rebased) = base.checked_add(off) else {
  324. return false;
  325. };
  326. (rebased, 1u32, 0u32)
  327. }
  328. }
  329. }
  330. None => (src_gpu, 0u32, 0u32),
  331. };
  332. let constants = [kind, stride, records, args_offset, has_count | (u32::from(ahead) << 1), count_offset];
  333. // SAFETY: an open list; our root signature and pipeline; live source,
  334. // count, scratch destination, and budget buffers. `src` and `count` stay
  335. // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst`
  336. // transitions `COMMON -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`.
  337. // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two
  338. // waits for every earlier shader write out (the state changes stay).
  339. #[cfg(feature = "diagnostics")]
  340. crate::copystat::add(crate::copystat::C::IndirectBounded, 1);
  341. #[cfg(feature = "diagnostics")]
  342. let waits = crate::copystat::barrier_test() & 2 == 0;
  343. #[cfg(not(feature = "diagnostics"))]
  344. let waits = true;
  345. let first = [
  346. uav_barrier(),
  347. transition(
  348. dst,
  349. D3D12_RESOURCE_STATE_COMMON,
  350. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  351. ),
  352. ];
  353. let second = [
  354. uav_barrier(),
  355. transition(
  356. dst,
  357. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  358. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  359. ),
  360. ];
  361. let skip = usize::from(!waits);
  362. unsafe {
  363. // Earlier shader writes (the title's argument and count passes) first.
  364. l.ResourceBarrier(&first[skip..]);
  365. if records > 0 {
  366. l.SetComputeRootSignature(&c.root);
  367. l.SetPipelineState(&c.pso);
  368. l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  369. l.SetComputeRootShaderResourceView(1, src_gpu);
  370. l.SetComputeRootShaderResourceView(2, count_gpu);
  371. l.SetComputeRootUnorderedAccessView(3, dst_gpu);
  372. l.SetComputeRootUnorderedAccessView(4, budget);
  373. l.Dispatch(records.div_ceil(64), 1, 1);
  374. }
  375. l.ResourceBarrier(&second[skip..]);
  376. }
  377. true
  378. }
  379. /// After indirect execution (or if preparation failed after [`bound`]):
  380. /// returns the scratch buffer to the common state for the next call.
  381. pub(crate) fn done(list: &HostList, scratch: &ID3D12Resource) {
  382. done_on(&list.list, scratch);
  383. }
  384. fn done_on(list: &ID3D12GraphicsCommandList, scratch: &ID3D12Resource) {
  385. // SAFETY: an open list and a live scratch buffer in INDIRECT_ARGUMENT.
  386. unsafe {
  387. list.ResourceBarrier(&[transition(
  388. scratch,
  389. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  390. D3D12_RESOURCE_STATE_COMMON,
  391. )])
  392. };
  393. }
  394. fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
  395. D3D12_RESOURCE_BARRIER {
  396. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  397. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  398. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  399. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  400. pResource: std::mem::ManuallyDrop::new(None),
  401. }),
  402. },
  403. }
  404. }
  405. #[cfg(test)]
  406. mod tests {
  407. use super::*;
  408. use windows::Win32::Foundation::HANDLE;
  409. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  410. use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
  411. use windows::Win32::Graphics::Dxgi::*;
  412. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  413. use windows::core::Interface;
  414. const WORKER_CS: &str = r#"
  415. #define RS "UAV(u0)"
  416. RWByteAddressBuffer hits : register(u0);
  417. [RootSignature(RS)]
  418. [numthreads(1, 1, 1)]
  419. void main() {
  420. uint prev;
  421. hits.InterlockedAdd(0, 1, prev);
  422. }
  423. "#;
  424. struct WarpHarness {
  425. device: ID3D12Device,
  426. queue: ID3D12CommandQueue,
  427. allocator: ID3D12CommandAllocator,
  428. list: ID3D12GraphicsCommandList,
  429. fence: ID3D12Fence,
  430. submitted: u64,
  431. event: HANDLE,
  432. clamp: Clamp,
  433. worker: Clamp,
  434. }
  435. impl WarpHarness {
  436. fn new() -> Option<Self> {
  437. // SAFETY: plain DXGI WARP query and D3D12 test harness setup.
  438. unsafe {
  439. let factory: IDXGIFactory4 =
  440. CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
  441. let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?;
  442. let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?;
  443. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  444. return None;
  445. }
  446. let mut device: Option<ID3D12Device> = None;
  447. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  448. let device = device?;
  449. let queue: ID3D12CommandQueue = device
  450. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  451. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  452. ..Default::default()
  453. })
  454. .ok()?;
  455. let allocator: ID3D12CommandAllocator = device
  456. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)
  457. .ok()?;
  458. let list: ID3D12GraphicsCommandList = device
  459. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  460. .ok()?;
  461. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  462. let event = CreateEventW(None, false, false, None).ok()?;
  463. let clamp = make_for(&device).expect("clamp shader must compile on WARP");
  464. let worker = compile_cs(&device, WORKER_CS).expect("worker shader must compile");
  465. Some(Self {
  466. device,
  467. queue,
  468. allocator,
  469. list,
  470. fence,
  471. submitted: 0,
  472. event,
  473. clamp,
  474. worker,
  475. })
  476. }
  477. }
  478. /// CPU-mapped L0 write-back buffer matching `Shadow`'s heap type.
  479. fn shared_buffer(&self, size: u64) -> (ID3D12Resource, *mut u8, u64) {
  480. let heap = D3D12_HEAP_PROPERTIES {
  481. Type: D3D12_HEAP_TYPE_CUSTOM,
  482. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  483. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  484. ..Default::default()
  485. };
  486. let desc = D3D12_RESOURCE_DESC {
  487. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  488. Width: size.max(4),
  489. Height: 1,
  490. DepthOrArraySize: 1,
  491. MipLevels: 1,
  492. SampleDesc: DXGI_SAMPLE_DESC {
  493. Count: 1,
  494. Quality: 0,
  495. },
  496. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  497. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  498. ..Default::default()
  499. };
  500. let mut buffer: Option<ID3D12Resource> = None;
  501. let mut data = std::ptr::null_mut();
  502. // SAFETY: plain buffer creation and persistent CPU mapping.
  503. unsafe {
  504. self.device
  505. .CreateCommittedResource(
  506. &heap,
  507. D3D12_HEAP_FLAG_NONE,
  508. &desc,
  509. D3D12_RESOURCE_STATE_COMMON,
  510. None,
  511. &mut buffer,
  512. )
  513. .unwrap();
  514. let buffer = buffer.unwrap();
  515. buffer.Map(0, None, Some(&mut data)).unwrap();
  516. let gpu = buffer.GetGPUVirtualAddress();
  517. (buffer, data.cast(), gpu)
  518. }
  519. }
  520. /// Device-local `DEFAULT`-heap UAV scratch buffer.
  521. fn default_uav(&self, size: u64) -> ID3D12Resource {
  522. let heap = D3D12_HEAP_PROPERTIES {
  523. Type: D3D12_HEAP_TYPE_DEFAULT,
  524. ..Default::default()
  525. };
  526. let desc = D3D12_RESOURCE_DESC {
  527. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  528. Width: size.max(64 << 10),
  529. Height: 1,
  530. DepthOrArraySize: 1,
  531. MipLevels: 1,
  532. SampleDesc: DXGI_SAMPLE_DESC {
  533. Count: 1,
  534. Quality: 0,
  535. },
  536. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  537. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  538. ..Default::default()
  539. };
  540. let mut buffer: Option<ID3D12Resource> = None;
  541. // SAFETY: plain device-local buffer creation.
  542. unsafe {
  543. self.device
  544. .CreateCommittedResource(
  545. &heap,
  546. D3D12_HEAP_FLAG_NONE,
  547. &desc,
  548. D3D12_RESOURCE_STATE_COMMON,
  549. None,
  550. &mut buffer,
  551. )
  552. .unwrap();
  553. }
  554. buffer.unwrap()
  555. }
  556. fn signature(&self, kind: u32, stride: u32) -> ID3D12CommandSignature {
  557. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  558. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  559. ..Default::default()
  560. };
  561. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  562. ByteStride: stride,
  563. NumArgumentDescs: 1,
  564. pArgumentDescs: &arg,
  565. NodeMask: 0,
  566. };
  567. let mut sig: Option<ID3D12CommandSignature> = None;
  568. // SAFETY: valid single-argument command signature description.
  569. unsafe {
  570. self.device
  571. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  572. .unwrap();
  573. }
  574. sig.unwrap()
  575. }
  576. fn submit_and_wait(&mut self) {
  577. self.submitted += 1;
  578. // SAFETY: closing, executing, waiting on fence, and resetting our list.
  579. unsafe {
  580. self.list.Close().unwrap();
  581. let cmd: ID3D12CommandList = self.list.cast().unwrap();
  582. self.queue.ExecuteCommandLists(&[Some(cmd)]);
  583. self.queue.Signal(&self.fence, self.submitted).unwrap();
  584. self.fence
  585. .SetEventOnCompletion(self.submitted, self.event)
  586. .unwrap();
  587. WaitForSingleObject(self.event, INFINITE);
  588. self.allocator.Reset().unwrap();
  589. self.list.Reset(&self.allocator, None).unwrap();
  590. }
  591. }
  592. }
  593. fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
  594. let mut code: Option<ID3DBlob> = None;
  595. // SAFETY: source and entry names outlive `D3DCompile`.
  596. unsafe {
  597. D3DCompile(
  598. source.as_ptr().cast(),
  599. source.len(),
  600. s!("worker"),
  601. None,
  602. None,
  603. s!("main"),
  604. s!("cs_5_1"),
  605. 0,
  606. 0,
  607. &mut code,
  608. None,
  609. )?;
  610. let code = code.unwrap();
  611. let bytes = std::slice::from_raw_parts(
  612. code.GetBufferPointer().cast::<u8>(),
  613. code.GetBufferSize(),
  614. );
  615. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  616. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  617. pRootSignature: std::mem::transmute_copy(&root),
  618. CS: D3D12_SHADER_BYTECODE {
  619. pShaderBytecode: bytes.as_ptr().cast(),
  620. BytecodeLength: bytes.len(),
  621. },
  622. ..Default::default()
  623. })?;
  624. Ok(Clamp { root, pso })
  625. }
  626. }
  627. /// The compare of copies in the card's memory (`crate::host`), on the
  628. /// software adapter. Told 1 it flags the pieces whose bytes are not
  629. /// what was hashed last and leaves the hashes: a piece a shader changed
  630. /// and a later one changed back then looks untouched, which is right
  631. /// only if the piece was fetched after both. Told 2 (submissions sent
  632. /// ahead with the relay, whose pieces are fetched flight by flight) it
  633. /// stores the hash it made: each compare flags what changed since the
  634. /// compare before it, also a change back.
  635. #[test]
  636. fn warp_card_compare_stores_the_hash_it_made_when_told() {
  637. let Some(mut warp) = WarpHarness::new() else {
  638. return;
  639. };
  640. let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP");
  641. const PIECE: usize = 64 << 10;
  642. const PIECES: u32 = 3;
  643. let size = PIECE * PIECES as usize;
  644. let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64);
  645. let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES));
  646. let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64);
  647. let content: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect();
  648. // SAFETY: the mapping holds `size` bytes.
  649. unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) };
  650. // One pass over the three pieces; what it left in `differs` (7s
  651. // where it stored nothing).
  652. let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] {
  653. // SAFETY: our open list, live buffers, the compare's own root
  654. // signature; the mappings hold what is read and written.
  655. unsafe {
  656. for piece in 0..PIECES as usize {
  657. differs_ptr.cast::<u32>().add(piece).write_volatile(7);
  658. }
  659. warp.list.SetComputeRootSignature(&compare.root);
  660. warp.list.SetPipelineState(&compare.pso);
  661. let constants = [0u32, 0, size as u32, PIECES, 0, mode];
  662. warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  663. warp.list.SetComputeRootShaderResourceView(1, now_gpu);
  664. warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu);
  665. warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu);
  666. warp.list.Dispatch(PIECES.div_ceil(64), 1, 1);
  667. }
  668. warp.submit_and_wait();
  669. // SAFETY: as above.
  670. [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::<u32>().add(piece).read_volatile() })
  671. };
  672. let at = PIECE + 1234;
  673. // SAFETY (each): inside the mapping.
  674. let set = |value: u8| unsafe { now_ptr.add(at).write_volatile(value) };
  675. // 0: the hashes are stored, nothing is flagged.
  676. assert_eq!(run(&mut warp, 0), [7, 7, 7]);
  677. assert_eq!(run(&mut warp, 1), [0, 0, 0]);
  678. // A change in the second piece: flagged, and with 1 flagged again
  679. // (the hash stays the old one).
  680. set(content[at] ^ 0x40);
  681. assert_eq!(run(&mut warp, 1), [0, 1, 0]);
  682. assert_eq!(run(&mut warp, 1), [0, 1, 0]);
  683. // Changed back: with 1 the piece looks untouched.
  684. set(content[at]);
  685. assert_eq!(run(&mut warp, 1), [0, 0, 0]);
  686. // With 2 the change is flagged once, and the hash is the new one.
  687. set(content[at] ^ 0x40);
  688. assert_eq!(run(&mut warp, 2), [0, 1, 0]);
  689. assert_eq!(run(&mut warp, 2), [0, 0, 0]);
  690. // Changed back: flagged, where 1 saw nothing.
  691. set(content[at]);
  692. assert_eq!(run(&mut warp, 2), [0, 1, 0]);
  693. assert_eq!(run(&mut warp, 2), [0, 0, 0]);
  694. }
  695. /// The clamp compiles with the system's compiler and the host takes it.
  696. #[test]
  697. fn argument_clamp_builds() {
  698. if super::host().is_none() {
  699. return; // no host GPU here
  700. }
  701. assert!(super::clamp().is_some());
  702. }
  703. #[test]
  704. fn rejects_unaligned_or_undersized_layouts() {
  705. assert_eq!(validate_layout((0, 16, 4), 0, None), Some(64));
  706. assert_eq!(validate_layout((1, 20, 4), 64, Some(128)), Some(80));
  707. assert_eq!(validate_layout((2, 12, 0), 0, Some(0)), Some(0));
  708. assert_eq!(validate_layout((10, 16, 2), 8, None), Some(32));
  709. // Undersized strides for each kind.
  710. assert_eq!(validate_layout((0, 12, 1), 0, None), None);
  711. assert_eq!(validate_layout((1, 16, 1), 0, None), None);
  712. assert_eq!(validate_layout((2, 8, 1), 0, None), None);
  713. assert_eq!(validate_layout((10, 8, 1), 0, None), None);
  714. // Unknown kind.
  715. assert_eq!(validate_layout((3, 16, 1), 0, None), None);
  716. // Unaligned stride, source offset, or count offset.
  717. assert_eq!(validate_layout((0, 18, 1), 0, None), None);
  718. assert_eq!(validate_layout((0, 16, 1), 2, None), None);
  719. assert_eq!(validate_layout((0, 16, 1), 0, Some(6)), None);
  720. // Total byte size exceeding 32-bit ByteAddressBuffer indexing.
  721. assert_eq!(validate_layout((1, 20, u32::MAX), 0, None), None);
  722. }
  723. /// WARP D3D12 execution test proving:
  724. /// (a) `countBuffer` with a small count (`3`) and `4,093` garbage tail slots
  725. /// (`max = 4096`) does NOT blow `BUDGET` or zero valid dispatches in
  726. /// this or subsequent `ExecuteIndirect` calls in the same list,
  727. /// (b) `src_args` (and `count_buf`) are NOT mutated in-place, and
  728. /// (c) full `stride` bytes (`stride = 24` > `12`) are copied for active
  729. /// records into `dst_args` at offset `0`.
  730. #[test]
  731. fn warp_count_buffer_ignores_garbage_tail_and_preserves_source() {
  732. let Some(mut warp) = WarpHarness::new() else {
  733. return;
  734. };
  735. const KIND_DISPATCH: u32 = 2;
  736. const STRIDE: u32 = 24; // 6 dwords: 3 dispatch group counts + 3 extra payload dwords
  737. const MAX: u32 = 4096;
  738. const ARGS_OFFSET: usize = 64; // non-zero offset with sentinel prefix
  739. const COUNT_OFFSET_1: usize = 128;
  740. const COUNT_OFFSET_2: usize = 192;
  741. let src_bytes = ARGS_OFFSET + (STRIDE as usize) * (MAX as usize) + 64;
  742. let (src_buf, src_ptr, _) = warp.shared_buffer(src_bytes as u64);
  743. let (count_buf, count_ptr, _) = warp.shared_buffer(512);
  744. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  745. let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256);
  746. let (readback_buf, readback_ptr, _) = warp.shared_buffer((STRIDE * 8) as u64);
  747. let dst_buf = warp.default_uav(u64::from(STRIDE) * u64::from(MAX));
  748. let sig = warp.signature(KIND_DISPATCH, STRIDE);
  749. // Fill the entire source buffer with non-zero sentinel bytes, then
  750. // populate 3 valid records at `ARGS_OFFSET` and 4,093 huge garbage
  751. // records in `3..MAX` that would exhaust `BUDGET` ~2,000x over if read.
  752. let mut initial_src = vec![0xA5u8; src_bytes];
  753. let write_record = |buf: &mut [u8], idx: usize, words: [u32; 6]| {
  754. let base = ARGS_OFFSET + idx * (STRIDE as usize);
  755. for (w, val) in words.into_iter().enumerate() {
  756. buf[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
  757. }
  758. };
  759. write_record(
  760. &mut initial_src,
  761. 0,
  762. [3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666],
  763. );
  764. write_record(
  765. &mut initial_src,
  766. 1,
  767. [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC],
  768. );
  769. // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1).
  770. write_record(
  771. &mut initial_src,
  772. 2,
  773. [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567],
  774. );
  775. for slot in 3..MAX as usize {
  776. // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups
  777. // (`cost = 67,107,840 ~= BUDGET / 2`), exhausting `BUDGET` immediately!
  778. write_record(
  779. &mut initial_src,
  780. slot,
  781. [0xFFFF_FFFF, 16, 1, 0xDEAD_BEEF, 0xBAD0_C0DE, slot as u32],
  782. );
  783. }
  784. // Second indirect call's source records (at offset 0 of a second buffer,
  785. // or later in `count_buf`): put 2 active records + garbage tail in a
  786. // second range to run back-to-back in the SAME command list.
  787. let mut initial_count = vec![0x5Au8; 512];
  788. initial_count[COUNT_OFFSET_1..COUNT_OFFSET_1 + 4].copy_from_slice(&3u32.to_le_bytes());
  789. initial_count[COUNT_OFFSET_2..COUNT_OFFSET_2 + 4].copy_from_slice(&2u32.to_le_bytes());
  790. // SAFETY: buffers are mapped with exact capacities above.
  791. unsafe {
  792. std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, src_bytes);
  793. std::ptr::copy_nonoverlapping(initial_count.as_ptr(), count_ptr, 512);
  794. (budget_ptr as *mut u32).write_volatile(0);
  795. (hits_ptr as *mut u32).write_volatile(0);
  796. std::ptr::write_bytes(readback_ptr, 0, (STRIDE * 8) as usize);
  797. }
  798. // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first
  799. // 5 records of `dst_buf` out for inspection, then record Call #2
  800. // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list!
  801. assert!(record_clamp(
  802. &warp.clamp,
  803. &warp.list,
  804. &dst_buf,
  805. budget_gpu,
  806. (&src_buf, ARGS_OFFSET as u64),
  807. Some((&count_buf, COUNT_OFFSET_1 as u64)),
  808. (KIND_DISPATCH, STRIDE, MAX),
  809. ));
  810. // SAFETY: open command list, valid worker PSO/root and buffers.
  811. unsafe {
  812. warp.list.SetComputeRootSignature(&warp.worker.root);
  813. warp.list.SetPipelineState(&warp.worker.pso);
  814. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  815. warp.list.ExecuteIndirect(
  816. &sig,
  817. MAX,
  818. &dst_buf,
  819. 0,
  820. Some(&count_buf),
  821. COUNT_OFFSET_1 as u64,
  822. );
  823. }
  824. done_on(&warp.list, &dst_buf);
  825. // Snapshot `dst_buf` after Call #1 (from `COMMON`, copy 5 * STRIDE bytes,
  826. // then return `dst_buf` to `COMMON` before Call #2).
  827. // SAFETY: open command list; `dst_buf` returned to `COMMON` by `done_on`.
  828. unsafe {
  829. warp.list.ResourceBarrier(&[transition(
  830. &dst_buf,
  831. D3D12_RESOURCE_STATE_COMMON,
  832. D3D12_RESOURCE_STATE_COPY_SOURCE,
  833. )]);
  834. warp.list
  835. .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, u64::from(STRIDE * 5));
  836. warp.list.ResourceBarrier(&[transition(
  837. &dst_buf,
  838. D3D12_RESOURCE_STATE_COPY_SOURCE,
  839. D3D12_RESOURCE_STATE_COMMON,
  840. )]);
  841. }
  842. // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1:
  843. // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`!
  844. assert!(record_clamp(
  845. &warp.clamp,
  846. &warp.list,
  847. &dst_buf,
  848. budget_gpu,
  849. (&src_buf, ARGS_OFFSET as u64),
  850. Some((&count_buf, COUNT_OFFSET_2 as u64)),
  851. (KIND_DISPATCH, STRIDE, MAX),
  852. ));
  853. // SAFETY: open command list, valid worker PSO/root and buffers.
  854. unsafe {
  855. warp.list.SetComputeRootSignature(&warp.worker.root);
  856. warp.list.SetPipelineState(&warp.worker.pso);
  857. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  858. warp.list.ExecuteIndirect(
  859. &sig,
  860. MAX,
  861. &dst_buf,
  862. 0,
  863. Some(&count_buf),
  864. COUNT_OFFSET_2 as u64,
  865. );
  866. }
  867. done_on(&warp.list, &dst_buf);
  868. warp.submit_and_wait();
  869. // SAFETY: GPU execution finished; read mapped host results.
  870. let (hits, spent, after_src, after_count, clamped_words) = unsafe {
  871. let hits = (hits_ptr as *const u32).read_volatile();
  872. let spent = (budget_ptr as *const u32).read_volatile();
  873. let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), src_bytes).to_vec();
  874. let after_count = std::slice::from_raw_parts(count_ptr.cast_const(), 512).to_vec();
  875. let words = std::slice::from_raw_parts(
  876. readback_ptr.cast::<u32>().cast_const(),
  877. (STRIDE as usize / 4) * 5,
  878. )
  879. .to_vec();
  880. (hits, spent, after_src, after_count, words)
  881. };
  882. // Call #1: (3*2*1) + (5*1*1) + (65535*1*1) = 65,546 groups.
  883. // Call #2: (3*2*1) + (5*1*1) = 11 groups.
  884. let expected_groups = (6 + 5 + 65_535) + (6 + 5);
  885. assert_eq!(
  886. hits, expected_groups,
  887. "valid indirect dispatches must all execute"
  888. );
  889. assert_eq!(
  890. spent,
  891. expected_groups * 64,
  892. "budget must reflect only active records below countBuffer"
  893. );
  894. assert_eq!(
  895. after_src, initial_src,
  896. "src_args must never be mutated in-place"
  897. );
  898. assert_eq!(
  899. after_count, initial_count,
  900. "count_buf must never be mutated"
  901. );
  902. // Check `dst_args` records 0..3: clamped group counts + preserved extra stride words.
  903. assert_eq!(
  904. &clamped_words[0..6],
  905. &[3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666]
  906. );
  907. assert_eq!(
  908. &clamped_words[6..12],
  909. &[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC]
  910. );
  911. assert_eq!(
  912. &clamped_words[12..18],
  913. &[65_535, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567]
  914. );
  915. // Inactive slot 3 was never copied from `src_args`.
  916. assert_ne!(clamped_words[21], 0xDEAD_BEEF);
  917. }
  918. /// WARP D3D12 test proving `BUDGET` saturates without 32-bit unsigned
  919. /// wraparound across >64 huge indexed-draw records (`count = None`), while
  920. /// preserving `StartIndexLocation`, `BaseVertexLocation`,
  921. /// `StartInstanceLocation`, and custom stride padding, and leaving
  922. /// `src_args` untouched.
  923. /// A window of mesh records clamped ahead: the filled ones come out as
  924. /// they are and are charged, the slots of all ones come out empty and
  925. /// charge nothing; clamped as single records the same slots are clamped
  926. /// to the most and spend the budget.
  927. #[test]
  928. fn warp_window_leaves_unfilled_slots_empty_and_uncharged() {
  929. let Some(mut warp) = WarpHarness::new() else {
  930. return;
  931. };
  932. const KIND_MESH: u32 = 10;
  933. const STRIDE: u32 = 32;
  934. const RECORDS: u32 = 16;
  935. let filled = [5u32, 0, 519];
  936. let total = (STRIDE * RECORDS) as usize;
  937. let mut src = vec![0xffu8; total];
  938. for (i, groups) in filled.into_iter().enumerate() {
  939. let words = [groups, 1, 1, 0xAB00 + i as u32];
  940. for (w, word) in words.into_iter().enumerate() {
  941. let at = i * STRIDE as usize + w * 4;
  942. src[at..at + 4].copy_from_slice(&word.to_le_bytes());
  943. }
  944. }
  945. for ahead in [true, false] {
  946. let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64);
  947. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  948. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64);
  949. let dst_buf = warp.default_uav(total as u64);
  950. // SAFETY: mapped buffers of these sizes.
  951. unsafe {
  952. std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total);
  953. std::ptr::write_bytes(budget_ptr, 0, 256);
  954. std::ptr::write_bytes(readback_ptr, 0, total);
  955. }
  956. assert!(record_clamp_as(
  957. &warp.clamp,
  958. &warp.list,
  959. &dst_buf,
  960. budget_gpu,
  961. (&src_buf, 0),
  962. None,
  963. (KIND_MESH, STRIDE, RECORDS),
  964. ahead,
  965. ));
  966. done_on(&warp.list, &dst_buf);
  967. // SAFETY: an open list; the scratch buffer is copied for the check.
  968. unsafe {
  969. warp.list.ResourceBarrier(&[transition(
  970. &dst_buf,
  971. D3D12_RESOURCE_STATE_COMMON,
  972. D3D12_RESOURCE_STATE_COPY_SOURCE,
  973. )]);
  974. warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64);
  975. warp.list.ResourceBarrier(&[transition(
  976. &dst_buf,
  977. D3D12_RESOURCE_STATE_COPY_SOURCE,
  978. D3D12_RESOURCE_STATE_COMMON,
  979. )]);
  980. }
  981. warp.submit_and_wait();
  982. // SAFETY: the work is done; mapped buffers.
  983. let (spent, largest, out) = unsafe {
  984. (
  985. (budget_ptr as *const u32).read_volatile(),
  986. (budget_ptr as *const u32).add(1).read_volatile(),
  987. std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4).to_vec(),
  988. )
  989. };
  990. for (i, groups) in filled.into_iter().enumerate() {
  991. let rec = &out[i * 8..i * 8 + 4];
  992. assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}");
  993. }
  994. let charged_filled = (5 + 519) * 128;
  995. if ahead {
  996. for i in filled.len()..RECORDS as usize {
  997. assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty");
  998. assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are");
  999. }
  1000. assert_eq!(spent, charged_filled, "unfilled slots charge nothing");
  1001. assert_eq!(largest, 519, "and are not counted as asked for");
  1002. } else {
  1003. // Thirteen slots at 65,535 groups: sixteen would be all of it.
  1004. assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most");
  1005. assert_eq!(largest, u32::MAX);
  1006. }
  1007. }
  1008. }
  1009. #[test]
  1010. fn warp_budget_saturates_without_wraparound_and_preserves_draw_fields() {
  1011. let Some(mut warp) = WarpHarness::new() else {
  1012. return;
  1013. };
  1014. const KIND_INDEXED: u32 = 1;
  1015. const STRIDE: u32 = 24; // 5 indexed-draw words + 1 trailing custom word
  1016. const RECORDS: u32 = 128; // 2 waves of 64: old InterlockedAdd wrapped 2^32 at 64!
  1017. const BUDGET_CAP: u32 = 1 << 27;
  1018. let total_bytes = (STRIDE * RECORDS) as usize;
  1019. let (src_buf, src_ptr, _) = warp.shared_buffer(total_bytes as u64);
  1020. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1021. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total_bytes as u64);
  1022. let dst_buf = warp.default_uav(total_bytes as u64);
  1023. let mut initial_src = vec![0u8; total_bytes];
  1024. for i in 0..RECORDS as usize {
  1025. let words: [u32; 6] = [
  1026. u32::MAX, // IndexCount -> clamps to 1 << 24
  1027. u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26)
  1028. 1000 + i as u32, // StartIndexLocation
  1029. (-200i32 + i as i32) as u32, // BaseVertexLocation
  1030. 5000 + i as u32, // StartInstanceLocation
  1031. 0xCAFE_0000 | (i as u32), // Extra stride word
  1032. ];
  1033. let base = i * (STRIDE as usize);
  1034. for (w, val) in words.into_iter().enumerate() {
  1035. initial_src[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
  1036. }
  1037. }
  1038. // SAFETY: mapped buffers have sufficient capacity.
  1039. unsafe {
  1040. std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, total_bytes);
  1041. (budget_ptr as *mut u32).write_volatile(0);
  1042. std::ptr::write_bytes(readback_ptr, 0, total_bytes);
  1043. }
  1044. assert!(record_clamp(
  1045. &warp.clamp,
  1046. &warp.list,
  1047. &dst_buf,
  1048. budget_gpu,
  1049. (&src_buf, 0),
  1050. None,
  1051. (KIND_INDEXED, STRIDE, RECORDS),
  1052. ));
  1053. done_on(&warp.list, &dst_buf);
  1054. // SAFETY: open command list; copy clamped scratch buffer for verification.
  1055. unsafe {
  1056. warp.list.ResourceBarrier(&[transition(
  1057. &dst_buf,
  1058. D3D12_RESOURCE_STATE_COMMON,
  1059. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1060. )]);
  1061. warp.list
  1062. .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64);
  1063. warp.list.ResourceBarrier(&[transition(
  1064. &dst_buf,
  1065. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1066. D3D12_RESOURCE_STATE_COMMON,
  1067. )]);
  1068. }
  1069. warp.submit_and_wait();
  1070. // SAFETY: GPU work completed.
  1071. let (spent, after_src, out_words) = unsafe {
  1072. let spent = (budget_ptr as *const u32).read_volatile();
  1073. let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), total_bytes).to_vec();
  1074. let out_words = std::slice::from_raw_parts(
  1075. readback_ptr.cast::<u32>().cast_const(),
  1076. total_bytes / 4,
  1077. )
  1078. .to_vec();
  1079. (spent, after_src, out_words)
  1080. };
  1081. assert_eq!(
  1082. spent, BUDGET_CAP,
  1083. "budget must saturate at BUDGET without wrapping"
  1084. );
  1085. assert_eq!(after_src, initial_src, "src_args must remain untouched");
  1086. let mut kept = 0usize;
  1087. let mut zeroed = 0usize;
  1088. for i in 0..RECORDS as usize {
  1089. let rec = &out_words[i * 6..(i + 1) * 6];
  1090. if rec[0] == (1 << 24) && rec[1] == 4 {
  1091. kept += 1;
  1092. } else {
  1093. assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed");
  1094. zeroed += 1;
  1095. }
  1096. assert_eq!(rec[2], 1000 + i as u32);
  1097. assert_eq!(rec[3], (-200i32 + i as i32) as u32);
  1098. assert_eq!(rec[4], 5000 + i as u32);
  1099. assert_eq!(rec[5], 0xCAFE_0000 | (i as u32));
  1100. }
  1101. assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2));
  1102. }
  1103. /// Exercises `HostList::indirect_scratch`, `bound`, `done`, `Host::execute`,
  1104. /// and `HostList::reset` end-to-end on the host device.
  1105. #[test]
  1106. fn host_list_reuses_and_grows_scratch_across_submissions() {
  1107. let Some(host) = super::host() else {
  1108. return;
  1109. };
  1110. let Ok(list) = host.new_list() else {
  1111. return;
  1112. };
  1113. let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else {
  1114. return;
  1115. };
  1116. let Some((count_buf, count_ptr)) = host.shared_buffer(256) else {
  1117. return;
  1118. };
  1119. // SAFETY: mapped host buffers.
  1120. unsafe {
  1121. std::ptr::write_bytes(src_ptr, 0x7F, 256 << 10);
  1122. (count_ptr as *mut u32).write_volatile(2);
  1123. }
  1124. // First two calls fit inside the initial 64 KiB scratch buffer and
  1125. // must reuse the exact same `ID3D12Resource`.
  1126. let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap();
  1127. done(&list, &b1);
  1128. let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap();
  1129. done(&list, &b2);
  1130. assert_eq!(
  1131. b1.as_raw(),
  1132. b2.as_raw(),
  1133. "scratch buffer within capacity must be reused"
  1134. );
  1135. // A call needing >64 KiB grows the scratch buffer mid-list while keeping
  1136. // `b1` alive until reset.
  1137. let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap();
  1138. done(&list, &b3);
  1139. assert_ne!(
  1140. b3.as_raw(),
  1141. b1.as_raw(),
  1142. "larger request must grow scratch buffer"
  1143. );
  1144. list.close();
  1145. host.execute(&[&list]);
  1146. list.reset();
  1147. // After reset, requests up to the grown high-water mark reuse `b3` with
  1148. // zero new allocations.
  1149. let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap();
  1150. done(&list, &b4);
  1151. assert_eq!(
  1152. b4.as_raw(),
  1153. b3.as_raw(),
  1154. "grown scratch buffer must persist across reset"
  1155. );
  1156. list.close();
  1157. host.execute(&[&list]);
  1158. list.reset();
  1159. }
  1160. }