indirect.rs 99 KB

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