indirect.rs 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  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. //! The scratch buffer is left readable as indirect arguments after a clamp
  12. //! and stays so until the next clamp into it, which moves it straight back
  13. //! to unordered access; it goes back to the common state once, when the
  14. //! list closes. The executions that read it record no barrier of their
  15. //! own, so draws that read records clamped together (`crate::draw`'s
  16. //! windows) follow each other with nothing between them. Before, each
  17. //! execution was followed by a move of the scratch buffer back to the
  18. //! common state, which drivers may treat as a full wait.
  19. //!
  20. //! When a count buffer is given, threads at or past `min(max, count)` return
  21. //! immediately without charging the list's budget or reading uninitialized
  22. //! tail slots. Each list has a budget (2^27 vertex instances or threads,
  23. //! groups counted as 64 threads, mesh groups as 128): active records past it
  24. //! run empty, saturating without 32-bit wraparound so a list of thousands of
  25. //! garbage records cannot run for seconds either.
  26. //!
  27. //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
  28. //! groups per dimension and 2^20 per dispatch, one-dimensional mesh
  29. //! dispatches, the budget) cut legitimate work beyond them; raise them if
  30. //! the title needs more.
  31. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  32. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  33. use windows::Win32::Graphics::Direct3D12::*;
  34. use windows::core::s;
  35. use crate::host::{HostList, host, transition};
  36. const SOURCE: &str = r#"
  37. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
  38. cbuffer Record : register(b0) {
  39. uint kind;
  40. uint stride;
  41. uint records;
  42. uint args_offset;
  43. // Bit 0: a count buffer bounds the records. Bit 1: the records are a
  44. // window clamped ahead of their draws: one that asks for more than can
  45. // run is left empty and costs nothing.
  46. uint has_count;
  47. uint count_offset;
  48. };
  49. ByteAddressBuffer src_args : register(t0);
  50. ByteAddressBuffer count_buf : register(t1);
  51. RWByteAddressBuffer dst_args : register(u0);
  52. // The list's work so far (vertex instances, threads): past the budget,
  53. // records run empty.
  54. RWByteAddressBuffer budget : register(u1);
  55. static const uint BUDGET = 1u << 27;
  56. // Groups of one dispatch; more run empty.
  57. static const uint GROUPS = 1u << 20;
  58. // Each group charges the budget once: the costs of its records go here,
  59. // one thread charges their sum, saturating as each record would in lane
  60. // order, and every thread then reads whether its own record fitted. A
  61. // compare and swap per record, 64 threads racing for one word, cost a
  62. // round for each record of a window, and in memory the CPU maps (where the
  63. // budget was, and is with VICTORY_INDIRECT_CARD_BUDGET=0) every atomic
  64. // crosses the bus on a card of its own.
  65. groupshared uint costs[64];
  66. groupshared uint fits[64];
  67. groupshared uint largest_asked;
  68. groupshared uint all_asked;
  69. [RootSignature(RS)]
  70. [numthreads(64, 1, 1)]
  71. void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
  72. uint eff_count = records;
  73. bool ahead = (has_count & 2u) != 0;
  74. if ((has_count & 1u) != 0) {
  75. eff_count = min(eff_count, count_buf.Load(count_offset));
  76. }
  77. // Threads past the records take part in the group's charge (cost 0)
  78. // and store nothing.
  79. bool active = id.x < eff_count;
  80. uint src_at = args_offset + id.x * stride;
  81. uint dst_at = id.x * stride;
  82. uint cost = 0;
  83. uint asked = 0;
  84. uint2 draw_counts = uint2(0, 0);
  85. uint3 groups = uint3(0, 0, 0);
  86. if (gi == 0) {
  87. largest_asked = 0;
  88. all_asked = 0;
  89. }
  90. if (active && kind <= 1) {
  91. // Draws: vertex or index count, then instances.
  92. uint2 want = src_args.Load2(src_at);
  93. if (ahead && (want.x > (1u << 24) || want.y > (1u << 24))) {
  94. want = uint2(0, 0);
  95. }
  96. uint count = min(want.x, 1u << 24);
  97. uint instances = min(want.y, (1u << 26) / max(count, 1u));
  98. cost = count * instances;
  99. draw_counts = uint2(count, instances);
  100. } else if (active && kind == 2) {
  101. uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u));
  102. // x * y fits 32 bits; the whole count may not.
  103. if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
  104. g = uint3(0, 0, 0);
  105. }
  106. cost = g.x * g.y * g.z * 64u;
  107. groups = g;
  108. } else if (active) {
  109. // Mesh dispatches: the console's are one-dimensional.
  110. uint3 g = src_args.Load3(src_at);
  111. // Ahead of its draw, a record over the most a dispatch runs is a
  112. // slot the title has not filled (the title leaves all
  113. // ones there): empty, and not counted below either.
  114. if (ahead && g.x > 65535u) {
  115. g = uint3(0, 0, 0);
  116. }
  117. asked = g.x;
  118. g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
  119. cost = g.x * g.y * g.z * 128u;
  120. groups = g;
  121. }
  122. costs[gi] = cost;
  123. GroupMemoryBarrierWithGroupSync();
  124. if (active && kind > 2) {
  125. // Diagnostics, in the budget buffer's next words (below): the
  126. // largest group count a mesh record asked for, and the groups
  127. // asked in all.
  128. uint was;
  129. InterlockedMax(largest_asked, asked, was);
  130. InterlockedAdd(all_asked, min(asked, 1u << 24), was);
  131. }
  132. if (gi == 0) {
  133. // What the records charge, from `before` on, in lane order: a
  134. // record that does not fit whole runs empty and takes the rest.
  135. // Only the group's own records are walked (one, clamped alone).
  136. uint first = id.x;
  137. uint n = eff_count > first ? min(64u, eff_count - first) : 0u;
  138. uint before;
  139. budget.InterlockedOr(0, 0, before);
  140. [allow_uav_condition]
  141. while (before < BUDGET) {
  142. uint next = before;
  143. for (uint j = 0; j < n; j++) {
  144. uint c = costs[j];
  145. if (c > 0 && next < BUDGET) {
  146. next = (BUDGET - next <= c) ? BUDGET : (next + c);
  147. }
  148. }
  149. if (next == before) break;
  150. uint prev;
  151. budget.InterlockedCompareExchange(0, before, next, prev);
  152. if (prev == before) break;
  153. before = prev;
  154. }
  155. uint at = before;
  156. for (uint k = 0; k < n; k++) {
  157. uint c = costs[k];
  158. uint fit = 1;
  159. if (c > 0) {
  160. fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u;
  161. at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c);
  162. }
  163. fits[k] = fit;
  164. }
  165. }
  166. GroupMemoryBarrierWithGroupSync();
  167. if (gi == 0 && kind > 2) {
  168. uint was;
  169. budget.InterlockedMax(4, largest_asked, was);
  170. budget.InterlockedAdd(8, all_asked, was);
  171. }
  172. if (!active) {
  173. return;
  174. }
  175. bool over = fits[gi] == 0;
  176. if (kind <= 1) {
  177. if (over) {
  178. draw_counts = uint2(0, 0);
  179. }
  180. dst_args.Store2(dst_at, draw_counts);
  181. for (uint off = 8; off < stride; off += 4) {
  182. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  183. }
  184. } else {
  185. if (over) {
  186. groups = uint3(0, 0, 0);
  187. }
  188. dst_args.Store3(dst_at, groups);
  189. for (uint off = 12; off < stride; off += 4) {
  190. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  191. }
  192. }
  193. }
  194. "#;
  195. struct Clamp {
  196. root: ID3D12RootSignature,
  197. pso: ID3D12PipelineState,
  198. }
  199. // SAFETY: D3D12 objects are free-threaded.
  200. unsafe impl Send for Clamp {}
  201. // SAFETY: as above.
  202. unsafe impl Sync for Clamp {}
  203. fn clamp() -> Option<&'static Clamp> {
  204. static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
  205. CLAMP
  206. .get_or_init(|| match make() {
  207. Ok(c) => Some(c),
  208. Err(e) => {
  209. tracing::warn!(error = %e, "no argument clamp: indirect execution dropped");
  210. None
  211. }
  212. })
  213. .as_ref()
  214. }
  215. fn make() -> windows::core::Result<Clamp> {
  216. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  217. make_for(device)
  218. }
  219. fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> {
  220. make_from(device, SOURCE)
  221. }
  222. /// The clamp compiled from `source` (ours, or in the benchmark the one it
  223. /// replaced).
  224. fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
  225. let mut code: Option<ID3DBlob> = None;
  226. let mut errors: Option<ID3DBlob> = None;
  227. // SAFETY: the source and names live through the call; out pointers ours.
  228. let compiled = unsafe {
  229. D3DCompile(
  230. source.as_ptr().cast(),
  231. source.len(),
  232. s!("clamp"),
  233. None,
  234. None,
  235. s!("main"),
  236. s!("cs_5_1"),
  237. 0,
  238. 0,
  239. &mut code,
  240. Some(&mut errors),
  241. )
  242. };
  243. if let Err(e) = compiled {
  244. if let Some(errors) = errors {
  245. // SAFETY: the blob's own bytes.
  246. let text = unsafe {
  247. std::slice::from_raw_parts(
  248. errors.GetBufferPointer().cast::<u8>(),
  249. errors.GetBufferSize(),
  250. )
  251. };
  252. tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text));
  253. }
  254. return Err(e);
  255. }
  256. let code = code.ok_or_else(windows::core::Error::empty)?;
  257. // SAFETY: the blob's own bytes; the root signature is inside the shader.
  258. unsafe {
  259. let bytes =
  260. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  261. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  262. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  263. pRootSignature: std::mem::transmute_copy(&root),
  264. CS: D3D12_SHADER_BYTECODE {
  265. pShaderBytecode: bytes.as_ptr().cast(),
  266. BytecodeLength: bytes.len(),
  267. },
  268. ..Default::default()
  269. })?;
  270. Ok(Clamp { root, pso })
  271. }
  272. }
  273. /// Minimum record byte stride for a supported PC indirect argument `kind`.
  274. fn min_stride(kind: u32) -> Option<u32> {
  275. match kind {
  276. 0 => Some(16),
  277. 1 => Some(20),
  278. 2 | 10 => Some(12),
  279. _ => None,
  280. }
  281. }
  282. /// Validates record alignment and returns the scratch byte size `stride * records`.
  283. fn validate_layout(
  284. (kind, stride, records): (u32, u32, u32),
  285. src_offset: u64,
  286. count_offset: Option<u64>,
  287. ) -> Option<u64> {
  288. let min = min_stride(kind)?;
  289. if stride < min || !stride.is_multiple_of(4) || !src_offset.is_multiple_of(4) {
  290. return None;
  291. }
  292. if count_offset.is_some_and(|off| !off.is_multiple_of(4)) {
  293. return None;
  294. }
  295. let bytes = u64::from(stride).checked_mul(u64::from(records))?;
  296. (bytes <= u64::from(u32::MAX)).then_some(bytes)
  297. }
  298. /// Records, in `list`, the non-destructive clamp of up to `records` records of
  299. /// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded
  300. /// by the 32-bit count in `count` when given) into a device-local scratch
  301. /// buffer, at offset `0`. The scratch buffer is left in `INDIRECT_ARGUMENT`
  302. /// until the next clamp into it: executions read it with no barrier of
  303. /// their own. Replaces the list's compute root signature and pipeline
  304. /// (callers bind theirs after). `None` if the clamp or alignment is not
  305. /// available.
  306. pub(crate) fn bound(
  307. list: &HostList,
  308. src: (&ID3D12Resource, u64),
  309. count: Option<(&ID3D12Resource, u64)>,
  310. spec: (u32, u32, u32),
  311. ) -> Option<ID3D12Resource> {
  312. let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?;
  313. let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
  314. clamp_into(list, c, &dst, budget, src, count, spec, false).then_some(dst)
  315. }
  316. /// [`bound`] for a window of records clamped ahead of the draws that will
  317. /// read them (`crate::draw`'s windows; no count buffer). The records past
  318. /// the ones the title filled are whatever the buffer holds, and each
  319. /// record clamped charges the list's budget when it is clamped: a slot of
  320. /// all ones, clamped to the most a mesh dispatch runs (65,535 groups),
  321. /// charged a sixteenth of the budget, so sixteen of them emptied every
  322. /// draw of the list after them (run 93: "the largest group count asked for
  323. /// 4294967295", 43 to 153 such records a frame). Here a record that asks
  324. /// for more than can run is left empty and charges nothing; a record
  325. /// clamped alone is clamped and charged as before.
  326. pub(crate) fn bound_ahead(
  327. list: &HostList,
  328. src: (&ID3D12Resource, u64),
  329. spec: (u32, u32, u32),
  330. ) -> Option<ID3D12Resource> {
  331. let bytes = validate_layout(spec, src.1, None)?;
  332. let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
  333. clamp_into(list, c, &dst, budget, src, None, spec, true).then_some(dst)
  334. }
  335. /// [`record_clamp_as`] into `list`'s scratch buffer `dst`, from the state
  336. /// the list left it in; afterwards the list knows it is readable as
  337. /// indirect arguments.
  338. #[allow(clippy::too_many_arguments)]
  339. fn clamp_into(
  340. list: &HostList,
  341. c: &Clamp,
  342. dst: &ID3D12Resource,
  343. budget: u64,
  344. src: (&ID3D12Resource, u64),
  345. count: Option<(&ID3D12Resource, u64)>,
  346. spec: (u32, u32, u32),
  347. ahead: bool,
  348. ) -> bool {
  349. let before = list.indirect_state(dst);
  350. let recorded = record_clamp_as(c, &list.list, (dst, before), budget, src, count, spec, ahead);
  351. if recorded {
  352. list.indirect_readable(dst);
  353. }
  354. recorded
  355. }
  356. /// Records the clamp into `dst`, which is in state `before` (common, or
  357. /// indirect arguments after an earlier clamp into it), and leaves `dst` in
  358. /// `INDIRECT_ARGUMENT`. `ahead`: the records are a window clamped ahead of
  359. /// their draws ([`bound_ahead`]). False, with nothing recorded, if the
  360. /// layout or the addresses do not fit the clamp.
  361. #[allow(clippy::too_many_arguments)]
  362. fn record_clamp_as(
  363. c: &Clamp,
  364. l: &ID3D12GraphicsCommandList,
  365. (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES),
  366. budget: u64,
  367. (src, src_offset): (&ID3D12Resource, u64),
  368. count: Option<(&ID3D12Resource, u64)>,
  369. (kind, stride, records): (u32, u32, u32),
  370. ahead: bool,
  371. ) -> bool {
  372. let Some(bytes) = validate_layout(
  373. (kind, stride, records),
  374. src_offset,
  375. count.map(|(_, off)| off),
  376. ) else {
  377. return false;
  378. };
  379. // SAFETY: live D3D12 buffer resources.
  380. let (src_base, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) };
  381. if !src_base.is_multiple_of(4) || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) {
  382. return false;
  383. }
  384. let (src_gpu, args_offset) = match src_offset
  385. .checked_add(bytes)
  386. .filter(|&end| end <= u64::from(u32::MAX))
  387. {
  388. Some(_) => (src_base, src_offset as u32),
  389. None => {
  390. let Some(rebased) = src_base.checked_add(src_offset) else {
  391. return false;
  392. };
  393. (rebased, 0)
  394. }
  395. };
  396. let (count_gpu, has_count, count_offset) = match count {
  397. Some((buf, off)) => {
  398. // SAFETY: a live D3D12 buffer resource.
  399. let base = unsafe { buf.GetGPUVirtualAddress() };
  400. if !base.is_multiple_of(4) {
  401. return false;
  402. }
  403. match off.checked_add(4).filter(|&end| end <= u64::from(u32::MAX)) {
  404. Some(_) => (base, 1u32, off as u32),
  405. None => {
  406. let Some(rebased) = base.checked_add(off) else {
  407. return false;
  408. };
  409. (rebased, 1u32, 0u32)
  410. }
  411. }
  412. }
  413. None => (src_gpu, 0u32, 0u32),
  414. };
  415. let constants = [kind, stride, records, args_offset, has_count | (u32::from(ahead) << 1), count_offset];
  416. // SAFETY: an open list; our root signature and pipeline; live source,
  417. // count, scratch destination, and budget buffers. `src` and `count` stay
  418. // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst`
  419. // transitions `before -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. Moving
  420. // it out of `INDIRECT_ARGUMENT` orders this clamp's writes after every
  421. // earlier execution's reads of the scratch buffer; nothing else writes it.
  422. // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two
  423. // waits for every earlier shader write out (the state changes stay).
  424. #[cfg(feature = "diagnostics")]
  425. crate::copystat::add(crate::copystat::C::IndirectBounded, 1);
  426. #[cfg(feature = "diagnostics")]
  427. let waits = crate::copystat::barrier_test() & 2 == 0;
  428. #[cfg(not(feature = "diagnostics"))]
  429. let waits = true;
  430. let first = [
  431. uav_barrier(),
  432. transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
  433. ];
  434. let second = [
  435. uav_barrier(),
  436. transition(
  437. dst,
  438. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  439. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  440. ),
  441. ];
  442. let skip = usize::from(!waits);
  443. unsafe {
  444. // Earlier shader writes (the title's argument and count passes) first.
  445. l.ResourceBarrier(&first[skip..]);
  446. if records > 0 {
  447. l.SetComputeRootSignature(&c.root);
  448. l.SetPipelineState(&c.pso);
  449. l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  450. l.SetComputeRootShaderResourceView(1, src_gpu);
  451. l.SetComputeRootShaderResourceView(2, count_gpu);
  452. l.SetComputeRootUnorderedAccessView(3, dst_gpu);
  453. l.SetComputeRootUnorderedAccessView(4, budget);
  454. l.Dispatch(records.div_ceil(64), 1, 1);
  455. }
  456. l.ResourceBarrier(&second[skip..]);
  457. }
  458. true
  459. }
  460. fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
  461. D3D12_RESOURCE_BARRIER {
  462. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  463. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  464. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  465. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  466. pResource: std::mem::ManuallyDrop::new(None),
  467. }),
  468. },
  469. }
  470. }
  471. #[cfg(test)]
  472. mod tests {
  473. use super::*;
  474. use windows::Win32::Foundation::HANDLE;
  475. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  476. use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
  477. use windows::Win32::Graphics::Dxgi::*;
  478. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  479. use windows::core::Interface;
  480. const WORKER_CS: &str = r#"
  481. #define RS "UAV(u0)"
  482. RWByteAddressBuffer hits : register(u0);
  483. [RootSignature(RS)]
  484. [numthreads(1, 1, 1)]
  485. void main() {
  486. uint prev;
  487. hits.InterlockedAdd(0, 1, prev);
  488. }
  489. "#;
  490. struct WarpHarness {
  491. device: ID3D12Device,
  492. queue: ID3D12CommandQueue,
  493. allocator: ID3D12CommandAllocator,
  494. list: ID3D12GraphicsCommandList,
  495. fence: ID3D12Fence,
  496. submitted: u64,
  497. event: HANDLE,
  498. clamp: Clamp,
  499. worker: Clamp,
  500. }
  501. impl WarpHarness {
  502. fn new() -> Option<Self> {
  503. // SAFETY: plain DXGI WARP query and D3D12 test harness setup.
  504. unsafe {
  505. let factory: IDXGIFactory4 =
  506. CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
  507. let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?;
  508. let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?;
  509. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  510. return None;
  511. }
  512. let mut device: Option<ID3D12Device> = None;
  513. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  514. let device = device?;
  515. let queue: ID3D12CommandQueue = device
  516. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  517. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  518. ..Default::default()
  519. })
  520. .ok()?;
  521. let allocator: ID3D12CommandAllocator = device
  522. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)
  523. .ok()?;
  524. let list: ID3D12GraphicsCommandList = device
  525. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  526. .ok()?;
  527. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  528. let event = CreateEventW(None, false, false, None).ok()?;
  529. let clamp = make_for(&device).expect("clamp shader must compile on WARP");
  530. let worker = compile_cs(&device, WORKER_CS).expect("worker shader must compile");
  531. Some(Self {
  532. device,
  533. queue,
  534. allocator,
  535. list,
  536. fence,
  537. submitted: 0,
  538. event,
  539. clamp,
  540. worker,
  541. })
  542. }
  543. }
  544. /// CPU-mapped L0 write-back buffer matching `Shadow`'s heap type.
  545. fn shared_buffer(&self, size: u64) -> (ID3D12Resource, *mut u8, u64) {
  546. let heap = D3D12_HEAP_PROPERTIES {
  547. Type: D3D12_HEAP_TYPE_CUSTOM,
  548. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  549. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  550. ..Default::default()
  551. };
  552. let desc = D3D12_RESOURCE_DESC {
  553. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  554. Width: size.max(4),
  555. Height: 1,
  556. DepthOrArraySize: 1,
  557. MipLevels: 1,
  558. SampleDesc: DXGI_SAMPLE_DESC {
  559. Count: 1,
  560. Quality: 0,
  561. },
  562. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  563. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  564. ..Default::default()
  565. };
  566. let mut buffer: Option<ID3D12Resource> = None;
  567. let mut data = std::ptr::null_mut();
  568. // SAFETY: plain buffer creation and persistent CPU mapping.
  569. unsafe {
  570. self.device
  571. .CreateCommittedResource(
  572. &heap,
  573. D3D12_HEAP_FLAG_NONE,
  574. &desc,
  575. D3D12_RESOURCE_STATE_COMMON,
  576. None,
  577. &mut buffer,
  578. )
  579. .unwrap();
  580. let buffer = buffer.unwrap();
  581. buffer.Map(0, None, Some(&mut data)).unwrap();
  582. let gpu = buffer.GetGPUVirtualAddress();
  583. (buffer, data.cast(), gpu)
  584. }
  585. }
  586. /// Device-local `DEFAULT`-heap UAV scratch buffer.
  587. fn default_uav(&self, size: u64) -> ID3D12Resource {
  588. let heap = D3D12_HEAP_PROPERTIES {
  589. Type: D3D12_HEAP_TYPE_DEFAULT,
  590. ..Default::default()
  591. };
  592. let desc = D3D12_RESOURCE_DESC {
  593. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  594. Width: size.max(64 << 10),
  595. Height: 1,
  596. DepthOrArraySize: 1,
  597. MipLevels: 1,
  598. SampleDesc: DXGI_SAMPLE_DESC {
  599. Count: 1,
  600. Quality: 0,
  601. },
  602. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  603. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  604. ..Default::default()
  605. };
  606. let mut buffer: Option<ID3D12Resource> = None;
  607. // SAFETY: plain device-local buffer creation.
  608. unsafe {
  609. self.device
  610. .CreateCommittedResource(
  611. &heap,
  612. D3D12_HEAP_FLAG_NONE,
  613. &desc,
  614. D3D12_RESOURCE_STATE_COMMON,
  615. None,
  616. &mut buffer,
  617. )
  618. .unwrap();
  619. }
  620. buffer.unwrap()
  621. }
  622. fn signature(&self, kind: u32, stride: u32) -> ID3D12CommandSignature {
  623. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  624. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  625. ..Default::default()
  626. };
  627. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  628. ByteStride: stride,
  629. NumArgumentDescs: 1,
  630. pArgumentDescs: &arg,
  631. NodeMask: 0,
  632. };
  633. let mut sig: Option<ID3D12CommandSignature> = None;
  634. // SAFETY: valid single-argument command signature description.
  635. unsafe {
  636. self.device
  637. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  638. .unwrap();
  639. }
  640. sig.unwrap()
  641. }
  642. fn submit_and_wait(&mut self) {
  643. self.submitted += 1;
  644. // SAFETY: closing, executing, waiting on fence, and resetting our list.
  645. unsafe {
  646. self.list.Close().unwrap();
  647. let cmd: ID3D12CommandList = self.list.cast().unwrap();
  648. self.queue.ExecuteCommandLists(&[Some(cmd)]);
  649. self.queue.Signal(&self.fence, self.submitted).unwrap();
  650. self.fence
  651. .SetEventOnCompletion(self.submitted, self.event)
  652. .unwrap();
  653. WaitForSingleObject(self.event, INFINITE);
  654. self.allocator.Reset().unwrap();
  655. self.list.Reset(&self.allocator, None).unwrap();
  656. }
  657. }
  658. }
  659. fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
  660. let mut code: Option<ID3DBlob> = None;
  661. // SAFETY: source and entry names outlive `D3DCompile`.
  662. unsafe {
  663. D3DCompile(
  664. source.as_ptr().cast(),
  665. source.len(),
  666. s!("worker"),
  667. None,
  668. None,
  669. s!("main"),
  670. s!("cs_5_1"),
  671. 0,
  672. 0,
  673. &mut code,
  674. None,
  675. )?;
  676. let code = code.unwrap();
  677. let bytes = std::slice::from_raw_parts(
  678. code.GetBufferPointer().cast::<u8>(),
  679. code.GetBufferSize(),
  680. );
  681. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  682. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  683. pRootSignature: std::mem::transmute_copy(&root),
  684. CS: D3D12_SHADER_BYTECODE {
  685. pShaderBytecode: bytes.as_ptr().cast(),
  686. BytecodeLength: bytes.len(),
  687. },
  688. ..Default::default()
  689. })?;
  690. Ok(Clamp { root, pso })
  691. }
  692. }
  693. /// The compare of copies in the card's memory (`crate::host`), on the
  694. /// software adapter. Told 1 it flags the pieces whose bytes are not
  695. /// what was hashed last and leaves the hashes: a piece a shader changed
  696. /// and a later one changed back then looks untouched, which is right
  697. /// only if the piece was fetched after both. Told 2 (submissions sent
  698. /// ahead with the relay, whose pieces are fetched flight by flight) it
  699. /// stores the hash it made: each compare flags what changed since the
  700. /// compare before it, also a change back.
  701. #[test]
  702. fn warp_card_compare_stores_the_hash_it_made_when_told() {
  703. let Some(mut warp) = WarpHarness::new() else {
  704. return;
  705. };
  706. let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP");
  707. const PIECE: usize = 64 << 10;
  708. const PIECES: u32 = 3;
  709. let size = PIECE * PIECES as usize;
  710. let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64);
  711. let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES));
  712. let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64);
  713. let content: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect();
  714. // SAFETY: the mapping holds `size` bytes.
  715. unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) };
  716. // One pass over the three pieces; what it left in `differs` (7s
  717. // where it stored nothing).
  718. let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] {
  719. // SAFETY: our open list, live buffers, the compare's own root
  720. // signature; the mappings hold what is read and written.
  721. unsafe {
  722. for piece in 0..PIECES as usize {
  723. differs_ptr.cast::<u32>().add(piece).write_volatile(7);
  724. }
  725. warp.list.SetComputeRootSignature(&compare.root);
  726. warp.list.SetPipelineState(&compare.pso);
  727. let constants = [0u32, 0, size as u32, PIECES, 0, mode];
  728. warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  729. warp.list.SetComputeRootShaderResourceView(1, now_gpu);
  730. warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu);
  731. warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu);
  732. warp.list.Dispatch(PIECES.div_ceil(64), 1, 1);
  733. }
  734. warp.submit_and_wait();
  735. // SAFETY: as above.
  736. [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::<u32>().add(piece).read_volatile() })
  737. };
  738. let at = PIECE + 1234;
  739. // SAFETY (each): inside the mapping.
  740. let set = |value: u8| unsafe { now_ptr.add(at).write_volatile(value) };
  741. // 0: the hashes are stored, nothing is flagged.
  742. assert_eq!(run(&mut warp, 0), [7, 7, 7]);
  743. assert_eq!(run(&mut warp, 1), [0, 0, 0]);
  744. // A change in the second piece: flagged, and with 1 flagged again
  745. // (the hash stays the old one).
  746. set(content[at] ^ 0x40);
  747. assert_eq!(run(&mut warp, 1), [0, 1, 0]);
  748. assert_eq!(run(&mut warp, 1), [0, 1, 0]);
  749. // Changed back: with 1 the piece looks untouched.
  750. set(content[at]);
  751. assert_eq!(run(&mut warp, 1), [0, 0, 0]);
  752. // With 2 the change is flagged once, and the hash is the new one.
  753. set(content[at] ^ 0x40);
  754. assert_eq!(run(&mut warp, 2), [0, 1, 0]);
  755. assert_eq!(run(&mut warp, 2), [0, 0, 0]);
  756. // Changed back: flagged, where 1 saw nothing.
  757. set(content[at]);
  758. assert_eq!(run(&mut warp, 2), [0, 1, 0]);
  759. assert_eq!(run(&mut warp, 2), [0, 0, 0]);
  760. }
  761. /// The clamp compiles with the system's compiler and the host takes it.
  762. #[test]
  763. fn argument_clamp_builds() {
  764. if super::host().is_none() {
  765. return; // no host GPU here
  766. }
  767. assert!(super::clamp().is_some());
  768. }
  769. #[test]
  770. fn rejects_unaligned_or_undersized_layouts() {
  771. assert_eq!(validate_layout((0, 16, 4), 0, None), Some(64));
  772. assert_eq!(validate_layout((1, 20, 4), 64, Some(128)), Some(80));
  773. assert_eq!(validate_layout((2, 12, 0), 0, Some(0)), Some(0));
  774. assert_eq!(validate_layout((10, 16, 2), 8, None), Some(32));
  775. // Undersized strides for each kind.
  776. assert_eq!(validate_layout((0, 12, 1), 0, None), None);
  777. assert_eq!(validate_layout((1, 16, 1), 0, None), None);
  778. assert_eq!(validate_layout((2, 8, 1), 0, None), None);
  779. assert_eq!(validate_layout((10, 8, 1), 0, None), None);
  780. // Unknown kind.
  781. assert_eq!(validate_layout((3, 16, 1), 0, None), None);
  782. // Unaligned stride, source offset, or count offset.
  783. assert_eq!(validate_layout((0, 18, 1), 0, None), None);
  784. assert_eq!(validate_layout((0, 16, 1), 2, None), None);
  785. assert_eq!(validate_layout((0, 16, 1), 0, Some(6)), None);
  786. // Total byte size exceeding 32-bit ByteAddressBuffer indexing.
  787. assert_eq!(validate_layout((1, 20, u32::MAX), 0, None), None);
  788. }
  789. /// WARP D3D12 execution test proving:
  790. /// (a) `countBuffer` with a small count (`3`) and `4,093` garbage tail slots
  791. /// (`max = 4096`) does NOT blow `BUDGET` or zero valid dispatches in
  792. /// this or subsequent `ExecuteIndirect` calls in the same list,
  793. /// (b) `src_args` (and `count_buf`) are NOT mutated in-place, and
  794. /// (c) full `stride` bytes (`stride = 24` > `12`) are copied for active
  795. /// records into `dst_args` at offset `0`.
  796. #[test]
  797. fn warp_count_buffer_ignores_garbage_tail_and_preserves_source() {
  798. let Some(mut warp) = WarpHarness::new() else {
  799. return;
  800. };
  801. const KIND_DISPATCH: u32 = 2;
  802. const STRIDE: u32 = 24; // 6 dwords: 3 dispatch group counts + 3 extra payload dwords
  803. const MAX: u32 = 4096;
  804. const ARGS_OFFSET: usize = 64; // non-zero offset with sentinel prefix
  805. const COUNT_OFFSET_1: usize = 128;
  806. const COUNT_OFFSET_2: usize = 192;
  807. let src_bytes = ARGS_OFFSET + (STRIDE as usize) * (MAX as usize) + 64;
  808. let (src_buf, src_ptr, _) = warp.shared_buffer(src_bytes as u64);
  809. let (count_buf, count_ptr, _) = warp.shared_buffer(512);
  810. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  811. let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256);
  812. let (readback_buf, readback_ptr, _) = warp.shared_buffer((STRIDE * 8) as u64);
  813. let dst_buf = warp.default_uav(u64::from(STRIDE) * u64::from(MAX));
  814. let sig = warp.signature(KIND_DISPATCH, STRIDE);
  815. // Fill the entire source buffer with non-zero sentinel bytes, then
  816. // populate 3 valid records at `ARGS_OFFSET` and 4,093 huge garbage
  817. // records in `3..MAX` that would exhaust `BUDGET` ~2,000x over if read.
  818. let mut initial_src = vec![0xA5u8; src_bytes];
  819. let write_record = |buf: &mut [u8], idx: usize, words: [u32; 6]| {
  820. let base = ARGS_OFFSET + idx * (STRIDE as usize);
  821. for (w, val) in words.into_iter().enumerate() {
  822. buf[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
  823. }
  824. };
  825. write_record(
  826. &mut initial_src,
  827. 0,
  828. [3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666],
  829. );
  830. write_record(
  831. &mut initial_src,
  832. 1,
  833. [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC],
  834. );
  835. // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1).
  836. write_record(
  837. &mut initial_src,
  838. 2,
  839. [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567],
  840. );
  841. for slot in 3..MAX as usize {
  842. // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups
  843. // (`cost = 67,107,840 ~= BUDGET / 2`), exhausting `BUDGET` immediately!
  844. write_record(
  845. &mut initial_src,
  846. slot,
  847. [0xFFFF_FFFF, 16, 1, 0xDEAD_BEEF, 0xBAD0_C0DE, slot as u32],
  848. );
  849. }
  850. // Second indirect call's source records (at offset 0 of a second buffer,
  851. // or later in `count_buf`): put 2 active records + garbage tail in a
  852. // second range to run back-to-back in the SAME command list.
  853. let mut initial_count = vec![0x5Au8; 512];
  854. initial_count[COUNT_OFFSET_1..COUNT_OFFSET_1 + 4].copy_from_slice(&3u32.to_le_bytes());
  855. initial_count[COUNT_OFFSET_2..COUNT_OFFSET_2 + 4].copy_from_slice(&2u32.to_le_bytes());
  856. // SAFETY: buffers are mapped with exact capacities above.
  857. unsafe {
  858. std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, src_bytes);
  859. std::ptr::copy_nonoverlapping(initial_count.as_ptr(), count_ptr, 512);
  860. (budget_ptr as *mut u32).write_volatile(0);
  861. (hits_ptr as *mut u32).write_volatile(0);
  862. std::ptr::write_bytes(readback_ptr, 0, (STRIDE * 8) as usize);
  863. }
  864. // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first
  865. // 5 records of `dst_buf` out for inspection, then record Call #2
  866. // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list!
  867. assert!(record_clamp_as(
  868. &warp.clamp,
  869. &warp.list,
  870. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  871. budget_gpu,
  872. (&src_buf, ARGS_OFFSET as u64),
  873. Some((&count_buf, COUNT_OFFSET_1 as u64)),
  874. (KIND_DISPATCH, STRIDE, MAX),
  875. false,
  876. ));
  877. // SAFETY: open command list, valid worker PSO/root and buffers.
  878. unsafe {
  879. warp.list.SetComputeRootSignature(&warp.worker.root);
  880. warp.list.SetPipelineState(&warp.worker.pso);
  881. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  882. warp.list.ExecuteIndirect(
  883. &sig,
  884. MAX,
  885. &dst_buf,
  886. 0,
  887. Some(&count_buf),
  888. COUNT_OFFSET_1 as u64,
  889. );
  890. }
  891. // Snapshot `dst_buf` after Call #1 (copy 5 * STRIDE bytes, then leave
  892. // `dst_buf` readable as arguments again, as the clamp left it).
  893. // SAFETY: open command list; the clamp left `dst_buf` in `INDIRECT_ARGUMENT`.
  894. unsafe {
  895. warp.list.ResourceBarrier(&[transition(
  896. &dst_buf,
  897. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  898. D3D12_RESOURCE_STATE_COPY_SOURCE,
  899. )]);
  900. warp.list
  901. .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, u64::from(STRIDE * 5));
  902. warp.list.ResourceBarrier(&[transition(
  903. &dst_buf,
  904. D3D12_RESOURCE_STATE_COPY_SOURCE,
  905. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  906. )]);
  907. }
  908. // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1:
  909. // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`!
  910. // The scratch buffer goes straight from arguments back to unordered
  911. // access.
  912. assert!(record_clamp_as(
  913. &warp.clamp,
  914. &warp.list,
  915. (&dst_buf, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
  916. budget_gpu,
  917. (&src_buf, ARGS_OFFSET as u64),
  918. Some((&count_buf, COUNT_OFFSET_2 as u64)),
  919. (KIND_DISPATCH, STRIDE, MAX),
  920. false,
  921. ));
  922. // SAFETY: open command list, valid worker PSO/root and buffers.
  923. unsafe {
  924. warp.list.SetComputeRootSignature(&warp.worker.root);
  925. warp.list.SetPipelineState(&warp.worker.pso);
  926. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  927. warp.list.ExecuteIndirect(
  928. &sig,
  929. MAX,
  930. &dst_buf,
  931. 0,
  932. Some(&count_buf),
  933. COUNT_OFFSET_2 as u64,
  934. );
  935. }
  936. warp.submit_and_wait();
  937. // SAFETY: GPU execution finished; read mapped host results.
  938. let (hits, spent, after_src, after_count, clamped_words) = unsafe {
  939. let hits = (hits_ptr as *const u32).read_volatile();
  940. let spent = (budget_ptr as *const u32).read_volatile();
  941. let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), src_bytes).to_vec();
  942. let after_count = std::slice::from_raw_parts(count_ptr.cast_const(), 512).to_vec();
  943. let words = std::slice::from_raw_parts(
  944. readback_ptr.cast::<u32>().cast_const(),
  945. (STRIDE as usize / 4) * 5,
  946. )
  947. .to_vec();
  948. (hits, spent, after_src, after_count, words)
  949. };
  950. // Call #1: (3*2*1) + (5*1*1) + (65535*1*1) = 65,546 groups.
  951. // Call #2: (3*2*1) + (5*1*1) = 11 groups.
  952. let expected_groups = (6 + 5 + 65_535) + (6 + 5);
  953. assert_eq!(
  954. hits, expected_groups,
  955. "valid indirect dispatches must all execute"
  956. );
  957. assert_eq!(
  958. spent,
  959. expected_groups * 64,
  960. "budget must reflect only active records below countBuffer"
  961. );
  962. assert_eq!(
  963. after_src, initial_src,
  964. "src_args must never be mutated in-place"
  965. );
  966. assert_eq!(
  967. after_count, initial_count,
  968. "count_buf must never be mutated"
  969. );
  970. // Check `dst_args` records 0..3: clamped group counts + preserved extra stride words.
  971. assert_eq!(
  972. &clamped_words[0..6],
  973. &[3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666]
  974. );
  975. assert_eq!(
  976. &clamped_words[6..12],
  977. &[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC]
  978. );
  979. assert_eq!(
  980. &clamped_words[12..18],
  981. &[65_535, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567]
  982. );
  983. // Inactive slot 3 was never copied from `src_args`.
  984. assert_ne!(clamped_words[21], 0xDEAD_BEEF);
  985. }
  986. /// WARP D3D12 test proving `BUDGET` saturates without 32-bit unsigned
  987. /// wraparound across >64 huge indexed-draw records (`count = None`), while
  988. /// preserving `StartIndexLocation`, `BaseVertexLocation`,
  989. /// `StartInstanceLocation`, and custom stride padding, and leaving
  990. /// `src_args` untouched.
  991. /// A window of mesh records clamped ahead: the filled ones come out as
  992. /// they are and are charged, the slots of all ones come out empty and
  993. /// charge nothing; clamped as single records the same slots are clamped
  994. /// to the most and spend the budget.
  995. #[test]
  996. fn warp_window_leaves_unfilled_slots_empty_and_uncharged() {
  997. let Some(mut warp) = WarpHarness::new() else {
  998. return;
  999. };
  1000. const KIND_MESH: u32 = 10;
  1001. const STRIDE: u32 = 32;
  1002. const RECORDS: u32 = 16;
  1003. let filled = [5u32, 0, 519];
  1004. let total = (STRIDE * RECORDS) as usize;
  1005. let mut src = vec![0xffu8; total];
  1006. for (i, groups) in filled.into_iter().enumerate() {
  1007. let words = [groups, 1, 1, 0xAB00 + i as u32];
  1008. for (w, word) in words.into_iter().enumerate() {
  1009. let at = i * STRIDE as usize + w * 4;
  1010. src[at..at + 4].copy_from_slice(&word.to_le_bytes());
  1011. }
  1012. }
  1013. for ahead in [true, false] {
  1014. let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64);
  1015. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1016. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64);
  1017. let dst_buf = warp.default_uav(total as u64);
  1018. // SAFETY: mapped buffers of these sizes.
  1019. unsafe {
  1020. std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total);
  1021. std::ptr::write_bytes(budget_ptr, 0, 256);
  1022. std::ptr::write_bytes(readback_ptr, 0, total);
  1023. }
  1024. assert!(record_clamp_as(
  1025. &warp.clamp,
  1026. &warp.list,
  1027. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1028. budget_gpu,
  1029. (&src_buf, 0),
  1030. None,
  1031. (KIND_MESH, STRIDE, RECORDS),
  1032. ahead,
  1033. ));
  1034. // SAFETY: an open list; the scratch buffer, which the clamp left
  1035. // readable as arguments, is copied for the check.
  1036. unsafe {
  1037. warp.list.ResourceBarrier(&[transition(
  1038. &dst_buf,
  1039. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1040. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1041. )]);
  1042. warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64);
  1043. }
  1044. warp.submit_and_wait();
  1045. // SAFETY: the work is done; mapped buffers.
  1046. let (spent, largest, out) = unsafe {
  1047. (
  1048. (budget_ptr as *const u32).read_volatile(),
  1049. (budget_ptr as *const u32).add(1).read_volatile(),
  1050. std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4).to_vec(),
  1051. )
  1052. };
  1053. for (i, groups) in filled.into_iter().enumerate() {
  1054. let rec = &out[i * 8..i * 8 + 4];
  1055. assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}");
  1056. }
  1057. let charged_filled = (5 + 519) * 128;
  1058. if ahead {
  1059. for i in filled.len()..RECORDS as usize {
  1060. assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty");
  1061. assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are");
  1062. }
  1063. assert_eq!(spent, charged_filled, "unfilled slots charge nothing");
  1064. assert_eq!(largest, 519, "and are not counted as asked for");
  1065. } else {
  1066. // Thirteen slots at 65,535 groups: sixteen would be all of it.
  1067. assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most");
  1068. assert_eq!(largest, u32::MAX);
  1069. }
  1070. }
  1071. }
  1072. #[test]
  1073. fn warp_budget_saturates_without_wraparound_and_preserves_draw_fields() {
  1074. let Some(mut warp) = WarpHarness::new() else {
  1075. return;
  1076. };
  1077. const KIND_INDEXED: u32 = 1;
  1078. const STRIDE: u32 = 24; // 5 indexed-draw words + 1 trailing custom word
  1079. const RECORDS: u32 = 128; // 2 waves of 64: old InterlockedAdd wrapped 2^32 at 64!
  1080. const BUDGET_CAP: u32 = 1 << 27;
  1081. let total_bytes = (STRIDE * RECORDS) as usize;
  1082. let (src_buf, src_ptr, _) = warp.shared_buffer(total_bytes as u64);
  1083. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1084. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total_bytes as u64);
  1085. let dst_buf = warp.default_uav(total_bytes as u64);
  1086. let mut initial_src = vec![0u8; total_bytes];
  1087. for i in 0..RECORDS as usize {
  1088. let words: [u32; 6] = [
  1089. u32::MAX, // IndexCount -> clamps to 1 << 24
  1090. u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26)
  1091. 1000 + i as u32, // StartIndexLocation
  1092. (-200i32 + i as i32) as u32, // BaseVertexLocation
  1093. 5000 + i as u32, // StartInstanceLocation
  1094. 0xCAFE_0000 | (i as u32), // Extra stride word
  1095. ];
  1096. let base = i * (STRIDE as usize);
  1097. for (w, val) in words.into_iter().enumerate() {
  1098. initial_src[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
  1099. }
  1100. }
  1101. // SAFETY: mapped buffers have sufficient capacity.
  1102. unsafe {
  1103. std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, total_bytes);
  1104. (budget_ptr as *mut u32).write_volatile(0);
  1105. std::ptr::write_bytes(readback_ptr, 0, total_bytes);
  1106. }
  1107. assert!(record_clamp_as(
  1108. &warp.clamp,
  1109. &warp.list,
  1110. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1111. budget_gpu,
  1112. (&src_buf, 0),
  1113. None,
  1114. (KIND_INDEXED, STRIDE, RECORDS),
  1115. false,
  1116. ));
  1117. // SAFETY: open command list; copy clamped scratch buffer (left
  1118. // readable as arguments) for verification.
  1119. unsafe {
  1120. warp.list.ResourceBarrier(&[transition(
  1121. &dst_buf,
  1122. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1123. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1124. )]);
  1125. warp.list
  1126. .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64);
  1127. }
  1128. warp.submit_and_wait();
  1129. // SAFETY: GPU work completed.
  1130. let (spent, after_src, out_words) = unsafe {
  1131. let spent = (budget_ptr as *const u32).read_volatile();
  1132. let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), total_bytes).to_vec();
  1133. let out_words = std::slice::from_raw_parts(
  1134. readback_ptr.cast::<u32>().cast_const(),
  1135. total_bytes / 4,
  1136. )
  1137. .to_vec();
  1138. (spent, after_src, out_words)
  1139. };
  1140. assert_eq!(
  1141. spent, BUDGET_CAP,
  1142. "budget must saturate at BUDGET without wrapping"
  1143. );
  1144. assert_eq!(after_src, initial_src, "src_args must remain untouched");
  1145. let mut kept = 0usize;
  1146. let mut zeroed = 0usize;
  1147. for i in 0..RECORDS as usize {
  1148. let rec = &out_words[i * 6..(i + 1) * 6];
  1149. if rec[0] == (1 << 24) && rec[1] == 4 {
  1150. kept += 1;
  1151. } else {
  1152. assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed");
  1153. zeroed += 1;
  1154. }
  1155. assert_eq!(rec[2], 1000 + i as u32);
  1156. assert_eq!(rec[3], (-200i32 + i as i32) as u32);
  1157. assert_eq!(rec[4], 5000 + i as u32);
  1158. assert_eq!(rec[5], 0xCAFE_0000 | (i as u32));
  1159. }
  1160. assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2));
  1161. }
  1162. /// Exercises `HostList::indirect_scratch`, `bound`, the scratch buffer's
  1163. /// tracked state, `Host::execute`, and `HostList::reset` end-to-end on
  1164. /// the host device.
  1165. #[test]
  1166. fn host_list_reuses_and_grows_scratch_across_submissions() {
  1167. let Some(host) = super::host() else {
  1168. return;
  1169. };
  1170. // What earlier tests left in the debug layer's queue, if it is on.
  1171. let _ = host.log_messages();
  1172. let Ok(list) = host.new_list() else {
  1173. return;
  1174. };
  1175. let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else {
  1176. return;
  1177. };
  1178. let Some((count_buf, count_ptr)) = host.shared_buffer(256) else {
  1179. return;
  1180. };
  1181. // SAFETY: mapped host buffers.
  1182. unsafe {
  1183. std::ptr::write_bytes(src_ptr, 0x7F, 256 << 10);
  1184. (count_ptr as *mut u32).write_volatile(2);
  1185. }
  1186. let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  1187. // First two calls fit inside the initial 64 KiB scratch buffer and
  1188. // must reuse the exact same `ID3D12Resource`, which stays readable
  1189. // as arguments between them.
  1190. let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap();
  1191. assert_eq!(
  1192. list.indirect_state(&b1),
  1193. args,
  1194. "a clamp leaves the scratch readable as arguments"
  1195. );
  1196. let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap();
  1197. assert_eq!(
  1198. b1.as_raw(),
  1199. b2.as_raw(),
  1200. "scratch buffer within capacity must be reused"
  1201. );
  1202. assert_eq!(list.indirect_state(&b2), args);
  1203. // A call needing >64 KiB grows the scratch buffer mid-list while keeping
  1204. // `b1` alive until reset. The new buffer starts out common.
  1205. let grown = list.indirect_scratch(5000 * 20).unwrap();
  1206. assert_eq!(
  1207. list.indirect_state(&grown),
  1208. D3D12_RESOURCE_STATE_COMMON,
  1209. "a new scratch buffer is common"
  1210. );
  1211. let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap();
  1212. assert_eq!(b3.as_raw(), grown.as_raw());
  1213. assert_ne!(
  1214. b3.as_raw(),
  1215. b1.as_raw(),
  1216. "larger request must grow scratch buffer"
  1217. );
  1218. assert_eq!(list.indirect_state(&b3), args);
  1219. assert_eq!(
  1220. list.indirect_state(&b1),
  1221. D3D12_RESOURCE_STATE_COMMON,
  1222. "the replaced buffer went back to common"
  1223. );
  1224. list.close();
  1225. // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics):
  1226. // every barrier recorded named the state the buffer was in. Read
  1227. // before the submission, which moves the messages to the log.
  1228. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1229. host.execute(&[&list]);
  1230. list.reset();
  1231. // After reset, requests up to the grown high-water mark reuse `b3` with
  1232. // zero new allocations; the buffer decayed to common when the
  1233. // submission ran.
  1234. assert_eq!(
  1235. list.indirect_state(&b3),
  1236. D3D12_RESOURCE_STATE_COMMON,
  1237. "a reset list starts with a common scratch buffer"
  1238. );
  1239. let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap();
  1240. assert_eq!(
  1241. b4.as_raw(),
  1242. b3.as_raw(),
  1243. "grown scratch buffer must persist across reset"
  1244. );
  1245. assert_eq!(list.indirect_state(&b4), args);
  1246. list.close();
  1247. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1248. host.execute(&[&list]);
  1249. list.reset();
  1250. }
  1251. /// A group charges its records in lane order: with 300 left of the
  1252. /// budget, the first draw (100) fits, the second (250) does not and
  1253. /// takes the rest, and the ones after it run empty. (Racing for the
  1254. /// word record by record, which of them fitted was up to the GPU.)
  1255. #[test]
  1256. fn warp_a_group_charges_its_records_in_lane_order() {
  1257. let Some(mut warp) = WarpHarness::new() else {
  1258. return;
  1259. };
  1260. const KIND_DRAW: u32 = 0;
  1261. const STRIDE: u32 = 16;
  1262. const BUDGET_CAP: u32 = 1 << 27;
  1263. let counts = [100u32, 250, 50, 100];
  1264. let total = counts.len() * STRIDE as usize;
  1265. let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64);
  1266. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1267. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64);
  1268. let dst_buf = warp.default_uav(total as u64);
  1269. // SAFETY: mapped buffers of these sizes.
  1270. unsafe {
  1271. for (i, &count) in counts.iter().enumerate() {
  1272. let words = [count, 1, 7, 9];
  1273. std::ptr::copy_nonoverlapping(
  1274. words.as_ptr().cast::<u8>(),
  1275. src_ptr.add(i * STRIDE as usize),
  1276. 16,
  1277. );
  1278. }
  1279. std::ptr::write_bytes(budget_ptr, 0, 256);
  1280. (budget_ptr as *mut u32).write_volatile(BUDGET_CAP - 300);
  1281. }
  1282. assert!(record_clamp_as(
  1283. &warp.clamp,
  1284. &warp.list,
  1285. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1286. budget_gpu,
  1287. (&src_buf, 0),
  1288. None,
  1289. (KIND_DRAW, STRIDE, counts.len() as u32),
  1290. false,
  1291. ));
  1292. // SAFETY: an open list; the clamped records are copied for the check.
  1293. unsafe {
  1294. warp.list.ResourceBarrier(&[transition(
  1295. &dst_buf,
  1296. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1297. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1298. )]);
  1299. warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64);
  1300. }
  1301. warp.submit_and_wait();
  1302. // SAFETY: the work is done; mapped buffers.
  1303. let (spent, out) = unsafe {
  1304. (
  1305. (budget_ptr as *const u32).read_volatile(),
  1306. std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4)
  1307. .to_vec(),
  1308. )
  1309. };
  1310. assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits");
  1311. for i in 1..counts.len() {
  1312. assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty");
  1313. }
  1314. assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest");
  1315. }
  1316. /// The list's budget starts empty at each submission, wherever it
  1317. /// lives (the card's copy is zeroed in the list): a recording whose
  1318. /// clamps spend all of it is followed, after the reset, by one whose
  1319. /// small record still runs.
  1320. #[test]
  1321. fn host_list_budget_starts_empty_at_each_submission() {
  1322. let Some(host) = super::host() else {
  1323. return;
  1324. };
  1325. let Ok(list) = host.new_list() else {
  1326. return;
  1327. };
  1328. let _ = host.log_messages();
  1329. let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
  1330. const KIND_DISPATCH: u32 = 2;
  1331. const STRIDE: u32 = 12;
  1332. let signature = {
  1333. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  1334. Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32),
  1335. ..Default::default()
  1336. };
  1337. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  1338. ByteStride: STRIDE,
  1339. NumArgumentDescs: 1,
  1340. pArgumentDescs: &arg,
  1341. NodeMask: 0,
  1342. };
  1343. let mut sig: Option<ID3D12CommandSignature> = None;
  1344. // SAFETY: a valid single-argument command signature description.
  1345. unsafe {
  1346. host.device
  1347. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  1348. .unwrap();
  1349. }
  1350. sig.unwrap()
  1351. };
  1352. // Three records of 65,535 x 16 groups: about half the budget each.
  1353. let Some((big, big_ptr)) = host.shared_buffer(3 * u64::from(STRIDE)) else {
  1354. return;
  1355. };
  1356. let Some((small, small_ptr)) = host.shared_buffer(u64::from(STRIDE)) else {
  1357. return;
  1358. };
  1359. let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
  1360. return;
  1361. };
  1362. // SAFETY: mapped buffers of these sizes; nothing runs yet.
  1363. unsafe {
  1364. for i in 0..3 {
  1365. let words = [65535u32, 16, 1];
  1366. std::ptr::copy_nonoverlapping(
  1367. words.as_ptr().cast::<u8>(),
  1368. big_ptr.add(i * STRIDE as usize),
  1369. 12,
  1370. );
  1371. }
  1372. std::ptr::copy_nonoverlapping([1u32, 1, 1].as_ptr().cast::<u8>(), small_ptr, 12);
  1373. std::ptr::write_bytes(hits_ptr, 0, 256);
  1374. }
  1375. // SAFETY: a live buffer.
  1376. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
  1377. for round in 0..2 {
  1378. // Spends the budget (clamped, not executed), then one group.
  1379. bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3)).unwrap();
  1380. let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap();
  1381. // SAFETY: an open list; the worker's root signature and
  1382. // pipeline; buffers the test holds until the list has run.
  1383. unsafe {
  1384. list.list.SetComputeRootSignature(&worker.root);
  1385. list.list.SetPipelineState(&worker.pso);
  1386. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1387. list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0);
  1388. }
  1389. list.close();
  1390. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1391. host.execute(&[&list]);
  1392. list.reset();
  1393. // SAFETY: the list has run; a mapped buffer.
  1394. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  1395. // The small record comes after the big ones spent the budget:
  1396. // it runs empty, in every round alike (none carries over).
  1397. assert_eq!(hits, 0, "round {round}: the spent budget empties the record after it");
  1398. }
  1399. // A recording with only the small record: the budget is empty
  1400. // again, so it runs.
  1401. let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap();
  1402. // SAFETY: as above.
  1403. unsafe {
  1404. list.list.SetComputeRootSignature(&worker.root);
  1405. list.list.SetPipelineState(&worker.pso);
  1406. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1407. list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0);
  1408. }
  1409. list.close();
  1410. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1411. host.execute(&[&list]);
  1412. list.reset();
  1413. // SAFETY: the list has run; a mapped buffer.
  1414. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  1415. assert_eq!(hits, 1, "the budget starts empty at the next submission");
  1416. }
  1417. /// Records the dispatch records `groups` (three words each, `step`
  1418. /// bytes apart, the rest of each record ones) into a fresh mapped
  1419. /// buffer of `warp`'s device.
  1420. fn dispatch_records(warp: &WarpHarness, groups: &[u32], step: u32) -> ID3D12Resource {
  1421. let total = groups.len() * step as usize;
  1422. let (buffer, ptr, _) = warp.shared_buffer(total as u64);
  1423. let mut bytes = vec![0xffu8; total];
  1424. for (i, &g) in groups.iter().enumerate() {
  1425. for (w, word) in [g, 1, 1].into_iter().enumerate() {
  1426. let at = i * step as usize + w * 4;
  1427. bytes[at..at + 4].copy_from_slice(&word.to_le_bytes());
  1428. }
  1429. }
  1430. // SAFETY: the mapping holds `total` bytes.
  1431. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) };
  1432. buffer
  1433. }
  1434. /// Two windows in one list, as `crate::draw` records them: each clamps
  1435. /// its records ahead, then one execution per record reads the scratch
  1436. /// buffer with no barrier between them; the second clamp moves the
  1437. /// scratch buffer straight from arguments back to unordered access.
  1438. /// Every record runs once, with the group count it asked for.
  1439. #[test]
  1440. fn warp_window_executions_read_their_records_with_no_barrier_between() {
  1441. let Some(mut warp) = WarpHarness::new() else {
  1442. return;
  1443. };
  1444. const KIND_DISPATCH: u32 = 2;
  1445. // The title names 12 bytes and keeps its records 32 apart.
  1446. const STRIDE: u32 = 12;
  1447. const STEP: u32 = 32;
  1448. let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]];
  1449. let sources: Vec<ID3D12Resource> =
  1450. windows.iter().map(|g| dispatch_records(&warp, g, STEP)).collect();
  1451. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1452. let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256);
  1453. let dst_buf = warp.default_uav(u64::from(STEP) * 4);
  1454. let sig = warp.signature(KIND_DISPATCH, STRIDE);
  1455. // SAFETY: mapped buffers of these sizes.
  1456. unsafe {
  1457. std::ptr::write_bytes(budget_ptr, 0, 256);
  1458. std::ptr::write_bytes(hits_ptr, 0, 256);
  1459. }
  1460. let mut state = D3D12_RESOURCE_STATE_COMMON;
  1461. for (groups, src) in windows.iter().zip(&sources) {
  1462. assert!(record_clamp_as(
  1463. &warp.clamp,
  1464. &warp.list,
  1465. (&dst_buf, state),
  1466. budget_gpu,
  1467. (src, 0),
  1468. None,
  1469. (KIND_DISPATCH, STEP, groups.len() as u32),
  1470. true,
  1471. ));
  1472. state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  1473. // SAFETY: an open list; the worker's root signature and
  1474. // pipeline; the scratch buffer is readable as arguments.
  1475. unsafe {
  1476. warp.list.SetComputeRootSignature(&warp.worker.root);
  1477. warp.list.SetPipelineState(&warp.worker.pso);
  1478. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1479. for i in 0..groups.len() as u64 {
  1480. warp.list.ExecuteIndirect(&sig, 1, &dst_buf, i * u64::from(STEP), None, 0);
  1481. }
  1482. }
  1483. }
  1484. warp.submit_and_wait();
  1485. // SAFETY: the work is done; mapped buffers.
  1486. let (hits, spent) = unsafe {
  1487. (
  1488. (hits_ptr as *const u32).read_volatile(),
  1489. (budget_ptr as *const u32).read_volatile(),
  1490. )
  1491. };
  1492. let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum();
  1493. assert_eq!(hits, expected, "every record of both windows runs once");
  1494. assert_eq!(spent, expected * 64, "and is charged what it asked for");
  1495. }
  1496. /// The windows of `warp_window_executions_read_their_records_with_no_barrier_between`
  1497. /// through a host list (`bound_ahead`, the list's tracked scratch state,
  1498. /// `Host::execute`), twice: on the first recording the scratch buffer
  1499. /// starts common, on the second (after the reset) it starts common
  1500. /// again. With the debug layer on (`VICTORY_D3D12_DEBUG=1` in a
  1501. /// diagnostics build) no barrier names a state the buffer is not in.
  1502. #[test]
  1503. fn host_list_window_executions_need_no_barrier_of_their_own() {
  1504. let Some(host) = super::host() else {
  1505. return;
  1506. };
  1507. // What earlier tests left in the debug layer's queue, if it is on.
  1508. let _ = host.log_messages();
  1509. let Ok(list) = host.new_list() else {
  1510. return;
  1511. };
  1512. let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
  1513. const KIND_DISPATCH: u32 = 2;
  1514. const STRIDE: u32 = 12;
  1515. const STEP: u32 = 32;
  1516. let signature = {
  1517. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  1518. Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32),
  1519. ..Default::default()
  1520. };
  1521. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  1522. ByteStride: STRIDE,
  1523. NumArgumentDescs: 1,
  1524. pArgumentDescs: &arg,
  1525. NodeMask: 0,
  1526. };
  1527. let mut sig: Option<ID3D12CommandSignature> = None;
  1528. // SAFETY: a valid single-argument command signature description.
  1529. unsafe {
  1530. host.device
  1531. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  1532. .unwrap();
  1533. }
  1534. sig.unwrap()
  1535. };
  1536. let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]];
  1537. let mut sources = Vec::new();
  1538. for groups in windows {
  1539. let total = groups.len() * STEP as usize;
  1540. let Some((buffer, ptr)) = host.shared_buffer(total as u64) else {
  1541. return;
  1542. };
  1543. let mut bytes = vec![0xffu8; total];
  1544. for (i, &g) in groups.iter().enumerate() {
  1545. for (w, word) in [g, 1, 1].into_iter().enumerate() {
  1546. let at = i * STEP as usize + w * 4;
  1547. bytes[at..at + 4].copy_from_slice(&word.to_le_bytes());
  1548. }
  1549. }
  1550. // SAFETY: the mapping holds `total` bytes.
  1551. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) };
  1552. sources.push(buffer);
  1553. }
  1554. let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
  1555. return;
  1556. };
  1557. let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum();
  1558. // SAFETY: a live buffer.
  1559. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
  1560. for _ in 0..2 {
  1561. // SAFETY: the mapping holds 256 bytes; nothing runs.
  1562. unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) };
  1563. for (groups, src) in windows.iter().zip(&sources) {
  1564. let spec = (KIND_DISPATCH, STEP, groups.len() as u32);
  1565. let scratch = bound_ahead(&list, (src, 0), spec).unwrap();
  1566. assert_eq!(list.indirect_state(&scratch), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  1567. // SAFETY: an open list; the worker's root signature and
  1568. // pipeline; buffers the test holds until the list has run.
  1569. unsafe {
  1570. list.list.SetComputeRootSignature(&worker.root);
  1571. list.list.SetPipelineState(&worker.pso);
  1572. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1573. for i in 0..groups.len() as u64 {
  1574. let at = i * u64::from(STEP);
  1575. list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0);
  1576. }
  1577. }
  1578. }
  1579. list.close();
  1580. // With the debug layer on: nothing it objects to was recorded.
  1581. // Read before the submission, which moves the messages to the log.
  1582. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1583. host.execute(&[&list]);
  1584. list.reset();
  1585. // SAFETY: the list has run; a mapped buffer.
  1586. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  1587. assert_eq!(hits, expected, "every record of both windows runs once");
  1588. }
  1589. }
  1590. }
  1591. /// The benchmark of the clamp and its barriers (ignored by default).
  1592. #[cfg(test)]
  1593. mod bench;