indirect.rs 177 KB

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