2
0

indirect.rs 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731
  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. //! The executions of one record without a count buffer (all the title's)
  21. //! are clamped in batches ([`batch`], `VICTORY_INDIRECT_BATCH`): the rest of
  22. //! this is for the others.
  23. //!
  24. //! When a count buffer is given, threads at or past `min(max, count)` return
  25. //! immediately without charging the list's budget or reading uninitialized
  26. //! tail slots. Each list has a budget (2^27 vertex instances or threads,
  27. //! groups counted as 64 threads, mesh groups as 128): active records past it
  28. //! run empty, saturating without 32-bit wraparound so a list of thousands of
  29. //! garbage records cannot run for seconds either.
  30. //!
  31. //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
  32. //! groups per dimension and 2^20 per dispatch, one-dimensional mesh
  33. //! dispatches, the budget) cut legitimate work beyond them; raise them if
  34. //! the title needs more.
  35. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  36. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  37. use windows::Win32::Graphics::Direct3D12::*;
  38. use windows::core::s;
  39. use crate::host::{HostList, host, transition};
  40. pub(crate) mod batch;
  41. const SOURCE: &str = r#"
  42. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
  43. cbuffer Record : register(b0) {
  44. uint kind;
  45. uint stride;
  46. uint records;
  47. uint args_offset;
  48. // Bit 0: a count buffer bounds the records. Bit 1: the records are a
  49. // window clamped ahead of their draws: one that asks for more than can
  50. // run is left empty and costs nothing.
  51. uint has_count;
  52. uint count_offset;
  53. };
  54. ByteAddressBuffer src_args : register(t0);
  55. ByteAddressBuffer count_buf : register(t1);
  56. RWByteAddressBuffer dst_args : register(u0);
  57. // The list's work so far (vertex instances, threads): past the budget,
  58. // records run empty.
  59. RWByteAddressBuffer budget : register(u1);
  60. static const uint BUDGET = 1u << 27;
  61. // Groups of one dispatch; more run empty.
  62. static const uint GROUPS = 1u << 20;
  63. // Each group charges the budget once: the costs of its records go here,
  64. // one thread charges their sum, saturating as each record would in lane
  65. // order, and every thread then reads whether its own record fitted. A
  66. // compare and swap per record, 64 threads racing for one word, cost a
  67. // round for each record of a window, and in memory the CPU maps (where the
  68. // budget was, and is with VICTORY_INDIRECT_CARD_BUDGET=0) every atomic
  69. // crosses the bus on a card of its own.
  70. groupshared uint costs[64];
  71. groupshared uint fits[64];
  72. groupshared uint largest_asked;
  73. groupshared uint all_asked;
  74. [RootSignature(RS)]
  75. [numthreads(64, 1, 1)]
  76. void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
  77. uint eff_count = records;
  78. bool ahead = (has_count & 2u) != 0;
  79. if ((has_count & 1u) != 0) {
  80. eff_count = min(eff_count, count_buf.Load(count_offset));
  81. }
  82. // Threads past the records take part in the group's charge (cost 0)
  83. // and store nothing.
  84. bool active = id.x < eff_count;
  85. uint src_at = args_offset + id.x * stride;
  86. uint dst_at = id.x * stride;
  87. uint cost = 0;
  88. uint asked = 0;
  89. uint2 draw_counts = uint2(0, 0);
  90. uint3 groups = uint3(0, 0, 0);
  91. if (gi == 0) {
  92. largest_asked = 0;
  93. all_asked = 0;
  94. }
  95. if (active && kind <= 1) {
  96. // Draws: vertex or index count, then instances.
  97. uint2 want = src_args.Load2(src_at);
  98. if (ahead && (want.x > (1u << 24) || want.y > (1u << 24))) {
  99. want = uint2(0, 0);
  100. }
  101. uint count = min(want.x, 1u << 24);
  102. uint instances = min(want.y, (1u << 26) / max(count, 1u));
  103. cost = count * instances;
  104. draw_counts = uint2(count, instances);
  105. } else if (active && kind == 2) {
  106. uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u));
  107. // x * y fits 32 bits; the whole count may not.
  108. if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
  109. g = uint3(0, 0, 0);
  110. }
  111. cost = g.x * g.y * g.z * 64u;
  112. groups = g;
  113. } else if (active) {
  114. // Mesh dispatches: the console's are one-dimensional.
  115. uint3 g = src_args.Load3(src_at);
  116. // Ahead of its draw, a record over the most a dispatch runs is a
  117. // slot the title has not filled (the title leaves all
  118. // ones there): empty, and not counted below either.
  119. if (ahead && g.x > 65535u) {
  120. g = uint3(0, 0, 0);
  121. }
  122. asked = g.x;
  123. g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
  124. cost = g.x * g.y * g.z * 128u;
  125. groups = g;
  126. }
  127. costs[gi] = cost;
  128. GroupMemoryBarrierWithGroupSync();
  129. if (active && kind > 2) {
  130. // Diagnostics, in the budget buffer's next words (below): the
  131. // largest group count a mesh record asked for, and the groups
  132. // asked in all.
  133. uint was;
  134. InterlockedMax(largest_asked, asked, was);
  135. InterlockedAdd(all_asked, min(asked, 1u << 24), was);
  136. }
  137. // The group's own records: none for a group past a count buffer's
  138. // count (an execution may ask for thousands and count a few), which
  139. // touches the budget not at all, as its threads did not before.
  140. uint first = id.x - gi;
  141. uint n = eff_count > first ? min(64u, eff_count - first) : 0u;
  142. if (gi == 0 && n > 0) {
  143. // What the records charge, from `before` on, in lane order: a
  144. // record that does not fit whole runs empty and takes the rest.
  145. // Only the group's own records are walked (one, clamped alone).
  146. uint before;
  147. budget.InterlockedOr(0, 0, before);
  148. [allow_uav_condition]
  149. while (before < BUDGET) {
  150. uint next = before;
  151. for (uint j = 0; j < n; j++) {
  152. uint c = costs[j];
  153. if (c > 0 && next < BUDGET) {
  154. next = (BUDGET - next <= c) ? BUDGET : (next + c);
  155. }
  156. }
  157. if (next == before) break;
  158. uint prev;
  159. budget.InterlockedCompareExchange(0, before, next, prev);
  160. if (prev == before) break;
  161. before = prev;
  162. }
  163. uint at = before;
  164. for (uint k = 0; k < n; k++) {
  165. uint c = costs[k];
  166. uint fit = 1;
  167. if (c > 0) {
  168. fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u;
  169. at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c);
  170. }
  171. fits[k] = fit;
  172. }
  173. }
  174. GroupMemoryBarrierWithGroupSync();
  175. if (gi == 0 && kind > 2 && n > 0) {
  176. uint was;
  177. budget.InterlockedMax(4, largest_asked, was);
  178. budget.InterlockedAdd(8, all_asked, was);
  179. }
  180. if (!active) {
  181. return;
  182. }
  183. bool over = fits[gi] == 0;
  184. if (kind <= 1) {
  185. if (over) {
  186. draw_counts = uint2(0, 0);
  187. }
  188. dst_args.Store2(dst_at, draw_counts);
  189. for (uint off = 8; off < stride; off += 4) {
  190. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  191. }
  192. } else {
  193. if (over) {
  194. groups = uint3(0, 0, 0);
  195. }
  196. dst_args.Store3(dst_at, groups);
  197. for (uint off = 12; off < stride; off += 4) {
  198. dst_args.Store(dst_at + off, src_args.Load(src_at + off));
  199. }
  200. }
  201. }
  202. "#;
  203. struct Clamp {
  204. root: ID3D12RootSignature,
  205. pso: ID3D12PipelineState,
  206. }
  207. // SAFETY: D3D12 objects are free-threaded.
  208. unsafe impl Send for Clamp {}
  209. // SAFETY: as above.
  210. unsafe impl Sync for Clamp {}
  211. fn clamp() -> Option<&'static Clamp> {
  212. static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
  213. CLAMP
  214. .get_or_init(|| match make() {
  215. Ok(c) => Some(c),
  216. Err(e) => {
  217. tracing::warn!(error = %e, "no argument clamp: indirect execution dropped");
  218. None
  219. }
  220. })
  221. .as_ref()
  222. }
  223. fn make() -> windows::core::Result<Clamp> {
  224. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  225. make_for(device)
  226. }
  227. fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> {
  228. make_from(device, SOURCE)
  229. }
  230. /// The clamp compiled from `source` (ours, or in the benchmark the one it
  231. /// replaced).
  232. fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
  233. let mut code: Option<ID3DBlob> = None;
  234. let mut errors: Option<ID3DBlob> = None;
  235. // SAFETY: the source and names live through the call; out pointers ours.
  236. let compiled = unsafe {
  237. D3DCompile(
  238. source.as_ptr().cast(),
  239. source.len(),
  240. s!("clamp"),
  241. None,
  242. None,
  243. s!("main"),
  244. s!("cs_5_1"),
  245. 0,
  246. 0,
  247. &mut code,
  248. Some(&mut errors),
  249. )
  250. };
  251. if let Err(e) = compiled {
  252. if let Some(errors) = errors {
  253. // SAFETY: the blob's own bytes.
  254. let text = unsafe {
  255. std::slice::from_raw_parts(
  256. errors.GetBufferPointer().cast::<u8>(),
  257. errors.GetBufferSize(),
  258. )
  259. };
  260. tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text));
  261. }
  262. return Err(e);
  263. }
  264. let code = code.ok_or_else(windows::core::Error::empty)?;
  265. // SAFETY: the blob's own bytes; the root signature is inside the shader.
  266. unsafe {
  267. let bytes =
  268. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  269. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  270. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  271. pRootSignature: std::mem::transmute_copy(&root),
  272. CS: D3D12_SHADER_BYTECODE {
  273. pShaderBytecode: bytes.as_ptr().cast(),
  274. BytecodeLength: bytes.len(),
  275. },
  276. ..Default::default()
  277. })?;
  278. #[cfg(feature = "diagnostics")]
  279. crate::host::name(&pso, || crate::replay::play::CLAMP.into());
  280. Ok(Clamp { root, pso })
  281. }
  282. }
  283. /// Minimum record byte stride for a supported PC indirect argument `kind`.
  284. fn min_stride(kind: u32) -> Option<u32> {
  285. match kind {
  286. 0 => Some(16),
  287. 1 => Some(20),
  288. 2 | 10 => Some(12),
  289. _ => None,
  290. }
  291. }
  292. /// Validates record alignment and returns the scratch byte size `stride * records`.
  293. fn validate_layout(
  294. (kind, stride, records): (u32, u32, u32),
  295. src_offset: u64,
  296. count_offset: Option<u64>,
  297. ) -> Option<u64> {
  298. let min = min_stride(kind)?;
  299. if stride < min || !stride.is_multiple_of(4) || !src_offset.is_multiple_of(4) {
  300. return None;
  301. }
  302. if count_offset.is_some_and(|off| !off.is_multiple_of(4)) {
  303. return None;
  304. }
  305. let bytes = u64::from(stride).checked_mul(u64::from(records))?;
  306. (bytes <= u64::from(u32::MAX)).then_some(bytes)
  307. }
  308. /// Records, in `list`, the non-destructive clamp of up to `records` records of
  309. /// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded
  310. /// by the 32-bit count in `count` when given) into a device-local scratch
  311. /// buffer, at offset `0`. The scratch buffer is left in `INDIRECT_ARGUMENT`
  312. /// until the next clamp into it: executions read it with no barrier of
  313. /// their own. Replaces the list's compute root signature and pipeline
  314. /// (callers bind theirs after). `None` if the clamp or alignment is not
  315. /// available.
  316. pub(crate) fn bound(
  317. list: &HostList,
  318. src: (&ID3D12Resource, u64),
  319. count: Option<(&ID3D12Resource, u64)>,
  320. spec: (u32, u32, u32),
  321. ) -> Option<ID3D12Resource> {
  322. let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?;
  323. let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
  324. clamp_into(list, c, &dst, budget, src, count, spec, false).then_some(dst)
  325. }
  326. /// [`bound`] for a window of records clamped ahead of the draws that will
  327. /// read them (`crate::draw`'s windows; no count buffer). The records past
  328. /// the ones the title filled are whatever the buffer holds, and each
  329. /// record clamped charges the list's budget when it is clamped: a slot of
  330. /// all ones, clamped to the most a mesh dispatch runs (65,535 groups),
  331. /// charged a sixteenth of the budget, so sixteen of them emptied every
  332. /// draw of the list after them (run 93: "the largest group count asked for
  333. /// 4294967295", 43 to 153 such records a frame). Here a record that asks
  334. /// for more than can run is left empty and charges nothing; a record
  335. /// clamped alone is clamped and charged as before.
  336. pub(crate) fn bound_ahead(
  337. list: &HostList,
  338. src: (&ID3D12Resource, u64),
  339. spec: (u32, u32, u32),
  340. ) -> Option<ID3D12Resource> {
  341. let bytes = validate_layout(spec, src.1, None)?;
  342. let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?);
  343. clamp_into(list, c, &dst, budget, src, None, spec, true).then_some(dst)
  344. }
  345. /// [`record_clamp_as`] into `list`'s scratch buffer `dst`, from the state
  346. /// the list left it in; afterwards the list knows it is readable as
  347. /// indirect arguments.
  348. #[allow(clippy::too_many_arguments)]
  349. fn clamp_into(
  350. list: &HostList,
  351. c: &Clamp,
  352. dst: &ID3D12Resource,
  353. budget: u64,
  354. src: (&ID3D12Resource, u64),
  355. count: Option<(&ID3D12Resource, u64)>,
  356. spec: (u32, u32, u32),
  357. ahead: bool,
  358. ) -> bool {
  359. let before = list.indirect_state(dst);
  360. let recorded = record_clamp_as(c, &list.list, (dst, before), budget, src, count, spec, ahead);
  361. if recorded {
  362. list.indirect_readable(dst);
  363. }
  364. recorded
  365. }
  366. /// Records the clamp into `dst`, which is in state `before` (common, or
  367. /// indirect arguments after an earlier clamp into it), and leaves `dst` in
  368. /// `INDIRECT_ARGUMENT`. `ahead`: the records are a window clamped ahead of
  369. /// their draws ([`bound_ahead`]). False, with nothing recorded, if the
  370. /// layout or the addresses do not fit the clamp.
  371. #[allow(clippy::too_many_arguments)]
  372. fn record_clamp_as(
  373. c: &Clamp,
  374. l: &ID3D12GraphicsCommandList,
  375. (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES),
  376. budget: u64,
  377. (src, src_offset): (&ID3D12Resource, u64),
  378. count: Option<(&ID3D12Resource, u64)>,
  379. (kind, stride, records): (u32, u32, u32),
  380. ahead: bool,
  381. ) -> bool {
  382. let Some(bytes) = validate_layout(
  383. (kind, stride, records),
  384. src_offset,
  385. count.map(|(_, off)| off),
  386. ) else {
  387. return false;
  388. };
  389. // SAFETY: live D3D12 buffer resources.
  390. let (src_base, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) };
  391. if !src_base.is_multiple_of(4) || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) {
  392. return false;
  393. }
  394. let (src_gpu, args_offset) = match src_offset
  395. .checked_add(bytes)
  396. .filter(|&end| end <= u64::from(u32::MAX))
  397. {
  398. Some(_) => (src_base, src_offset as u32),
  399. None => {
  400. let Some(rebased) = src_base.checked_add(src_offset) else {
  401. return false;
  402. };
  403. (rebased, 0)
  404. }
  405. };
  406. let (count_gpu, has_count, count_offset) = match count {
  407. Some((buf, off)) => {
  408. // SAFETY: a live D3D12 buffer resource.
  409. let base = unsafe { buf.GetGPUVirtualAddress() };
  410. if !base.is_multiple_of(4) {
  411. return false;
  412. }
  413. match off.checked_add(4).filter(|&end| end <= u64::from(u32::MAX)) {
  414. Some(_) => (base, 1u32, off as u32),
  415. None => {
  416. let Some(rebased) = base.checked_add(off) else {
  417. return false;
  418. };
  419. (rebased, 1u32, 0u32)
  420. }
  421. }
  422. }
  423. None => (src_gpu, 0u32, 0u32),
  424. };
  425. let constants = [kind, stride, records, args_offset, has_count | (u32::from(ahead) << 1), count_offset];
  426. // SAFETY: an open list; our root signature and pipeline; live source,
  427. // count, scratch destination, and budget buffers. `src` and `count` stay
  428. // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst`
  429. // transitions `before -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. Moving
  430. // it out of `INDIRECT_ARGUMENT` orders this clamp's writes after every
  431. // earlier execution's reads of the scratch buffer; nothing else writes it.
  432. // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two
  433. // waits for every earlier shader write out (the state changes stay).
  434. #[cfg(feature = "diagnostics")]
  435. crate::copystat::add(crate::copystat::C::IndirectBounded, 1);
  436. #[cfg(feature = "diagnostics")]
  437. let waits = crate::copystat::barrier_test() & 2 == 0;
  438. #[cfg(not(feature = "diagnostics"))]
  439. let waits = true;
  440. let first = [
  441. uav_barrier(),
  442. transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
  443. ];
  444. let second = [
  445. uav_barrier(),
  446. transition(
  447. dst,
  448. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  449. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  450. ),
  451. ];
  452. let skip = usize::from(!waits);
  453. unsafe {
  454. // Earlier shader writes (the title's argument and count passes) first.
  455. l.ResourceBarrier(&first[skip..]);
  456. if records > 0 {
  457. l.SetComputeRootSignature(&c.root);
  458. l.SetPipelineState(&c.pso);
  459. l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  460. l.SetComputeRootShaderResourceView(1, src_gpu);
  461. l.SetComputeRootShaderResourceView(2, count_gpu);
  462. l.SetComputeRootUnorderedAccessView(3, dst_gpu);
  463. l.SetComputeRootUnorderedAccessView(4, budget);
  464. l.Dispatch(records.div_ceil(64), 1, 1);
  465. }
  466. l.ResourceBarrier(&second[skip..]);
  467. }
  468. true
  469. }
  470. /// The batched clamp's pipeline ([`batch`]).
  471. fn batch_clamp() -> Option<&'static Clamp> {
  472. static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
  473. CLAMP
  474. .get_or_init(|| {
  475. let made = host().ok_or_else(windows::core::Error::empty).and_then(|h| make_from(&h.device, batch::SOURCE));
  476. match made {
  477. Ok(c) => Some(c),
  478. Err(e) => {
  479. tracing::warn!(error = %e, "no batched argument clamp: records are clamped one at a time");
  480. None
  481. }
  482. }
  483. })
  484. .as_ref()
  485. }
  486. /// Opens a batch in `list` ([`batch`]): a pass that clamps the records of
  487. /// the executions recorded after it, of `source` (a host copy's number and
  488. /// buffer) and of the `recent` ones after it. The table to add them to,
  489. /// and the scratch buffer its places are in. Replaces the list's compute
  490. /// root signature and pipeline (callers bind theirs after). `None` if the
  491. /// clamp is not available.
  492. pub(crate) fn open_batch(
  493. list: &HostList,
  494. source: (u64, &ID3D12Resource),
  495. recent: &[(u64, ID3D12Resource)],
  496. ) -> Option<(batch::Table, ID3D12Resource)> {
  497. let c = batch_clamp()?;
  498. let budget = list.budget()?;
  499. let (jobs, at) = list.scratch(batch::TABLE)?;
  500. let (dst, base, before) = list.batch_place()?;
  501. let gpu = |b: &ID3D12Resource| {
  502. // SAFETY: a live buffer.
  503. Some(unsafe { b.GetGPUVirtualAddress() }).filter(|at| at.is_multiple_of(4))
  504. };
  505. // A source there is none of is the first again, which no job names.
  506. let mut ids = [0u64; batch::SOURCES];
  507. let mut sources = [gpu(source.1)?; batch::SOURCES];
  508. ids[0] = source.0;
  509. let others = recent.iter().filter(|r| r.0 != source.0).take(batch::SOURCES - 1);
  510. for (i, (id, buffer)) in others.enumerate() {
  511. if let Some(at) = gpu(buffer) {
  512. // Bound, and read only if a job names it: kept alive like the
  513. // copies draws read (`Shadow::refresh`).
  514. list.keep(buffer);
  515. (ids[i + 1], sources[i + 1]) = (*id, at);
  516. }
  517. }
  518. #[cfg(feature = "diagnostics")]
  519. crate::copystat::add(crate::copystat::C::IndirectBounded, 1);
  520. batch::record(c, &list.list, (&dst, before), budget, sources, jobs);
  521. // SAFETY: the list's own upload memory of that many bytes, 256-byte
  522. // aligned, until it is reset.
  523. Some((unsafe { batch::Table::new(at, base, ids) }, dst))
  524. }
  525. /// The batched clamp's root signature and pipeline on `device`, for the
  526. /// replayer.
  527. #[cfg(feature = "diagnostics")]
  528. pub(crate) fn batch_for(device: &ID3D12Device) -> windows::core::Result<(ID3D12RootSignature, ID3D12PipelineState)> {
  529. make_from(device, batch::SOURCE).map(|c| (c.root, c.pso))
  530. }
  531. fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
  532. D3D12_RESOURCE_BARRIER {
  533. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  534. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  535. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  536. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  537. pResource: std::mem::ManuallyDrop::new(None),
  538. }),
  539. },
  540. }
  541. }
  542. #[cfg(test)]
  543. pub(crate) mod tests {
  544. use super::*;
  545. use windows::Win32::Foundation::HANDLE;
  546. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  547. use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
  548. use windows::Win32::Graphics::Dxgi::*;
  549. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  550. use windows::core::Interface;
  551. const WORKER_CS: &str = r#"
  552. #define RS "UAV(u0)"
  553. RWByteAddressBuffer hits : register(u0);
  554. [RootSignature(RS)]
  555. [numthreads(1, 1, 1)]
  556. void main() {
  557. uint prev;
  558. hits.InterlockedAdd(0, 1, prev);
  559. }
  560. "#;
  561. struct WarpHarness {
  562. device: ID3D12Device,
  563. queue: ID3D12CommandQueue,
  564. allocator: ID3D12CommandAllocator,
  565. list: ID3D12GraphicsCommandList,
  566. fence: ID3D12Fence,
  567. submitted: u64,
  568. event: HANDLE,
  569. clamp: Clamp,
  570. worker: Clamp,
  571. /// Last, so given up last.
  572. _turn: std::sync::MutexGuard<'static, ()>,
  573. }
  574. /// The software adapter is one test's at a time. Two tests that compile
  575. /// and run shaders on it at once (it is one device for the process) make
  576. /// `d3d10warp.dll` (10.0.26100) crash now and then: access violations in
  577. /// its own shader compiler, on its own worker threads, in 12% of runs of
  578. /// all tests and 3% of runs of these alone on two threads; none in 100
  579. /// runs one after the other.
  580. pub(crate) fn warp_turn() -> std::sync::MutexGuard<'static, ()> {
  581. static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());
  582. TURN.lock().unwrap_or_else(|e| e.into_inner())
  583. }
  584. impl WarpHarness {
  585. fn new() -> Option<Self> {
  586. Self::on(true)
  587. }
  588. /// On the software adapter, or the first one (for measurements).
  589. fn on(software: bool) -> Option<Self> {
  590. let turn = warp_turn();
  591. // SAFETY: plain DXGI query and D3D12 test harness setup.
  592. unsafe {
  593. let factory: IDXGIFactory4 =
  594. CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
  595. let adapter: IDXGIAdapter = if software {
  596. factory.EnumWarpAdapter().ok()?
  597. } else {
  598. factory.EnumAdapters(0).ok()?
  599. };
  600. let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?;
  601. if software != (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) {
  602. return None;
  603. }
  604. let mut device: Option<ID3D12Device> = None;
  605. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  606. let device = device?;
  607. let queue: ID3D12CommandQueue = device
  608. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  609. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  610. ..Default::default()
  611. })
  612. .ok()?;
  613. let allocator: ID3D12CommandAllocator = device
  614. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)
  615. .ok()?;
  616. let list: ID3D12GraphicsCommandList = device
  617. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  618. .ok()?;
  619. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  620. let event = CreateEventW(None, false, false, None).ok()?;
  621. let clamp = make_for(&device).expect("clamp shader must compile on WARP");
  622. let worker = compile_cs(&device, WORKER_CS).expect("worker shader must compile");
  623. Some(Self {
  624. device,
  625. queue,
  626. allocator,
  627. list,
  628. fence,
  629. submitted: 0,
  630. event,
  631. clamp,
  632. worker,
  633. _turn: turn,
  634. })
  635. }
  636. }
  637. /// CPU-mapped L0 write-back buffer matching `Shadow`'s heap type.
  638. fn shared_buffer(&self, size: u64) -> (ID3D12Resource, *mut u8, u64) {
  639. let heap = D3D12_HEAP_PROPERTIES {
  640. Type: D3D12_HEAP_TYPE_CUSTOM,
  641. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  642. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  643. ..Default::default()
  644. };
  645. let desc = D3D12_RESOURCE_DESC {
  646. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  647. Width: size.max(4),
  648. Height: 1,
  649. DepthOrArraySize: 1,
  650. MipLevels: 1,
  651. SampleDesc: DXGI_SAMPLE_DESC {
  652. Count: 1,
  653. Quality: 0,
  654. },
  655. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  656. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  657. ..Default::default()
  658. };
  659. let mut buffer: Option<ID3D12Resource> = None;
  660. let mut data = std::ptr::null_mut();
  661. // SAFETY: plain buffer creation and persistent CPU mapping.
  662. unsafe {
  663. self.device
  664. .CreateCommittedResource(
  665. &heap,
  666. D3D12_HEAP_FLAG_NONE,
  667. &desc,
  668. D3D12_RESOURCE_STATE_COMMON,
  669. None,
  670. &mut buffer,
  671. )
  672. .unwrap();
  673. let buffer = buffer.unwrap();
  674. buffer.Map(0, None, Some(&mut data)).unwrap();
  675. let gpu = buffer.GetGPUVirtualAddress();
  676. (buffer, data.cast(), gpu)
  677. }
  678. }
  679. /// Device-local `DEFAULT`-heap UAV scratch buffer.
  680. fn default_uav(&self, size: u64) -> ID3D12Resource {
  681. let heap = D3D12_HEAP_PROPERTIES {
  682. Type: D3D12_HEAP_TYPE_DEFAULT,
  683. ..Default::default()
  684. };
  685. let desc = D3D12_RESOURCE_DESC {
  686. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  687. Width: size.max(64 << 10),
  688. Height: 1,
  689. DepthOrArraySize: 1,
  690. MipLevels: 1,
  691. SampleDesc: DXGI_SAMPLE_DESC {
  692. Count: 1,
  693. Quality: 0,
  694. },
  695. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  696. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  697. ..Default::default()
  698. };
  699. let mut buffer: Option<ID3D12Resource> = None;
  700. // SAFETY: plain device-local buffer creation.
  701. unsafe {
  702. self.device
  703. .CreateCommittedResource(
  704. &heap,
  705. D3D12_HEAP_FLAG_NONE,
  706. &desc,
  707. D3D12_RESOURCE_STATE_COMMON,
  708. None,
  709. &mut buffer,
  710. )
  711. .unwrap();
  712. }
  713. buffer.unwrap()
  714. }
  715. fn signature(&self, kind: u32, stride: u32) -> ID3D12CommandSignature {
  716. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  717. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  718. ..Default::default()
  719. };
  720. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  721. ByteStride: stride,
  722. NumArgumentDescs: 1,
  723. pArgumentDescs: &arg,
  724. NodeMask: 0,
  725. };
  726. let mut sig: Option<ID3D12CommandSignature> = None;
  727. // SAFETY: valid single-argument command signature description.
  728. unsafe {
  729. self.device
  730. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  731. .unwrap();
  732. }
  733. sig.unwrap()
  734. }
  735. fn submit_and_wait(&mut self) {
  736. self.submitted += 1;
  737. // SAFETY: closing, executing, waiting on fence, and resetting our list.
  738. unsafe {
  739. self.list.Close().unwrap();
  740. let cmd: ID3D12CommandList = self.list.cast().unwrap();
  741. self.queue.ExecuteCommandLists(&[Some(cmd)]);
  742. self.queue.Signal(&self.fence, self.submitted).unwrap();
  743. self.fence
  744. .SetEventOnCompletion(self.submitted, self.event)
  745. .unwrap();
  746. WaitForSingleObject(self.event, INFINITE);
  747. self.allocator.Reset().unwrap();
  748. self.list.Reset(&self.allocator, None).unwrap();
  749. }
  750. }
  751. }
  752. fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
  753. let mut code: Option<ID3DBlob> = None;
  754. // SAFETY: source and entry names outlive `D3DCompile`.
  755. unsafe {
  756. D3DCompile(
  757. source.as_ptr().cast(),
  758. source.len(),
  759. s!("worker"),
  760. None,
  761. None,
  762. s!("main"),
  763. s!("cs_5_1"),
  764. 0,
  765. 0,
  766. &mut code,
  767. None,
  768. )?;
  769. let code = code.unwrap();
  770. let bytes = std::slice::from_raw_parts(
  771. code.GetBufferPointer().cast::<u8>(),
  772. code.GetBufferSize(),
  773. );
  774. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  775. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  776. pRootSignature: std::mem::transmute_copy(&root),
  777. CS: D3D12_SHADER_BYTECODE {
  778. pShaderBytecode: bytes.as_ptr().cast(),
  779. BytecodeLength: bytes.len(),
  780. },
  781. ..Default::default()
  782. })?;
  783. Ok(Clamp { root, pso })
  784. }
  785. }
  786. /// The compare of copies in the card's memory (`crate::host`), on the
  787. /// software adapter. Told 1 it flags the pieces whose bytes are not
  788. /// what was hashed last and leaves the hashes: a piece a shader changed
  789. /// and a later one changed back then looks untouched, which is right
  790. /// only if the piece was fetched after both. Told 2 (submissions sent
  791. /// ahead with the relay, whose pieces are fetched flight by flight) it
  792. /// stores the hash it made: each compare flags what changed since the
  793. /// compare before it, also a change back.
  794. #[test]
  795. fn warp_card_compare_stores_the_hash_it_made_when_told() {
  796. let Some(mut warp) = WarpHarness::new() else {
  797. return;
  798. };
  799. let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP");
  800. const PIECE: usize = 64 << 10;
  801. const PIECES: u32 = 3;
  802. let size = PIECE * PIECES as usize;
  803. let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64);
  804. let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES));
  805. let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64);
  806. let content: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect();
  807. // SAFETY: the mapping holds `size` bytes.
  808. unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) };
  809. // One pass over the three pieces; what it left in `differs` (7s
  810. // where it stored nothing).
  811. let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] {
  812. // SAFETY: our open list, live buffers, the compare's own root
  813. // signature; the mappings hold what is read and written.
  814. unsafe {
  815. for piece in 0..PIECES as usize {
  816. differs_ptr.cast::<u32>().add(piece).write_volatile(7);
  817. }
  818. warp.list.SetComputeRootSignature(&compare.root);
  819. warp.list.SetPipelineState(&compare.pso);
  820. let constants = [0u32, 0, size as u32, PIECES, 0, mode];
  821. warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  822. warp.list.SetComputeRootShaderResourceView(1, now_gpu);
  823. warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu);
  824. warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu);
  825. warp.list.Dispatch(PIECES, 1, 1);
  826. }
  827. warp.submit_and_wait();
  828. // SAFETY: as above.
  829. let found = [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::<u32>().add(piece).read_volatile() });
  830. if mode == 0 {
  831. return found;
  832. }
  833. // Above the flag, the hash: as `host::torn` makes it of the bytes.
  834. for (piece, d) in found.iter().enumerate() {
  835. // SAFETY: inside the mapping, which the card has read.
  836. let bytes = unsafe { std::slice::from_raw_parts(now_ptr.add(piece * PIECE).cast_const(), PIECE) };
  837. assert_eq!(d >> 1, crate::host::piece_hash(bytes), "piece {piece}");
  838. }
  839. found.map(|d| d & 1)
  840. };
  841. let at = PIECE + 1234;
  842. // SAFETY (each): inside the mapping.
  843. let set = |value: u8| unsafe { now_ptr.add(at).write_volatile(value) };
  844. // 0: the hashes are stored, nothing is flagged.
  845. assert_eq!(run(&mut warp, 0), [7, 7, 7]);
  846. assert_eq!(run(&mut warp, 1), [0, 0, 0]);
  847. // A change in the second piece: flagged, and with 1 flagged again
  848. // (the hash stays the old one).
  849. set(content[at] ^ 0x40);
  850. assert_eq!(run(&mut warp, 1), [0, 1, 0]);
  851. assert_eq!(run(&mut warp, 1), [0, 1, 0]);
  852. // Changed back: with 1 the piece looks untouched.
  853. set(content[at]);
  854. assert_eq!(run(&mut warp, 1), [0, 0, 0]);
  855. // With 2 the change is flagged once, and the hash is the new one.
  856. set(content[at] ^ 0x40);
  857. assert_eq!(run(&mut warp, 2), [0, 1, 0]);
  858. assert_eq!(run(&mut warp, 2), [0, 0, 0]);
  859. // Changed back: flagged, where 1 saw nothing.
  860. set(content[at]);
  861. assert_eq!(run(&mut warp, 2), [0, 1, 0]);
  862. assert_eq!(run(&mut warp, 2), [0, 0, 0]);
  863. }
  864. /// What the passes over copies in the card's memory cost on the card
  865. /// (ignored: a measurement): rounds of a few passes of some pieces and a
  866. /// wait, as a frame has them. `VICTORY_BENCH_CS=<file>` times another
  867. /// source of the shader.
  868. #[test]
  869. #[ignore]
  870. fn card_compare_costs() {
  871. let Some(mut gpu) = WarpHarness::on(false) else {
  872. return;
  873. };
  874. let other = std::env::var("VICTORY_BENCH_CS").ok().map(|f| std::fs::read_to_string(f).unwrap());
  875. let source: &'static str = other.map_or(crate::host::CARD_COMPARE, |s| Box::leak(s.into_boxed_str()));
  876. let walked_alone = source.contains("SV_DispatchThreadID");
  877. let compare = compile_cs(&gpu.device, source).expect("the compare must compile");
  878. let now = gpu.default_uav(256 << 20);
  879. let hashes = gpu.default_uav(64 << 10);
  880. let differs = gpu.default_uav(64 << 10);
  881. for (rounds, passes, pieces) in [(80u32, 5u32, 1u32), (80, 5, 5), (80, 5, 64), (80, 5, 500), (1, 1, 4000)] {
  882. let mut best = f64::MAX;
  883. for _ in 0..6 {
  884. // SAFETY: our open list, live buffers, the compare's own
  885. // root signature; the pieces lie in the buffers.
  886. unsafe {
  887. gpu.list.SetComputeRootSignature(&compare.root);
  888. gpu.list.SetPipelineState(&compare.pso);
  889. gpu.list.SetComputeRootShaderResourceView(1, now.GetGPUVirtualAddress());
  890. gpu.list.SetComputeRootUnorderedAccessView(2, hashes.GetGPUVirtualAddress());
  891. gpu.list.SetComputeRootUnorderedAccessView(3, differs.GetGPUVirtualAddress());
  892. for _ in 0..rounds {
  893. for pass in 0..passes {
  894. let first = if pieces * passes < 4096 { pass * pieces } else { 0 };
  895. let constants = [first, 0u32, 256 << 20, pieces, 0, 1];
  896. gpu.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  897. gpu.list.Dispatch(if walked_alone { pieces.div_ceil(64) } else { pieces }, 1, 1);
  898. }
  899. gpu.list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  900. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  901. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  902. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  903. pResource: std::mem::ManuallyDrop::new(None),
  904. }),
  905. },
  906. ..Default::default()
  907. }]);
  908. }
  909. }
  910. let t = std::time::Instant::now();
  911. gpu.submit_and_wait();
  912. best = best.min(t.elapsed().as_secs_f64() * 1e3);
  913. }
  914. let mb = f64::from(rounds * passes * pieces) / 16.0;
  915. println!("{rounds} rounds of {passes} passes of {pieces} pieces: {best:.2} ms ({mb:.0} MB, {:.0} GB/s)", mb / best / 1.024);
  916. }
  917. }
  918. /// The clamp compiles with the system's compiler and the host takes it.
  919. #[test]
  920. fn argument_clamp_builds() {
  921. if super::host().is_none() {
  922. return; // no host GPU here
  923. }
  924. assert!(super::clamp().is_some());
  925. }
  926. #[test]
  927. fn rejects_unaligned_or_undersized_layouts() {
  928. assert_eq!(validate_layout((0, 16, 4), 0, None), Some(64));
  929. assert_eq!(validate_layout((1, 20, 4), 64, Some(128)), Some(80));
  930. assert_eq!(validate_layout((2, 12, 0), 0, Some(0)), Some(0));
  931. assert_eq!(validate_layout((10, 16, 2), 8, None), Some(32));
  932. // Undersized strides for each kind.
  933. assert_eq!(validate_layout((0, 12, 1), 0, None), None);
  934. assert_eq!(validate_layout((1, 16, 1), 0, None), None);
  935. assert_eq!(validate_layout((2, 8, 1), 0, None), None);
  936. assert_eq!(validate_layout((10, 8, 1), 0, None), None);
  937. // Unknown kind.
  938. assert_eq!(validate_layout((3, 16, 1), 0, None), None);
  939. // Unaligned stride, source offset, or count offset.
  940. assert_eq!(validate_layout((0, 18, 1), 0, None), None);
  941. assert_eq!(validate_layout((0, 16, 1), 2, None), None);
  942. assert_eq!(validate_layout((0, 16, 1), 0, Some(6)), None);
  943. // Total byte size exceeding 32-bit ByteAddressBuffer indexing.
  944. assert_eq!(validate_layout((1, 20, u32::MAX), 0, None), None);
  945. }
  946. /// WARP D3D12 execution test proving:
  947. /// (a) `countBuffer` with a small count (`3`) and `4,093` garbage tail slots
  948. /// (`max = 4096`) does NOT blow `BUDGET` or zero valid dispatches in
  949. /// this or subsequent `ExecuteIndirect` calls in the same list,
  950. /// (b) `src_args` (and `count_buf`) are NOT mutated in-place, and
  951. /// (c) full `stride` bytes (`stride = 24` > `12`) are copied for active
  952. /// records into `dst_args` at offset `0`.
  953. #[test]
  954. fn warp_count_buffer_ignores_garbage_tail_and_preserves_source() {
  955. let Some(mut warp) = WarpHarness::new() else {
  956. return;
  957. };
  958. const KIND_DISPATCH: u32 = 2;
  959. const STRIDE: u32 = 24; // 6 dwords: 3 dispatch group counts + 3 extra payload dwords
  960. const MAX: u32 = 4096;
  961. const ARGS_OFFSET: usize = 64; // non-zero offset with sentinel prefix
  962. const COUNT_OFFSET_1: usize = 128;
  963. const COUNT_OFFSET_2: usize = 192;
  964. let src_bytes = ARGS_OFFSET + (STRIDE as usize) * (MAX as usize) + 64;
  965. let (src_buf, src_ptr, _) = warp.shared_buffer(src_bytes as u64);
  966. let (count_buf, count_ptr, _) = warp.shared_buffer(512);
  967. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  968. let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256);
  969. let (readback_buf, readback_ptr, _) = warp.shared_buffer((STRIDE * 8) as u64);
  970. let dst_buf = warp.default_uav(u64::from(STRIDE) * u64::from(MAX));
  971. let sig = warp.signature(KIND_DISPATCH, STRIDE);
  972. // Fill the entire source buffer with non-zero sentinel bytes, then
  973. // populate 3 valid records at `ARGS_OFFSET` and 4,093 huge garbage
  974. // records in `3..MAX` that would exhaust `BUDGET` ~2,000x over if read.
  975. let mut initial_src = vec![0xA5u8; src_bytes];
  976. let write_record = |buf: &mut [u8], idx: usize, words: [u32; 6]| {
  977. let base = ARGS_OFFSET + idx * (STRIDE as usize);
  978. for (w, val) in words.into_iter().enumerate() {
  979. buf[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
  980. }
  981. };
  982. write_record(
  983. &mut initial_src,
  984. 0,
  985. [3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666],
  986. );
  987. write_record(
  988. &mut initial_src,
  989. 1,
  990. [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC],
  991. );
  992. // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1).
  993. write_record(
  994. &mut initial_src,
  995. 2,
  996. [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567],
  997. );
  998. for slot in 3..MAX as usize {
  999. // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups
  1000. // (`cost = 67,107,840 ~= BUDGET / 2`), exhausting `BUDGET` immediately!
  1001. write_record(
  1002. &mut initial_src,
  1003. slot,
  1004. [0xFFFF_FFFF, 16, 1, 0xDEAD_BEEF, 0xBAD0_C0DE, slot as u32],
  1005. );
  1006. }
  1007. // Second indirect call's source records (at offset 0 of a second buffer,
  1008. // or later in `count_buf`): put 2 active records + garbage tail in a
  1009. // second range to run back-to-back in the SAME command list.
  1010. let mut initial_count = vec![0x5Au8; 512];
  1011. initial_count[COUNT_OFFSET_1..COUNT_OFFSET_1 + 4].copy_from_slice(&3u32.to_le_bytes());
  1012. initial_count[COUNT_OFFSET_2..COUNT_OFFSET_2 + 4].copy_from_slice(&2u32.to_le_bytes());
  1013. // SAFETY: buffers are mapped with exact capacities above.
  1014. unsafe {
  1015. std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, src_bytes);
  1016. std::ptr::copy_nonoverlapping(initial_count.as_ptr(), count_ptr, 512);
  1017. (budget_ptr as *mut u32).write_volatile(0);
  1018. (hits_ptr as *mut u32).write_volatile(0);
  1019. std::ptr::write_bytes(readback_ptr, 0, (STRIDE * 8) as usize);
  1020. }
  1021. // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first
  1022. // 5 records of `dst_buf` out for inspection, then record Call #2
  1023. // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list!
  1024. assert!(record_clamp_as(
  1025. &warp.clamp,
  1026. &warp.list,
  1027. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1028. budget_gpu,
  1029. (&src_buf, ARGS_OFFSET as u64),
  1030. Some((&count_buf, COUNT_OFFSET_1 as u64)),
  1031. (KIND_DISPATCH, STRIDE, MAX),
  1032. false,
  1033. ));
  1034. // SAFETY: open command list, valid worker PSO/root and buffers.
  1035. unsafe {
  1036. warp.list.SetComputeRootSignature(&warp.worker.root);
  1037. warp.list.SetPipelineState(&warp.worker.pso);
  1038. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1039. warp.list.ExecuteIndirect(
  1040. &sig,
  1041. MAX,
  1042. &dst_buf,
  1043. 0,
  1044. Some(&count_buf),
  1045. COUNT_OFFSET_1 as u64,
  1046. );
  1047. }
  1048. // Snapshot `dst_buf` after Call #1 (copy 5 * STRIDE bytes, then leave
  1049. // `dst_buf` readable as arguments again, as the clamp left it).
  1050. // SAFETY: open command list; the clamp left `dst_buf` in `INDIRECT_ARGUMENT`.
  1051. unsafe {
  1052. warp.list.ResourceBarrier(&[transition(
  1053. &dst_buf,
  1054. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1055. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1056. )]);
  1057. warp.list
  1058. .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, u64::from(STRIDE * 5));
  1059. warp.list.ResourceBarrier(&[transition(
  1060. &dst_buf,
  1061. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1062. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1063. )]);
  1064. }
  1065. // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1:
  1066. // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`!
  1067. // The scratch buffer goes straight from arguments back to unordered
  1068. // access.
  1069. assert!(record_clamp_as(
  1070. &warp.clamp,
  1071. &warp.list,
  1072. (&dst_buf, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT),
  1073. budget_gpu,
  1074. (&src_buf, ARGS_OFFSET as u64),
  1075. Some((&count_buf, COUNT_OFFSET_2 as u64)),
  1076. (KIND_DISPATCH, STRIDE, MAX),
  1077. false,
  1078. ));
  1079. // SAFETY: open command list, valid worker PSO/root and buffers.
  1080. unsafe {
  1081. warp.list.SetComputeRootSignature(&warp.worker.root);
  1082. warp.list.SetPipelineState(&warp.worker.pso);
  1083. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1084. warp.list.ExecuteIndirect(
  1085. &sig,
  1086. MAX,
  1087. &dst_buf,
  1088. 0,
  1089. Some(&count_buf),
  1090. COUNT_OFFSET_2 as u64,
  1091. );
  1092. }
  1093. warp.submit_and_wait();
  1094. // SAFETY: GPU execution finished; read mapped host results.
  1095. let (hits, spent, after_src, after_count, clamped_words) = unsafe {
  1096. let hits = (hits_ptr as *const u32).read_volatile();
  1097. let spent = (budget_ptr as *const u32).read_volatile();
  1098. let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), src_bytes).to_vec();
  1099. let after_count = std::slice::from_raw_parts(count_ptr.cast_const(), 512).to_vec();
  1100. let words = std::slice::from_raw_parts(
  1101. readback_ptr.cast::<u32>().cast_const(),
  1102. (STRIDE as usize / 4) * 5,
  1103. )
  1104. .to_vec();
  1105. (hits, spent, after_src, after_count, words)
  1106. };
  1107. // Call #1: (3*2*1) + (5*1*1) + (65535*1*1) = 65,546 groups.
  1108. // Call #2: (3*2*1) + (5*1*1) = 11 groups.
  1109. let expected_groups = (6 + 5 + 65_535) + (6 + 5);
  1110. assert_eq!(
  1111. hits, expected_groups,
  1112. "valid indirect dispatches must all execute"
  1113. );
  1114. assert_eq!(
  1115. spent,
  1116. expected_groups * 64,
  1117. "budget must reflect only active records below countBuffer"
  1118. );
  1119. assert_eq!(
  1120. after_src, initial_src,
  1121. "src_args must never be mutated in-place"
  1122. );
  1123. assert_eq!(
  1124. after_count, initial_count,
  1125. "count_buf must never be mutated"
  1126. );
  1127. // Check `dst_args` records 0..3: clamped group counts + preserved extra stride words.
  1128. assert_eq!(
  1129. &clamped_words[0..6],
  1130. &[3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666]
  1131. );
  1132. assert_eq!(
  1133. &clamped_words[6..12],
  1134. &[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC]
  1135. );
  1136. assert_eq!(
  1137. &clamped_words[12..18],
  1138. &[65_535, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567]
  1139. );
  1140. // Inactive slot 3 was never copied from `src_args`.
  1141. assert_ne!(clamped_words[21], 0xDEAD_BEEF);
  1142. }
  1143. /// WARP D3D12 test proving `BUDGET` saturates without 32-bit unsigned
  1144. /// wraparound across >64 huge indexed-draw records (`count = None`), while
  1145. /// preserving `StartIndexLocation`, `BaseVertexLocation`,
  1146. /// `StartInstanceLocation`, and custom stride padding, and leaving
  1147. /// `src_args` untouched.
  1148. /// A window of mesh records clamped ahead: the filled ones come out as
  1149. /// they are and are charged, the slots of all ones come out empty and
  1150. /// charge nothing; clamped as single records the same slots are clamped
  1151. /// to the most and spend the budget.
  1152. #[test]
  1153. fn warp_window_leaves_unfilled_slots_empty_and_uncharged() {
  1154. let Some(mut warp) = WarpHarness::new() else {
  1155. return;
  1156. };
  1157. const KIND_MESH: u32 = 10;
  1158. const STRIDE: u32 = 32;
  1159. const RECORDS: u32 = 16;
  1160. let filled = [5u32, 0, 519];
  1161. let total = (STRIDE * RECORDS) as usize;
  1162. let mut src = vec![0xffu8; total];
  1163. for (i, groups) in filled.into_iter().enumerate() {
  1164. let words = [groups, 1, 1, 0xAB00 + i as u32];
  1165. for (w, word) in words.into_iter().enumerate() {
  1166. let at = i * STRIDE as usize + w * 4;
  1167. src[at..at + 4].copy_from_slice(&word.to_le_bytes());
  1168. }
  1169. }
  1170. for ahead in [true, false] {
  1171. let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64);
  1172. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1173. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64);
  1174. let dst_buf = warp.default_uav(total as u64);
  1175. // SAFETY: mapped buffers of these sizes.
  1176. unsafe {
  1177. std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total);
  1178. std::ptr::write_bytes(budget_ptr, 0, 256);
  1179. std::ptr::write_bytes(readback_ptr, 0, total);
  1180. }
  1181. assert!(record_clamp_as(
  1182. &warp.clamp,
  1183. &warp.list,
  1184. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1185. budget_gpu,
  1186. (&src_buf, 0),
  1187. None,
  1188. (KIND_MESH, STRIDE, RECORDS),
  1189. ahead,
  1190. ));
  1191. // SAFETY: an open list; the scratch buffer, which the clamp left
  1192. // readable as arguments, is copied for the check.
  1193. unsafe {
  1194. warp.list.ResourceBarrier(&[transition(
  1195. &dst_buf,
  1196. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1197. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1198. )]);
  1199. warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64);
  1200. }
  1201. warp.submit_and_wait();
  1202. // SAFETY: the work is done; mapped buffers.
  1203. let (spent, largest, out) = unsafe {
  1204. (
  1205. (budget_ptr as *const u32).read_volatile(),
  1206. (budget_ptr as *const u32).add(1).read_volatile(),
  1207. std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4).to_vec(),
  1208. )
  1209. };
  1210. for (i, groups) in filled.into_iter().enumerate() {
  1211. let rec = &out[i * 8..i * 8 + 4];
  1212. assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}");
  1213. }
  1214. let charged_filled = (5 + 519) * 128;
  1215. if ahead {
  1216. for i in filled.len()..RECORDS as usize {
  1217. assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty");
  1218. assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are");
  1219. }
  1220. assert_eq!(spent, charged_filled, "unfilled slots charge nothing");
  1221. assert_eq!(largest, 519, "and are not counted as asked for");
  1222. } else {
  1223. // Thirteen slots at 65,535 groups: sixteen would be all of it.
  1224. assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most");
  1225. assert_eq!(largest, u32::MAX);
  1226. }
  1227. }
  1228. }
  1229. #[test]
  1230. fn warp_budget_saturates_without_wraparound_and_preserves_draw_fields() {
  1231. let Some(mut warp) = WarpHarness::new() else {
  1232. return;
  1233. };
  1234. const KIND_INDEXED: u32 = 1;
  1235. const STRIDE: u32 = 24; // 5 indexed-draw words + 1 trailing custom word
  1236. const RECORDS: u32 = 128; // 2 waves of 64: old InterlockedAdd wrapped 2^32 at 64!
  1237. const BUDGET_CAP: u32 = 1 << 27;
  1238. let total_bytes = (STRIDE * RECORDS) as usize;
  1239. let (src_buf, src_ptr, _) = warp.shared_buffer(total_bytes as u64);
  1240. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1241. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total_bytes as u64);
  1242. let dst_buf = warp.default_uav(total_bytes as u64);
  1243. let mut initial_src = vec![0u8; total_bytes];
  1244. for i in 0..RECORDS as usize {
  1245. let words: [u32; 6] = [
  1246. u32::MAX, // IndexCount -> clamps to 1 << 24
  1247. u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26)
  1248. 1000 + i as u32, // StartIndexLocation
  1249. (-200i32 + i as i32) as u32, // BaseVertexLocation
  1250. 5000 + i as u32, // StartInstanceLocation
  1251. 0xCAFE_0000 | (i as u32), // Extra stride word
  1252. ];
  1253. let base = i * (STRIDE as usize);
  1254. for (w, val) in words.into_iter().enumerate() {
  1255. initial_src[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes());
  1256. }
  1257. }
  1258. // SAFETY: mapped buffers have sufficient capacity.
  1259. unsafe {
  1260. std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, total_bytes);
  1261. (budget_ptr as *mut u32).write_volatile(0);
  1262. std::ptr::write_bytes(readback_ptr, 0, total_bytes);
  1263. }
  1264. assert!(record_clamp_as(
  1265. &warp.clamp,
  1266. &warp.list,
  1267. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1268. budget_gpu,
  1269. (&src_buf, 0),
  1270. None,
  1271. (KIND_INDEXED, STRIDE, RECORDS),
  1272. false,
  1273. ));
  1274. // SAFETY: open command list; copy clamped scratch buffer (left
  1275. // readable as arguments) for verification.
  1276. unsafe {
  1277. warp.list.ResourceBarrier(&[transition(
  1278. &dst_buf,
  1279. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1280. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1281. )]);
  1282. warp.list
  1283. .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64);
  1284. }
  1285. warp.submit_and_wait();
  1286. // SAFETY: GPU work completed.
  1287. let (spent, after_src, out_words) = unsafe {
  1288. let spent = (budget_ptr as *const u32).read_volatile();
  1289. let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), total_bytes).to_vec();
  1290. let out_words = std::slice::from_raw_parts(
  1291. readback_ptr.cast::<u32>().cast_const(),
  1292. total_bytes / 4,
  1293. )
  1294. .to_vec();
  1295. (spent, after_src, out_words)
  1296. };
  1297. assert_eq!(
  1298. spent, BUDGET_CAP,
  1299. "budget must saturate at BUDGET without wrapping"
  1300. );
  1301. assert_eq!(after_src, initial_src, "src_args must remain untouched");
  1302. let mut kept = 0usize;
  1303. let mut zeroed = 0usize;
  1304. for i in 0..RECORDS as usize {
  1305. let rec = &out_words[i * 6..(i + 1) * 6];
  1306. if rec[0] == (1 << 24) && rec[1] == 4 {
  1307. kept += 1;
  1308. } else {
  1309. assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed");
  1310. zeroed += 1;
  1311. }
  1312. assert_eq!(rec[2], 1000 + i as u32);
  1313. assert_eq!(rec[3], (-200i32 + i as i32) as u32);
  1314. assert_eq!(rec[4], 5000 + i as u32);
  1315. assert_eq!(rec[5], 0xCAFE_0000 | (i as u32));
  1316. }
  1317. assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2));
  1318. }
  1319. /// Exercises `HostList::indirect_scratch`, `bound`, the scratch buffer's
  1320. /// tracked state, `Host::execute`, and `HostList::reset` end-to-end on
  1321. /// the host device.
  1322. #[test]
  1323. fn host_list_reuses_and_grows_scratch_across_submissions() {
  1324. let Some(host) = super::host() else {
  1325. return;
  1326. };
  1327. // What earlier tests left in the debug layer's queue, if it is on.
  1328. let _ = host.log_messages();
  1329. let Ok(list) = host.new_list() else {
  1330. return;
  1331. };
  1332. let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else {
  1333. return;
  1334. };
  1335. let Some((count_buf, count_ptr)) = host.shared_buffer(256) else {
  1336. return;
  1337. };
  1338. // SAFETY: mapped host buffers.
  1339. unsafe {
  1340. std::ptr::write_bytes(src_ptr, 0x7F, 256 << 10);
  1341. (count_ptr as *mut u32).write_volatile(2);
  1342. }
  1343. let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  1344. // First two calls fit inside the initial 64 KiB scratch buffer and
  1345. // must reuse the exact same `ID3D12Resource`, which stays readable
  1346. // as arguments between them.
  1347. let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap();
  1348. assert_eq!(
  1349. list.indirect_state(&b1),
  1350. args,
  1351. "a clamp leaves the scratch readable as arguments"
  1352. );
  1353. let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap();
  1354. assert_eq!(
  1355. b1.as_raw(),
  1356. b2.as_raw(),
  1357. "scratch buffer within capacity must be reused"
  1358. );
  1359. assert_eq!(list.indirect_state(&b2), args);
  1360. // A call needing >64 KiB grows the scratch buffer mid-list while keeping
  1361. // `b1` alive until reset. The new buffer starts out common.
  1362. let grown = list.indirect_scratch(5000 * 20).unwrap();
  1363. assert_eq!(
  1364. list.indirect_state(&grown),
  1365. D3D12_RESOURCE_STATE_COMMON,
  1366. "a new scratch buffer is common"
  1367. );
  1368. let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap();
  1369. assert_eq!(b3.as_raw(), grown.as_raw());
  1370. assert_ne!(
  1371. b3.as_raw(),
  1372. b1.as_raw(),
  1373. "larger request must grow scratch buffer"
  1374. );
  1375. assert_eq!(list.indirect_state(&b3), args);
  1376. assert_eq!(
  1377. list.indirect_state(&b1),
  1378. D3D12_RESOURCE_STATE_COMMON,
  1379. "the replaced buffer went back to common"
  1380. );
  1381. list.close();
  1382. // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics):
  1383. // every barrier recorded named the state the buffer was in. Read
  1384. // before the submission, which moves the messages to the log.
  1385. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1386. host.execute(&[&list]);
  1387. list.reset();
  1388. // After reset, requests up to the grown high-water mark reuse `b3` with
  1389. // zero new allocations; the buffer decayed to common when the
  1390. // submission ran.
  1391. assert_eq!(
  1392. list.indirect_state(&b3),
  1393. D3D12_RESOURCE_STATE_COMMON,
  1394. "a reset list starts with a common scratch buffer"
  1395. );
  1396. let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap();
  1397. assert_eq!(
  1398. b4.as_raw(),
  1399. b3.as_raw(),
  1400. "grown scratch buffer must persist across reset"
  1401. );
  1402. assert_eq!(list.indirect_state(&b4), args);
  1403. list.close();
  1404. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1405. host.execute(&[&list]);
  1406. list.reset();
  1407. }
  1408. /// A group charges its records in lane order: with 300 left of the
  1409. /// budget, the first draw (100) fits, the second (250) does not and
  1410. /// takes the rest, and the ones after it run empty. (Racing for the
  1411. /// word record by record, which of them fitted was up to the GPU.)
  1412. #[test]
  1413. fn warp_a_group_charges_its_records_in_lane_order() {
  1414. let Some(mut warp) = WarpHarness::new() else {
  1415. return;
  1416. };
  1417. const KIND_DRAW: u32 = 0;
  1418. const STRIDE: u32 = 16;
  1419. const BUDGET_CAP: u32 = 1 << 27;
  1420. let counts = [100u32, 250, 50, 100];
  1421. let total = counts.len() * STRIDE as usize;
  1422. let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64);
  1423. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1424. let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64);
  1425. let dst_buf = warp.default_uav(total as u64);
  1426. // SAFETY: mapped buffers of these sizes.
  1427. unsafe {
  1428. for (i, &count) in counts.iter().enumerate() {
  1429. let words = [count, 1, 7, 9];
  1430. std::ptr::copy_nonoverlapping(
  1431. words.as_ptr().cast::<u8>(),
  1432. src_ptr.add(i * STRIDE as usize),
  1433. 16,
  1434. );
  1435. }
  1436. std::ptr::write_bytes(budget_ptr, 0, 256);
  1437. (budget_ptr as *mut u32).write_volatile(BUDGET_CAP - 300);
  1438. }
  1439. assert!(record_clamp_as(
  1440. &warp.clamp,
  1441. &warp.list,
  1442. (&dst_buf, D3D12_RESOURCE_STATE_COMMON),
  1443. budget_gpu,
  1444. (&src_buf, 0),
  1445. None,
  1446. (KIND_DRAW, STRIDE, counts.len() as u32),
  1447. false,
  1448. ));
  1449. // SAFETY: an open list; the clamped records are copied for the check.
  1450. unsafe {
  1451. warp.list.ResourceBarrier(&[transition(
  1452. &dst_buf,
  1453. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  1454. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1455. )]);
  1456. warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64);
  1457. }
  1458. warp.submit_and_wait();
  1459. // SAFETY: the work is done; mapped buffers.
  1460. let (spent, out) = unsafe {
  1461. (
  1462. (budget_ptr as *const u32).read_volatile(),
  1463. std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4)
  1464. .to_vec(),
  1465. )
  1466. };
  1467. assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits");
  1468. for i in 1..counts.len() {
  1469. assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty");
  1470. }
  1471. assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest");
  1472. }
  1473. /// The list's budget starts empty at each submission, wherever it
  1474. /// lives (the card's copy is zeroed in the list): a recording whose
  1475. /// clamps spend all of it is followed, after the reset, by one whose
  1476. /// small record still runs.
  1477. #[test]
  1478. fn host_list_budget_starts_empty_at_each_submission() {
  1479. let Some(host) = super::host() else {
  1480. return;
  1481. };
  1482. let Ok(list) = host.new_list() else {
  1483. return;
  1484. };
  1485. let _ = host.log_messages();
  1486. let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
  1487. const KIND_DISPATCH: u32 = 2;
  1488. const STRIDE: u32 = 12;
  1489. let signature = {
  1490. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  1491. Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32),
  1492. ..Default::default()
  1493. };
  1494. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  1495. ByteStride: STRIDE,
  1496. NumArgumentDescs: 1,
  1497. pArgumentDescs: &arg,
  1498. NodeMask: 0,
  1499. };
  1500. let mut sig: Option<ID3D12CommandSignature> = None;
  1501. // SAFETY: a valid single-argument command signature description.
  1502. unsafe {
  1503. host.device
  1504. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  1505. .unwrap();
  1506. }
  1507. sig.unwrap()
  1508. };
  1509. // Three records of 65,535 x 16 groups: about half the budget each.
  1510. let Some((big, big_ptr)) = host.shared_buffer(3 * u64::from(STRIDE)) else {
  1511. return;
  1512. };
  1513. let Some((small, small_ptr)) = host.shared_buffer(u64::from(STRIDE)) else {
  1514. return;
  1515. };
  1516. let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
  1517. return;
  1518. };
  1519. // SAFETY: mapped buffers of these sizes; nothing runs yet.
  1520. unsafe {
  1521. for i in 0..3 {
  1522. let words = [65535u32, 16, 1];
  1523. std::ptr::copy_nonoverlapping(
  1524. words.as_ptr().cast::<u8>(),
  1525. big_ptr.add(i * STRIDE as usize),
  1526. 12,
  1527. );
  1528. }
  1529. std::ptr::copy_nonoverlapping([1u32, 1, 1].as_ptr().cast::<u8>(), small_ptr, 12);
  1530. std::ptr::write_bytes(hits_ptr, 0, 256);
  1531. }
  1532. // SAFETY: a live buffer.
  1533. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
  1534. for round in 0..2 {
  1535. // Spends the budget (clamped, not executed), then one group.
  1536. bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3)).unwrap();
  1537. let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap();
  1538. // SAFETY: an open list; the worker's root signature and
  1539. // pipeline; buffers the test holds until the list has run.
  1540. unsafe {
  1541. list.list.SetComputeRootSignature(&worker.root);
  1542. list.list.SetPipelineState(&worker.pso);
  1543. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1544. list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0);
  1545. }
  1546. list.close();
  1547. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1548. host.execute(&[&list]);
  1549. list.reset();
  1550. // SAFETY: the list has run; a mapped buffer.
  1551. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  1552. // The small record comes after the big ones spent the budget:
  1553. // it runs empty, in every round alike (none carries over).
  1554. assert_eq!(hits, 0, "round {round}: the spent budget empties the record after it");
  1555. }
  1556. // A recording with only the small record: the budget is empty
  1557. // again, so it runs.
  1558. let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap();
  1559. // SAFETY: as above.
  1560. unsafe {
  1561. list.list.SetComputeRootSignature(&worker.root);
  1562. list.list.SetPipelineState(&worker.pso);
  1563. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1564. list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0);
  1565. }
  1566. list.close();
  1567. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1568. host.execute(&[&list]);
  1569. list.reset();
  1570. // SAFETY: the list has run; a mapped buffer.
  1571. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  1572. assert_eq!(hits, 1, "the budget starts empty at the next submission");
  1573. }
  1574. /// Records the dispatch records `groups` (three words each, `step`
  1575. /// bytes apart, the rest of each record ones) into a fresh mapped
  1576. /// buffer of `warp`'s device.
  1577. fn dispatch_records(warp: &WarpHarness, groups: &[u32], step: u32) -> ID3D12Resource {
  1578. let total = groups.len() * step as usize;
  1579. let (buffer, ptr, _) = warp.shared_buffer(total as u64);
  1580. let mut bytes = vec![0xffu8; total];
  1581. for (i, &g) in groups.iter().enumerate() {
  1582. for (w, word) in [g, 1, 1].into_iter().enumerate() {
  1583. let at = i * step as usize + w * 4;
  1584. bytes[at..at + 4].copy_from_slice(&word.to_le_bytes());
  1585. }
  1586. }
  1587. // SAFETY: the mapping holds `total` bytes.
  1588. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) };
  1589. buffer
  1590. }
  1591. /// Two windows in one list, as `crate::draw` records them: each clamps
  1592. /// its records ahead, then one execution per record reads the scratch
  1593. /// buffer with no barrier between them; the second clamp moves the
  1594. /// scratch buffer straight from arguments back to unordered access.
  1595. /// Every record runs once, with the group count it asked for.
  1596. #[test]
  1597. fn warp_window_executions_read_their_records_with_no_barrier_between() {
  1598. let Some(mut warp) = WarpHarness::new() else {
  1599. return;
  1600. };
  1601. const KIND_DISPATCH: u32 = 2;
  1602. // The title names 12 bytes and keeps its records 32 apart.
  1603. const STRIDE: u32 = 12;
  1604. const STEP: u32 = 32;
  1605. let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]];
  1606. let sources: Vec<ID3D12Resource> =
  1607. windows.iter().map(|g| dispatch_records(&warp, g, STEP)).collect();
  1608. let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1609. let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256);
  1610. let dst_buf = warp.default_uav(u64::from(STEP) * 4);
  1611. let sig = warp.signature(KIND_DISPATCH, STRIDE);
  1612. // SAFETY: mapped buffers of these sizes.
  1613. unsafe {
  1614. std::ptr::write_bytes(budget_ptr, 0, 256);
  1615. std::ptr::write_bytes(hits_ptr, 0, 256);
  1616. }
  1617. let mut state = D3D12_RESOURCE_STATE_COMMON;
  1618. for (groups, src) in windows.iter().zip(&sources) {
  1619. assert!(record_clamp_as(
  1620. &warp.clamp,
  1621. &warp.list,
  1622. (&dst_buf, state),
  1623. budget_gpu,
  1624. (src, 0),
  1625. None,
  1626. (KIND_DISPATCH, STEP, groups.len() as u32),
  1627. true,
  1628. ));
  1629. state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  1630. // SAFETY: an open list; the worker's root signature and
  1631. // pipeline; the scratch buffer is readable as arguments.
  1632. unsafe {
  1633. warp.list.SetComputeRootSignature(&warp.worker.root);
  1634. warp.list.SetPipelineState(&warp.worker.pso);
  1635. warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1636. for i in 0..groups.len() as u64 {
  1637. warp.list.ExecuteIndirect(&sig, 1, &dst_buf, i * u64::from(STEP), None, 0);
  1638. }
  1639. }
  1640. }
  1641. warp.submit_and_wait();
  1642. // SAFETY: the work is done; mapped buffers.
  1643. let (hits, spent) = unsafe {
  1644. (
  1645. (hits_ptr as *const u32).read_volatile(),
  1646. (budget_ptr as *const u32).read_volatile(),
  1647. )
  1648. };
  1649. let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum();
  1650. assert_eq!(hits, expected, "every record of both windows runs once");
  1651. assert_eq!(spent, expected * 64, "and is charged what it asked for");
  1652. }
  1653. /// The windows of `warp_window_executions_read_their_records_with_no_barrier_between`
  1654. /// through a host list (`bound_ahead`, the list's tracked scratch state,
  1655. /// `Host::execute`), twice: on the first recording the scratch buffer
  1656. /// starts common, on the second (after the reset) it starts common
  1657. /// again. With the debug layer on (`VICTORY_D3D12_DEBUG=1` in a
  1658. /// diagnostics build) no barrier names a state the buffer is not in.
  1659. #[test]
  1660. fn host_list_window_executions_need_no_barrier_of_their_own() {
  1661. let Some(host) = super::host() else {
  1662. return;
  1663. };
  1664. // What earlier tests left in the debug layer's queue, if it is on.
  1665. let _ = host.log_messages();
  1666. let Ok(list) = host.new_list() else {
  1667. return;
  1668. };
  1669. let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
  1670. const KIND_DISPATCH: u32 = 2;
  1671. const STRIDE: u32 = 12;
  1672. const STEP: u32 = 32;
  1673. let signature = {
  1674. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  1675. Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32),
  1676. ..Default::default()
  1677. };
  1678. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  1679. ByteStride: STRIDE,
  1680. NumArgumentDescs: 1,
  1681. pArgumentDescs: &arg,
  1682. NodeMask: 0,
  1683. };
  1684. let mut sig: Option<ID3D12CommandSignature> = None;
  1685. // SAFETY: a valid single-argument command signature description.
  1686. unsafe {
  1687. host.device
  1688. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig)
  1689. .unwrap();
  1690. }
  1691. sig.unwrap()
  1692. };
  1693. let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]];
  1694. let mut sources = Vec::new();
  1695. for groups in windows {
  1696. let total = groups.len() * STEP as usize;
  1697. let Some((buffer, ptr)) = host.shared_buffer(total as u64) else {
  1698. return;
  1699. };
  1700. let mut bytes = vec![0xffu8; total];
  1701. for (i, &g) in groups.iter().enumerate() {
  1702. for (w, word) in [g, 1, 1].into_iter().enumerate() {
  1703. let at = i * STEP as usize + w * 4;
  1704. bytes[at..at + 4].copy_from_slice(&word.to_le_bytes());
  1705. }
  1706. }
  1707. // SAFETY: the mapping holds `total` bytes.
  1708. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) };
  1709. sources.push(buffer);
  1710. }
  1711. let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
  1712. return;
  1713. };
  1714. let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum();
  1715. // SAFETY: a live buffer.
  1716. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
  1717. for _ in 0..2 {
  1718. // SAFETY: the mapping holds 256 bytes; nothing runs.
  1719. unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) };
  1720. for (groups, src) in windows.iter().zip(&sources) {
  1721. let spec = (KIND_DISPATCH, STEP, groups.len() as u32);
  1722. let scratch = bound_ahead(&list, (src, 0), spec).unwrap();
  1723. assert_eq!(list.indirect_state(&scratch), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
  1724. // SAFETY: an open list; the worker's root signature and
  1725. // pipeline; buffers the test holds until the list has run.
  1726. unsafe {
  1727. list.list.SetComputeRootSignature(&worker.root);
  1728. list.list.SetPipelineState(&worker.pso);
  1729. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1730. for i in 0..groups.len() as u64 {
  1731. let at = i * u64::from(STEP);
  1732. list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0);
  1733. }
  1734. }
  1735. }
  1736. list.close();
  1737. // With the debug layer on: nothing it objects to was recorded.
  1738. // Read before the submission, which moves the messages to the log.
  1739. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1740. host.execute(&[&list]);
  1741. list.reset();
  1742. // SAFETY: the list has run; a mapped buffer.
  1743. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  1744. assert_eq!(hits, expected, "every record of both windows runs once");
  1745. }
  1746. }
  1747. /// A command signature of one argument of `kind` on `device`.
  1748. fn one_argument(device: &ID3D12Device, kind: u32, stride: u32) -> ID3D12CommandSignature {
  1749. let arg = D3D12_INDIRECT_ARGUMENT_DESC {
  1750. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  1751. ..Default::default()
  1752. };
  1753. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  1754. ByteStride: stride,
  1755. NumArgumentDescs: 1,
  1756. pArgumentDescs: &arg,
  1757. NodeMask: 0,
  1758. };
  1759. let mut sig: Option<ID3D12CommandSignature> = None;
  1760. // SAFETY: a valid single-argument command signature description.
  1761. unsafe {
  1762. device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig).unwrap();
  1763. }
  1764. sig.unwrap()
  1765. }
  1766. /// What a batch's table says of records added to it: one job per
  1767. /// record, charged for every execution that reads it, and none for what
  1768. /// the pass cannot read.
  1769. #[test]
  1770. fn batch_tables() {
  1771. use batch::{JOBS, SLOT, TABLE, TIMES, Table, job};
  1772. let mut memory = vec![0xffff_ffffu32; TABLE as usize / 4 + 1];
  1773. // SAFETY: the vector holds the table and outlives its use.
  1774. let mut t = unsafe { Table::new(memory.as_mut_ptr().cast(), 4096, [7, 9, 0, 0]) };
  1775. assert_eq!(t.place(7, 64, 10), Some(4096));
  1776. assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT)));
  1777. assert_eq!(t.place(7, 64, 2), Some(4096 + 2 * u64::from(SLOT)), "another kind is another record");
  1778. // The same record again: the same place, charged twice.
  1779. assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT)));
  1780. assert_eq!(&memory[..4], [3, 0xffff_ffff, 0xffff_ffff, 0xffff_ffff]);
  1781. assert_eq!(memory[4..8], [job(0, 10, 1), 64, 4096, 0]);
  1782. assert_eq!(memory[8..12], [job(1, 10, 2), 64, 4096 + SLOT, 0]);
  1783. assert_eq!(job(1, 10, 2), 1 | 10 << 4 | 3 << 8 | 2 << 16);
  1784. // Not a copy of the pass, not on 4 bytes, past 32 bits, not a kind.
  1785. for (id, offset, kind) in [(8, 64, 10), (7, 66, 10), (7, 1 << 32, 10), (7, u64::from(u32::MAX) & !3, 10), (7, 64, 3)] {
  1786. assert_eq!(t.place(id, offset, kind), None);
  1787. }
  1788. // Read more often than one job may be charged for: another job.
  1789. for _ in 1..TIMES {
  1790. assert_eq!(t.place(7, 64, 10), Some(4096));
  1791. }
  1792. assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT)));
  1793. assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT)));
  1794. for i in 4..u64::from(JOBS) {
  1795. assert_eq!(t.place(7, 1024 + 16 * i, 0), Some(4096 + i * u64::from(SLOT)));
  1796. }
  1797. assert_eq!(t.place(7, 1024, 1), None, "full");
  1798. assert_eq!(t.place(7, 1024 + 16 * 5, 0), Some(4096 + 5 * u64::from(SLOT)));
  1799. assert_eq!((memory[0], memory[TABLE as usize / 4]), (JOBS, 0xffff_ffff));
  1800. }
  1801. /// A batch clamps records exactly as the clamp of one execution does, of
  1802. /// any kind, sensible or not; they are added to its table after the pass
  1803. /// was recorded; it charges each as often as it is read.
  1804. #[test]
  1805. fn warp_batch_clamps_as_the_clamp_of_one_does() {
  1806. let Some(mut warp) = WarpHarness::new() else {
  1807. return;
  1808. };
  1809. let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP");
  1810. let kinds = [0u32, 1, 2, 10];
  1811. let values = [0u32, 1, 3, 100, 65_535, 65_536, 1 << 20, 1 << 24, (1 << 26) + 1, u32::MAX];
  1812. // Every kind with many records, in two sources.
  1813. let mut records: Vec<(u32, [u32; 5])> = Vec::new();
  1814. for kind in kinds {
  1815. for (i, a) in values.into_iter().enumerate() {
  1816. for (k, b) in values.into_iter().enumerate() {
  1817. records.push((kind, [a, b, values[(i * 3 + k) % 4], 77, 0xABCD]));
  1818. }
  1819. }
  1820. }
  1821. // In passes of so few that the budget holds whatever one asks for,
  1822. // and one pass of them all, which it does not.
  1823. let (src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10);
  1824. let (_other, other_ptr, other_gpu) = warp.shared_buffer(64 << 10);
  1825. for (i, (_, words)) in records.iter().enumerate() {
  1826. for (w, word) in words.iter().enumerate() {
  1827. // SAFETY: 400 records of 32 bytes in 64 KiB.
  1828. unsafe {
  1829. src_ptr.cast::<u32>().add(i * 8 + w).write_volatile(*word);
  1830. other_ptr.cast::<u32>().add(i * 8 + w).write_volatile(*word);
  1831. }
  1832. }
  1833. }
  1834. let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1835. let (back, back_ptr, _) = warp.shared_buffer(64 << 10);
  1836. let dst = warp.default_uav(64 << 10);
  1837. let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE);
  1838. for (i, (kind, _)) in records.iter().enumerate().step_by(3) {
  1839. let offset = i as u64 * 32;
  1840. let words = batch::words(*kind).unwrap();
  1841. let stride = words * 4;
  1842. let read = |p: *mut u8| -> Vec<u32> {
  1843. // SAFETY: the mapping holds more.
  1844. (0..words as usize).map(|w| unsafe { p.cast::<u32>().add(w).read_volatile() }).collect()
  1845. };
  1846. let mut seen = Vec::new();
  1847. for batched in [false, true] {
  1848. // SAFETY: mapped buffers; nothing runs.
  1849. unsafe { std::ptr::write_bytes(budget_ptr, 0, 256) };
  1850. if batched {
  1851. batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu, other_gpu, src_gpu, src_gpu], table_gpu);
  1852. // SAFETY: the mapped table; the list has not run.
  1853. let mut table = unsafe { batch::Table::new(table_ptr, 0, [1, 2, 0, 0]) };
  1854. assert_eq!(table.place(1 + i as u64 % 2, offset, *kind), Some(0));
  1855. } else {
  1856. assert!(record_clamp_as(
  1857. &warp.clamp,
  1858. &warp.list,
  1859. (&dst, D3D12_RESOURCE_STATE_COMMON),
  1860. budget_gpu,
  1861. (&src, offset),
  1862. None,
  1863. (*kind, stride, 1),
  1864. false,
  1865. ));
  1866. }
  1867. // SAFETY: an open list; the records are readable as arguments.
  1868. unsafe {
  1869. warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
  1870. warp.list.CopyBufferRegion(&back, 0, &dst, 0, u64::from(stride));
  1871. warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]);
  1872. }
  1873. warp.submit_and_wait();
  1874. // SAFETY: the list has run; mapped words.
  1875. let budget: Vec<u32> = (0..3).map(|k| unsafe { budget_ptr.cast::<u32>().add(k).read_volatile() }).collect();
  1876. seen.push((read(back_ptr), budget));
  1877. }
  1878. // (A mesh record that asks for nothing notes nothing.)
  1879. assert_eq!(seen[0], seen[1], "record {i} of kind {kind}: {:?}", records[i].1);
  1880. }
  1881. }
  1882. /// Records past the list's budget come out empty, and one read by many
  1883. /// executions is charged for each.
  1884. #[test]
  1885. fn warp_batch_charges_every_execution() {
  1886. let Some(mut warp) = WarpHarness::new() else {
  1887. return;
  1888. };
  1889. let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP");
  1890. const BUDGET: u32 = 1 << 27;
  1891. // 2^26 vertices each, as much as a draw is let run: two fill it.
  1892. for (times, records, filled) in [(1u32, 3u64, 2usize), (2, 1, 1), (1, 1, 1), (3, 1, 0)] {
  1893. let (_src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10);
  1894. let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256);
  1895. let (back, back_ptr, _) = warp.shared_buffer(1024);
  1896. let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE);
  1897. let dst = warp.default_uav(64 << 10);
  1898. batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu);
  1899. // SAFETY: mapped buffers, which the list has not read yet.
  1900. let mut table = unsafe {
  1901. std::ptr::write_bytes(budget_ptr, 0, 256);
  1902. for r in 0..records {
  1903. for (w, word) in [1u32 << 24, 4, 5, 6].into_iter().enumerate() {
  1904. src_ptr.cast::<u32>().add(r as usize * 4 + w).write_volatile(word);
  1905. }
  1906. }
  1907. batch::Table::new(table_ptr, 0, [1, 0, 0, 0])
  1908. };
  1909. for _ in 0..times {
  1910. for r in 0..records {
  1911. assert_eq!(table.place(1, r * 16, 0), Some(r * u64::from(batch::SLOT)));
  1912. }
  1913. }
  1914. // SAFETY: an open list; the records are readable as arguments.
  1915. unsafe {
  1916. warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
  1917. warp.list.CopyBufferRegion(&back, 0, &dst, 0, 256);
  1918. }
  1919. warp.submit_and_wait();
  1920. // SAFETY: the list has run; mapped words.
  1921. let (spent, out): (u32, Vec<u32>) = unsafe {
  1922. (
  1923. budget_ptr.cast::<u32>().read_volatile(),
  1924. (0..records as usize).map(|r| back_ptr.cast::<u32>().add(r * batch::SLOT as usize / 4).read_volatile()).collect(),
  1925. )
  1926. };
  1927. assert_eq!(out.iter().filter(|&&v| v == 1 << 24).count(), filled, "{times} times {records}: {out:?}");
  1928. assert!(out.iter().all(|&v| v == 0 || v == 1 << 24));
  1929. assert_eq!(spent, BUDGET.min((1 << 26) * times * records as u32));
  1930. }
  1931. }
  1932. /// Two batches through a host list, twice (the second recording finds
  1933. /// the scratch buffer as the first one's end left it): executions with
  1934. /// nothing between them read what they asked for, of two source buffers,
  1935. /// the second batch while the first one's places are still read. With
  1936. /// the debug layer on no barrier names a state the buffer is not in.
  1937. #[test]
  1938. fn host_list_batches() {
  1939. let Some(host) = super::host() else {
  1940. return;
  1941. };
  1942. let _ = host.log_messages();
  1943. let Ok(list) = host.new_list() else {
  1944. return;
  1945. };
  1946. let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
  1947. let signature = one_argument(&host.device, 2, 12);
  1948. let mut sources = Vec::new();
  1949. for first in [1u32, 100] {
  1950. let Some((buffer, ptr)) = host.shared_buffer(1024) else {
  1951. return;
  1952. };
  1953. for i in 0..16u32 {
  1954. for (w, word) in [first + i, 1, 1].into_iter().enumerate() {
  1955. // SAFETY: inside the mapping.
  1956. unsafe { ptr.cast::<u32>().add(i as usize * 8 + w).write_volatile(word) };
  1957. }
  1958. }
  1959. sources.push(buffer);
  1960. }
  1961. let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
  1962. return;
  1963. };
  1964. // SAFETY: a live buffer.
  1965. let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
  1966. for _ in 0..2 {
  1967. // SAFETY: the mapping holds 256 bytes; nothing runs.
  1968. unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) };
  1969. let mut expected = 0;
  1970. // More batches than one scratch buffer holds.
  1971. for k in 0..12u32 {
  1972. let (mut table, scratch) =
  1973. open_batch(&list, (1, &sources[0]), &[(1, sources[0].clone()), (2, sources[1].clone())]).unwrap();
  1974. // SAFETY: an open list; the worker's root signature and
  1975. // pipeline; buffers the test holds until the list has run.
  1976. unsafe {
  1977. list.list.SetComputeRootSignature(&worker.root);
  1978. list.list.SetPipelineState(&worker.pso);
  1979. list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  1980. }
  1981. for (id, record) in [(1u64, 3 + k % 4), (2, 5), (1, 0), (2, 5)] {
  1982. let at = table.place(id, u64::from(record) * 32, 2).unwrap();
  1983. // SAFETY: as above.
  1984. unsafe { list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0) };
  1985. expected += record + if id == 1 { 1 } else { 100 };
  1986. }
  1987. }
  1988. list.close();
  1989. assert_eq!(host.log_messages(), None, "the debug layer found an error");
  1990. host.execute(&[&list]);
  1991. list.reset();
  1992. // SAFETY: the list has run; a mapped buffer.
  1993. let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
  1994. assert_eq!(hits, expected, "every execution runs what it asked for");
  1995. }
  1996. }
  1997. /// What clamps of a frame cost on the card one by one and in batches
  1998. /// (ignored: a measurement): 2,355 executions of an empty dispatch, in
  1999. /// 49 lists' worth of runs, as in the captured frame.
  2000. #[test]
  2001. #[ignore]
  2002. fn batch_costs() {
  2003. let Some(mut gpu) = WarpHarness::on(false) else {
  2004. return;
  2005. };
  2006. const EXECUTIONS: u32 = 2355;
  2007. let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile");
  2008. let sig = gpu.signature(2, 12);
  2009. let groups: Vec<u32> = vec![1; 2048];
  2010. let src = dispatch_records(&gpu, &groups, 32);
  2011. // SAFETY: a live buffer.
  2012. let src_gpu = unsafe { src.GetGPUVirtualAddress() };
  2013. let budget = gpu.default_uav(256);
  2014. let hits = gpu.default_uav(256);
  2015. // SAFETY: live buffers.
  2016. let (budget_gpu, hits_gpu) = unsafe { (budget.GetGPUVirtualAddress(), hits.GetGPUVirtualAddress()) };
  2017. let (_tables, tables_ptr, tables_gpu) = gpu.shared_buffer(batch::TABLE * 2400);
  2018. let dst = gpu.default_uav(4 << 20);
  2019. for run in [0u32, 2355 / 49, 5, 1] {
  2020. let mut best = f64::MAX;
  2021. for _ in 0..6 {
  2022. let mut state = D3D12_RESOURCE_STATE_COMMON;
  2023. let mut table = batch::Table::default();
  2024. for i in 0..EXECUTIONS {
  2025. if run == 0 {
  2026. assert!(record_clamp_as(&gpu.clamp, &gpu.list, (&dst, state), budget_gpu, (&src, u64::from(i % 2048) * 32), None, (2, 12, 1), false));
  2027. } else if i % run == 0 {
  2028. let k = u64::from(i / run) * batch::TABLE;
  2029. batch::record(&pass, &gpu.list, (&dst, state), budget_gpu, [src_gpu; 4], tables_gpu + k);
  2030. // SAFETY: the mapped table; the list has not run.
  2031. table = unsafe { batch::Table::new(tables_ptr.add(k as usize), 0, [1, 0, 0, 0]) };
  2032. }
  2033. state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  2034. let at = if run == 0 { 0 } else { table.place(1, u64::from(i % 2048) * 32, 2).unwrap() };
  2035. // SAFETY: an open list; live buffers.
  2036. unsafe {
  2037. if run == 0 || i % run == 0 {
  2038. gpu.list.SetComputeRootSignature(&gpu.worker.root);
  2039. gpu.list.SetPipelineState(&gpu.worker.pso);
  2040. gpu.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
  2041. }
  2042. gpu.list.ExecuteIndirect(&sig, 1, &dst, at, None, 0);
  2043. }
  2044. }
  2045. let t = std::time::Instant::now();
  2046. gpu.submit_and_wait();
  2047. best = best.min(t.elapsed().as_secs_f64() * 1e3);
  2048. }
  2049. let what = if run == 0 { "each clamped on its own".to_owned() } else { format!("a batch every {run}") };
  2050. println!("{EXECUTIONS} indirect dispatches, {what}: {best:.2} ms");
  2051. }
  2052. }
  2053. }
  2054. /// The benchmark of the clamp and its barriers (ignored by default).
  2055. #[cfg(test)]
  2056. mod bench;
  2057. /// What one small draw costs this card, bare and with one thing changed
  2058. /// between every two draws: a measurement, not a check (it asserts only
  2059. /// that the card answered). The timing run of the lit scene (run 187) has
  2060. /// some 11,000 small commands a frame at 5 to 16 microseconds each, and no
  2061. /// log says whether that is what we put around a command or what the card
  2062. /// takes for one. Each variant here is 10,000 one-triangle draws into a
  2063. /// 2560x1440 target, timed on the card by one pair of timestamps around
  2064. /// the whole batch (not one per command, which would time the stamps).
  2065. ///
  2066. /// Run by name, no game needed:
  2067. /// `cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture`
  2068. #[cfg(test)]
  2069. mod bare_cost {
  2070. use windows::Win32::Foundation::{HANDLE, RECT};
  2071. use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY};
  2072. use windows::Win32::Graphics::Direct3D12::*;
  2073. use windows::Win32::Graphics::Dxgi::Common::*;
  2074. use windows::Win32::Graphics::Dxgi::*;
  2075. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  2076. use windows::core::{Interface, s};
  2077. use crate::host::{compile, transition};
  2078. /// Draws in a batch.
  2079. const DRAWS: u32 = 10_000;
  2080. const WIDTH: u32 = 2560;
  2081. const HEIGHT: u32 = 1440;
  2082. /// One small triangle in the middle of the target (about 180 pixels),
  2083. /// and two pixel programs that read one texel of a texture through a
  2084. /// table, so that the view heap set is in use.
  2085. const DRAW: &str = r#"
  2086. #define RS "DescriptorTable(SRV(t0))"
  2087. Texture2D<float4> image : register(t0);
  2088. [RootSignature(RS)]
  2089. float4 corner(uint i : SV_VertexID) : SV_Position {
  2090. float2 p = float2((i << 1) & 2, i & 2);
  2091. return float4(p * 0.02 - 0.01, 0.5, 1.0);
  2092. }
  2093. [RootSignature(RS)]
  2094. float4 first(float4 at : SV_Position) : SV_Target {
  2095. return image.Load(int3(0, 0, 0));
  2096. }
  2097. [RootSignature(RS)]
  2098. float4 second(float4 at : SV_Position) : SV_Target {
  2099. return 1.0 - image.Load(int3(0, 0, 0));
  2100. }
  2101. "#;
  2102. /// A compute pass of next to nothing, as our clamp of an indirect
  2103. /// record is: one group of one thread that writes one word.
  2104. const WORK: &str = r#"
  2105. #define RS "UAV(u0)"
  2106. RWByteAddressBuffer words : register(u0);
  2107. [RootSignature(RS)]
  2108. [numthreads(1, 1, 1)]
  2109. void work() {
  2110. words.Store(0, words.Load(0) + 1);
  2111. }
  2112. "#;
  2113. /// What changes between every two draws of a batch.
  2114. #[derive(Clone, Copy, PartialEq)]
  2115. enum Between {
  2116. /// Nothing.
  2117. Nothing,
  2118. /// The pipeline: two alternate.
  2119. Pipeline,
  2120. /// A second texture goes from target to shader read and back.
  2121. BarrierPair,
  2122. /// The depth texture bound for testing goes from write to read or
  2123. /// back.
  2124. DepthMove,
  2125. /// The pair of descriptor heaps: two pairs alternate.
  2126. Heaps,
  2127. /// The colour target: two alternate.
  2128. Targets,
  2129. /// A compute pass of ours of one group, and the pipeline back.
  2130. Compute,
  2131. /// The same between two waits for every earlier shader write, as
  2132. /// the clamp records them.
  2133. ComputeWithWaits,
  2134. }
  2135. struct Rig {
  2136. queue: ID3D12CommandQueue,
  2137. allocator: ID3D12CommandAllocator,
  2138. list: ID3D12GraphicsCommandList,
  2139. fence: ID3D12Fence,
  2140. submitted: u64,
  2141. event: HANDLE,
  2142. root: ID3D12RootSignature,
  2143. pipelines: [ID3D12PipelineState; 2],
  2144. work_root: ID3D12RootSignature,
  2145. work: ID3D12PipelineState,
  2146. words: ID3D12Resource,
  2147. other: ID3D12Resource,
  2148. depth: ID3D12Resource,
  2149. /// Kept alive: the views below name them.
  2150. _kept: Vec<ID3D12Resource>,
  2151. _target_heaps: [ID3D12DescriptorHeap; 2],
  2152. heap_pairs: [[Option<ID3D12DescriptorHeap>; 2]; 2],
  2153. tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2],
  2154. targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2],
  2155. depth_written: D3D12_CPU_DESCRIPTOR_HANDLE,
  2156. depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE,
  2157. stamps: ID3D12QueryHeap,
  2158. back: ID3D12Resource,
  2159. card: String,
  2160. }
  2161. fn texture(
  2162. device: &ID3D12Device,
  2163. (width, height): (u32, u32),
  2164. format: DXGI_FORMAT,
  2165. flags: D3D12_RESOURCE_FLAGS,
  2166. state: D3D12_RESOURCE_STATES,
  2167. ) -> ID3D12Resource {
  2168. let heap = D3D12_HEAP_PROPERTIES {
  2169. Type: D3D12_HEAP_TYPE_DEFAULT,
  2170. ..Default::default()
  2171. };
  2172. let desc = D3D12_RESOURCE_DESC {
  2173. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  2174. Width: u64::from(width),
  2175. Height: height,
  2176. DepthOrArraySize: 1,
  2177. MipLevels: 1,
  2178. Format: format,
  2179. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  2180. Flags: flags,
  2181. ..Default::default()
  2182. };
  2183. let mut out: Option<ID3D12Resource> = None;
  2184. // SAFETY: plain texture creation.
  2185. unsafe {
  2186. device
  2187. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out)
  2188. .unwrap();
  2189. }
  2190. out.unwrap()
  2191. }
  2192. fn buffer(
  2193. device: &ID3D12Device,
  2194. size: u64,
  2195. kind: D3D12_HEAP_TYPE,
  2196. flags: D3D12_RESOURCE_FLAGS,
  2197. state: D3D12_RESOURCE_STATES,
  2198. ) -> ID3D12Resource {
  2199. let heap = D3D12_HEAP_PROPERTIES {
  2200. Type: kind,
  2201. ..Default::default()
  2202. };
  2203. let desc = D3D12_RESOURCE_DESC {
  2204. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  2205. Width: size,
  2206. Height: 1,
  2207. DepthOrArraySize: 1,
  2208. MipLevels: 1,
  2209. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  2210. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  2211. Flags: flags,
  2212. ..Default::default()
  2213. };
  2214. let mut out: Option<ID3D12Resource> = None;
  2215. // SAFETY: plain buffer creation.
  2216. unsafe {
  2217. device
  2218. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out)
  2219. .unwrap();
  2220. }
  2221. out.unwrap()
  2222. }
  2223. fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap {
  2224. let flags = if visible {
  2225. D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE
  2226. } else {
  2227. D3D12_DESCRIPTOR_HEAP_FLAG_NONE
  2228. };
  2229. // SAFETY: plain heap creation.
  2230. unsafe {
  2231. device
  2232. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  2233. Type: kind,
  2234. NumDescriptors: count,
  2235. Flags: flags,
  2236. NodeMask: 0,
  2237. })
  2238. .unwrap()
  2239. }
  2240. }
  2241. fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState {
  2242. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  2243. pShaderBytecode: bytes.as_ptr().cast(),
  2244. BytecodeLength: bytes.len(),
  2245. };
  2246. let mut blend = D3D12_BLEND_DESC::default();
  2247. blend.RenderTarget[0].RenderTargetWriteMask = 0xf;
  2248. let mut formats = [DXGI_FORMAT(0); 8];
  2249. formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  2250. // SAFETY: the description points at live data and never releases
  2251. // its pointer to the root signature.
  2252. unsafe {
  2253. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  2254. pRootSignature: std::mem::transmute_copy(root),
  2255. VS: code(vs),
  2256. PS: code(ps),
  2257. BlendState: blend,
  2258. SampleMask: u32::MAX,
  2259. RasterizerState: D3D12_RASTERIZER_DESC {
  2260. FillMode: D3D12_FILL_MODE_SOLID,
  2261. CullMode: D3D12_CULL_MODE_NONE,
  2262. DepthClipEnable: true.into(),
  2263. ..Default::default()
  2264. },
  2265. // Depth is tested and never written, so the texture may be
  2266. // in the write state or in the read state under one view.
  2267. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  2268. DepthEnable: true.into(),
  2269. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO,
  2270. DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL,
  2271. ..Default::default()
  2272. },
  2273. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  2274. NumRenderTargets: 1,
  2275. RTVFormats: formats,
  2276. DSVFormat: DXGI_FORMAT_D32_FLOAT,
  2277. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  2278. ..Default::default()
  2279. };
  2280. device.CreateGraphicsPipelineState(&desc).unwrap()
  2281. }
  2282. }
  2283. impl Rig {
  2284. /// The default adapter, as the layer takes it; `None` without one
  2285. /// or on a software adapter.
  2286. fn new() -> Option<Self> {
  2287. let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?;
  2288. let ps = [
  2289. compile(DRAW, s!("first"), s!("ps_5_1")).ok()?,
  2290. compile(DRAW, s!("second"), s!("ps_5_1")).ok()?,
  2291. ];
  2292. let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?;
  2293. // SAFETY: plain object creation on a device of our own; the
  2294. // views are made in heaps that live as long as the rig.
  2295. unsafe {
  2296. let mut device: Option<ID3D12Device> = None;
  2297. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
  2298. let device = device?;
  2299. let desc = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  2300. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  2301. .ok()?
  2302. .cast::<IDXGIAdapter1>()
  2303. .ok()?
  2304. .GetDesc1()
  2305. .ok()?;
  2306. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
  2307. return None;
  2308. }
  2309. let card = String::from_utf16_lossy(&desc.Description)
  2310. .trim_end_matches('\0')
  2311. .to_owned();
  2312. let queue: ID3D12CommandQueue = device
  2313. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  2314. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  2315. ..Default::default()
  2316. })
  2317. .ok()?;
  2318. let allocator: ID3D12CommandAllocator =
  2319. device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?;
  2320. let list: ID3D12GraphicsCommandList = device
  2321. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  2322. .ok()?;
  2323. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  2324. let event = CreateEventW(None, false, false, None).ok()?;
  2325. let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?;
  2326. let pipelines = [
  2327. pipeline(&device, &root, &vs, &ps[0]),
  2328. pipeline(&device, &root, &vs, &ps[1]),
  2329. ];
  2330. let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?;
  2331. let work: ID3D12PipelineState = device
  2332. .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  2333. pRootSignature: std::mem::transmute_copy(&work_root),
  2334. CS: D3D12_SHADER_BYTECODE {
  2335. pShaderBytecode: cs.as_ptr().cast(),
  2336. BytecodeLength: cs.len(),
  2337. },
  2338. ..Default::default()
  2339. })
  2340. .ok()?;
  2341. let size = (WIDTH, HEIGHT);
  2342. let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state);
  2343. let target = [
  2344. colour(D3D12_RESOURCE_STATE_RENDER_TARGET),
  2345. colour(D3D12_RESOURCE_STATE_RENDER_TARGET),
  2346. ];
  2347. let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET);
  2348. let depth = texture(
  2349. &device,
  2350. size,
  2351. DXGI_FORMAT_D32_FLOAT,
  2352. D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
  2353. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  2354. );
  2355. let image = texture(
  2356. &device,
  2357. (4, 4),
  2358. DXGI_FORMAT_R8G8B8A8_UNORM,
  2359. D3D12_RESOURCE_FLAG_NONE,
  2360. D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
  2361. );
  2362. let words = buffer(
  2363. &device,
  2364. 64 << 10,
  2365. D3D12_HEAP_TYPE_DEFAULT,
  2366. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  2367. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  2368. );
  2369. let back = buffer(
  2370. &device,
  2371. 16,
  2372. D3D12_HEAP_TYPE_READBACK,
  2373. D3D12_RESOURCE_FLAG_NONE,
  2374. D3D12_RESOURCE_STATE_COPY_DEST,
  2375. );
  2376. let mut stamps: Option<ID3D12QueryHeap> = None;
  2377. device
  2378. .CreateQueryHeap(
  2379. &D3D12_QUERY_HEAP_DESC {
  2380. Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
  2381. Count: 2,
  2382. NodeMask: 0,
  2383. },
  2384. &mut stamps,
  2385. )
  2386. .ok()?;
  2387. let stamps = stamps?;
  2388. // Target and depth views.
  2389. let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false);
  2390. let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize;
  2391. let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2];
  2392. targets[1].ptr += rtv_step;
  2393. device.CreateRenderTargetView(&target[0], None, targets[0]);
  2394. device.CreateRenderTargetView(&target[1], None, targets[1]);
  2395. let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false);
  2396. let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize;
  2397. let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart();
  2398. let mut depth_tested = depth_written;
  2399. depth_tested.ptr += dsv_step;
  2400. device.CreateDepthStencilView(&depth, None, depth_written);
  2401. let tested = D3D12_DEPTH_STENCIL_VIEW_DESC {
  2402. Format: DXGI_FORMAT_D32_FLOAT,
  2403. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
  2404. Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH,
  2405. ..Default::default()
  2406. };
  2407. device.CreateDepthStencilView(&depth, Some(&tested), depth_tested);
  2408. // Two pairs of shader-visible heaps: views (one view of the
  2409. // small texture each) and samplers (none used).
  2410. let view_heaps = [
  2411. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true),
  2412. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true),
  2413. ];
  2414. let sampler_heaps = [
  2415. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true),
  2416. heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true),
  2417. ];
  2418. for views in &view_heaps {
  2419. device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart());
  2420. }
  2421. let tables = [
  2422. view_heaps[0].GetGPUDescriptorHandleForHeapStart(),
  2423. view_heaps[1].GetGPUDescriptorHandleForHeapStart(),
  2424. ];
  2425. let heap_pairs = [
  2426. [Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())],
  2427. [Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())],
  2428. ];
  2429. // The first list: both targets and the depth texture cleared.
  2430. list.ClearRenderTargetView(targets[0], &[0.0; 4], None);
  2431. list.ClearRenderTargetView(targets[1], &[0.0; 4], None);
  2432. list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None);
  2433. let [first_target, second_target] = target;
  2434. let mut rig = Rig {
  2435. queue,
  2436. allocator,
  2437. list,
  2438. fence,
  2439. submitted: 0,
  2440. event,
  2441. root,
  2442. pipelines,
  2443. work_root,
  2444. work,
  2445. words,
  2446. other,
  2447. depth,
  2448. _kept: vec![first_target, second_target, image],
  2449. _target_heaps: [rtvs, dsvs],
  2450. heap_pairs,
  2451. tables,
  2452. targets,
  2453. depth_written,
  2454. depth_tested,
  2455. stamps,
  2456. back,
  2457. card,
  2458. };
  2459. rig.finish();
  2460. Some(rig)
  2461. }
  2462. }
  2463. /// Closes the open list, runs it, waits for the card and opens the
  2464. /// list again.
  2465. fn finish(&mut self) {
  2466. self.submitted += 1;
  2467. // SAFETY: our list, queue and fence; the allocator is reset
  2468. // only after the card finished everything recorded from it.
  2469. unsafe {
  2470. self.list.Close().unwrap();
  2471. let run: ID3D12CommandList = self.list.cast().unwrap();
  2472. self.queue.ExecuteCommandLists(&[Some(run)]);
  2473. self.queue.Signal(&self.fence, self.submitted).unwrap();
  2474. self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap();
  2475. WaitForSingleObject(self.event, INFINITE);
  2476. self.allocator.Reset().unwrap();
  2477. self.list.Reset(&self.allocator, None).unwrap();
  2478. }
  2479. }
  2480. /// What every list starts with: a new list has nothing set.
  2481. fn begin(&self) {
  2482. let l = &self.list;
  2483. // SAFETY: an open list and live objects and views.
  2484. unsafe {
  2485. l.SetDescriptorHeaps(&self.heap_pairs[0]);
  2486. l.SetGraphicsRootSignature(&self.root);
  2487. l.SetPipelineState(&self.pipelines[0]);
  2488. l.SetGraphicsRootDescriptorTable(0, self.tables[0]);
  2489. l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested));
  2490. l.RSSetViewports(&[D3D12_VIEWPORT {
  2491. TopLeftX: 0.0,
  2492. TopLeftY: 0.0,
  2493. Width: WIDTH as f32,
  2494. Height: HEIGHT as f32,
  2495. MinDepth: 0.0,
  2496. MaxDepth: 1.0,
  2497. }]);
  2498. l.RSSetScissorRects(&[RECT {
  2499. left: 0,
  2500. top: 0,
  2501. right: WIDTH as i32,
  2502. bottom: HEIGHT as i32,
  2503. }]);
  2504. // A triangle list.
  2505. l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4));
  2506. }
  2507. }
  2508. /// One batch of [`DRAWS`] draws in `lists` lists run one by one,
  2509. /// with `between` recorded before every draw: the microseconds a
  2510. /// draw took on the card, and the milliseconds recording took.
  2511. fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) {
  2512. let (target, read, written, tested) = (
  2513. D3D12_RESOURCE_STATE_RENDER_TARGET,
  2514. D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
  2515. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  2516. D3D12_RESOURCE_STATE_DEPTH_READ,
  2517. );
  2518. let started = std::time::Instant::now();
  2519. let mut drawn = 0u32;
  2520. for part in 0..lists {
  2521. let l = &self.list;
  2522. // SAFETY: an open list; our query heap; live objects.
  2523. unsafe {
  2524. if part == 0 {
  2525. l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0);
  2526. }
  2527. }
  2528. self.begin();
  2529. // SAFETY: an open list with everything set; live objects.
  2530. // Every state moved is moved back within the batch (the
  2531. // draws of a list are an even number).
  2532. unsafe {
  2533. for _ in 0..DRAWS / lists {
  2534. let odd = (drawn % 2) as usize;
  2535. match between {
  2536. Between::Nothing => {}
  2537. Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]),
  2538. Between::BarrierPair => {
  2539. l.ResourceBarrier(&[transition(&self.other, target, read)]);
  2540. l.ResourceBarrier(&[transition(&self.other, read, target)]);
  2541. }
  2542. Between::DepthMove => {
  2543. let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) };
  2544. l.ResourceBarrier(&[transition(&self.depth, from, to)]);
  2545. }
  2546. Between::Heaps => {
  2547. l.SetDescriptorHeaps(&self.heap_pairs[odd]);
  2548. l.SetGraphicsRootDescriptorTable(0, self.tables[odd]);
  2549. }
  2550. Between::Targets => {
  2551. l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested));
  2552. }
  2553. Between::Compute | Between::ComputeWithWaits => {
  2554. let waits = between == Between::ComputeWithWaits;
  2555. if waits {
  2556. l.ResourceBarrier(&[super::uav_barrier()]);
  2557. }
  2558. l.SetComputeRootSignature(&self.work_root);
  2559. l.SetPipelineState(&self.work);
  2560. l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress());
  2561. l.Dispatch(1, 1, 1);
  2562. if waits {
  2563. l.ResourceBarrier(&[super::uav_barrier()]);
  2564. }
  2565. l.SetPipelineState(&self.pipelines[0]);
  2566. }
  2567. }
  2568. l.DrawInstanced(3, 1, 0, 0);
  2569. drawn += 1;
  2570. }
  2571. if part + 1 < lists {
  2572. // The next list of the batch: this one is sent on
  2573. // its own and the list is opened again at once
  2574. // (the allocator is not reset before the card is
  2575. // done with all of them).
  2576. l.Close().unwrap();
  2577. let run: ID3D12CommandList = l.cast().unwrap();
  2578. self.queue.ExecuteCommandLists(&[Some(run)]);
  2579. l.Reset(&self.allocator, None).unwrap();
  2580. } else {
  2581. l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1);
  2582. l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0);
  2583. }
  2584. }
  2585. }
  2586. let recording = started.elapsed().as_secs_f64() * 1e3;
  2587. self.finish();
  2588. let mut data = std::ptr::null_mut();
  2589. let range = D3D12_RANGE { Begin: 0, End: 16 };
  2590. // SAFETY: a read-back buffer the finished list resolved two
  2591. // timestamps into.
  2592. let ticks = unsafe {
  2593. self.back.Map(0, Some(&range), Some(&mut data)).unwrap();
  2594. let stamps = std::slice::from_raw_parts(data.cast::<u64>(), 2).to_vec();
  2595. self.back.Unmap(0, None);
  2596. stamps[1].saturating_sub(stamps[0])
  2597. };
  2598. // SAFETY: a plain query of our queue.
  2599. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1);
  2600. (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording)
  2601. }
  2602. }
  2603. #[test]
  2604. #[ignore = "a measurement on the card: run it by name with --ignored --nocapture"]
  2605. fn bare_command_cost() {
  2606. let Some(mut rig) = Rig::new() else {
  2607. eprintln!("no hardware adapter, or our shaders did not compile; skipped");
  2608. return;
  2609. };
  2610. eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card);
  2611. // The first batch pays for whatever the driver does at first use.
  2612. rig.batch(Between::Nothing, 1);
  2613. let variants = [
  2614. ("(a) nothing changes between draws", Between::Nothing, 1),
  2615. ("(b) another pipeline every draw", Between::Pipeline, 1),
  2616. ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1),
  2617. ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1),
  2618. ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1),
  2619. ("(f) another colour target every draw", Between::Targets, 1),
  2620. ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100),
  2621. ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1),
  2622. ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1),
  2623. ];
  2624. let mut least = Vec::new();
  2625. for (name, between, lists) in variants {
  2626. let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect();
  2627. runs.sort_by(|a, b| a.0.total_cmp(&b.0));
  2628. eprintln!(
  2629. "{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms",
  2630. runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1
  2631. );
  2632. least.push(runs[0].0);
  2633. }
  2634. assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch");
  2635. }
  2636. }