indirect.rs 68 KB

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