indirect.rs 150 KB

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