indirect.rs 73 KB

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