host.rs 315 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299
  1. //! The host GPU: one D3D12 device and direct queue (decision 0007), and a
  2. //! window to present on.
  3. //!
  4. //! shortcut: every submission is waited for, so CPU and GPU never overlap
  5. //! (unless `VICTORY_LATE_WAIT=1`, see [`late`]);
  6. //! overlap them with per-submission fences once more than clears run.
  7. use std::sync::atomic::{AtomicU32, Ordering};
  8. use std::sync::{Mutex, OnceLock};
  9. use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
  10. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  11. use windows::Win32::Graphics::Direct3D12::*;
  12. use windows::Win32::Graphics::Dxgi::Common::*;
  13. use windows::Win32::Graphics::Dxgi::*;
  14. use windows::Win32::System::LibraryLoader::GetModuleHandleW;
  15. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  16. use windows::Win32::UI::WindowsAndMessaging::*;
  17. use windows::core::{Interface, PCWSTR, w};
  18. /// Resource states without the console's own bits (compression hints from
  19. /// bit 25 up), which the host rejects.
  20. pub(crate) fn pc_state(state: u32) -> u32 {
  21. state & 0x01ff_ffff
  22. }
  23. /// A console state as a host texture state: PC bits only, and none of the
  24. /// buffer-only ones the console allows on textures (vertex, constant and
  25. /// index buffer, stream out, indirect arguments, as in "generic read").
  26. pub(crate) fn texture_state(state: u32) -> u32 {
  27. const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
  28. pc_state(state) & !BUFFER_ONLY
  29. }
  30. /// Render target views live only until their command is recorded, so a
  31. /// ring of host descriptors is enough.
  32. const RTV_RING: u32 = 1024;
  33. pub(crate) struct Host {
  34. pub(crate) device: ID3D12Device,
  35. queue: ID3D12CommandQueue,
  36. fence: ID3D12Fence,
  37. /// The last value signalled on `fence`, behind the submission lock.
  38. submitted: Mutex<u64>,
  39. event: HANDLE,
  40. rtvs: ID3D12DescriptorHeap,
  41. rtv_size: u32,
  42. /// A ring of depth views, used as `rtvs`.
  43. dsvs: ID3D12DescriptorHeap,
  44. dsv_size: u32,
  45. next_dsv: AtomicU32,
  46. /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug
  47. /// layer's messages.
  48. messages: Option<ID3D12InfoQueue>,
  49. next_rtv: AtomicU32,
  50. presenter: Mutex<Option<Presenter>>,
  51. /// The adapter the device is on, for its memory budget
  52. /// ([`Host::video_memory`]); `None` if the system does not name it.
  53. adapter: Option<IDXGIAdapter3>,
  54. }
  55. // SAFETY: D3D12 devices, queues, fences and descriptor heaps are
  56. // free-threaded; the event handle is only waited on under `submitted`.
  57. unsafe impl Send for Host {}
  58. // SAFETY: as above.
  59. unsafe impl Sync for Host {}
  60. /// Host objects the title let go of while a submission may still use them
  61. /// (a texture its descriptors name, a descriptor slot's old resource), by
  62. /// the submission count they wait for. The title's descriptor writes and
  63. /// releases reach the host at once, from its own threads, while the host
  64. /// runs a submission: freeing there is a GPU page fault on the freed
  65. /// texture (a device hang).
  66. static RETIRED: Mutex<Vec<(u64, Retired)>> = Mutex::new(Vec::new());
  67. /// Submissions started and finished (waited for).
  68. static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  69. static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  70. /// A retired object, dropped on whatever thread finishes the submission.
  71. struct Retired(#[allow(dead_code)] Box<dyn std::any::Any>);
  72. // SAFETY: what is retired is D3D12 objects (free-threaded) and the
  73. // reference-counted wrappers holding them, dropped once.
  74. unsafe impl Send for Retired {}
  75. /// Milliseconds since the first call.
  76. pub(crate) fn now_ms() -> u64 {
  77. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  78. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  79. }
  80. /// This moment, for telling later how long ago it was ([`long_ago`]): the
  81. /// frames begun so far (high half, `crate::frame::current`) and tenths of a
  82. /// second since the start. Host copies of title memory, staging buffers and
  83. /// host textures note when they were last used with it.
  84. pub(crate) fn moment() -> u64 {
  85. (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff)
  86. }
  87. /// Whether `moment` lies at least `ms` milliseconds and `frames` frames
  88. /// back. Both: at seconds per frame, what every frame uses is not touched
  89. /// for seconds, and at many frames per second not for many frames. (A title
  90. /// that never waits for frames has no frame count: nothing is then idle.)
  91. pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
  92. let now = self::moment();
  93. let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
  94. (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
  95. }
  96. /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
  97. pub(crate) fn available_physical_ram() -> Option<u64> {
  98. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  99. // SAFETY: plain data the call fills in.
  100. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  101. m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
  102. // SAFETY: a sized structure.
  103. let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
  104. ok.then_some(m.ullAvailPhys)
  105. }
  106. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  107. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  108. /// handles not yet recorded into a list or slot remain protected.
  109. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  110. const NORMAL_MS: u64 = 5_000;
  111. const MODERATE_MS: u64 = 2_500;
  112. const HIGH_MS: u64 = 1_000;
  113. let Some([budget, used, ..]) = video_memory else {
  114. return NORMAL_MS;
  115. };
  116. if budget == 0 {
  117. return NORMAL_MS;
  118. }
  119. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  120. if used_pct >= 85 {
  121. HIGH_MS
  122. } else if used_pct >= 75 {
  123. MODERATE_MS
  124. } else {
  125. NORMAL_MS
  126. }
  127. }
  128. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  129. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  130. /// when free physical RAM is low. Never returns less than 2,000 ms.
  131. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  132. const GIB: u64 = 1024 * 1024 * 1024;
  133. const NORMAL_MS: u64 = 10_000;
  134. const MODERATE_MS: u64 = 5_000;
  135. const HIGH_MS: u64 = 2_000;
  136. let Some(avail) = avail_phys else {
  137. return NORMAL_MS;
  138. };
  139. if avail < 2 * GIB {
  140. HIGH_MS
  141. } else if avail < 4 * GIB {
  142. MODERATE_MS
  143. } else {
  144. NORMAL_MS
  145. }
  146. }
  147. /// How many references are held on a host object (its COM count): ours
  148. /// all, since the host's views and commands hold none. A buffer or texture
  149. /// with one is held by its owner alone: no descriptor slot keeps it
  150. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  151. pub(crate) fn references(object: &impl Interface) -> u32 {
  152. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  153. let raw = object.as_raw();
  154. // SAFETY: a live COM object, whose first three methods are those of
  155. // `IUnknown` (query, add a reference, release one); the pair leaves the
  156. // count as it was, and the release returns it. The first is not called.
  157. unsafe {
  158. let methods = *raw.cast::<*const [Method; 3]>();
  159. ((*methods)[1])(raw);
  160. ((*methods)[2])(raw)
  161. }
  162. }
  163. /// Once a second, before a submission starts: lets go of what nothing
  164. /// names any more (copies of windows of title memory, staging buffers,
  165. /// host copies of textures the title fills).
  166. /// `VICTORY_SWEEP=0` keeps everything, as before.
  167. fn sweep() {
  168. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  169. crate::inplace::tick();
  170. static ON: OnceLock<bool> = OnceLock::new();
  171. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  172. return;
  173. }
  174. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  175. let now = now_ms();
  176. let last = LAST.load(Ordering::Relaxed);
  177. if now < last + 1000
  178. || LAST
  179. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  180. .is_err()
  181. {
  182. return;
  183. }
  184. crate::pipeline::trim_library();
  185. crate::shadow::let_go_idle();
  186. crate::texture::let_go_idle();
  187. crate::resource::let_go_idle();
  188. }
  189. /// Drops `object` once every submission running now has finished: at once
  190. /// if none is.
  191. pub(crate) fn retire<T: 'static>(object: T) {
  192. let started = STARTED.load(Ordering::Acquire);
  193. if started <= FINISHED.load(Ordering::Acquire) {
  194. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  195. drop(object);
  196. return;
  197. }
  198. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  199. RETIRED
  200. .lock()
  201. .unwrap_or_else(|e| e.into_inner())
  202. .push((started, Retired(Box::new(object))));
  203. }
  204. /// Drops what waited for submissions up to `finished`.
  205. fn bury(finished: u64) {
  206. let done: Vec<(u64, Retired)> = {
  207. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  208. if retired.is_empty() {
  209. return;
  210. }
  211. let (done, keep) = std::mem::take(&mut *retired)
  212. .into_iter()
  213. .partition(|(at, _)| *at <= finished);
  214. *retired = keep;
  215. done
  216. };
  217. drop(done);
  218. }
  219. /// Objects [`retire`] dropped at once (no submission was running) and
  220. /// kept until a running submission finished, since the start.
  221. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  222. /// What the layer did to the host's objects lately, newest last (sweeps
  223. /// that let host copies go, pipeline library calls, saves and trims): said
  224. /// once when the host device is removed ([`log_removal_context`]), with
  225. /// what the submitting thread and the pipeline workers were doing at that
  226. /// moment. A device the driver removes "internally" names no command, and
  227. /// the pass that happens to notice first names only the view it was at:
  228. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  229. /// pipeline library call that no line of the log tied to them.
  230. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  231. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  232. /// The entries kept.
  233. const TRAIL_MOST: usize = 96;
  234. fn trail_on() -> bool {
  235. static ON: OnceLock<bool> = OnceLock::new();
  236. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  237. }
  238. /// Microseconds since the first call.
  239. pub(crate) fn now_us() -> u64 {
  240. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  241. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  242. }
  243. /// The calling thread, as the log's other lines name threads.
  244. pub(crate) fn thread_id() -> u32 {
  245. // SAFETY: a plain query.
  246. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  247. }
  248. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  249. /// run when the trail is kept.
  250. pub(crate) fn trail(what: impl FnOnce() -> String) {
  251. if !trail_on() {
  252. return;
  253. }
  254. let entry = (now_us(), thread_id(), what());
  255. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  256. if trail.len() >= TRAIL_MOST {
  257. trail.pop_front();
  258. }
  259. trail.push_back(entry);
  260. }
  261. /// What the submitting thread is doing (0 nothing: between submissions,
  262. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  263. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  264. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  265. fn submitting(phase: u64, lists: usize) {
  266. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  267. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  268. SUBMITTING[0].store(phase, Ordering::Relaxed);
  269. }
  270. /// What was going on when the host device went: whether a submission was
  271. /// on the card, the pipeline library's state and the calls running in it,
  272. /// and the trail.
  273. pub(crate) fn removal_context() -> String {
  274. use std::fmt::Write;
  275. let now = now_us();
  276. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  277. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  278. 0 => "between submissions (nothing of ours was running on the card)",
  279. 1 => "preparing a submission (nothing of ours was running on the card)",
  280. 2 => "waiting for the card to run a submission",
  281. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  282. };
  283. let mut text = format!(
  284. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  285. SUBMITTING[1].load(Ordering::Relaxed),
  286. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  287. crate::pipeline::library_removal_note(),
  288. RETIREMENTS[0].load(Ordering::Relaxed),
  289. RETIREMENTS[1].load(Ordering::Relaxed),
  290. STARTED.load(Ordering::Relaxed),
  291. FINISHED.load(Ordering::Relaxed),
  292. );
  293. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  294. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  295. for (at, thread, what) in trail.iter() {
  296. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  297. }
  298. text
  299. }
  300. /// Says [`removal_context`] in the log, once: called by whoever finds the
  301. /// host device removed.
  302. pub(crate) fn log_removal_context() {
  303. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  304. if !trail_on() || SAID.swap(true, Ordering::Relaxed) {
  305. return;
  306. }
  307. tracing::error!("when the host device went: {}", removal_context());
  308. }
  309. /// Time spent in submissions since the last frame-rate line, in
  310. /// microseconds: preparing them on the CPU (title memory copies, texture
  311. /// detiling), then waiting for the GPU.
  312. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  313. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  314. /// After submissions: shader-written ranges compared and copied back into
  315. /// title memory (microseconds, bytes that differed), since the last
  316. /// frame-rate line.
  317. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  318. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  319. /// The card's clock, for the frame line of every run, in microseconds since
  320. /// the last one: how long the card had nothing of ours queued; how much of
  321. /// that while the thread that holds the submission lock was working (the
  322. /// card idle behind us: preparing and copying back are done with the card
  323. /// standing); and how long that thread stood waiting for the card.
  324. ///
  325. /// Every send of lists to the queue is followed by a signal on a fence of
  326. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  327. /// the newest signal and notes the moment the card reached it with nothing
  328. /// newer sent; the next send ends that idle stretch.
  329. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  330. /// Of the thread that holds the submission lock: the microseconds it has
  331. /// worked so far (preparing, copying back; not its waits for the card), and
  332. /// since when it works now ([`now_us`] plus one; 0: it does not).
  333. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  334. /// The thread that holds the submission lock starts (`on`) or stops
  335. /// working; whether it worked until now.
  336. fn working(on: bool) -> bool {
  337. let now = now_us() + 1;
  338. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  339. if since != 0 {
  340. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  341. }
  342. since != 0
  343. }
  344. /// [`WORKING`] as of now: microseconds worked so far.
  345. fn worked() -> u64 {
  346. let since = WORKING[1].load(Ordering::Relaxed);
  347. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  348. WORKING[0].load(Ordering::Relaxed) + now
  349. }
  350. /// The thread that holds the submission lock stood waiting for the card
  351. /// from `since` until now ([`CARD_CLOCK_US`]).
  352. fn stood(since: std::time::Instant) {
  353. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  354. }
  355. /// What [`CARD_CLOCK_US`] is measured with.
  356. struct CardClock {
  357. fence: ID3D12Fence,
  358. /// Signals sent so far; and, while the card has reached the last of
  359. /// them, since when and what [`worked`] said then.
  360. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  361. sent: std::sync::Condvar,
  362. }
  363. // SAFETY: a fence (free-threaded) behind a lock.
  364. unsafe impl Send for CardClock {}
  365. // SAFETY: as above.
  366. unsafe impl Sync for CardClock {}
  367. /// The clock's thread: waits for the newest signal sent and notes when the
  368. /// card got there with nothing newer behind it.
  369. fn card_clock_watch(clock: &'static CardClock) {
  370. // SAFETY: a plain event of our own.
  371. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  372. return;
  373. };
  374. let mut seen = 0;
  375. loop {
  376. let target = {
  377. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  378. while state.0 == seen {
  379. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  380. }
  381. state.0
  382. };
  383. // SAFETY: the clock's fence and this thread's event.
  384. unsafe {
  385. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  386. WaitForSingleObject(event, INFINITE);
  387. }
  388. }
  389. seen = target;
  390. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  391. if state.0 == target && state.1.is_none() {
  392. state.1 = Some((std::time::Instant::now(), worked()));
  393. }
  394. }
  395. }
  396. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  397. /// frame's time.
  398. fn card_clock_line(frames: f64, ms: f64) {
  399. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  400. tracing::info!(
  401. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  402. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  403. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  404. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  405. );
  406. }
  407. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  408. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  409. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  410. std::sync::atomic::AtomicU64::new(0),
  411. std::sync::atomic::AtomicU64::new(0),
  412. std::sync::atomic::AtomicU64::new(0),
  413. std::sync::atomic::AtomicU64::new(0),
  414. ];
  415. /// Host buffers made since the start, as (count, bytes): in the upload heap
  416. /// (staging, list scratch), shared with the processor (host copies of title
  417. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  418. /// For the memory line: against what is alive, they show what was let go.
  419. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  420. /// What of that is alive now, for the memory line (`MADE` counts what was
  421. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  422. /// and nothing said how many were alive): host lists; the lists' scratch
  423. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  424. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  425. /// instead of made, since the start; and the lists' other upload buffers
  426. /// (texture data copied from buffers, scratch too big for a chunk) and
  427. /// their bytes.
  428. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  429. /// About host lists, for the memory line: lists made by the host since the
  430. /// start; preludes made (a list's second allocator and list, made when it
  431. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  432. /// bytes the process's private memory grew by while lists were being made
  433. /// (what a list costs: host objects with the driver's command memory; 631
  434. /// lists were alive in run 65, each with a prelude it may never use).
  435. /// Then the lists alive that were never reset since they were made: the
  436. /// host sides of title lists the title made and has not used (a host list
  437. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  438. /// makes at its start).
  439. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  440. /// The process's private bytes (diagnostics: around the making of lists).
  441. #[cfg(feature = "diagnostics")]
  442. fn private_bytes() -> u64 {
  443. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  444. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  445. let mut c = PROCESS_MEMORY_COUNTERS {
  446. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  447. ..Default::default()
  448. };
  449. // SAFETY: our own process and a sized structure.
  450. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  451. c.PagefileUsage as u64
  452. }
  453. /// What the runtime does when the host GPU fails for good: report it like a
  454. /// crash and end the run. The console has no such state, and carrying on
  455. /// draws nothing at seconds per frame.
  456. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  457. /// Sets what a host GPU failure does (the runtime's crash report).
  458. pub fn on_failure(report: fn(&str) -> !) {
  459. let _ = ON_FAILURE.set(report);
  460. }
  461. /// Ends the run on a host GPU failure: what failed, the removal reason and
  462. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  463. /// diagnostics build names the command).
  464. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  465. let mut text = what.to_string();
  466. if let Some(host) = host() {
  467. // SAFETY: a plain query.
  468. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  469. text.push_str(&format!("; device removed: {e}"));
  470. log_removal_context();
  471. }
  472. match host.log_messages() {
  473. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  474. None if host.messages.is_none() => text.push_str(
  475. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  476. ),
  477. None => {}
  478. }
  479. }
  480. tracing::error!("{text}");
  481. // Tests have no log: the reason goes to their output.
  482. #[cfg(test)]
  483. eprintln!("host GPU failure: {text}");
  484. match ON_FAILURE.get() {
  485. Some(report) => report(&text),
  486. None => std::process::abort(),
  487. }
  488. }
  489. /// The host GPU, created on first use; `None` without one (a run then
  490. /// behaves as before: nothing executes).
  491. pub(crate) fn host() -> Option<&'static Host> {
  492. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  493. HOST.get_or_init(|| match create() {
  494. Ok(host) => Some(host),
  495. Err(e) => {
  496. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  497. None
  498. }
  499. })
  500. .as_ref()
  501. }
  502. fn create() -> windows::core::Result<Host> {
  503. // SAFETY: plain D3D12 object creation with valid descriptions.
  504. unsafe {
  505. // The debug layer only in builds with diagnostics.
  506. let debug =
  507. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some();
  508. if debug {
  509. let mut layer: Option<ID3D12Debug> = None;
  510. match D3D12GetDebugInterface(&mut layer) {
  511. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  512. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  513. }
  514. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  515. // descriptor heap indices and the like become messages naming
  516. // the command instead of page faults. Without state tracking
  517. // (directly indexed textures are not transitioned).
  518. if std::env::var_os("VICTORY_D3D12_GBV").is_some()
  519. && let Some(l) = &layer
  520. {
  521. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  522. d1.SetEnableGPUBasedValidation(true);
  523. }
  524. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  525. d2.SetGPUBasedValidationFlags(
  526. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  527. );
  528. }
  529. tracing::info!("GPU-based validation on");
  530. }
  531. }
  532. // Diagnostics: device-removed data (the command that faulted, the
  533. // faulting address), read when the device is removed.
  534. if dred_on() {
  535. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  536. if D3D12GetDebugInterface(&mut dred).is_ok()
  537. && let Some(dred) = dred
  538. {
  539. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  540. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  541. }
  542. }
  543. let mut device: Option<ID3D12Device> = None;
  544. // Diagnostics: the software adapter, on which a shader's wild access
  545. // is an access violation in this process (a crash report with the
  546. // address and instruction) instead of a GPU fault and driver reset.
  547. if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() {
  548. let adapter = warp_adapter()?;
  549. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  550. tracing::info!("host device on the software adapter (WARP)");
  551. } else {
  552. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  553. }
  554. let device = device.ok_or_else(windows::core::Error::empty)?;
  555. // Before anything is made with it (`VICTORY_RECORD`).
  556. #[cfg(feature = "diagnostics")]
  557. crate::replay::record::from_env(&device);
  558. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  559. // driver compiling shaders again on the "D3D Background Thread"s,
  560. // for minutes after pipelines were made or loaded) is switched off.
  561. // An experiment: while those threads ran, the same shot took
  562. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  563. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  564. // whether the card is slower with the shaders it then keeps is not
  565. // known.
  566. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  567. && let Ok(device6) = device.cast::<ID3D12Device6>()
  568. {
  569. let set = device6.SetBackgroundProcessingMode(
  570. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  571. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  572. None,
  573. None,
  574. );
  575. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  576. }
  577. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  578. // cross-lane code stays in 32-lane halves translated for waves of 32
  579. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  580. if device
  581. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  582. .is_ok()
  583. {
  584. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  585. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  586. }
  587. let messages = debug
  588. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  589. .flatten();
  590. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  591. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  592. ..Default::default()
  593. })?;
  594. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  595. let event = CreateEventW(None, false, false, None)?;
  596. let rtvs: ID3D12DescriptorHeap =
  597. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  598. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  599. NumDescriptors: RTV_RING,
  600. ..Default::default()
  601. })?;
  602. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  603. let dsvs: ID3D12DescriptorHeap =
  604. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  605. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  606. NumDescriptors: RTV_RING,
  607. ..Default::default()
  608. })?;
  609. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  610. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  611. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  612. .ok();
  613. tracing::info!("host D3D12 device ready");
  614. Ok(Host {
  615. device,
  616. queue,
  617. fence,
  618. submitted: Mutex::new(0),
  619. event,
  620. rtvs,
  621. rtv_size,
  622. dsvs,
  623. dsv_size,
  624. next_dsv: AtomicU32::new(0),
  625. messages,
  626. next_rtv: AtomicU32::new(0),
  627. presenter: Mutex::new(None),
  628. adapter,
  629. })
  630. }
  631. }
  632. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  633. /// Reject it before creating a device in diagnostics' software-only mode.
  634. fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  635. // SAFETY: plain DXGI adapter queries.
  636. unsafe {
  637. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  638. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  639. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  640. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  641. tracing::warn!(
  642. vendor = format_args!("{:#x}", desc.VendorId),
  643. flags = format_args!("{:#x}", desc.Flags),
  644. "DXGI did not identify the WARP adapter as software; refusing device"
  645. );
  646. return Err(windows::core::Error::from_hresult(
  647. windows::Win32::Foundation::E_FAIL,
  648. ));
  649. }
  650. Ok(adapter)
  651. }
  652. }
  653. #[cfg(test)]
  654. mod tests {
  655. #[test]
  656. fn sparse_copies_preserve_islands_and_observe_remaps() {
  657. use windows_sys::Win32::System::Memory::*;
  658. const N: usize = 5 << 16;
  659. // SAFETY: we reserve a private region, commit selected pages inside it,
  660. // and only directly access the pages while they are writable.
  661. unsafe {
  662. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  663. assert!(!base.is_null());
  664. let mut expected = vec![0; N];
  665. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  666. let at = base.add(offset);
  667. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  668. at.write_bytes(value, 4096);
  669. expected[offset..offset + 4096].fill(value);
  670. }
  671. for remap in [false, true] {
  672. if remap {
  673. let mut old = 0;
  674. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  675. expected[..4096].fill(0);
  676. let at = base.add(1 << 16);
  677. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  678. at.write_bytes(0xc7, 4096);
  679. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  680. }
  681. let mut out = vec![0xee; N];
  682. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  683. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  684. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  685. }
  686. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  687. }
  688. }
  689. use super::*;
  690. #[test]
  691. fn warp_adapter_accepts_only_software() {
  692. // This probes DXGI without creating a D3D12 device or running a title.
  693. // SAFETY: plain DXGI adapter queries.
  694. let raw = unsafe {
  695. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  696. else {
  697. return;
  698. };
  699. factory.EnumWarpAdapter::<IDXGIAdapter>()
  700. };
  701. let Ok(raw) = raw else { return };
  702. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  703. // IDXGIAdapter1; `raw` owns that interface.
  704. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  705. eprintln!(
  706. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  707. desc.VendorId, desc.Flags
  708. );
  709. assert_eq!(
  710. warp_adapter().is_ok(),
  711. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  712. );
  713. }
  714. }
  715. /// The batches of clamped records in one scratch buffer
  716. /// ([`HostList::batch_place`]).
  717. const BATCHES: u32 = 8;
  718. /// A host command list and its allocator, always used together.
  719. pub(crate) struct HostList {
  720. allocator: ID3D12CommandAllocator,
  721. pub(crate) list: ID3D12GraphicsCommandList,
  722. /// Work for submission time, in recorded order.
  723. deferred: Mutex<Deferred>,
  724. /// Upload memory for data the list's draws make (expanded vertices),
  725. /// reused after a reset.
  726. scratch: Mutex<Scratch>,
  727. /// Host texture states the list assumes, by host copy: at its start and
  728. /// at its end. Lists are recorded on many threads and run in submission
  729. /// order, so the transitions from a texture's real state are made at
  730. /// submission, in `prelude`. Holding the copies keeps every texture the
  731. /// list names alive until it is reset, even if the title releases the
  732. /// resource first.
  733. states: Mutex<States>,
  734. /// What the list does with depth textures that have a colour twin, by
  735. /// twin ([`TwinUse`]).
  736. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  737. /// The list that runs those transitions just before this one, made
  738. /// when the list first has such transitions ([`lazy_prelude`]).
  739. prelude: OnceLock<Option<Prelude>>,
  740. /// The pipelines the list binds, for reports of slow submissions.
  741. pipelines: Mutex<std::collections::BTreeSet<String>>,
  742. /// The work its indirect executions may still do (`indirect`): a
  743. /// shader-writable word, zeroed when the list is submitted, and after
  744. /// it what the clamp notes about mesh records. In memory the CPU maps.
  745. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  746. /// The same words in the card's own memory ([`card_budget`]), which the
  747. /// clamp uses instead when there is one: zeroed in the list before its
  748. /// first clamp, its notes copied to `budget` when the list closes.
  749. card_budget: OnceLock<Option<ID3D12Resource>>,
  750. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  751. /// grown to the largest indirect execution recorded on the list.
  752. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  753. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  754. /// how many batches of this recording have a place in them.
  755. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  756. /// Counts the list in [`ALIVE`] while it lives.
  757. _alive: Counted,
  758. /// The texts of the markers `note_op` set, in order (for device-removed
  759. /// data without marker texts), with the host GPU range a copy reads.
  760. #[cfg(feature = "diagnostics")]
  761. notes: Mutex<Vec<Note>>,
  762. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  763. /// and at the end, and where they are read back.
  764. #[cfg(feature = "diagnostics")]
  765. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  766. }
  767. /// A list's prelude: an allocator and a closed list.
  768. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  769. /// Whether a host list's prelude is made when the list first needs one. A
  770. /// prelude runs the texture transitions and twin copies a list needs before
  771. /// it; lists that name no texture never have one, and every host list was
  772. /// made with one all the same: twice the host objects per list, for the
  773. /// title's 630 lists and for every list made anew.
  774. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  775. fn lazy_prelude() -> bool {
  776. static ON: OnceLock<bool> = OnceLock::new();
  777. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  778. }
  779. /// Timestamps per list (diagnostics); commands past them are not timed.
  780. #[cfg(feature = "diagnostics")]
  781. const STAMPS: u32 = 4096;
  782. /// A marker's text and the host range its command reads (diagnostics).
  783. #[cfg(feature = "diagnostics")]
  784. type Note = (String, Option<(u64, u64)>);
  785. type States = std::collections::HashMap<
  786. usize,
  787. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  788. >;
  789. /// What a list does with a depth texture that has a colour twin
  790. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  791. /// in submission order, so a list cannot know which side an earlier list
  792. /// leaves behind: it notes which sides it uses as it finds them, and its
  793. /// prelude copies one side into the other at submission if that side is
  794. /// behind then. From its first use of a side on, the list knows.
  795. struct TwinUse {
  796. /// The depth texture (the title resource's host copy) and its twin.
  797. depth: std::sync::Arc<crate::resource::HostTexture>,
  798. twin: std::sync::Arc<crate::resource::Twin>,
  799. /// The sides (depth texture, twin) the list uses as it finds them.
  800. needs: [bool; 2],
  801. /// Whether each side lacks what the other was written last, where the
  802. /// list is now; `None`: as the list found it.
  803. behind: [Option<bool>; 2],
  804. /// The draw or dispatch being prepared writes the twin.
  805. writing: bool,
  806. /// The depth plane's twin holds what the plane lacks although the list
  807. /// copied the twins since: the plane's pass waits for the list's close.
  808. late: bool,
  809. }
  810. /// The pass that draws the twin of a depth plane into the plane: one
  811. /// triangle over each mip of each slice, its pixel shader writing the
  812. /// twin's texel as the depth, with the depth test "always" and no stencil
  813. /// (the stencil plane is copied through a buffer and not touched here).
  814. ///
  815. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  816. /// the step times the float nearest 1/65535 (0x37800080). That is how
  817. /// The title's tiled lighting computes the depth of the
  818. /// rectangles it then draws with the test "equal", one class of materials
  819. /// a draw (all six of its vertex shaders multiply the class number by that
  820. /// constant), so the pass and the draw give the host the same float, and
  821. /// the host turns the same float into the same 24 bits. The step divided
  822. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  823. /// and lands in another 24-bit step for 127 of them (none under 385).
  824. const PLANE_CORNERS: &str = r#"
  825. float4 corner(uint i : SV_VertexID) : SV_Position {
  826. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  827. }
  828. "#;
  829. const PLANE_STEPS: &str = r#"
  830. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  831. Texture2DArray<uint> twin : register(t0);
  832. [RootSignature(RS)]
  833. float plane(float4 p : SV_Position) : SV_Depth {
  834. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  835. }
  836. "#;
  837. const PLANE_FLOATS: &str = r#"
  838. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  839. Texture2DArray<float> twin : register(t0);
  840. [RootSignature(RS)]
  841. float plane(float4 p : SV_Position) : SV_Depth {
  842. return twin.Load(int4(int2(p.xy), 0, 0));
  843. }
  844. "#;
  845. /// Views of twins the pass reads, in a heap of ours used as a ring.
  846. /// shortcut: a view must last until its list has run; with one or two
  847. /// passes a frame the ring is far from coming round.
  848. const PLANE_VIEWS: u32 = 256;
  849. /// What the pass draws with: the heap of its views of twins, and per kind
  850. /// of twin (16-bit steps or floats) and depth format the root signature
  851. /// and pipeline, made when first needed (`None`: the host refused).
  852. struct PlanePass {
  853. views: ID3D12DescriptorHeap,
  854. cpu: usize,
  855. gpu: u64,
  856. step: u32,
  857. next: AtomicU32,
  858. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  859. }
  860. /// The pass's root signature and pipeline for one kind of twin and one
  861. /// depth format.
  862. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  863. // SAFETY: D3D12 objects are free-threaded.
  864. unsafe impl Send for PlanePass {}
  865. // SAFETY: as above.
  866. unsafe impl Sync for PlanePass {}
  867. fn plane_pass() -> Option<&'static PlanePass> {
  868. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  869. PASS.get_or_init(|| {
  870. let host = host()?;
  871. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  872. // SAFETY: plain heap creation and queries.
  873. unsafe {
  874. let views: ID3D12DescriptorHeap = host
  875. .device
  876. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  877. Type: kind,
  878. NumDescriptors: PLANE_VIEWS,
  879. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  880. NodeMask: 0,
  881. })
  882. .ok()?;
  883. Some(PlanePass {
  884. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  885. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  886. step: host.device.GetDescriptorHandleIncrementSize(kind),
  887. views,
  888. next: AtomicU32::new(0),
  889. made: Mutex::default(),
  890. })
  891. }
  892. })
  893. .as_ref()
  894. }
  895. /// Compiles function `entry` of `source` for `target` with the system's
  896. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  897. pub(crate) fn compile(
  898. source: &str,
  899. entry: windows::core::PCSTR,
  900. target: windows::core::PCSTR,
  901. ) -> windows::core::Result<Vec<u8>> {
  902. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  903. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  904. let mut code: Option<ID3DBlob> = None;
  905. let mut errors: Option<ID3DBlob> = None;
  906. // SAFETY: the source and names live through the call; out pointers ours.
  907. let compiled = unsafe {
  908. D3DCompile(
  909. source.as_ptr().cast(),
  910. source.len(),
  911. windows::core::s!("victory"),
  912. None,
  913. None,
  914. entry,
  915. target,
  916. 0,
  917. 0,
  918. &mut code,
  919. Some(&mut errors),
  920. )
  921. };
  922. if let Err(e) = compiled {
  923. if let Some(errors) = errors {
  924. // SAFETY: the blob's own bytes.
  925. let text = unsafe {
  926. std::slice::from_raw_parts(
  927. errors.GetBufferPointer().cast::<u8>(),
  928. errors.GetBufferSize(),
  929. )
  930. };
  931. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  932. }
  933. return Err(e);
  934. }
  935. let code = code.ok_or_else(windows::core::Error::empty)?;
  936. // SAFETY: the blob's own bytes.
  937. let bytes = unsafe {
  938. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  939. };
  940. Ok(bytes.to_vec())
  941. }
  942. impl PlanePass {
  943. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  944. /// or of floats and the depth format `format`.
  945. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  946. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  947. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  948. return pipeline.clone();
  949. }
  950. let pipeline = match Self::make(steps, format) {
  951. Ok(pipeline) => Some(pipeline),
  952. Err(e) => {
  953. tracing::warn!(
  954. error = %e,
  955. steps,
  956. format = format.0,
  957. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  958. );
  959. None
  960. }
  961. };
  962. made.push((steps, format.0, pipeline.clone()));
  963. pipeline
  964. }
  965. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  966. use windows::core::s;
  967. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  968. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  969. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  970. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  971. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  972. pShaderBytecode: bytes.as_ptr().cast(),
  973. BytecodeLength: bytes.len(),
  974. };
  975. // SAFETY: the root signature is inside the pixel shader; the
  976. // description points at live data and never releases its pointer.
  977. unsafe {
  978. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  979. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  980. pRootSignature: std::mem::transmute_copy(&root),
  981. VS: code(&vs[..]),
  982. PS: code(&ps[..]),
  983. SampleMask: u32::MAX,
  984. RasterizerState: D3D12_RASTERIZER_DESC {
  985. FillMode: D3D12_FILL_MODE_SOLID,
  986. CullMode: D3D12_CULL_MODE_NONE,
  987. DepthClipEnable: true.into(),
  988. ..Default::default()
  989. },
  990. // Every texel is written; stencil stays off.
  991. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  992. DepthEnable: true.into(),
  993. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  994. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  995. ..Default::default()
  996. },
  997. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  998. DSVFormat: format,
  999. SampleDesc: DXGI_SAMPLE_DESC {
  1000. Count: 1,
  1001. Quality: 0,
  1002. },
  1003. ..Default::default()
  1004. };
  1005. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1006. Ok((root, pipeline))
  1007. }
  1008. }
  1009. }
  1010. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1011. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1012. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1013. /// heap, graphics root signature, pipeline, depth target, viewport,
  1014. /// scissor and topology and puts none of them back: it is for a list that
  1015. /// records nothing of the title's after it.
  1016. fn record_plane_pass(
  1017. list: &ID3D12GraphicsCommandList,
  1018. depth: &ID3D12Resource,
  1019. plane: &ID3D12Resource,
  1020. ) {
  1021. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1022. return;
  1023. };
  1024. // SAFETY: live resources.
  1025. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1026. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1027. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1028. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1029. let steps = twin.Format.0 == 53;
  1030. let format = DXGI_FORMAT(match of.Format.0 {
  1031. 44 => 45,
  1032. 19 => 20,
  1033. typed => typed,
  1034. });
  1035. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1036. return;
  1037. };
  1038. for slice in 0..u32::from(of.DepthOrArraySize) {
  1039. for mip in 0..u32::from(of.MipLevels) {
  1040. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1041. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1042. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1043. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1044. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1045. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1046. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1047. MostDetailedMip: mip,
  1048. MipLevels: 1,
  1049. FirstArraySlice: slice,
  1050. ArraySize: 1,
  1051. ..Default::default()
  1052. },
  1053. },
  1054. };
  1055. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1056. Format: format,
  1057. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1058. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1059. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1060. MipSlice: mip,
  1061. FirstArraySlice: slice,
  1062. ArraySize: 1,
  1063. },
  1064. },
  1065. ..Default::default()
  1066. };
  1067. let target = host.dsv(depth, Some(&target));
  1068. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1069. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1070. ptr: pass.cpu + (slot * pass.step) as usize,
  1071. };
  1072. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1073. ptr: pass.gpu + u64::from(slot * pass.step),
  1074. };
  1075. // SAFETY: an open list; a slot of our heap; live resources and
  1076. // objects (the pass's own live as long as the process).
  1077. unsafe {
  1078. host.device
  1079. .CreateShaderResourceView(plane, Some(&view), cpu);
  1080. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1081. list.SetGraphicsRootSignature(&root);
  1082. list.SetPipelineState(&pipeline);
  1083. list.SetGraphicsRootDescriptorTable(0, gpu);
  1084. list.OMSetRenderTargets(0, None, false, Some(&target));
  1085. list.RSSetViewports(&[D3D12_VIEWPORT {
  1086. TopLeftX: 0.0,
  1087. TopLeftY: 0.0,
  1088. Width: width as f32,
  1089. Height: height as f32,
  1090. MinDepth: 0.0,
  1091. MaxDepth: 1.0,
  1092. }]);
  1093. list.RSSetScissorRects(&[RECT {
  1094. left: 0,
  1095. top: 0,
  1096. right: width as i32,
  1097. bottom: height as i32,
  1098. }]);
  1099. list.IASetPrimitiveTopology(
  1100. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1101. );
  1102. list.DrawInstanced(3, 1, 0, 0);
  1103. }
  1104. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1105. }
  1106. }
  1107. }
  1108. /// Records into `list` the copy of a depth texture into its colour twin
  1109. /// (`colour`) or of the twin into the depth texture, both already in their
  1110. /// copy states: whole textures of one size in one format family, which the
  1111. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1112. /// alone, through the twin's buffer.
  1113. fn record_twin_copy(
  1114. list: &ID3D12GraphicsCommandList,
  1115. depth: &ID3D12Resource,
  1116. twin: &crate::resource::Twin,
  1117. colour: bool,
  1118. ) {
  1119. let (from, to) = if colour {
  1120. (depth, &twin.colour.texture)
  1121. } else {
  1122. (&twin.colour.texture, depth)
  1123. };
  1124. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1125. // shortcut: the depth plane's twin is not given the plane (that is a
  1126. // pass the other way: the plane read by a shader, the twin as its
  1127. // target). The twin then lacks what draws and clears wrote to the
  1128. // plane since shaders last wrote the twin. In the title
  1129. // nothing writes that plane but the twin's pass (its 192 draws against
  1130. // it only test, run 29), so the twin lacks nothing. Counted.
  1131. if colour && twin.plane.is_some() {
  1132. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1133. }
  1134. let Some(through) = &twin.through else {
  1135. // SAFETY: an open list and two live textures.
  1136. unsafe { list.CopyResource(to, from) };
  1137. return;
  1138. };
  1139. // A stencil plane and its twin: each mip and slice of the plane goes
  1140. // into the buffer, laid out as the host lays the plane out for copies,
  1141. // and from the buffer into the other texture, whole subresources both
  1142. // times. In the depth texture the stencil plane's subresources follow
  1143. // the depth plane's; the twin has the one plane.
  1144. let Some(host) = host() else { return };
  1145. // SAFETY: a live texture.
  1146. let of = unsafe { depth.GetDesc() };
  1147. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1148. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1149. // SAFETY: a plain query writing `planes` footprints.
  1150. unsafe {
  1151. host.device.GetCopyableFootprints(
  1152. &of,
  1153. planes,
  1154. planes,
  1155. 0,
  1156. Some(rows.as_mut_ptr()),
  1157. None,
  1158. None,
  1159. None,
  1160. );
  1161. }
  1162. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1163. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1164. // SAFETY: a borrowed pointer the location never releases.
  1165. pResource: unsafe { std::mem::transmute_copy(texture) },
  1166. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1167. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1168. SubresourceIndex: index,
  1169. },
  1170. };
  1171. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1172. // SAFETY: as above.
  1173. pResource: unsafe { std::mem::transmute_copy(through) },
  1174. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1175. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1176. PlacedFootprint: *row,
  1177. },
  1178. };
  1179. let (common, source, dest) = (
  1180. D3D12_RESOURCE_STATE_COMMON,
  1181. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1182. D3D12_RESOURCE_STATE_COPY_DEST,
  1183. );
  1184. // SAFETY: an open list and live resources; the buffer was made as big
  1185. // as these footprints, and rests in the common state between copies.
  1186. unsafe {
  1187. list.ResourceBarrier(&[transition(through, common, dest)]);
  1188. for (i, row) in rows.iter().enumerate() {
  1189. let index = first_from + i as u32;
  1190. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1191. }
  1192. list.ResourceBarrier(&[transition(through, dest, source)]);
  1193. for (i, row) in rows.iter().enumerate() {
  1194. let index = first_to + i as u32;
  1195. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1196. }
  1197. list.ResourceBarrier(&[transition(through, source, common)]);
  1198. }
  1199. }
  1200. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1201. /// builds).
  1202. pub(crate) fn dred_on() -> bool {
  1203. static ON: OnceLock<bool> = OnceLock::new();
  1204. *ON.get_or_init(|| {
  1205. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some()
  1206. })
  1207. }
  1208. /// Indirect mesh dispatches since the last frame line: the largest group
  1209. /// count a record asked for, and the groups asked in all (from the lists'
  1210. /// budget buffers, a run late).
  1211. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1212. /// Whether a list's indirect-work budget lives in the card's own memory
  1213. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1214. /// before). The clamp charges it with atomics, at least two in a row for
  1215. /// every clamp; in mapped memory on a card of its own each of them
  1216. /// crosses the bus.
  1217. fn card_budget() -> bool {
  1218. static ON: OnceLock<bool> = OnceLock::new();
  1219. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1220. }
  1221. /// Whether each list of a submission runs and is timed on its own, slow
  1222. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1223. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1224. #[cfg(feature = "diagnostics")]
  1225. fn timing() -> bool {
  1226. static ON: OnceLock<bool> = OnceLock::new();
  1227. *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some())
  1228. }
  1229. /// Names a host object for the device-removed report, which names the
  1230. /// allocations a page fault hit (only with device-removed data on), or for
  1231. /// the frame recorder (`VICTORY_RECORD`).
  1232. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1233. #[cfg(feature = "diagnostics")]
  1234. if crate::replay::record::on() {
  1235. let text = text();
  1236. crate::replay::record::name(object, &text);
  1237. if dred_on()
  1238. && let Ok(object) = object.cast::<ID3D12Object>()
  1239. {
  1240. // SAFETY: a plain call on a live object.
  1241. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1242. }
  1243. return;
  1244. }
  1245. if dred_on()
  1246. && let Ok(object) = object.cast::<ID3D12Object>()
  1247. {
  1248. // SAFETY: a plain call on a live object.
  1249. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1250. }
  1251. }
  1252. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1253. /// [`LISTS`]`[3]` until it is first reset.
  1254. struct Counted {
  1255. /// Not reset since it was made.
  1256. fresh: std::sync::atomic::AtomicBool,
  1257. }
  1258. impl Counted {
  1259. fn new() -> Counted {
  1260. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1261. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1262. Counted {
  1263. fresh: std::sync::atomic::AtomicBool::new(true),
  1264. }
  1265. }
  1266. /// The list is reset: it is in use.
  1267. fn used(&self) {
  1268. if self.fresh.swap(false, Ordering::Relaxed) {
  1269. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1270. }
  1271. }
  1272. }
  1273. impl Drop for Counted {
  1274. fn drop(&mut self) {
  1275. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1276. self.used();
  1277. }
  1278. }
  1279. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1280. /// mapping and its host GPU address.
  1281. struct Chunk {
  1282. _buffer: ID3D12Resource,
  1283. data: usize,
  1284. gpu: u64,
  1285. }
  1286. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1287. // written only by the list that holds the chunk.
  1288. unsafe impl Send for Chunk {}
  1289. /// Upload chunks handed out front to back: the chunks (each with its
  1290. /// bytes), the one in use and the bytes used in it.
  1291. #[derive(Default)]
  1292. struct Scratch {
  1293. chunks: Vec<(Chunk, u64)>,
  1294. current: usize,
  1295. used: u64,
  1296. }
  1297. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1298. unsafe impl Send for Scratch {}
  1299. impl Drop for Scratch {
  1300. fn drop(&mut self) {
  1301. give_chunks(std::mem::take(&mut self.chunks));
  1302. }
  1303. }
  1304. const SCRATCH_CHUNK: u64 = 4 << 20;
  1305. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1306. /// lists put a few constants or a rectangle's corners there, and every
  1307. /// list that did took 4 MiB of the PC's memory for it.
  1308. const SCRATCH_FIRST: u64 = 256 << 10;
  1309. /// The most bytes of chunks kept while no list holds them.
  1310. const SPARE_MOST: u64 = 128 << 20;
  1311. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1312. /// first needs one, a small one first, and gives all of them back when it
  1313. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1314. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1315. /// host lists of held submissions, which live for one submission, each
  1316. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1317. /// freed per frame of gameplay (run 60).
  1318. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1319. fn scratch_pool() -> bool {
  1320. static ON: OnceLock<bool> = OnceLock::new();
  1321. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1322. }
  1323. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1324. /// for one of the same size.
  1325. struct Spare<T> {
  1326. kept: Vec<(T, u64)>,
  1327. bytes: u64,
  1328. }
  1329. impl<T> Spare<T> {
  1330. const fn new() -> Self {
  1331. Spare { kept: Vec::new(), bytes: 0 }
  1332. }
  1333. /// A kept thing of `size` bytes, the one given last.
  1334. fn take(&mut self, size: u64) -> Option<T> {
  1335. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1336. self.bytes -= size;
  1337. Some(self.kept.remove(at).0)
  1338. }
  1339. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1340. /// `most`: then it comes back.
  1341. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1342. if self.bytes + size > most {
  1343. return Some(thing);
  1344. }
  1345. self.bytes += size;
  1346. self.kept.push((thing, size));
  1347. None
  1348. }
  1349. }
  1350. /// Scratch chunks no list holds.
  1351. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1352. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1353. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1354. if scratch_pool()
  1355. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1356. {
  1357. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1358. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1359. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1360. return Some(chunk);
  1361. }
  1362. let (buffer, data) = host.upload_buffer(size)?;
  1363. name(&buffer, || "list scratch".into());
  1364. // SAFETY: a live buffer.
  1365. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  1366. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1367. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1368. Some(Chunk {
  1369. _buffer: buffer,
  1370. data: data as usize,
  1371. gpu,
  1372. })
  1373. }
  1374. /// A list is done with `chunks` (it was reset after its submissions ran,
  1375. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1376. /// without the pool.
  1377. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1378. if chunks.is_empty() {
  1379. return;
  1380. }
  1381. let mut freed = Vec::new();
  1382. {
  1383. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1384. for (chunk, size) in chunks {
  1385. let back = if scratch_pool() {
  1386. spare.give(chunk, size, SPARE_MOST)
  1387. } else {
  1388. Some(chunk)
  1389. };
  1390. match back {
  1391. None => {
  1392. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1393. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1394. }
  1395. Some(chunk) => {
  1396. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1397. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1398. freed.push(chunk);
  1399. }
  1400. }
  1401. }
  1402. }
  1403. // Freed outside the lock.
  1404. drop(freed);
  1405. }
  1406. /// What the host keeps for copies in the card's own memory
  1407. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1408. struct CardWork {
  1409. /// Before a submission's lists: what changed on the copies' CPU side
  1410. /// goes to their card side. Those not in use: a plan takes one and
  1411. /// gives it back when its submission has run (`Host::card_done`), so
  1412. /// that submissions sent ahead ([`late`]) each have their own.
  1413. sync: Vec<Prelude>,
  1414. /// After them, in the same submission: the compare of the declared
  1415. /// ranges with their bytes from before. As `sync`.
  1416. check: Vec<Prelude>,
  1417. /// After it ran: the pieces that differ come down.
  1418. fetch: Prelude,
  1419. root: ID3D12RootSignature,
  1420. pso: ID3D12PipelineState,
  1421. /// One dword per piece compared, set where the piece differs: PC
  1422. /// memory, mapped (buffer, mapping, bytes).
  1423. differs: (ID3D12Resource, usize, u64),
  1424. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1425. fetched: Option<(ID3D12Resource, usize, u64)>,
  1426. /// The dwords of `differs` taken by plans whose results were not read
  1427. /// yet.
  1428. taken: u32,
  1429. /// Plans made and not done with (`Host::card_done`).
  1430. out: u32,
  1431. }
  1432. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1433. // under the submission lock.
  1434. unsafe impl Send for CardWork {}
  1435. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1436. /// The compare of a declared range of a copy in the card's memory with
  1437. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1438. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1439. /// gets a dword per piece, 1 where a byte differs. The offsets are widened
  1440. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1441. /// byte just outside the range costs a fetch that finds nothing.
  1442. ///
  1443. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1444. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1445. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1446. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1447. /// those steps.
  1448. pub(crate) const CARD_COMPARE: &str = r#"
  1449. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1450. cbuffer Span : register(b0) {
  1451. uint first; // the first piece
  1452. uint skew; // where the copy starts in its piece 0
  1453. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1454. uint pieces;
  1455. uint out_at; // the first piece's dword in `differs`, in bytes
  1456. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1457. };
  1458. ByteAddressBuffer now : register(t0);
  1459. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1460. // last sent up (or hashed whole, the first time).
  1461. RWByteAddressBuffer hashes : register(u0);
  1462. RWByteAddressBuffer differs : register(u1);
  1463. groupshared uint4 parts[64];
  1464. [RootSignature(RS)]
  1465. [numthreads(64, 1, 1)]
  1466. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1467. uint piece = first + id.x;
  1468. uint lo = piece * 65536u;
  1469. lo = lo > skew ? lo - skew : 0u;
  1470. uint hi = min((piece + 1u) * 65536u - skew, size);
  1471. lo = lo & ~15u;
  1472. hi = (hi + 15u) & ~15u;
  1473. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1474. [loop]
  1475. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1476. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1477. h = h.yzwx ^ (h >> 15);
  1478. }
  1479. parts[thread] = h;
  1480. GroupMemoryBarrierWithGroupSync();
  1481. if (thread != 0u) return;
  1482. h = parts[0];
  1483. [loop]
  1484. for (uint i = 1u; i < 64u; ++i) {
  1485. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1486. h = h.yzwx ^ (h >> 15);
  1487. }
  1488. if (compare != 0u) {
  1489. differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u);
  1490. // With the copy-back on its own thread: the next compare of the
  1491. // piece finds what is written from here on.
  1492. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1493. } else {
  1494. hashes.Store4(piece * 16u, h);
  1495. }
  1496. }
  1497. "#;
  1498. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1499. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1500. /// parts a dispatch can hold.
  1501. ///
  1502. /// # Safety
  1503. /// The list is open with the compare's root signature, pipeline and buffers
  1504. /// set, and the pieces lie in the buffer.
  1505. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1506. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1507. let mut done = 0;
  1508. while done < span.pieces {
  1509. let n = (span.pieces - done).min(MOST);
  1510. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1511. // SAFETY: the caller's.
  1512. unsafe {
  1513. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1514. list.Dispatch(n, 1, 1);
  1515. }
  1516. done += n;
  1517. }
  1518. }
  1519. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1520. /// the card's memory are hashed in runs of pieces that touch, each piece
  1521. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1522. /// per range sent up.
  1523. ///
  1524. /// These passes are ours, they run on the card before every submission's
  1525. /// lists: a pass takes the time of one piece however few its pieces are.
  1526. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1527. /// a piece hashed when it need not be, or not hashed when it should, costs
  1528. /// a fetch that finds nothing and loses no shader write.
  1529. fn rehash_runs() -> bool {
  1530. static ON: OnceLock<bool> = OnceLock::new();
  1531. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1532. }
  1533. /// Since the last frame-rate line, of our own passes over copies in the
  1534. /// card's memory: hash passes after ranges were sent up, the pieces they
  1535. /// hashed, and compare passes after the lists.
  1536. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1537. /// Whether what shaders wrote to copies in the card's memory is merged
  1538. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1539. /// default). The pieces the card's compare found differing come down in
  1540. /// one fetch and were then merged one after the other on the thread that
  1541. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1542. /// with the copy's CPU side byte by byte and put into title memory through
  1543. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1544. /// so eight threads take an eighth of them each.
  1545. fn wide_merge() -> bool {
  1546. static ON: OnceLock<bool> = OnceLock::new();
  1547. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1548. }
  1549. /// One declared range of a copy in the card's memory, in a submission.
  1550. struct CardRange {
  1551. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1552. /// As declared (title addresses), for the statistics.
  1553. declared: (usize, usize),
  1554. span: crate::shadow::CardSpan,
  1555. /// Its first piece's dword in the compare's results.
  1556. at: u32,
  1557. /// Whether the card compares it; else every piece is fetched.
  1558. compared: bool,
  1559. }
  1560. /// What a submission does for copies in the card's memory.
  1561. struct CardPlan {
  1562. ranges: Vec<CardRange>,
  1563. /// The compare, run after the submission's lists.
  1564. check: Option<ID3D12CommandList>,
  1565. /// The copies whose card side was brought up to date, alive until the
  1566. /// submission has run.
  1567. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1568. /// The lists of ours the plan recorded (whether the compare, the
  1569. /// list), given back by `Host::card_done`.
  1570. lists: Vec<(bool, Prelude)>,
  1571. /// With [`relay`]: the number of the send to copies in the card's memory
  1572. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1573. sent_as: u64,
  1574. }
  1575. /// One piece of submission-time work, in recorded order.
  1576. enum Step {
  1577. /// A copy into title memory (destination, source, bytes): the title's
  1578. /// buffer copies, which later refreshes must see.
  1579. Copy(usize, usize, usize),
  1580. /// A copy of title memory into the list's own upload memory; if a
  1581. /// descriptor slot shows that memory and nothing else does (a constant
  1582. /// buffer of a table made for the draw), the title heap and the slot.
  1583. Fill(usize, usize, usize, Option<(usize, u32)>),
  1584. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1585. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1586. /// intervenes.
  1587. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1588. /// Work that may write title memory.
  1589. Run(Box<dyn Fn() + Send>),
  1590. /// Work that writes host memory only, and the title memory it reads
  1591. /// (from, to; empty for none).
  1592. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1593. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1594. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1595. /// Brings a texture's staging buffer up to date: once per submission,
  1596. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1597. Texture(std::sync::Arc<crate::texture::Staging>),
  1598. }
  1599. /// What a list does on the CPU when it is submitted: copies between host
  1600. /// memory regions (title buffers, upload buffers and buffer copies), and
  1601. /// the upload buffers its GPU commands read, kept until the list is reset.
  1602. #[derive(Default)]
  1603. struct Deferred {
  1604. /// Destination, source, bytes.
  1605. copies: Vec<Step>,
  1606. uploads: Vec<ID3D12Resource>,
  1607. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1608. upload_bytes: u64,
  1609. /// Host objects the list's commands name (pipelines, root signatures,
  1610. /// descriptor heaps): the title may release its objects before it
  1611. /// submits the list.
  1612. kept: Vec<windows::core::IUnknown>,
  1613. /// Buffer ranges refreshed since the last title copy (host copy,
  1614. /// address, bytes): refreshing them again would find the same bytes.
  1615. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1616. /// Textures whose contents the list brings up to date.
  1617. textures: std::collections::HashSet<usize>,
  1618. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1619. /// bytes.
  1620. writes: Vec<(usize, crate::queue::Written, usize)>,
  1621. /// Textures read back (texture to buffer copies), done once the list
  1622. /// has run: the host buffer the list copies the texels into, the title
  1623. /// memory they go to, the bytes of a row, the rows, the title's row
  1624. /// pitch.
  1625. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1626. /// Whether the indirect-work budget is zeroed for this recording (a
  1627. /// step on the CPU, or in the list for the card's copy).
  1628. budget_zeroed: bool,
  1629. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1630. /// interface pointer) that a clamp in this recording left readable as
  1631. /// indirect arguments; 0 if none. It stays readable until the next
  1632. /// clamp into it ([`HostList::indirect_state`]).
  1633. indirect_readable: usize,
  1634. }
  1635. impl Deferred {
  1636. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1637. /// reset.
  1638. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1639. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1640. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1641. self.upload_bytes += size;
  1642. self.uploads.push(buffer);
  1643. }
  1644. }
  1645. impl Drop for Deferred {
  1646. fn drop(&mut self) {
  1647. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1648. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1649. }
  1650. }
  1651. /// Whether a queue's submissions go to the card without a wait for each
  1652. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1653. /// waits for every list on its own).
  1654. ///
  1655. /// Every submission was prepared, sent, waited for and copied back before
  1656. /// the next one was looked at, so the card stood idle while we prepared
  1657. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1658. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1659. /// other, on the one thread that submits.
  1660. ///
  1661. /// With the switch a queue's submission is sent and joins a line of
  1662. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1663. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1664. /// for the card, what their shaders wrote copied back once per byte, then
  1665. /// their bottom-of-pipe writes and the fence signals behind them, in
  1666. /// order) at the next point where the title, or our own preparing, can
  1667. /// observe what they do. Those points, exactly:
  1668. ///
  1669. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1670. /// read-back or map of a texture, a clear or upload run at once;
  1671. /// 2. the next submission reads title memory that a flight's shaders may
  1672. /// write: a title buffer copy, a fill of upload memory, a texture's
  1673. /// memory, any step that runs code of ours on title memory
  1674. /// ([`late_blocked`]);
  1675. /// 3. the next submission refreshes a range of a host copy that a flight's
  1676. /// shaders may write, and the title wrote a page of it since it was last
  1677. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1678. /// alone until the flight's writes are back, as it always did within a
  1679. /// submission;
  1680. /// 4. a queue stands at a wait for a memory value that no flight's
  1681. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1682. /// write ([`late_met`]);
  1683. /// 5. the title blocks on a fence without an event;
  1684. /// 6. the card has run every flight (a thread of ours waits for that:
  1685. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1686. ///
  1687. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1688. /// when the card has really run the work, later than before and never
  1689. /// earlier; a fence signalled on a queue while flights are in the air is
  1690. /// set behind them. A wait for a memory value that a flight's
  1691. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1692. /// the card behind that flight, which is the order the wait asks for.
  1693. ///
  1694. /// What it assumes beyond today: memory the title rewrites between two of
  1695. /// its submissions, without waiting for the first, may be seen by the
  1696. /// first's shaders (as on the console, where the card reads title memory
  1697. /// when it runs, not when the list is submitted).
  1698. pub(crate) fn late() -> bool {
  1699. late_stage() > 0
  1700. }
  1701. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1702. fn late_stage() -> u8 {
  1703. static STAGE: OnceLock<u8> = OnceLock::new();
  1704. *STAGE.get_or_init(|| {
  1705. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1706. return 0;
  1707. }
  1708. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1709. Ok("1") => 1,
  1710. Ok("2") => 2,
  1711. Ok("3") => 3,
  1712. // The relay alone: on top of stage 3.
  1713. Err(_) if crate::shadow::relay() => 3,
  1714. _ => 0,
  1715. }
  1716. })
  1717. }
  1718. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1719. /// longer a point. Where the title wrote a page that lies in a range a
  1720. /// flight's shaders may write, the bytes the title changed are found (the
  1721. /// page as it is now against what the copy held when the flight was
  1722. /// prepared) and put into the copy, and only those: what the flight's
  1723. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1724. /// flights are settled for it only where that cannot be done: memory that
  1725. /// is not write-watched, or a copy in the card's memory with more changed
  1726. /// runs than a submission should send up one by one.
  1727. ///
  1728. /// In run 92 (stage 1) this point settled the flights five times a frame
  1729. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1730. /// frame of waiting were left of 200.
  1731. ///
  1732. /// What differs from settling first: a byte both the title and a flight's
  1733. /// shader wrote is the title's if the shader wrote it first, the shader's
  1734. /// if it wrote it afterwards; settled first it was always the shader's.
  1735. /// The title writing a byte a shader of its own is writing is a race on
  1736. /// the console too.
  1737. fn late_exact() -> bool {
  1738. late_stage() > 1
  1739. }
  1740. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1741. /// no longer a point where flights are settled). The copy to the back
  1742. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1743. /// its own for each present in the air) and the swap chain is told to
  1744. /// present behind it; the queue's call returns, and the card finishes the
  1745. /// frame while the title records the next one. What the title is told
  1746. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1747. /// has run it, by the settling thread.
  1748. ///
  1749. /// What is left out with it: the look whether the presented frame is black
  1750. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1751. /// or listed is presented the old way. Once every second and a half a
  1752. /// submission settles the flights all the same, for the sweep that lets
  1753. /// idle host objects go (it needs nothing in the air).
  1754. pub(crate) fn late_free_present() -> bool {
  1755. late_stage() > 2
  1756. }
  1757. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1758. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1759. /// and is off with it, in the timing run and with kept snapshots).
  1760. ///
  1761. /// With [`late`] alone every settle does three things on the thread that
  1762. /// holds the submission lock: it waits for everything in the air, copies
  1763. /// back with the card standing, and only then goes on preparing. The frame
  1764. /// stays a relay: the card works about 242 ms of it and one thread
  1765. /// prepares, waits and copies back for about 220.
  1766. ///
  1767. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1768. /// soon as the card has run them, in the order they were sent and without
  1769. /// the submission lock: it fetches and merges what their shaders wrote to
  1770. /// copies in the card's memory, compares and merges the other copies,
  1771. /// frees the flights' ranges, and then does their read-backs, their
  1772. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1773. /// order. The submitting thread meanwhile prepares and sends the next
  1774. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  1775. /// that thread has landed everything in the air, at the same points as
  1776. /// before (the list in [`late`]), so whoever can observe title memory, a
  1777. /// fence or a present still does so only after the flights before it are
  1778. /// merged.
  1779. ///
  1780. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  1781. /// flight; a merge that never stores into memory the card may be writing;
  1782. /// sends to card copies numbered) and here: flights land in the order of
  1783. /// [`LINE`] by one thread, so a later flight's results never reach title
  1784. /// memory before an earlier flight's; the compare on the card stores the
  1785. /// hash it made, so each flight's compare flags exactly what changed since
  1786. /// the compare before it, however late the pieces are fetched; the fetch
  1787. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  1788. /// title bytes the card had received when it ran.
  1789. pub(crate) fn relay() -> bool {
  1790. static ON: OnceLock<bool> = OnceLock::new();
  1791. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  1792. }
  1793. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  1794. /// title memory a flight's shaders may write (a title buffer copy, a fill
  1795. /// of upload memory, a texture) waits only until the flights that declared
  1796. /// that memory have landed, not for everything in the air; and at
  1797. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  1798. /// both wait for everything.
  1799. fn relay_exact() -> bool {
  1800. static ON: OnceLock<bool> = OnceLock::new();
  1801. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  1802. // since the walls of the first room were found drawn in every run with
  1803. // this set and in fewer than half without it).
  1804. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  1805. }
  1806. /// Whether the pieces the relay fetches from the card's memory come over the
  1807. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  1808. /// draws.
  1809. ///
  1810. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  1811. /// and with the relay that is most of a frame: the thread that lands flights
  1812. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  1813. /// a few milliseconds of copying, and everything that waits for a landing
  1814. /// (the title's fences, reads of memory flights may write) waited with it.
  1815. ///
  1816. /// What changes: the fetch runs when its flights are done and beside later
  1817. /// submissions, so of the sends of title bytes it is only known to have run
  1818. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  1819. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  1820. /// the title's, newer than what the flights wrote. A later flight's bytes
  1821. /// may be in what is fetched, as before.
  1822. fn relay_copy() -> bool {
  1823. static ON: OnceLock<bool> = OnceLock::new();
  1824. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  1825. }
  1826. /// Told when something joins [`LINE`], for the thread that lands flights
  1827. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  1828. /// what queues hold.
  1829. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  1830. /// Told when flights have landed ([`relay`]): who waits for that looks
  1831. /// again.
  1832. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  1833. /// With [`relay`], the order of what we put on the queue: the number of
  1834. /// sends of changed ranges to copies in the card's memory so far
  1835. /// (`Host::card_before`). Held from the taking of the ranges until their
  1836. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  1837. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  1838. /// later one.
  1839. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  1840. /// Since the last frame-rate line, of the thread that lands flights
  1841. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  1842. /// card with nothing to land, microseconds it waited for fetches of card
  1843. /// copies' pieces, microseconds of landing in all.
  1844. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  1845. /// Of the line's things in order (a flight: the value signalled on the
  1846. /// host's fence behind it; a write or a signal behind a flight: `None`):
  1847. /// how many, from the front, can be landed when the card has reached
  1848. /// `completed`: everything ahead of the first flight it has not run. A
  1849. /// later flight never lands before an earlier one, and what follows a
  1850. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  1851. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  1852. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  1853. }
  1854. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  1855. /// holds, for every piece of every range of the plan, the copy, the
  1856. /// piece's number in the copy and whether the compare flagged it there (or
  1857. /// did not run). The pieces to fetch, under whichever range: all of them
  1858. /// flagged under any. Two ranges of a plan may hold parts of the same
  1859. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  1860. /// the hash, so the second of them may find it stored already and not
  1861. /// flag it.
  1862. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> std::collections::HashSet<(usize, u32)> {
  1863. flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect()
  1864. }
  1865. #[cfg(test)]
  1866. mod relay_tests {
  1867. use super::{flagged_pieces, landable};
  1868. /// Two flights and what follows each: nothing of the second lands
  1869. /// before the card has run it, and nothing behind a flight lands
  1870. /// before the flight.
  1871. #[test]
  1872. fn flights_land_in_the_order_they_were_sent() {
  1873. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  1874. let line = [Some(5), None, None, Some(6), None];
  1875. assert_eq!(landable(&line, 4), 0);
  1876. assert_eq!(landable(&line, 5), 3);
  1877. assert_eq!(landable(&line, 6), 5);
  1878. assert_eq!(landable(&line, u64::MAX), 5);
  1879. // Signals with no flight ahead land at once; behind one they wait.
  1880. assert_eq!(landable(&[None, None], 0), 2);
  1881. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  1882. assert_eq!(landable(&[], 3), 0);
  1883. // After the first three landed, the rest when its turn comes.
  1884. assert_eq!(landable(&line[3..], 5), 0);
  1885. assert_eq!(landable(&line[3..], 6), 2);
  1886. }
  1887. /// A piece flagged under one range of a plan is fetched under every
  1888. /// range that holds a part of it; pieces of other copies are not.
  1889. #[test]
  1890. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  1891. let (a, b) = (0x1000usize, 0x2000usize);
  1892. // Copy a: piece 3 under two ranges, flagged under the first only;
  1893. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  1894. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  1895. let fetch = flagged_pieces(&flags);
  1896. assert!(fetch.contains(&(a, 3)));
  1897. assert!(!fetch.contains(&(a, 4)));
  1898. assert!(!fetch.contains(&(b, 3)));
  1899. assert!(fetch.contains(&(b, 9)));
  1900. assert_eq!(fetch.len(), 2);
  1901. }
  1902. }
  1903. /// The most host lists in the air before the flights are settled
  1904. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  1905. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  1906. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  1907. /// 32 settled the flights three times a
  1908. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  1909. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  1910. /// descriptor slots, upload
  1911. /// memory and scratch chunks are held until then, and a frame's lists held
  1912. /// all at once ran the slots out before (run 45).
  1913. fn late_most() -> usize {
  1914. static MOST: OnceLock<usize> = OnceLock::new();
  1915. *MOST.get_or_init(|| {
  1916. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  1917. })
  1918. }
  1919. /// Whether a submission with bottom-of-pipe writes may fly
  1920. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  1921. /// the title is told at once, as before; for telling a title that polls
  1922. /// such a value from one that does not).
  1923. fn late_writes() -> bool {
  1924. static ON: OnceLock<bool> = OnceLock::new();
  1925. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  1926. }
  1927. /// Per host copy, the ranges a submission's shaders may write, as declared
  1928. /// (address, end).
  1929. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  1930. /// What [`Host::submit`] hands back for a submission it sent and did not
  1931. /// wait for.
  1932. struct Sent {
  1933. /// Its number among the submissions started.
  1934. number: u64,
  1935. card: Option<CardPlan>,
  1936. back: Vec<Declared>,
  1937. /// What was taken off it to be done on the card.
  1938. own: Option<card_steps::Taken>,
  1939. /// Its bottom-of-pipe writes.
  1940. writes: Vec<(usize, crate::queue::Written, usize)>,
  1941. }
  1942. /// A submission on the card that has not been waited for ([`late`]): its
  1943. /// host lists, taken from the title's (which it may reset meanwhile), and
  1944. /// what is to be done once it has run.
  1945. struct Flight {
  1946. number: u64,
  1947. /// The value signalled on the host's fence behind it.
  1948. fence: u64,
  1949. lists: Vec<crate::list::Detached>,
  1950. order: Vec<usize>,
  1951. card: Option<CardPlan>,
  1952. back: Vec<Declared>,
  1953. /// The list of ours that ran ahead of them ([`card_steps`]).
  1954. own: Option<card_steps::Taken>,
  1955. }
  1956. /// One thing in the line of what waits for the card, in order.
  1957. enum Late {
  1958. Run(Flight),
  1959. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  1960. Write(usize, crate::queue::Written, usize),
  1961. /// A fence (its address) signalled behind the flights before it.
  1962. Signal(usize, u64),
  1963. }
  1964. struct Line {
  1965. line: Vec<Late>,
  1966. /// The title memory the flights' shaders may write (address, end), in
  1967. /// order and joined.
  1968. written: Vec<(usize, usize)>,
  1969. /// Host lists in the flights.
  1970. lists: usize,
  1971. /// The value signalled on the host's fence behind the last flight.
  1972. target: u64,
  1973. /// A settle has taken the line and is not done: a signal still goes
  1974. /// behind it.
  1975. settling: bool,
  1976. /// Something was settled away from a queue's own calls: the helper
  1977. /// thread looks at what queues hold.
  1978. poke: bool,
  1979. /// Host lists of settled flights, reset and given back outside the
  1980. /// submission lock ([`land`]: a settle may run under a caller's own
  1981. /// locks).
  1982. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  1983. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  1984. /// landed (taken out of `line`, not done yet), for [`late_met`].
  1985. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  1986. /// With [`card_steps`]: what the flights being landed write.
  1987. landing: Vec<card_steps::Writer>,
  1988. }
  1989. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  1990. // into; touched under the lock.
  1991. unsafe impl Send for Line {}
  1992. static LINE: Mutex<Line> = Mutex::new(Line {
  1993. line: Vec::new(),
  1994. written: Vec::new(),
  1995. lists: 0,
  1996. target: 0,
  1997. settling: false,
  1998. poke: false,
  1999. landed: Vec::new(),
  2000. in_hand: Vec::new(),
  2001. landing: Vec::new(),
  2002. });
  2003. /// Told when a flight joins [`LINE`] or it is poked.
  2004. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2005. fn line() -> std::sync::MutexGuard<'static, Line> {
  2006. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2007. }
  2008. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2009. const WHY_SYNC: usize = 2;
  2010. const WHY_CARD_DONE: usize = 3;
  2011. const WHY_VALUE: usize = 4;
  2012. const WHY_STALE: usize = 5;
  2013. const WHY_READ: usize = 6;
  2014. const WHY_RUN: usize = 7;
  2015. const WHY_MOST: usize = 8;
  2016. const WHY_WRITES: usize = 9;
  2017. const WHY_FENCE: usize = 10;
  2018. /// Since the last frame-rate line: submissions sent without a wait;
  2019. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2020. /// microseconds settles waited for the card; value waits met by a flight's
  2021. /// bottom-of-pipe write; fence signals set behind flights.
  2022. /// Then: the settles for title memory read, by what read it (a buffer
  2023. /// copy, a fill of upload memory, a texture).
  2024. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2025. /// Since the last frame-rate line: the microseconds settles waited for the
  2026. /// card, by why they settled (the `WHY_` places).
  2027. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2028. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2029. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2030. if from >= to {
  2031. return false;
  2032. }
  2033. let at = ranges.partition_point(|r| r.1 <= from);
  2034. ranges.get(at).is_some_and(|r| r.0 < to)
  2035. }
  2036. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2037. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2038. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2039. ranges.sort_unstable();
  2040. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2041. for &(from, to) in ranges.iter() {
  2042. match out.last_mut() {
  2043. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2044. _ => out.push((from, to)),
  2045. }
  2046. }
  2047. *ranges = out;
  2048. }
  2049. /// Whether anything is in the air.
  2050. fn flying() -> bool {
  2051. if !late() {
  2052. return false;
  2053. }
  2054. let line = line();
  2055. // (With the relay: also while flights are being landed.)
  2056. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2057. }
  2058. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2059. /// before they are settled, if so. Preparing reads title memory on the
  2060. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2061. /// runs steps of ours that may read or write it anywhere; what the
  2062. /// flights' shaders write is not there yet.
  2063. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2064. let (written, copies) = {
  2065. let line = line();
  2066. if line.written.is_empty() {
  2067. return None;
  2068. }
  2069. (line.written.clone(), card_steps::copies(&line))
  2070. };
  2071. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2072. }
  2073. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2074. /// flights when the title itself wrote the memory since they were given it
  2075. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2076. ///
  2077. /// The title's 174 MB heap is declared written as a whole (a root view has
  2078. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2079. /// bytes a frame, at a new place each time, waited for every flight's
  2080. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2081. /// named). The title writes those bytes just before the draw that reads
  2082. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2083. ///
  2084. /// Or no shader's write went into that page in the last 600 frames
  2085. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2086. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2087. /// before the page was taken.
  2088. ///
  2089. /// What can go wrong: a constant a flight's shader really writes, in a
  2090. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2091. /// for the first time, is read as it was before that flight.
  2092. fn fill_is_titles(src: usize, len: usize) -> bool {
  2093. const SMALL: usize = 64 << 10;
  2094. static ON: OnceLock<bool> = OnceLock::new();
  2095. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2096. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2097. }
  2098. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2099. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2100. /// in (start, bytes).
  2101. #[cfg(feature = "diagnostics")]
  2102. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2103. /// How often and how long, and the address the last one read.
  2104. #[cfg(feature = "diagnostics")]
  2105. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2106. /// What the wait that comes next is for, and why not on the card.
  2107. #[cfg(feature = "diagnostics")]
  2108. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2109. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2110. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2111. /// shaders.
  2112. #[cfg(feature = "diagnostics")]
  2113. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2114. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2115. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2116. /// raw address (1).
  2117. #[cfg(feature = "diagnostics")]
  2118. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2119. if len < 1 << 20 {
  2120. return;
  2121. }
  2122. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2123. let e = all
  2124. .get_or_insert_with(Default::default)
  2125. .entry((address as usize, (address + len) as usize, pipeline))
  2126. .or_insert_with(|| {
  2127. let shaders = match pipeline {
  2128. 0 => "a view in a table".into(),
  2129. 1 => "a raw address".into(),
  2130. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2131. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2132. }),
  2133. };
  2134. (0, shaders)
  2135. });
  2136. e.0 += 1;
  2137. }
  2138. #[cfg(feature = "diagnostics")]
  2139. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2140. let i = written.partition_point(|r| r.1 <= at);
  2141. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2142. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2143. let why = blamed.1;
  2144. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2145. }
  2146. /// Why [`card_steps`] left the submission to the wait that comes next.
  2147. #[cfg(feature = "diagnostics")]
  2148. fn refused(why: &'static str) {
  2149. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2150. }
  2151. /// The wait for what [`blame`] last named, or a wait of another reason than
  2152. /// title memory read, took `us`.
  2153. #[cfg(feature = "diagnostics")]
  2154. fn blamed(why: usize, us: u64) {
  2155. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2156. let (key, at) = match (why, named) {
  2157. (WHY_READ, Some(named)) => named,
  2158. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2159. _ => {
  2160. let kind = match why {
  2161. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2162. WHY_VALUE => "a memory value",
  2163. WHY_STALE => "title memory changed under shader writes",
  2164. WHY_RUN => "a step of ours",
  2165. WHY_MOST => "lists in the air",
  2166. WHY_FENCE => "a blocking fence wait",
  2167. _ => "another reason",
  2168. };
  2169. ((kind, "", 0, 0, 0), 0)
  2170. }
  2171. };
  2172. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2173. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2174. *e = (e.0 + 1, e.1 + us, at);
  2175. }
  2176. /// For the frame-rate line: the five that waited longest.
  2177. #[cfg(feature = "diagnostics")]
  2178. fn log_blame(frames: f64) {
  2179. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2180. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2181. let mut all: Vec<_> = all.into_iter().collect();
  2182. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2183. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2184. // The passes that declare it written, the ones that do so most.
  2185. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2186. for ((a, b, _), (n, shaders)) in &wide {
  2187. if *a < at + len && at < *b {
  2188. *passes.entry(shaders).or_default() += n;
  2189. }
  2190. }
  2191. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2192. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2193. let passes: Vec<String> =
  2194. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2195. tracing::info!(
  2196. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2197. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2198. us as f64 / 1e3 / frames,
  2199. n as f64 / frames,
  2200. passes.join(", "),
  2201. if why.is_empty() { "" } else { "; not done on the card: " },
  2202. );
  2203. }
  2204. }
  2205. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2206. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2207. touches(written, src, src + len) && !fill_is_titles(src, len)
  2208. }
  2209. /// Whether they stop a title buffer copy, and if so whether by its source.
  2210. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2211. let read = read_blocked(written, src, len);
  2212. (read || touches(written, dst, dst + len)).then_some(read)
  2213. }
  2214. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2215. /// may write (in order, joined); `count` whether the kind of read is
  2216. /// counted for the frame line.
  2217. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2218. if written.is_empty() {
  2219. return None;
  2220. }
  2221. for list in runs {
  2222. for step in &list.deferred().copies {
  2223. match step {
  2224. &Step::Copy(dst, src, len) => {
  2225. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2226. if count {
  2227. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2228. #[cfg(feature = "diagnostics")]
  2229. if _read {
  2230. blame("a buffer copy's source", written, src, len);
  2231. } else {
  2232. blame("a buffer copy's destination", written, dst, len);
  2233. }
  2234. }
  2235. return Some(WHY_READ);
  2236. }
  2237. }
  2238. &Step::Fill(_, src, len, _) => {
  2239. if read_blocked(written, src, len) {
  2240. if count {
  2241. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2242. #[cfg(feature = "diagnostics")]
  2243. blame("a fill of upload memory", written, src, len);
  2244. }
  2245. return Some(WHY_READ);
  2246. }
  2247. }
  2248. Step::Texture(staging) => {
  2249. let (at, len) = staging.memory();
  2250. if touches(written, at, at + len) {
  2251. if count {
  2252. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2253. #[cfg(feature = "diagnostics")]
  2254. blame("a texture", written, at, len);
  2255. }
  2256. return Some(WHY_READ);
  2257. }
  2258. }
  2259. Step::Run(_) => return Some(WHY_RUN),
  2260. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2261. }
  2262. }
  2263. }
  2264. None
  2265. }
  2266. /// With flights in the air, after the submission's write-watch asking:
  2267. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2268. /// may write and that the title wrote since it was last copied. The
  2269. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2270. /// the title's bytes there would reach the card a submission late.
  2271. fn stale_under_flights(runs: &[&HostList]) -> bool {
  2272. use std::sync::Arc;
  2273. // Per copy, the span of what is refreshed (a flush brings that much
  2274. // up to date at most).
  2275. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2276. for list in runs {
  2277. for step in &list.deferred().copies {
  2278. if let Step::Refresh(shadow, address, len) = step
  2279. && shadow.writes_pending()
  2280. {
  2281. match spans.iter_mut().find(|s| Arc::ptr_eq(&s.0, shadow)) {
  2282. Some(s) => (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len)),
  2283. None => spans.push((shadow.clone(), *address, *address + *len)),
  2284. }
  2285. }
  2286. }
  2287. }
  2288. if late_exact() {
  2289. // The title's bytes are put in beside the flights' writes; a
  2290. // settle is still due where that could not be done. At most this
  2291. // many changed runs go up to copies in the card's memory, each a
  2292. // copy of its own there.
  2293. let mut runs_left = 512;
  2294. return spans.iter().any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2295. }
  2296. spans.iter().any(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from))
  2297. }
  2298. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2299. /// air, if there are any, and is set when they are settled. Whether it
  2300. /// did; if not the caller sets the fence now.
  2301. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2302. if !late() {
  2303. return false;
  2304. }
  2305. let mut line = line();
  2306. if line.line.is_empty() && !line.settling {
  2307. return false;
  2308. }
  2309. line.line.push(Late::Signal(fence, value));
  2310. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2311. drop(line);
  2312. // A signal alone (behind a settle under way) has no flight to wake
  2313. // the helper thread for it.
  2314. LINE_MOVED.notify_one();
  2315. RELAY_MOVED.notify_one();
  2316. true
  2317. }
  2318. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2319. /// whether it is met once the flights in the air have run. A flight's
  2320. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2321. /// for the card: the part behind the wait goes to the card behind that
  2322. /// flight, which is the order the wait asks for. If the flights may write
  2323. /// the value in a way not known here (shaders, a timestamp, another
  2324. /// width), they are settled and memory is asked again.
  2325. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2326. let (address, bytes) = wait.place();
  2327. {
  2328. let line = line();
  2329. if line.line.is_empty() && line.in_hand.is_empty() {
  2330. return false;
  2331. }
  2332. let mut unsure = touches(&line.written, address, address + bytes);
  2333. // (With the relay: first the writes of flights being landed.)
  2334. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2335. Late::Write(at, what, n) => Some((at, what, n)),
  2336. _ => None,
  2337. }));
  2338. for (at, what, n) in writes {
  2339. if *at >= address + bytes || address >= *at + *n {
  2340. continue;
  2341. }
  2342. match what {
  2343. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2344. if wait.holds_for(*v) {
  2345. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2346. return true;
  2347. }
  2348. }
  2349. _ => unsure = true,
  2350. }
  2351. }
  2352. if !unsure {
  2353. return false;
  2354. }
  2355. }
  2356. settle_now(WHY_VALUE);
  2357. wait.met()
  2358. }
  2359. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2360. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2361. pub(crate) fn settle_now(why: usize) {
  2362. if !late() {
  2363. return;
  2364. }
  2365. let Some(host) = host() else {
  2366. return;
  2367. };
  2368. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2369. host.settle(&mut submitted, why);
  2370. }
  2371. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2372. pub(crate) fn settle_for_present() {
  2373. settle_now(WHY_SYNC);
  2374. }
  2375. pub(crate) fn settle_for_fence() {
  2376. settle_now(WHY_FENCE);
  2377. }
  2378. /// Resets the host lists of settled flights and keeps them for reuse, as
  2379. /// a queue does for the lists it ran (`crate::list::recycle`).
  2380. fn land() {
  2381. let landed = std::mem::take(&mut line().landed);
  2382. for (lists, order) in landed {
  2383. crate::list::recycle(lists, &order);
  2384. }
  2385. }
  2386. /// The thread that settles the flights once the card has run them all
  2387. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2388. /// at the next call that settles, and a title thread that polls such a
  2389. /// value while the submitting thread waits for that thread would never
  2390. /// see it.
  2391. fn late_helper() {
  2392. let Some(host) = host() else {
  2393. return;
  2394. };
  2395. // SAFETY: a plain event of our own.
  2396. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2397. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2398. return;
  2399. };
  2400. loop {
  2401. let target = {
  2402. let mut line = line();
  2403. loop {
  2404. if line.poke {
  2405. line.poke = false;
  2406. break None;
  2407. }
  2408. // (With the relay the flights are another thread's.)
  2409. if !relay() && !line.line.is_empty() && !line.settling {
  2410. break Some(line.target);
  2411. }
  2412. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2413. }
  2414. };
  2415. let Some(target) = target else {
  2416. land();
  2417. crate::queue::release_held(false);
  2418. continue;
  2419. };
  2420. // The card first, without the submission lock: the submitting
  2421. // thread prepares and sends meanwhile.
  2422. // SAFETY: our fence and event.
  2423. unsafe {
  2424. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2425. WaitForSingleObject(event, INFINITE);
  2426. }
  2427. }
  2428. {
  2429. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2430. // Something newer went up meanwhile: the card is waited for
  2431. // again, the submitting thread is not held up for it.
  2432. if line().target != target {
  2433. continue;
  2434. }
  2435. host.settle(&mut submitted, WHY_CARD_DONE);
  2436. }
  2437. land();
  2438. crate::queue::release_held(false);
  2439. }
  2440. }
  2441. /// Starts the threads of [`late`], once: the one that settles flights when
  2442. /// the card has run them and looks at what queues hold, and with [`relay`]
  2443. /// the one that lands flights.
  2444. fn late_threads() {
  2445. static HELPER: std::sync::Once = std::sync::Once::new();
  2446. HELPER.call_once(|| {
  2447. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2448. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2449. }
  2450. tracing::info!(
  2451. most = late_most(),
  2452. writes = late_writes(),
  2453. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2454. );
  2455. if relay() {
  2456. // Without it nothing would ever land.
  2457. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2458. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2459. }
  2460. tracing::info!(
  2461. exact = relay_exact(),
  2462. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2463. );
  2464. }
  2465. });
  2466. }
  2467. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2468. /// time flights have landed. Counted as a settle for `why`, and its time
  2469. /// as waiting for the card. The caller may hold the submission lock: the
  2470. /// thread that lands flights never takes it.
  2471. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2472. let mut line = line();
  2473. if done(&line) {
  2474. return;
  2475. }
  2476. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2477. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2478. let was_working = working(false);
  2479. let waiting = std::time::Instant::now();
  2480. while !done(&line) {
  2481. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2482. }
  2483. drop(line);
  2484. stood(waiting);
  2485. working(was_working);
  2486. let us = waiting.elapsed().as_micros() as u64;
  2487. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2488. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2489. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2490. #[cfg(feature = "diagnostics")]
  2491. blamed(why, us);
  2492. }
  2493. /// What the thread that lands flights fetches card copies' pieces with
  2494. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2495. /// behind the submission lock), and the memory the pieces come down to.
  2496. struct RelayFetch {
  2497. list: Prelude,
  2498. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2499. queue: Option<ID3D12CommandQueue>,
  2500. fence: ID3D12Fence,
  2501. event: HANDLE,
  2502. /// The last value signalled on `fence`.
  2503. sent: u64,
  2504. /// Buffer, mapping, bytes.
  2505. buffer: Option<(ID3D12Resource, usize, u64)>,
  2506. }
  2507. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2508. /// the first flights of the line it takes them, with what follows them,
  2509. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2510. /// the card, or for a flight. It takes neither the submission lock nor
  2511. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2512. /// lists and looking at what queues hold are left to [`late_helper`].
  2513. fn relay_worker() {
  2514. let Some(host) = host() else {
  2515. return;
  2516. };
  2517. // SAFETY: a plain event of our own.
  2518. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2519. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2520. };
  2521. let mut fetch: Option<RelayFetch> = None;
  2522. loop {
  2523. let next = {
  2524. let mut line = line();
  2525. loop {
  2526. if line.line.is_empty() {
  2527. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2528. continue;
  2529. }
  2530. let fences: Vec<Option<u64>> = line
  2531. .line
  2532. .iter()
  2533. .map(|l| match l {
  2534. Late::Run(flight) => Some(flight.fence),
  2535. _ => None,
  2536. })
  2537. .collect();
  2538. // SAFETY: a plain query.
  2539. let completed = unsafe { host.fence.GetCompletedValue() };
  2540. let n = landable(&fences, completed);
  2541. if n == 0 {
  2542. // The first thing is a flight the card has not run.
  2543. break Err(fences[0].unwrap_or(0));
  2544. }
  2545. line.settling = true;
  2546. let items: Vec<Late> = line.line.drain(..n).collect();
  2547. line.in_hand = items
  2548. .iter()
  2549. .filter_map(|l| match l {
  2550. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2551. _ => None,
  2552. })
  2553. .collect();
  2554. if card_steps::stage() > 0 {
  2555. line.landing = card_steps::writers(&items);
  2556. }
  2557. break Ok(items);
  2558. }
  2559. };
  2560. match next {
  2561. Ok(items) => host.relay_land(items, &mut fetch),
  2562. Err(target) => {
  2563. let waiting = std::time::Instant::now();
  2564. // SAFETY: the host's fence and this thread's event.
  2565. let waited = unsafe {
  2566. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2567. WaitForSingleObject(event, INFINITE);
  2568. })
  2569. };
  2570. if waited.is_err() {
  2571. std::thread::sleep(std::time::Duration::from_millis(1));
  2572. }
  2573. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2574. }
  2575. }
  2576. }
  2577. }
  2578. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2579. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2580. /// once, the pieces that differ found on several threads; but the merge is
  2581. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2582. /// are not done with here (each flight's are, afterwards).
  2583. fn relay_hand_back(back: &[Declared]) {
  2584. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2585. for (shadow, declared) in back {
  2586. if shadow.carded() {
  2587. continue;
  2588. }
  2589. let mut spans: Vec<(usize, usize)> = Vec::new();
  2590. join_ranges(&mut spans, declared.iter().copied());
  2591. for &(from, to) in &spans {
  2592. shadow.relay_compared(from, to - from);
  2593. }
  2594. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2595. }
  2596. if work.is_empty() {
  2597. return;
  2598. }
  2599. #[cfg(feature = "diagnostics")]
  2600. let scanning = std::time::Instant::now();
  2601. // Looked through without a lock: a piece that changes meanwhile (a
  2602. // later flight writing, the title's bytes going in) is found now or by
  2603. // that flight's landing, and the merge looks again under the lock.
  2604. let found = crate::shadow::find_all(&work);
  2605. #[cfg(feature = "diagnostics")]
  2606. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2607. let (mut now, mut title) = (Vec::new(), Vec::new());
  2608. for ((shadow, from, to), found) in work.iter().zip(found) {
  2609. let mut written = 0;
  2610. for (at, n) in found {
  2611. written += shadow.relay_merge(at, n, &mut now, &mut title);
  2612. }
  2613. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  2614. #[cfg(feature = "diagnostics")]
  2615. crate::copystat::compared(*from, to - from, written);
  2616. let _ = (from, to);
  2617. }
  2618. }
  2619. /// For the frame-rate line, with [`late`]: what the line of flights did
  2620. /// per frame since the last one.
  2621. fn late_line(frames: f64) {
  2622. if !late() {
  2623. return;
  2624. }
  2625. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2626. tracing::info!(
  2627. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2628. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2629. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2630. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2631. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2632. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2633. s[0],
  2634. s[1],
  2635. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2636. s[12] / 1000.0,
  2637. s[WHY_SYNC],
  2638. s[WHY_CARD_DONE],
  2639. s[WHY_VALUE],
  2640. s[WHY_STALE],
  2641. s[WHY_READ],
  2642. s[15],
  2643. s[16],
  2644. s[17],
  2645. s[WHY_RUN],
  2646. late_most(),
  2647. s[WHY_MOST],
  2648. s[WHY_WRITES],
  2649. s[WHY_FENCE],
  2650. s[13],
  2651. s[14],
  2652. );
  2653. {
  2654. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2655. tracing::info!(
  2656. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2657. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2658. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2659. w[WHY_SYNC],
  2660. w[WHY_CARD_DONE],
  2661. w[WHY_VALUE],
  2662. w[WHY_STALE],
  2663. w[WHY_READ],
  2664. w[WHY_RUN],
  2665. w[WHY_MOST],
  2666. w[WHY_WRITES],
  2667. w[WHY_FENCE],
  2668. );
  2669. }
  2670. if relay() {
  2671. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2672. tracing::info!(
  2673. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2674. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2675. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2676. \"settles\" above are waits of other threads for it)",
  2677. r[1],
  2678. r[0],
  2679. r[2] / 1000.0,
  2680. r[3] / 1000.0,
  2681. r[4] / 1000.0,
  2682. );
  2683. }
  2684. card_steps::log(frames);
  2685. #[cfg(feature = "diagnostics")]
  2686. log_blame(frames);
  2687. if late_exact() {
  2688. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  2689. tracing::info!(
  2690. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  2691. {runs:.0} changed runs, {:.2} MB",
  2692. bytes / (1 << 20) as f64
  2693. );
  2694. }
  2695. }
  2696. mod card_steps;
  2697. #[cfg(test)]
  2698. mod late_tests {
  2699. use super::{continues, join_ranges, touches};
  2700. /// Copies join only when both ends continue and the whole does not
  2701. /// overlap itself.
  2702. #[test]
  2703. fn copies_join_only_end_to_end_and_apart() {
  2704. // (destination, source, bytes)
  2705. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  2706. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  2707. // A gap, or only one side continues.
  2708. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  2709. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  2710. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  2711. // Together they would overlap: the second reads what the first wrote.
  2712. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  2713. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  2714. // They touch without overlapping.
  2715. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  2716. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  2717. }
  2718. /// Ranges are found by what they hold, not by where they start, and a
  2719. /// range that only touches another's end does not touch it.
  2720. #[test]
  2721. fn ranges_touch_where_they_overlap() {
  2722. let mut ranges = Vec::new();
  2723. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  2724. assert_eq!(ranges, [(10, 25), (40, 60)]);
  2725. join_ranges(&mut ranges, [(25, 40)]);
  2726. assert_eq!(ranges, [(10, 60)]);
  2727. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  2728. for (from, to, hit) in [
  2729. (0, 10, false),
  2730. (0, 11, true),
  2731. (24, 25, true),
  2732. (25, 40, false),
  2733. (25, 41, true),
  2734. (59, 200, true),
  2735. (60, 100, false),
  2736. (100, 101, true),
  2737. (101, 500, false),
  2738. (30, 30, false),
  2739. (50, 50, false),
  2740. ] {
  2741. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  2742. }
  2743. assert!(!touches(&[], 0, usize::MAX));
  2744. }
  2745. }
  2746. /// Whether a title buffer copy that continues the one recorded before it
  2747. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  2748. /// default).
  2749. ///
  2750. /// Each copy is done at submission through the kernel, which reports a
  2751. /// page that is not there instead of faulting (`copy_mapped`), tells the
  2752. /// write watch and the guards, and ends the refreshes gathered so far: a
  2753. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  2754. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  2755. /// continue the one before is counted either way and said on its own line
  2756. /// with the frame rate; the switch is worth that many kernel calls.
  2757. ///
  2758. /// Joined, the same bytes move: [`continues`] joins only copies whose
  2759. /// ranges, taken together, do not overlap, and nothing is recorded between
  2760. /// two steps that follow each other. What differs: a page that is not
  2761. /// mapped now fails the joined copy as a whole (it then goes page by page,
  2762. /// zeros for what cannot be read, as a single copy does), where before
  2763. /// only the copy that held it did.
  2764. fn join_copies() -> bool {
  2765. static ON: OnceLock<bool> = OnceLock::new();
  2766. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  2767. }
  2768. /// Since the last frame-rate line: title buffer copies recorded, and those
  2769. /// that continue the one before ([`join_copies`]).
  2770. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  2771. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  2772. /// where `last` ended, source and destination both, and the two as one do
  2773. /// not overlap (source over destination): then one copy of both moves the
  2774. /// bytes the two would move in turn.
  2775. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  2776. let ((d, s, n), (dst, src, len)) = (last, next);
  2777. let Some(all) = n.checked_add(len) else {
  2778. return false;
  2779. };
  2780. d.checked_add(n) == Some(dst)
  2781. && s.checked_add(n) == Some(src)
  2782. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  2783. }
  2784. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  2785. /// One list's lock at a time: a submission may name a list twice.
  2786. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  2787. let mut back: Vec<Declared> = Vec::new();
  2788. for list in runs {
  2789. for step in &list.deferred().copies {
  2790. if let Step::GpuWrite(shadow, address, len) = step {
  2791. let range = (*address, *address + *len);
  2792. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  2793. Some((_, ranges)) => {
  2794. if !ranges.contains(&range) {
  2795. ranges.push(range);
  2796. }
  2797. }
  2798. None => back.push((shadow.clone(), vec![range])),
  2799. }
  2800. }
  2801. }
  2802. }
  2803. back
  2804. }
  2805. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  2806. /// lines that say what the title's CPU was given while it decided whether
  2807. /// the camera is in a room. The values of the small read-backs
  2808. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  2809. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  2810. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  2811. /// copies found stale after their refresh (`shadow.rs`), and, in the
  2812. /// runtime, the read requests that fail (with 2: every request).
  2813. pub(crate) fn walls_trace() -> bool {
  2814. static ON: OnceLock<bool> = OnceLock::new();
  2815. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  2816. }
  2817. /// After `list` has run: the texels its read-backs copied into host
  2818. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  2819. ///
  2820. /// A submission that is waited for did this itself. One sent ahead
  2821. /// ([`late`]) did not, at any stage: the flights' lists were settled
  2822. /// without it, so the title read a buffer nobody wrote, as before read-backs
  2823. /// were made (the exposure metering's two small float targets, every frame).
  2824. fn read_backs(list: &HostList) {
  2825. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  2826. let mut data = std::ptr::null_mut();
  2827. // SAFETY: a read-back buffer of ours, written by the list that has
  2828. // run; the title's destination holds every row (checked when the
  2829. // copy was recorded).
  2830. unsafe {
  2831. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  2832. let from = data.cast::<u8>().cast_const();
  2833. for line in 0..*rows {
  2834. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  2835. }
  2836. // The walls trace: what the title is handed (one row of at
  2837. // most 24 values: its 5x1 and 1x1 float targets).
  2838. if walls_trace() && *rows == 1 && *row <= 96 {
  2839. let mut values = [0f32; 24];
  2840. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  2841. tracing::info!(
  2842. frame = crate::frame::current(),
  2843. to = format_args!("{:#x}", *at),
  2844. bytes = *row,
  2845. values = ?&values[..*row / 4],
  2846. "walls trace: a read-back lands in title memory"
  2847. );
  2848. }
  2849. buffer.Unmap(0, None);
  2850. }
  2851. }
  2852. }
  2853. }
  2854. /// After the card ran what declared `back`: what shaders wrote there goes
  2855. /// into title memory, and the ranges are done with.
  2856. fn hand_back(back: &[Declared]) {
  2857. if crate::shadow::wide_back() {
  2858. // Every range first (the pieces that differ, found on several
  2859. // threads), then the merges, in order, as below.
  2860. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2861. for (shadow, declared) in back {
  2862. if shadow.carded() {
  2863. continue;
  2864. }
  2865. let mut sorted = declared.clone();
  2866. sorted.sort_unstable();
  2867. let mut spans: Vec<(usize, usize)> = Vec::new();
  2868. for (from, to) in sorted {
  2869. match spans.last_mut() {
  2870. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2871. _ => spans.push((from, to)),
  2872. }
  2873. }
  2874. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2875. }
  2876. #[cfg(feature = "diagnostics")]
  2877. let scanning = std::time::Instant::now();
  2878. let found = crate::shadow::find_all(&work);
  2879. #[cfg(feature = "diagnostics")]
  2880. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2881. for ((shadow, from, to), found) in work.iter().zip(found) {
  2882. let written = shadow.copy_back_with(*from, to - from, Some(found));
  2883. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  2884. #[cfg(feature = "diagnostics")]
  2885. crate::copystat::compared(*from, to - from, written);
  2886. }
  2887. for (shadow, declared) in back {
  2888. shadow.copy_back_done(declared);
  2889. }
  2890. return;
  2891. }
  2892. for (shadow, declared) in back {
  2893. if shadow.carded() {
  2894. // Done before (`Host::card_back`).
  2895. shadow.copy_back_done(declared);
  2896. continue;
  2897. }
  2898. // Each byte compared once: the world declares dozens of views
  2899. // of its 174 MB heap that overlap almost entirely, and comparing
  2900. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  2901. // MB shaders wrote. Only ranges that overlap or touch are
  2902. // joined: what lies between two was not given to shaders (the
  2903. // snapshot does not hold it).
  2904. let mut sorted = declared.clone();
  2905. sorted.sort_unstable();
  2906. let mut spans: Vec<(usize, usize)> = Vec::new();
  2907. for (from, to) in sorted {
  2908. match spans.last_mut() {
  2909. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2910. _ => spans.push((from, to)),
  2911. }
  2912. }
  2913. for (from, to) in spans {
  2914. let written = shadow.copy_back(from, to - from);
  2915. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  2916. #[cfg(feature = "diagnostics")]
  2917. crate::copystat::compared(from, to - from, written);
  2918. }
  2919. shadow.copy_back_done(declared);
  2920. }
  2921. }
  2922. impl Host {
  2923. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  2924. /// mesh shaders need both); logged once.
  2925. pub(crate) fn mesh_shaders(&self) -> bool {
  2926. static MESH: OnceLock<bool> = OnceLock::new();
  2927. *MESH.get_or_init(|| {
  2928. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  2929. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  2930. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  2931. };
  2932. // SAFETY: each query writes its own structure of the given size.
  2933. let ok = unsafe {
  2934. self.device
  2935. .CheckFeatureSupport(
  2936. D3D12_FEATURE_D3D12_OPTIONS7,
  2937. (&raw mut options).cast(),
  2938. size_of_val(&options) as u32,
  2939. )
  2940. .is_ok()
  2941. && self
  2942. .device
  2943. .CheckFeatureSupport(
  2944. D3D12_FEATURE_SHADER_MODEL,
  2945. (&raw mut model).cast(),
  2946. size_of_val(&model) as u32,
  2947. )
  2948. .is_ok()
  2949. };
  2950. let mesh = ok
  2951. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  2952. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  2953. tracing::info!(mesh, "host mesh shader support");
  2954. mesh
  2955. })
  2956. }
  2957. /// Whether the host GPU supports the depth bounds test; logged once.
  2958. pub(crate) fn depth_bounds(&self) -> bool {
  2959. static BOUNDS: OnceLock<bool> = OnceLock::new();
  2960. *BOUNDS.get_or_init(|| {
  2961. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  2962. // SAFETY: writes `options` of the given size.
  2963. let ok = unsafe {
  2964. self.device
  2965. .CheckFeatureSupport(
  2966. D3D12_FEATURE_D3D12_OPTIONS2,
  2967. (&raw mut options).cast(),
  2968. size_of_val(&options) as u32,
  2969. )
  2970. .is_ok()
  2971. };
  2972. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  2973. tracing::info!(supported, "host depth bounds support");
  2974. supported
  2975. })
  2976. }
  2977. /// A new list, open for recording.
  2978. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  2979. #[cfg(feature = "diagnostics")]
  2980. let started = std::time::Instant::now();
  2981. #[cfg(feature = "diagnostics")]
  2982. let before = private_bytes();
  2983. let list = self.make_list();
  2984. LISTS[0].fetch_add(1, Ordering::Relaxed);
  2985. // (May shrink while a list is made, on another thread's account:
  2986. // added as it is, the sum is what counts.)
  2987. #[cfg(feature = "diagnostics")]
  2988. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  2989. #[cfg(feature = "diagnostics")]
  2990. {
  2991. use crate::copystat::{C, add};
  2992. add(C::HostLists, 1);
  2993. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  2994. }
  2995. list
  2996. }
  2997. /// An allocator and a closed list for a prelude.
  2998. fn make_prelude(&self) -> Option<Prelude> {
  2999. // SAFETY: plain object creation.
  3000. let made: windows::core::Result<Prelude> = unsafe {
  3001. (|| {
  3002. let allocator: ID3D12CommandAllocator =
  3003. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3004. let list: ID3D12GraphicsCommandList =
  3005. self.device
  3006. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3007. list.Close()?;
  3008. Ok((allocator, list))
  3009. })()
  3010. };
  3011. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3012. match made {
  3013. Ok(prelude) => Some(prelude),
  3014. Err(e) => {
  3015. tracing::warn!(error = %e, "no host list for a prelude");
  3016. None
  3017. }
  3018. }
  3019. }
  3020. fn make_list(&self) -> windows::core::Result<HostList> {
  3021. // SAFETY: plain object creation.
  3022. unsafe {
  3023. let allocator: ID3D12CommandAllocator = self
  3024. .device
  3025. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3026. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3027. 0,
  3028. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3029. &allocator,
  3030. None,
  3031. )?;
  3032. let prelude = OnceLock::new();
  3033. if !lazy_prelude() {
  3034. let _ = prelude.set(self.make_prelude());
  3035. }
  3036. Ok(HostList {
  3037. allocator,
  3038. list,
  3039. deferred: Mutex::default(),
  3040. scratch: Mutex::default(),
  3041. states: Mutex::default(),
  3042. twins: Mutex::default(),
  3043. prelude,
  3044. pipelines: Mutex::default(),
  3045. budget: OnceLock::new(),
  3046. card_budget: OnceLock::new(),
  3047. indirect_args: Mutex::default(),
  3048. batch_args: Mutex::default(),
  3049. _alive: Counted::new(),
  3050. #[cfg(feature = "diagnostics")]
  3051. notes: Mutex::default(),
  3052. #[cfg(feature = "diagnostics")]
  3053. stamps: OnceLock::new(),
  3054. })
  3055. }
  3056. }
  3057. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3058. fn card_clock(&self) -> Option<&'static CardClock> {
  3059. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3060. static WATCH: std::sync::Once = std::sync::Once::new();
  3061. let clock = CLOCK
  3062. .get_or_init(|| {
  3063. // SAFETY: a plain fence on our device.
  3064. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3065. Some(CardClock {
  3066. fence,
  3067. state: Mutex::new((0, None)),
  3068. sent: std::sync::Condvar::new(),
  3069. })
  3070. })
  3071. .as_ref()?;
  3072. WATCH.call_once(|| {
  3073. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3074. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3075. }
  3076. });
  3077. Some(clock)
  3078. }
  3079. /// Lists of ours just went to the queue: the clock's signal goes
  3080. /// behind them, and an idle stretch of the card, if one was under way,
  3081. /// ends here ([`CARD_CLOCK_US`]).
  3082. fn card_sent(&self) {
  3083. let Some(clock) = self.card_clock() else {
  3084. return;
  3085. };
  3086. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3087. state.0 += 1;
  3088. // SAFETY: our queue and the clock's fence.
  3089. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3090. if let Some((since, worked_then)) = state.1.take() {
  3091. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3092. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3093. }
  3094. drop(state);
  3095. clock.sent.notify_one();
  3096. }
  3097. /// Whether the host has what copies in the card's memory need (three
  3098. /// lists and the compare); made at the first ask. A copy goes to the
  3099. /// card's memory only if it has.
  3100. pub(crate) fn card_ready(&self) -> bool {
  3101. static READY: OnceLock<bool> = OnceLock::new();
  3102. *READY.get_or_init(|| match self.make_card_work() {
  3103. Ok(work) => {
  3104. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3105. true
  3106. }
  3107. Err(e) => {
  3108. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3109. false
  3110. }
  3111. })
  3112. }
  3113. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3114. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3115. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3116. let mut code: Option<ID3DBlob> = None;
  3117. // SAFETY: the source and names live through the call; the out
  3118. // pointer is ours.
  3119. unsafe {
  3120. D3DCompile(
  3121. CARD_COMPARE.as_ptr().cast(),
  3122. CARD_COMPARE.len(),
  3123. windows::core::s!("card compare"),
  3124. None,
  3125. None,
  3126. windows::core::s!("main"),
  3127. windows::core::s!("cs_5_1"),
  3128. 0,
  3129. 0,
  3130. &mut code,
  3131. None,
  3132. )?;
  3133. }
  3134. let code = code.ok_or_else(windows::core::Error::empty)?;
  3135. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3136. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3137. // in one submission.
  3138. const RESULTS: u64 = 1 << 20;
  3139. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3140. name(&differs, || "card compare results".into());
  3141. // SAFETY: the blob's own bytes; the root signature is inside the
  3142. // shader.
  3143. unsafe {
  3144. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3145. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3146. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3147. pRootSignature: std::mem::transmute_copy(&root),
  3148. CS: D3D12_SHADER_BYTECODE {
  3149. pShaderBytecode: bytes.as_ptr().cast(),
  3150. BytecodeLength: bytes.len(),
  3151. },
  3152. ..Default::default()
  3153. })?;
  3154. #[cfg(feature = "diagnostics")]
  3155. name(&pso, || crate::replay::play::COMPARE.into());
  3156. Ok(CardWork {
  3157. sync: vec![list()?],
  3158. check: vec![list()?],
  3159. fetch: list()?,
  3160. root,
  3161. pso,
  3162. differs: (differs, data as usize, RESULTS),
  3163. fetched: None,
  3164. taken: 0,
  3165. out: 0,
  3166. })
  3167. }
  3168. }
  3169. /// Before a submission's lists run, for copies in the card's memory
  3170. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3171. /// the last submission goes to their card side (a list of ours, run
  3172. /// now; the submission's lists follow it on the queue), and the ranges
  3173. /// this submission's shaders may write get a compare to run after its
  3174. /// lists. `None` if there is nothing to do.
  3175. ///
  3176. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3177. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3178. /// `relay`).
  3179. fn card_before(&self, runs: &[&HostList], flown: bool) -> Option<CardPlan> {
  3180. use std::sync::Arc;
  3181. if !crate::shadow::cards() {
  3182. return None;
  3183. }
  3184. // The ranges this submission's shaders may write, per copy.
  3185. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3186. for list in runs {
  3187. for step in &list.deferred().copies {
  3188. if let Step::GpuWrite(shadow, address, len) = step
  3189. && shadow.carded()
  3190. {
  3191. let range = (*address, *address + *len);
  3192. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3193. Some((_, ranges)) => {
  3194. if !ranges.contains(&range) {
  3195. ranges.push(range);
  3196. }
  3197. }
  3198. None => declared.push((shadow.clone(), vec![range])),
  3199. }
  3200. }
  3201. }
  3202. }
  3203. // With the relay: the order of the queue is held from here until
  3204. // what is taken is on the queue, and the taking is numbered.
  3205. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3206. let sent_as = match order.as_mut() {
  3207. Some(order) => {
  3208. **order += 1;
  3209. **order
  3210. }
  3211. None => 0,
  3212. };
  3213. let mut dirty = crate::shadow::card_dirty(sent_as);
  3214. if declared.is_empty() && dirty.is_empty() {
  3215. return None;
  3216. }
  3217. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3218. let work = work.as_mut()?;
  3219. // A copy whose shader writes are declared for the first time gets
  3220. // its bytes from before, whole.
  3221. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3222. for (shadow, _) in &declared {
  3223. if shadow.card_make_before(|size| {
  3224. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3225. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3226. Some(before)
  3227. }) {
  3228. whole.push(shadow.clone());
  3229. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3230. dirty.push((shadow.clone(), Vec::new()));
  3231. }
  3232. }
  3233. }
  3234. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3235. if !dirty.is_empty() {
  3236. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3237. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3238. };
  3239. let (allocator, list) = &sync;
  3240. // SAFETY: the list's last run finished (it ran ahead of a
  3241. // submission that was waited for, and came back after that);
  3242. // live buffers, and the ranges lie in them.
  3243. let recorded = unsafe {
  3244. (|| -> windows::core::Result<()> {
  3245. allocator.Reset()?;
  3246. list.Reset(allocator, None)?;
  3247. // Every copy first, then one barrier call, then every
  3248. // pass: a wait between each copy and its pass had the
  3249. // card do them one after the other.
  3250. let mut sent = Vec::new();
  3251. for (shadow, ranges) in &dirty {
  3252. let Some((staging, before, _)) = shadow.card_sides() else {
  3253. continue;
  3254. };
  3255. for &(a, b) in ranges {
  3256. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3257. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3258. }
  3259. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3260. if before.is_some() && !ranges.is_empty() {
  3261. sent.push(transition(
  3262. &shadow.buffer,
  3263. D3D12_RESOURCE_STATE_COPY_DEST,
  3264. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3265. ));
  3266. }
  3267. }
  3268. if !sent.is_empty() {
  3269. list.ResourceBarrier(&sent);
  3270. }
  3271. list.SetComputeRootSignature(&work.root);
  3272. list.SetPipelineState(&work.pso);
  3273. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3274. for (shadow, ranges) in &dirty {
  3275. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3276. continue;
  3277. };
  3278. // No twin (it cost the card the copy's size again,
  3279. // 399 MB in run 75): `before` holds a 128-bit hash
  3280. // of each 64 KiB piece. The pieces just sent up are
  3281. // hashed again, all of them the first time; the
  3282. // compare after the lists hashes the declared
  3283. // pieces and flags those whose hash is another.
  3284. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3285. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3286. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3287. vec![shadow.card_run(0, usize::MAX)]
  3288. } else {
  3289. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3290. };
  3291. // The same pieces in fewer passes (`rehash_runs`).
  3292. let runs = if rehash_runs() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3293. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3294. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3295. for run in runs {
  3296. card_pass(list, &run, size as u32, 0, 0);
  3297. }
  3298. }
  3299. list.Close()?;
  3300. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3301. Ok(())
  3302. })()
  3303. };
  3304. if let Err(e) = recorded {
  3305. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3306. }
  3307. used.push((false, sync));
  3308. }
  3309. drop(order);
  3310. let mut plan = CardPlan {
  3311. ranges: Vec::new(),
  3312. check: None,
  3313. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3314. lists: used,
  3315. sent_as,
  3316. };
  3317. // Each byte once, as the copy-back joins the declared ranges. The
  3318. // results go behind those of plans still in the air.
  3319. let mut at = work.taken;
  3320. for (shadow, ranges) in &declared {
  3321. let mut sorted = ranges.clone();
  3322. sorted.sort_unstable();
  3323. let mut spans: Vec<(usize, usize)> = Vec::new();
  3324. for (from, to) in sorted {
  3325. match spans.last_mut() {
  3326. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3327. _ => spans.push((from, to)),
  3328. }
  3329. }
  3330. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3331. for (from, to) in spans {
  3332. let Some(span) = shadow.card_span(from, to) else {
  3333. continue;
  3334. };
  3335. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3336. plan.ranges.push(CardRange {
  3337. shadow: shadow.clone(),
  3338. declared: (from, to),
  3339. span,
  3340. at,
  3341. compared,
  3342. });
  3343. if compared {
  3344. at += span.pieces;
  3345. }
  3346. }
  3347. }
  3348. work.taken = at;
  3349. if plan.ranges.iter().any(|r| r.compared) {
  3350. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3351. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3352. };
  3353. let (allocator, list) = &check;
  3354. // SAFETY: the list's last run finished (its submission was
  3355. // waited for, and it came back after that); live buffers; the
  3356. // compare's own root signature.
  3357. let recorded = unsafe {
  3358. (|| -> windows::core::Result<ID3D12CommandList> {
  3359. allocator.Reset()?;
  3360. list.Reset(allocator, None)?;
  3361. // What the submission's shaders wrote, first.
  3362. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3363. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3364. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3365. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3366. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3367. pResource: std::mem::ManuallyDrop::new(None),
  3368. }),
  3369. },
  3370. }]);
  3371. list.SetComputeRootSignature(&work.root);
  3372. list.SetPipelineState(&work.pso);
  3373. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3374. for r in plan.ranges.iter().filter(|r| r.compared) {
  3375. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3376. continue;
  3377. };
  3378. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3379. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3380. card_pass(list, &r.span, size as u32, r.at, if flown { 2 } else { 1 });
  3381. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3382. }
  3383. list.Close()?;
  3384. list.cast()
  3385. })()
  3386. };
  3387. match recorded {
  3388. Ok(list) => plan.check = Some(list),
  3389. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3390. }
  3391. plan.lists.push((true, check));
  3392. }
  3393. work.out += 1;
  3394. Some(plan)
  3395. }
  3396. /// With [`relay`]: whether the compare's result area is half taken by
  3397. /// plans in the air. It starts from the beginning only when no plan is
  3398. /// out, so the caller lets the flights land first.
  3399. fn card_results_low(&self) -> bool {
  3400. CARD_WORK
  3401. .lock()
  3402. .unwrap_or_else(|e| e.into_inner())
  3403. .as_ref()
  3404. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3405. }
  3406. /// The plan's submission has run and its results were read
  3407. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3408. /// when nothing of ours is on the card, so the compare's results start
  3409. /// from the beginning again.
  3410. fn card_done(&self, plan: CardPlan) {
  3411. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3412. let Some(work) = work.as_mut() else {
  3413. return;
  3414. };
  3415. for (check, list) in plan.lists {
  3416. if check { work.check.push(list) } else { work.sync.push(list) }
  3417. }
  3418. work.out = work.out.saturating_sub(1);
  3419. // With the relay other plans may be on the card, their results
  3420. // not read yet: the area starts again only when none is out.
  3421. if !relay() || work.out == 0 {
  3422. work.taken = 0;
  3423. }
  3424. }
  3425. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3426. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3427. // SAFETY: plain object creation.
  3428. let copying = relay_copy().then(|| unsafe {
  3429. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3430. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3431. let list: ID3D12GraphicsCommandList =
  3432. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3433. list.Close()?;
  3434. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3435. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3436. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3437. ..Default::default()
  3438. })?;
  3439. Ok(((allocator, list), queue))
  3440. })()
  3441. });
  3442. let (list, queue) = match copying {
  3443. Some(Ok((list, queue))) => (list, Some(queue)),
  3444. Some(Err(e)) => {
  3445. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3446. (self.make_prelude()?, None)
  3447. }
  3448. None => (self.make_prelude()?, None),
  3449. };
  3450. // SAFETY: plain objects of our own.
  3451. unsafe {
  3452. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3453. let event = CreateEventW(None, false, false, None).ok()?;
  3454. Some(RelayFetch {
  3455. list,
  3456. queue,
  3457. fence,
  3458. event,
  3459. sent: 0,
  3460. buffer: None,
  3461. })
  3462. }
  3463. }
  3464. /// [`relay`], on the thread that lands flights: for the plans of the
  3465. /// flights being landed (the card has run them), the pieces their
  3466. /// compares flagged are fetched, once each, with a list and a wait of
  3467. /// this thread's own, and what shaders wrote in them goes into title
  3468. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3469. /// no submission lock; a piece flagged under one range of a plan is
  3470. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3471. /// whatever was sent meanwhile, so it may bring a later flight's
  3472. /// bytes, which that flight's landing then finds merged already; and
  3473. /// nothing is sent back up.
  3474. fn relay_card_back(&self, plans: &[&CardPlan], fetch: &mut Option<RelayFetch>) {
  3475. let differs = {
  3476. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3477. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3478. };
  3479. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3480. let mut total = 0u64;
  3481. if let Some((differs, dwords)) = differs {
  3482. // SAFETY: the mapping of the results. The compares of these
  3483. // plans have run, and their dwords are given to no other plan
  3484. // before these are done with (`card_done`).
  3485. let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) };
  3486. let mut seen = std::collections::HashSet::new();
  3487. for plan in plans {
  3488. let flags: Vec<(usize, u32, bool)> = plan
  3489. .ranges
  3490. .iter()
  3491. .flat_map(|r| {
  3492. (0..r.span.pieces).map(move |p| {
  3493. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| d != 0);
  3494. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, flagged)
  3495. })
  3496. })
  3497. .collect();
  3498. let fetched = flagged_pieces(&flags);
  3499. for r in &plan.ranges {
  3500. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3501. for p in 0..r.span.pieces {
  3502. if !fetched.contains(&(copy, r.span.first + p)) {
  3503. continue;
  3504. }
  3505. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3506. if lo < hi && seen.insert((copy, lo, hi)) {
  3507. pieces.push((r.shadow.clone(), lo, hi, total));
  3508. total += (hi - lo) as u64;
  3509. }
  3510. }
  3511. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3512. }
  3513. }
  3514. }
  3515. if fetch.is_none() {
  3516. *fetch = self.make_relay_fetch();
  3517. }
  3518. // The sends these flights ran behind, all a fetch on the copy queue
  3519. // is known to have run behind.
  3520. let behind = plans.iter().map(|p| p.sent_as).max().unwrap_or(0);
  3521. if pieces.is_empty() {
  3522. // Nothing to fetch: every send so far is older than the next
  3523. // fetch, if that goes to the queue the sends went to.
  3524. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  3525. true => behind,
  3526. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  3527. };
  3528. crate::shadow::relay_fetched(after);
  3529. return;
  3530. }
  3531. let Some(f) = fetch.as_mut() else {
  3532. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  3533. };
  3534. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  3535. let size = total.next_multiple_of(16 << 20);
  3536. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3537. }
  3538. let Some((buffer, data, _)) = f.buffer.clone() else {
  3539. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  3540. };
  3541. f.sent += 1;
  3542. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  3543. let copy_queue = f.queue.clone();
  3544. let waiting = std::time::Instant::now();
  3545. // SAFETY: the list's last run was waited for by this thread; live
  3546. // buffers (the copies are held by the plans); the fence and the
  3547. // event are this thread's.
  3548. let ran = unsafe {
  3549. (|| -> windows::core::Result<u64> {
  3550. allocator.Reset()?;
  3551. list.Reset(&allocator, None)?;
  3552. for (shadow, lo, hi, at) in &pieces {
  3553. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  3554. }
  3555. list.Close()?;
  3556. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  3557. if let Some(queue) = &copy_queue {
  3558. queue.ExecuteCommandLists(&lists);
  3559. queue.Signal(&fence, sent)?;
  3560. fence.SetEventOnCompletion(sent, event)?;
  3561. WaitForSingleObject(event, INFINITE);
  3562. return Ok(behind);
  3563. }
  3564. // In the order of the queue: the sends of title bytes so
  3565. // far are ahead of this fetch, every later one behind it.
  3566. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  3567. self.queue.ExecuteCommandLists(&lists);
  3568. let after = *order;
  3569. drop(order);
  3570. self.card_sent();
  3571. self.queue.Signal(&fence, sent)?;
  3572. fence.SetEventOnCompletion(sent, event)?;
  3573. WaitForSingleObject(event, INFINITE);
  3574. Ok(after)
  3575. })()
  3576. };
  3577. let after = match ran {
  3578. Ok(after) => after,
  3579. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  3580. };
  3581. let us = waiting.elapsed().as_micros() as u64;
  3582. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  3583. {
  3584. use crate::shadow::CARD_STATS;
  3585. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  3586. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  3587. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  3588. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  3589. }
  3590. let mut title = Vec::new();
  3591. let mut written = 0;
  3592. for (shadow, lo, hi, at) in &pieces {
  3593. // SAFETY: the mapping of the fetched bytes, `total` of them;
  3594. // the copy into it has run.
  3595. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  3596. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  3597. shadow.walls_merged(gpu.len(), merged);
  3598. written += merged;
  3599. }
  3600. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3601. // Sends up to `after` are of no use to any later merge.
  3602. crate::shadow::relay_fetched(after);
  3603. }
  3604. /// [`relay`], on the thread that lands flights: `items` are the first
  3605. /// things of the line, flights the card has run and what follows them.
  3606. /// What their shaders wrote goes into title memory (copies in the
  3607. /// card's memory first, then the others, each byte once whichever
  3608. /// flights declared it); then every flight's ranges are done with;
  3609. /// then, in the line's order, each flight's read-backs, its
  3610. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  3611. /// is complete before the title is told anything.
  3612. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  3613. let landing = std::time::Instant::now();
  3614. {
  3615. let flights: Vec<&Flight> = items
  3616. .iter()
  3617. .filter_map(|l| match l {
  3618. Late::Run(flight) => Some(flight),
  3619. _ => None,
  3620. })
  3621. .collect();
  3622. if !flights.is_empty() {
  3623. // SAFETY: a plain query.
  3624. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  3625. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  3626. fail(format_args!(
  3627. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  3628. flights.len(),
  3629. runs.len(),
  3630. self.removal_data(&runs),
  3631. last_notes(&runs)
  3632. ));
  3633. }
  3634. let plans: Vec<&CardPlan> = flights.iter().filter_map(|f| f.card.as_ref()).collect();
  3635. self.relay_card_back(&plans, fetch);
  3636. let mut back: Vec<Declared> = Vec::new();
  3637. for flight in &flights {
  3638. for (shadow, ranges) in &flight.back {
  3639. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  3640. Some((_, all)) => {
  3641. for range in ranges {
  3642. if !all.contains(range) {
  3643. all.push(*range);
  3644. }
  3645. }
  3646. }
  3647. None => back.push((shadow.clone(), ranges.clone())),
  3648. }
  3649. }
  3650. }
  3651. relay_hand_back(&back);
  3652. // Only now, and flight by flight: a range another flight
  3653. // in the air declared too stays closed to refreshes.
  3654. for flight in &flights {
  3655. for (shadow, ranges) in &flight.back {
  3656. shadow.copy_back_done(ranges);
  3657. }
  3658. }
  3659. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  3660. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  3661. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  3662. }
  3663. }
  3664. // In the order given: what tells the title the card is done.
  3665. let mut last = 0;
  3666. let mut landed = Vec::new();
  3667. for item in items {
  3668. match item {
  3669. Late::Run(flight) => {
  3670. last = flight.number;
  3671. for &i in &flight.order {
  3672. read_backs(flight.lists[i].host());
  3673. }
  3674. if let Some(card) = flight.card {
  3675. self.card_done(card);
  3676. }
  3677. if let Some(own) = flight.own {
  3678. own.landed();
  3679. }
  3680. landed.push((flight.lists, flight.order));
  3681. }
  3682. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  3683. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  3684. }
  3685. }
  3686. if last > 0 {
  3687. FINISHED.store(last, Ordering::Release);
  3688. bury(last);
  3689. }
  3690. self.log_messages();
  3691. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  3692. {
  3693. let mut line = line();
  3694. let Line {
  3695. line: items,
  3696. written,
  3697. lists,
  3698. settling,
  3699. poke,
  3700. landed: kept,
  3701. in_hand,
  3702. landing,
  3703. ..
  3704. } = &mut *line;
  3705. kept.extend(landed);
  3706. in_hand.clear();
  3707. landing.clear();
  3708. // What is still in the air, from the flights that are.
  3709. written.clear();
  3710. *lists = 0;
  3711. let mut ranges = Vec::new();
  3712. for item in items.iter() {
  3713. if let Late::Run(flight) = item {
  3714. *lists += flight.order.len().max(1);
  3715. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  3716. }
  3717. }
  3718. join_ranges(written, ranges);
  3719. *settling = false;
  3720. // The landed lists are reset, and what queues hold looked at,
  3721. // by the helper thread (they take locks a waiter may hold).
  3722. *poke = true;
  3723. }
  3724. LINE_MOVED.notify_all();
  3725. LINE_LANDED.notify_all();
  3726. }
  3727. /// After a submission ran, for copies in the card's memory: the pieces
  3728. /// of the declared ranges that the compare found differing (all of a
  3729. /// range it did not compare) are fetched, with one more wait for the
  3730. /// card, and what shaders wrote in them goes into title memory.
  3731. /// `submitted` is the last value signalled on the fence. `seen` holds
  3732. /// the pieces fetched already since the card was last waited for
  3733. /// (several submissions settled together name the same ones).
  3734. fn card_back(
  3735. &self,
  3736. plan: &CardPlan,
  3737. submitted: &mut u64,
  3738. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  3739. ) {
  3740. if plan.ranges.is_empty() {
  3741. return;
  3742. }
  3743. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3744. let Some(work) = work.as_mut() else {
  3745. return;
  3746. };
  3747. // SAFETY: the mapping of the results, which the compare (it has
  3748. // run) wrote.
  3749. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  3750. // The pieces to fetch: the range, the offsets in its copy, and
  3751. // where the bytes come down.
  3752. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  3753. let mut total = 0u64;
  3754. for (i, r) in plan.ranges.iter().enumerate() {
  3755. for p in 0..r.span.pieces {
  3756. if r.compared && differs[(r.at + p) as usize] == 0 {
  3757. continue;
  3758. }
  3759. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3760. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  3761. pieces.push((i, lo, hi, total));
  3762. total += (hi - lo) as u64;
  3763. }
  3764. }
  3765. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3766. }
  3767. let mut written = vec![0usize; plan.ranges.len()];
  3768. if !pieces.is_empty() {
  3769. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  3770. let size = total.next_multiple_of(16 << 20);
  3771. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3772. }
  3773. let Some((fetched, data, _)) = &work.fetched else {
  3774. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  3775. };
  3776. let waiting = std::time::Instant::now();
  3777. let (allocator, list) = &work.fetch;
  3778. // SAFETY: the list's last run was waited for; live buffers; the
  3779. // fence and event are ours, under the submission lock.
  3780. let ran = unsafe {
  3781. (|| -> windows::core::Result<()> {
  3782. allocator.Reset()?;
  3783. list.Reset(allocator, None)?;
  3784. for &(i, lo, hi, at) in &pieces {
  3785. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  3786. }
  3787. list.Close()?;
  3788. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3789. self.card_sent();
  3790. *submitted += 1;
  3791. self.queue.Signal(&self.fence, *submitted)?;
  3792. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  3793. let was_working = working(false);
  3794. WaitForSingleObject(self.event, INFINITE);
  3795. stood(waiting);
  3796. working(was_working);
  3797. Ok(())
  3798. })()
  3799. };
  3800. if let Err(e) = ran {
  3801. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  3802. }
  3803. {
  3804. use crate::shadow::CARD_STATS;
  3805. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  3806. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  3807. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  3808. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  3809. }
  3810. if wide_merge() && pieces.len() >= 8 {
  3811. // The pieces are apart from one another (each its own bytes
  3812. // of its copy and of title memory): several at a time.
  3813. let fetched = *data;
  3814. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  3815. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  3816. let each = pieces.len().div_ceil(8);
  3817. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  3818. .chunks(each)
  3819. .map(|chunk| {
  3820. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  3821. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  3822. let counts = counts.clone();
  3823. Box::new(move || {
  3824. let mut title = Vec::new();
  3825. for (shadow, i, lo, hi, at) in chunk {
  3826. // SAFETY: the mapping of the fetched bytes;
  3827. // the copy into it has run, and the caller
  3828. // waits for this job.
  3829. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  3830. let merged = shadow.card_merge(lo, gpu, &mut title);
  3831. shadow.walls_merged(gpu.len(), merged);
  3832. counts[i].fetch_add(merged, Ordering::Relaxed);
  3833. }
  3834. }) as Box<dyn FnOnce() + Send>
  3835. })
  3836. .collect();
  3837. crate::shadow::wide_run(jobs);
  3838. for (written, count) in written.iter_mut().zip(counts.iter()) {
  3839. *written += count.load(Ordering::Relaxed);
  3840. }
  3841. } else {
  3842. let mut title = Vec::new();
  3843. for &(i, lo, hi, at) in &pieces {
  3844. // SAFETY: the mapping of the fetched bytes, `total` of
  3845. // them; the copy into it has run.
  3846. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  3847. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  3848. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  3849. written[i] += merged;
  3850. }
  3851. }
  3852. }
  3853. for (r, written) in plan.ranges.iter().zip(written) {
  3854. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3855. let (from, to) = r.declared;
  3856. #[cfg(feature = "diagnostics")]
  3857. crate::copystat::compared(from, to - from, written);
  3858. let _ = (from, to);
  3859. }
  3860. }
  3861. /// Runs closed lists and waits for them, and with [`late`] for
  3862. /// everything sent to the card before them, which is settled first.
  3863. pub(crate) fn execute(&self, runs: &[&HostList]) {
  3864. let _ = self.submit(runs, false);
  3865. }
  3866. /// A queue's submission with [`late`]: the host lists `lists`, taken
  3867. /// from the title's, go to the card in `order` and are not waited for.
  3868. /// They join the line of flights and are settled, with the others in
  3869. /// the air, at the next point where what they do can be observed
  3870. /// ([`late`] lists those points); their host lists are reset and kept
  3871. /// for reuse then, as a queue does for the lists it ran.
  3872. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  3873. if order.is_empty() {
  3874. crate::list::recycle(lists, &order);
  3875. return;
  3876. }
  3877. late_threads();
  3878. let sent = {
  3879. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  3880. self.submit(&runs, true)
  3881. };
  3882. let Some((mut submitted, sent)) = sent else {
  3883. // (Not reached: a submission sent ahead always comes back.)
  3884. crate::list::recycle(lists, &order);
  3885. return;
  3886. };
  3887. let told = !sent.writes.is_empty();
  3888. let most = {
  3889. let mut line = line();
  3890. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  3891. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  3892. *flying += order.len();
  3893. *target = *submitted;
  3894. items.push(Late::Run(Flight {
  3895. number: sent.number,
  3896. fence: *target,
  3897. lists,
  3898. order,
  3899. card: sent.card,
  3900. back: sent.back,
  3901. own: sent.own,
  3902. }));
  3903. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  3904. *flying >= late_most()
  3905. };
  3906. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  3907. RELAY_MOVED.notify_one();
  3908. if told && !late_writes() {
  3909. self.settle(&mut submitted, WHY_WRITES);
  3910. } else if most && relay_exact() {
  3911. // Until there are fewer, not until there are none.
  3912. relay_wait(WHY_MOST, |line| line.lists < late_most());
  3913. } else if most {
  3914. self.settle(&mut submitted, WHY_MOST);
  3915. } else {
  3916. LINE_MOVED.notify_one();
  3917. }
  3918. drop(submitted);
  3919. land();
  3920. }
  3921. /// Sends `list`, a closed list of ours (the present's copy), as a
  3922. /// flight ([`late_free_present`]): not waited for, settled with the
  3923. /// others. The caller keeps the list and does not reset it before the
  3924. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  3925. /// it ran and was waited for after all.
  3926. fn execute_own(&self, list: &HostList) -> u64 {
  3927. late_threads();
  3928. let Some((submitted, sent)) = self.submit(&[list], true) else {
  3929. return 0;
  3930. };
  3931. let number = sent.number;
  3932. {
  3933. let mut line = line();
  3934. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  3935. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  3936. *flying += 1;
  3937. *target = *submitted;
  3938. items.push(Late::Run(Flight {
  3939. number,
  3940. fence: *target,
  3941. lists: Vec::new(),
  3942. order: Vec::new(),
  3943. card: sent.card,
  3944. back: sent.back,
  3945. own: sent.own,
  3946. }));
  3947. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  3948. }
  3949. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  3950. LINE_MOVED.notify_one();
  3951. RELAY_MOVED.notify_one();
  3952. drop(submitted);
  3953. number
  3954. }
  3955. /// Waits for the card to run every flight in the air ([`late`]) and
  3956. /// does what they left to do, as [`Host::execute`] does for one
  3957. /// submission after its wait: the pieces their shaders wrote in copies
  3958. /// in the card's memory are fetched and merged (each once), the ranges
  3959. /// they declared in the other copies are compared and copied back
  3960. /// (each byte once, whichever flights declared it), and then, in the
  3961. /// order they were given: their bottom-of-pipe writes and the fence
  3962. /// signals behind them. `submitted` is the submission lock's value;
  3963. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  3964. ///
  3965. /// Everything in the air is settled, never the first flights alone:
  3966. /// the merge writes the copies' CPU side, which a flight still on the
  3967. /// card may be writing too.
  3968. fn settle(&self, submitted: &mut u64, why: usize) {
  3969. if !late() {
  3970. return;
  3971. }
  3972. if relay() {
  3973. // Nothing is settled here: the thread that lands flights does
  3974. // it, in order, and this waits until nothing is in the air and
  3975. // nothing is being landed. Every point that settled before
  3976. // comes here, so each still sees title memory, fences and
  3977. // bottom-of-pipe values as after a settle.
  3978. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  3979. return;
  3980. }
  3981. let was_working = working(true);
  3982. let mut counted = false;
  3983. loop {
  3984. let items = {
  3985. let mut line = line();
  3986. if line.line.is_empty() {
  3987. line.settling = false;
  3988. break;
  3989. }
  3990. line.settling = true;
  3991. line.written.clear();
  3992. line.lists = 0;
  3993. std::mem::take(&mut line.line)
  3994. };
  3995. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  3996. if !counted {
  3997. counted = true;
  3998. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  3999. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4000. }
  4001. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4002. if flights > 0 {
  4003. submitting(2, flights);
  4004. let waiting = std::time::Instant::now();
  4005. // SAFETY: the fence and event are ours, under the
  4006. // submission lock; `submitted` is the last value signalled.
  4007. unsafe {
  4008. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4009. Ok(()) => {
  4010. working(false);
  4011. WaitForSingleObject(self.event, INFINITE);
  4012. stood(waiting);
  4013. working(true);
  4014. }
  4015. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4016. }
  4017. }
  4018. let gpu = waiting.elapsed();
  4019. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4020. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4021. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4022. #[cfg(feature = "diagnostics")]
  4023. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4024. format!("{flights} submissions sent ahead, settled together")
  4025. });
  4026. // SAFETY: a plain query.
  4027. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4028. let runs: Vec<&HostList> = items
  4029. .iter()
  4030. .filter_map(|i| match i {
  4031. Late::Run(f) => Some(f),
  4032. _ => None,
  4033. })
  4034. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4035. .collect();
  4036. fail(format_args!(
  4037. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4038. runs.len(),
  4039. self.removal_data(&runs),
  4040. last_notes(&runs)
  4041. ));
  4042. }
  4043. submitting(3, flights);
  4044. let copying = std::time::Instant::now();
  4045. let mut seen = std::collections::HashSet::new();
  4046. let mut back: Vec<Declared> = Vec::new();
  4047. for item in &items {
  4048. let Late::Run(flight) = item else {
  4049. continue;
  4050. };
  4051. if let Some(card) = &flight.card {
  4052. self.card_back(card, submitted, &mut seen);
  4053. }
  4054. for (shadow, ranges) in &flight.back {
  4055. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4056. Some((_, all)) => {
  4057. for range in ranges {
  4058. if !all.contains(range) {
  4059. all.push(*range);
  4060. }
  4061. }
  4062. }
  4063. None => back.push((shadow.clone(), ranges.clone())),
  4064. }
  4065. }
  4066. }
  4067. hand_back(&back);
  4068. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4069. }
  4070. // In the order given: what tells the title the card is done.
  4071. let mut last = 0;
  4072. let mut landed = Vec::new();
  4073. for item in items {
  4074. match item {
  4075. Late::Run(flight) => {
  4076. last = flight.number;
  4077. for &i in &flight.order {
  4078. read_backs(flight.lists[i].host());
  4079. }
  4080. if let Some(card) = flight.card {
  4081. self.card_done(card);
  4082. }
  4083. landed.push((flight.lists, flight.order));
  4084. }
  4085. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4086. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4087. }
  4088. }
  4089. if last > 0 {
  4090. FINISHED.store(last, Ordering::Release);
  4091. bury(last);
  4092. }
  4093. line().landed.extend(landed);
  4094. }
  4095. if counted {
  4096. self.log_messages();
  4097. submitting(0, 0);
  4098. // What was settled may be what a queue stands at, and the
  4099. // caller may not be one that looks (a read-back, a present).
  4100. if why != WHY_CARD_DONE {
  4101. line().poke = true;
  4102. LINE_MOVED.notify_one();
  4103. }
  4104. }
  4105. working(was_working);
  4106. }
  4107. /// [`Host::execute`], or with `late` the first half of
  4108. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4109. /// to be done once they have run comes back with the submission lock
  4110. /// still held.
  4111. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4112. #[cfg(feature = "diagnostics")]
  4113. let called = std::time::Instant::now();
  4114. #[cfg(feature = "diagnostics")]
  4115. crate::copystat::submission_begins();
  4116. // One submission at a time from preparation to copy-back: snapshots
  4117. // and the ranges shaders write are per host copy, not per submission.
  4118. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4119. let was_working = working(true);
  4120. submitting(1, runs.len());
  4121. // Flights in the air ([`late`]): a submission that is waited for
  4122. // settles them first, one sent ahead only if preparing it reads
  4123. // what they write.
  4124. // Or the reads are done on the card, behind the flights.
  4125. let own = if late { self.card_steps(runs) } else { None };
  4126. if !late {
  4127. self.settle(&mut submitted, WHY_SYNC);
  4128. } else if own.is_none()
  4129. && let Some(why) = late_blocked(runs)
  4130. {
  4131. if relay_exact() && why == WHY_READ {
  4132. // Only until the flights that may write what is read have
  4133. // landed: their copy-back's end, not the card's other work.
  4134. relay_wait(why, |line| {
  4135. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4136. });
  4137. } else {
  4138. self.settle(&mut submitted, why);
  4139. }
  4140. }
  4141. // That list runs first, and is one of the submission's from here on.
  4142. let with: Vec<&HostList>;
  4143. let runs = match &own {
  4144. Some(own) => {
  4145. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4146. &with[..]
  4147. }
  4148. None => runs,
  4149. };
  4150. let behind = late && flying();
  4151. // Before this submission counts as started: what the sweep lets go
  4152. // of is named by no list, and nothing runs now (behind flights the
  4153. // sweep waits for a submission that finds none in the air: there is
  4154. // one at every present).
  4155. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4156. if !behind {
  4157. sweep();
  4158. SWEPT.store(now_ms(), Ordering::Relaxed);
  4159. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4160. // With the present sent ahead nothing else brings a moment
  4161. // with nothing in the air: one is made for the sweep.
  4162. self.settle(&mut submitted, WHY_SYNC);
  4163. sweep();
  4164. SWEPT.store(now_ms(), Ordering::Relaxed);
  4165. }
  4166. let behind = late && flying();
  4167. // The slots that waited for a texture's host copy, before the
  4168. // lists that may read them run.
  4169. crate::descriptor::make_waiting();
  4170. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4171. // The ranges shaders write are counted for it (with the relay).
  4172. crate::shadow::preparing(this_submission);
  4173. let started = std::time::Instant::now();
  4174. #[cfg(feature = "diagnostics")]
  4175. let lock = (started - called).as_micros() as u64;
  4176. #[cfg(feature = "diagnostics")]
  4177. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4178. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4179. // Where each run's lists start in `lists`.
  4180. let mut firsts = Vec::with_capacity(runs.len());
  4181. let mut batch = Batch::default();
  4182. // The time a settle of flights takes inside this preparing: the
  4183. // wait for the card and the copy-back have their own places on the
  4184. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4185. let mut settled = std::time::Duration::ZERO;
  4186. // One write-watch asking for everything the submission refreshes
  4187. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4188. if crate::watch::once() {
  4189. let mut spans: std::collections::HashMap<usize, (usize, usize)> = std::collections::HashMap::new();
  4190. for list in runs {
  4191. for step in &list.deferred().copies {
  4192. if let Step::Refresh(shadow, address, len) = step
  4193. && !shadow.unwatched()
  4194. {
  4195. let span = spans
  4196. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4197. .or_insert((*address, *address + *len));
  4198. *span = (span.0.min(*address), span.1.max(*address + *len));
  4199. }
  4200. }
  4201. }
  4202. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4203. crate::watch::ask_once(&ranges);
  4204. // Behind flights: the title wrote memory that a flight's shaders
  4205. // may write too, and this submission refreshes it. The flights
  4206. // are settled, and the asking made again: the copy-back wrote
  4207. // title memory, which other copies of it must see.
  4208. if behind && stale_under_flights(runs) {
  4209. let settling = std::time::Instant::now();
  4210. self.settle(&mut submitted, WHY_STALE);
  4211. settled += settling.elapsed();
  4212. crate::watch::ask_once(&ranges);
  4213. }
  4214. } else if behind && stale_under_flights(runs) {
  4215. let settling = std::time::Instant::now();
  4216. self.settle(&mut submitted, WHY_STALE);
  4217. settled += settling.elapsed();
  4218. }
  4219. for list in runs {
  4220. list.run_deferred(&mut batch, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4221. firsts.push(lists.len());
  4222. if let Some(prelude) = list.prelude() {
  4223. lists.push(Some(prelude));
  4224. }
  4225. lists.push(list.list.cast().ok());
  4226. }
  4227. batch.flush();
  4228. crate::watch::ask_once_end();
  4229. // The snapshots of the ranges shaders may write, if they were left
  4230. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4231. // lists have not gone to the card.
  4232. {
  4233. #[cfg(feature = "diagnostics")]
  4234. let snapshots = std::time::Instant::now();
  4235. crate::shadow::take_snapshots();
  4236. #[cfg(feature = "diagnostics")]
  4237. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4238. }
  4239. // Copies in the card's memory: what changed on their CPU side goes
  4240. // up ahead of the lists, and a compare of what the shaders may
  4241. // write follows them in the same submission.
  4242. let flown = late && relay();
  4243. if flown && self.card_results_low() {
  4244. let settling = std::time::Instant::now();
  4245. self.settle(&mut submitted, WHY_MOST);
  4246. settled += settling.elapsed();
  4247. }
  4248. let card = self.card_before(runs, flown);
  4249. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4250. lists.push(Some(check));
  4251. }
  4252. let prepared = std::time::Instant::now();
  4253. if late {
  4254. *submitted += 1;
  4255. // SAFETY: closed lists; the fence is ours.
  4256. let signalled = unsafe {
  4257. self.queue.ExecuteCommandLists(&lists);
  4258. self.queue.Signal(&self.fence, *submitted)
  4259. };
  4260. self.card_sent();
  4261. if let Err(e) = signalled {
  4262. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4263. }
  4264. let back = declared_writes(runs);
  4265. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4266. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4267. submitting(0, 0);
  4268. #[cfg(feature = "diagnostics")]
  4269. crate::copystat::submission_ends(lock);
  4270. let sent = Sent {
  4271. number: this_submission,
  4272. card,
  4273. back,
  4274. own,
  4275. writes,
  4276. };
  4277. working(was_working);
  4278. return Some((submitted, sent));
  4279. }
  4280. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4281. #[cfg(feature = "diagnostics")]
  4282. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4283. firsts
  4284. .iter()
  4285. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4286. .map(|(&a, &b)| &lists[a..b])
  4287. .collect()
  4288. } else {
  4289. vec![&lists[..]]
  4290. };
  4291. #[cfg(not(feature = "diagnostics"))]
  4292. let groups = [&lists[..]];
  4293. submitting(2, runs.len());
  4294. for (i, group) in groups.iter().enumerate() {
  4295. *submitted += 1;
  4296. let started = std::time::Instant::now();
  4297. // SAFETY: closed lists; the fence and event are ours.
  4298. unsafe {
  4299. self.queue.ExecuteCommandLists(group);
  4300. self.card_sent();
  4301. let waited = self
  4302. .queue
  4303. .Signal(&self.fence, *submitted)
  4304. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4305. match waited {
  4306. Ok(()) => {
  4307. working(false);
  4308. WaitForSingleObject(self.event, INFINITE);
  4309. stood(started);
  4310. working(true);
  4311. }
  4312. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4313. }
  4314. }
  4315. // With timing on each group is one of `runs` (and the compare
  4316. // of copies in the card's memory, with the last): every
  4317. // command's time on the card goes to the sums by pipeline.
  4318. #[cfg(feature = "diagnostics")]
  4319. if timing() {
  4320. // SAFETY: a plain query.
  4321. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4322. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4323. crate::copystat::command_took(&op, ms);
  4324. }
  4325. }
  4326. // A submission of one list was never named here (`groups.len()
  4327. // > 1` was the test): the two 50 ms lists of the gameplay
  4328. // frame, each a submission of its own, printed nothing.
  4329. #[cfg(feature = "diagnostics")]
  4330. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4331. // SAFETY: a plain query.
  4332. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4333. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4334. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4335. for (ms, op) in runs[i].slowest(frequency, 6) {
  4336. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4337. }
  4338. }
  4339. let _ = (i, started);
  4340. }
  4341. let _ = &firsts;
  4342. FINISHED.store(this_submission, Ordering::Release);
  4343. bury(this_submission);
  4344. let gpu = prepared.elapsed();
  4345. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4346. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4347. #[cfg(feature = "diagnostics")]
  4348. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4349. let pipelines: std::collections::BTreeSet<String> = runs
  4350. .iter()
  4351. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4352. .collect();
  4353. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  4354. text.chars().take(1200).collect()
  4355. });
  4356. // The host resets a device whose submission runs for about 2 s.
  4357. if gpu > std::time::Duration::from_millis(250) {
  4358. let pipelines: std::collections::BTreeSet<String> = runs
  4359. .iter()
  4360. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4361. .collect();
  4362. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  4363. }
  4364. // SAFETY: a plain query.
  4365. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4366. fail(format_args!(
  4367. "host GPU device removed after a submission of {} lists{}{}",
  4368. runs.len(),
  4369. self.removal_data(runs),
  4370. last_notes(runs)
  4371. ));
  4372. }
  4373. submitting(3, runs.len());
  4374. // What shaders wrote goes back before the bottom-of-pipe writes,
  4375. // which tell the title the GPU is done; each range once per
  4376. // submission, however many dispatches declared it (the world's
  4377. // passes declare the same big ranges dozens of times).
  4378. let copying = std::time::Instant::now();
  4379. // For copies in the card's memory the compare has run there: the
  4380. // pieces that differ are fetched and merged.
  4381. if let Some(card) = &card {
  4382. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  4383. }
  4384. let back = declared_writes(runs);
  4385. hand_back(&back);
  4386. if let Some(card) = card {
  4387. self.card_done(card);
  4388. }
  4389. #[cfg(feature = "diagnostics")]
  4390. if !back.is_empty() {
  4391. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  4392. }
  4393. // Nothing of this submission goes back to the title: no range of
  4394. // shader writes, no value written when it is done. The wait for
  4395. // such a one is only for order and for what the card still holds.
  4396. #[cfg(feature = "diagnostics")]
  4397. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  4398. use crate::copystat::{C, add};
  4399. add(C::NothingBack, 1);
  4400. add(C::NothingBackUs, gpu.as_micros() as u64);
  4401. }
  4402. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4403. for list in runs {
  4404. // Read backs first: a value written at the bottom of the pipe
  4405. // may be what tells the title that they are there.
  4406. read_backs(list);
  4407. for &(at, what, bytes) in &list.deferred().writes {
  4408. what.write(at as *mut u8, bytes);
  4409. }
  4410. }
  4411. self.log_messages();
  4412. submitting(0, 0);
  4413. #[cfg(feature = "diagnostics")]
  4414. crate::copystat::submission_ends(lock);
  4415. // With the relay: nothing is in the air now, so no fetch still to
  4416. // be merged is older than the sends to card copies so far, and
  4417. // their notes can go.
  4418. if relay() {
  4419. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  4420. }
  4421. working(was_working);
  4422. None
  4423. }
  4424. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  4425. /// it lies in (by the names we give them) or the title memory copy just
  4426. /// below it; for each list that did not finish, the command it stopped
  4427. /// at and what the draws and dispatches in flight there run (or, in
  4428. /// lists that never started, the pipelines they bind).
  4429. fn removal_data(&self, runs: &[&HostList]) -> String {
  4430. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  4431. return String::new();
  4432. };
  4433. let mut text = String::new();
  4434. let mut fault_va = None;
  4435. // SAFETY: the outputs are the runtime's, valid while the device
  4436. // lives; nodes are walked as linked, histories have their counts.
  4437. unsafe {
  4438. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  4439. && fault.PageFaultVA != 0
  4440. {
  4441. let va = fault.PageFaultVA;
  4442. fault_va = Some(va);
  4443. text.push_str(&format!("; page fault at {va:#x}"));
  4444. for (what, head) in [
  4445. ("inside", fault.pHeadExistingAllocationNode),
  4446. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  4447. ] {
  4448. let mut names = Vec::new();
  4449. let mut node = head;
  4450. while let Some(n) = node.as_ref()
  4451. && names.len() < 8
  4452. {
  4453. let name = if n.ObjectNameW.is_null() {
  4454. "unnamed".to_owned()
  4455. } else {
  4456. n.ObjectNameW.to_string().unwrap_or_default()
  4457. };
  4458. names.push(format!("{name} (type {})", n.AllocationType.0));
  4459. node = n.pNext;
  4460. }
  4461. if !names.is_empty() {
  4462. text.push_str(&format!("; {what} {names:?}"));
  4463. }
  4464. }
  4465. text.push_str(&crate::shadow::near(va));
  4466. text.push_str(&crate::descriptor::host::near_heaps(va));
  4467. }
  4468. // The plain output: the extended one (with marker texts) came
  4469. // back without stopped lists on this host.
  4470. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  4471. Ok(crumbs) => crumbs,
  4472. Err(e) => {
  4473. text.push_str(&format!("; no breadcrumbs ({e})"));
  4474. return text;
  4475. }
  4476. };
  4477. // Every list's progress (done/count), in the runtime's order.
  4478. let mut progress = Vec::new();
  4479. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  4480. while let Some(p) = node.as_ref() {
  4481. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4482. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  4483. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  4484. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  4485. node = p.pNext;
  4486. }
  4487. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  4488. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  4489. while let Some(p) = plain.as_ref() {
  4490. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4491. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  4492. let history =
  4493. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  4494. text.push_str(&format!(
  4495. "; a list stopped at command {done} of {} (op {})",
  4496. p.BreadcrumbCount, history[done as usize].0
  4497. ));
  4498. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  4499. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  4500. // The k-th marker command is the k-th note.
  4501. #[cfg(feature = "diagnostics")]
  4502. let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| {
  4503. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  4504. history
  4505. .iter()
  4506. .enumerate()
  4507. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  4508. .zip(notes.iter())
  4509. .map(|((at, _), (note, range))| {
  4510. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  4511. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  4512. })
  4513. .collect()
  4514. });
  4515. #[cfg(not(feature = "diagnostics"))]
  4516. let markers: Vec<(u32, String)> = Vec::new();
  4517. #[cfg(not(feature = "diagnostics"))]
  4518. let _ = fault_va;
  4519. if done > 0 {
  4520. text.push_str(&in_flight(history, &markers, done as usize));
  4521. } else if let Some(r) = run {
  4522. let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  4523. text.push_str(&format!(", its pipelines {pipelines:?}"));
  4524. }
  4525. }
  4526. plain = p.pNext;
  4527. }
  4528. }
  4529. text
  4530. }
  4531. /// Moves the debug layer's messages into our log; returns the first
  4532. /// error among them.
  4533. pub(crate) fn log_messages(&self) -> Option<String> {
  4534. let Some(queue) = &self.messages else {
  4535. return None;
  4536. };
  4537. let mut first_error = None;
  4538. // SAFETY: each message is read into a buffer of the size the queue
  4539. // reports, then the queue is emptied.
  4540. unsafe {
  4541. for i in 0..queue.GetNumStoredMessages() {
  4542. let mut size = 0;
  4543. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  4544. continue;
  4545. }
  4546. let mut buffer = vec![0u64; size.div_ceil(8)];
  4547. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  4548. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  4549. let m = &*message;
  4550. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  4551. let text = String::from_utf8_lossy(text);
  4552. let text = text.trim_end_matches('\0');
  4553. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  4554. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  4555. first_error = Some(text.to_owned());
  4556. }
  4557. }
  4558. }
  4559. queue.ClearStoredMessages();
  4560. }
  4561. first_error
  4562. }
  4563. /// A host render target view of `resource`, valid until it is recorded.
  4564. pub(crate) fn rtv(
  4565. &self,
  4566. resource: Option<&ID3D12Resource>,
  4567. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  4568. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4569. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4570. // SAFETY: a slot of our heap and a live resource, or none with a
  4571. // description (a typed null view).
  4572. unsafe {
  4573. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  4574. handle.ptr += (slot * self.rtv_size) as usize;
  4575. self.device
  4576. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  4577. handle
  4578. }
  4579. }
  4580. /// A host depth view of `resource`, valid until it is recorded.
  4581. pub(crate) fn dsv(
  4582. &self,
  4583. resource: &ID3D12Resource,
  4584. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  4585. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4586. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4587. // SAFETY: a slot of our heap and a live resource.
  4588. unsafe {
  4589. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  4590. handle.ptr += (slot * self.dsv_size) as usize;
  4591. self.device
  4592. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  4593. handle
  4594. }
  4595. }
  4596. }
  4597. impl HostList {
  4598. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  4599. #[cfg(feature = "diagnostics")]
  4600. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  4601. if !timing() {
  4602. return None;
  4603. }
  4604. self.stamps
  4605. .get_or_init(|| {
  4606. let device = &host()?.device;
  4607. let mut heap: Option<ID3D12QueryHeap> = None;
  4608. let mut back: Option<ID3D12Resource> = None;
  4609. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  4610. let desc = D3D12_RESOURCE_DESC {
  4611. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  4612. Width: u64::from(STAMPS) * 8,
  4613. Height: 1,
  4614. DepthOrArraySize: 1,
  4615. MipLevels: 1,
  4616. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  4617. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  4618. ..Default::default()
  4619. };
  4620. // SAFETY: plain object creation.
  4621. unsafe {
  4622. device
  4623. .CreateQueryHeap(
  4624. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  4625. &mut heap,
  4626. )
  4627. .ok()?;
  4628. device
  4629. .CreateCommittedResource(
  4630. &readback,
  4631. D3D12_HEAP_FLAG_NONE,
  4632. &desc,
  4633. D3D12_RESOURCE_STATE_COPY_DEST,
  4634. None,
  4635. &mut back,
  4636. )
  4637. .ok()?;
  4638. }
  4639. Some((heap?, back?))
  4640. })
  4641. .as_ref()
  4642. }
  4643. /// The noted commands that took longest on the GPU, longest first, as
  4644. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  4645. #[cfg(feature = "diagnostics")]
  4646. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  4647. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  4648. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  4649. return Vec::new();
  4650. };
  4651. let mut data = std::ptr::null_mut();
  4652. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  4653. // SAFETY: a read-back buffer the finished list resolved into.
  4654. let stamps: Vec<u64> = unsafe {
  4655. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  4656. return Vec::new();
  4657. }
  4658. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  4659. back.Unmap(0, None);
  4660. s
  4661. };
  4662. let mut times: Vec<(f64, String)> = (0..count)
  4663. .map(|i| {
  4664. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  4665. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  4666. })
  4667. .collect();
  4668. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  4669. times.truncate(n);
  4670. times
  4671. }
  4672. pub(crate) fn close(&self) {
  4673. self.twins_to_depth();
  4674. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  4675. if let Some((scratch, _)) = scratch {
  4676. self.indirect_common(&scratch);
  4677. }
  4678. self.batches_common();
  4679. self.card_budget_out();
  4680. #[cfg(feature = "diagnostics")]
  4681. if let Some((heap, back)) = self.stamps() {
  4682. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  4683. // SAFETY: an open list, our heap and read-back buffer.
  4684. unsafe {
  4685. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  4686. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  4687. }
  4688. }
  4689. // SAFETY: our list.
  4690. if let Err(e) = unsafe { self.list.Close() } {
  4691. fail(format_args!(
  4692. "a host command list did not close ({e}): a command recorded into it was invalid"
  4693. ));
  4694. }
  4695. }
  4696. /// Only after the list's last submission finished (every one is waited
  4697. /// for).
  4698. pub(crate) fn reset(&self) {
  4699. #[cfg(feature = "diagnostics")]
  4700. let started = std::time::Instant::now();
  4701. self._alive.used();
  4702. *self.deferred() = Deferred::default();
  4703. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  4704. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  4705. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  4706. #[cfg(feature = "diagnostics")]
  4707. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  4708. {
  4709. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  4710. (scratch.current, scratch.used) = (0, 0);
  4711. // Every submission of the list has run: nothing reads its
  4712. // scratch memory any more, and the next list to ask takes it.
  4713. if scratch_pool() {
  4714. give_chunks(std::mem::take(&mut scratch.chunks));
  4715. }
  4716. }
  4717. // SAFETY: the list is not executing.
  4718. let reset = unsafe {
  4719. self.allocator
  4720. .Reset()
  4721. .and_then(|()| self.list.Reset(&self.allocator, None))
  4722. };
  4723. if let Err(e) = reset {
  4724. fail(format_args!("a host command list did not reset ({e})"));
  4725. }
  4726. #[cfg(feature = "diagnostics")]
  4727. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  4728. }
  4729. /// Moves a title texture's host copy to `wanted` (a host state) in this
  4730. /// list: the host texture and the state it leaves, if that is a change.
  4731. /// The list's first use of a texture records nothing: its prelude brings
  4732. /// the texture there at submission.
  4733. pub(crate) fn transition(
  4734. &self,
  4735. resource: crate::object::This,
  4736. wanted: u32,
  4737. ) -> Option<(&'static ID3D12Resource, u32)> {
  4738. let texture = crate::resource::host_resource(resource)?;
  4739. let copy = crate::resource::host_copy(resource)?;
  4740. let wanted = legal_state(texture, wanted);
  4741. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  4742. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  4743. std::collections::hash_map::Entry::Vacant(v) => {
  4744. v.insert((wanted, wanted, copy));
  4745. None
  4746. }
  4747. std::collections::hash_map::Entry::Occupied(mut o) => {
  4748. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  4749. (before != wanted).then_some((texture, before))
  4750. }
  4751. }
  4752. }
  4753. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  4754. /// as [`HostList::transition`] does a title resource's host copy, and
  4755. /// records the barrier: for textures that are not a title resource's
  4756. /// host copy (colour twins) and for the copies between the two.
  4757. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  4758. let wanted = legal_state(&copy.texture, wanted);
  4759. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  4760. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  4761. std::collections::hash_map::Entry::Vacant(v) => {
  4762. v.insert((wanted, wanted, copy.clone()));
  4763. None
  4764. }
  4765. std::collections::hash_map::Entry::Occupied(mut o) => {
  4766. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  4767. (before != wanted).then_some(before)
  4768. }
  4769. };
  4770. drop(states);
  4771. if let Some(before) = before {
  4772. let barrier = transition(
  4773. &copy.texture,
  4774. D3D12_RESOURCE_STATES(before as i32),
  4775. D3D12_RESOURCE_STATES(wanted as i32),
  4776. );
  4777. // SAFETY: an open list and a live texture.
  4778. unsafe { self.list.ResourceBarrier(&[barrier]) };
  4779. }
  4780. }
  4781. /// A use of title texture `resource` about to be recorded, if it is a
  4782. /// depth texture with a colour twin (false if it is not): of the twin
  4783. /// (`colour`: unordered access) or of the depth texture (depth target,
  4784. /// clear, shader read, copy, resolve), writing it or only reading. The
  4785. /// side used is first brought up to date: by a copy recorded here if
  4786. /// this list wrote the other side since, by the list's prelude if the
  4787. /// list uses the side as it finds it. The twin is left in the
  4788. /// unordered access state; the caller moves the depth texture to the
  4789. /// state its use needs, as for any texture. A twin still ahead when the
  4790. /// list closes is copied then (`twins_to_depth`).
  4791. /// shortcut: every depth target bound for a draw counts as written
  4792. /// (also when the draw only tests), and every unordered access view a
  4793. /// shader names as written; views a shader picks from the heap by a
  4794. /// computed index are not seen here at all.
  4795. pub(crate) fn twin_use(
  4796. &self,
  4797. resource: crate::object::This,
  4798. colour: bool,
  4799. write: bool,
  4800. ) -> bool {
  4801. const UNORDERED_ACCESS: u32 = 0x8;
  4802. // Asked for every texture a draw reads: most have no twin.
  4803. let Some(twin) = crate::resource::twin(resource) else {
  4804. return false;
  4805. };
  4806. let Some(depth) = crate::resource::host_copy(resource) else {
  4807. return false;
  4808. };
  4809. let side = usize::from(colour);
  4810. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  4811. let u = twins
  4812. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  4813. .or_insert_with(|| TwinUse {
  4814. depth: depth.clone(),
  4815. twin: twin.clone(),
  4816. needs: [false; 2],
  4817. behind: [None; 2],
  4818. writing: false,
  4819. late: false,
  4820. });
  4821. let copy = match u.behind[side] {
  4822. Some(behind) => behind,
  4823. None => {
  4824. u.needs[side] = true;
  4825. false
  4826. }
  4827. };
  4828. u.behind[side] = Some(false);
  4829. match (write, colour) {
  4830. // Shaders write the twin when the draw or dispatch runs: what
  4831. // the same one reads of the depth texture is prepared before
  4832. // (`twins_written`).
  4833. (true, true) => u.writing = true,
  4834. (true, false) => u.behind[1] = Some(true),
  4835. (false, _) => {}
  4836. }
  4837. // shortcut: the depth plane's twin is not drawn into the plane
  4838. // here: the pass sets a pipeline and a target of ours, which a list
  4839. // still recording the title's commands cannot take. This use sees
  4840. // the plane as it was; the pass runs when the list closes
  4841. // (`twins_to_depth`). Counted.
  4842. if copy && !colour && twin.plane.is_some() {
  4843. u.late = true;
  4844. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  4845. }
  4846. drop(twins);
  4847. if copy {
  4848. self.twin_copy(&depth, &twin, colour);
  4849. } else if colour {
  4850. self.settle(&twin.colour, UNORDERED_ACCESS);
  4851. }
  4852. // The depth plane's twin is written through unordered access too.
  4853. if colour && let Some(plane) = &twin.plane {
  4854. self.settle(plane, UNORDERED_ACCESS);
  4855. }
  4856. true
  4857. }
  4858. /// Records the pass that draws the twin of the depth plane of `depth`
  4859. /// into the plane, if `twin` has one, with the moves to the states the
  4860. /// pass needs; the twin is left in the unordered access state. Only
  4861. /// for a list that records nothing of the title's afterwards
  4862. /// (`record_plane_pass`).
  4863. fn pass_plane(
  4864. &self,
  4865. depth: &std::sync::Arc<crate::resource::HostTexture>,
  4866. twin: &crate::resource::Twin,
  4867. ) {
  4868. const UNORDERED_ACCESS: u32 = 0x8;
  4869. const DEPTH_WRITE: u32 = 0x10;
  4870. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  4871. let Some(plane) = &twin.plane else { return };
  4872. self.settle(depth, DEPTH_WRITE);
  4873. self.settle(plane, PIXEL_SHADER_RESOURCE);
  4874. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  4875. self.settle(plane, UNORDERED_ACCESS);
  4876. }
  4877. /// Records the copy of a depth texture into its colour twin (`colour`)
  4878. /// or of the twin into the depth texture, with the moves to the copy
  4879. /// states. The twin is left in the unordered access state.
  4880. fn twin_copy(
  4881. &self,
  4882. depth: &std::sync::Arc<crate::resource::HostTexture>,
  4883. twin: &crate::resource::Twin,
  4884. colour: bool,
  4885. ) {
  4886. const UNORDERED_ACCESS: u32 = 0x8;
  4887. const COPY_DEST: u32 = 0x400;
  4888. const COPY_SOURCE: u32 = 0x800;
  4889. let (from, to) = if colour {
  4890. (depth, &twin.colour)
  4891. } else {
  4892. (&twin.colour, depth)
  4893. };
  4894. self.settle(from, COPY_SOURCE);
  4895. self.settle(to, COPY_DEST);
  4896. record_twin_copy(&self.list, &depth.texture, twin, colour);
  4897. self.settle(&twin.colour, UNORDERED_ACCESS);
  4898. }
  4899. /// Before the list closes: the depth textures whose twins it wrote last
  4900. /// are given what was written, and left readable by shaders. Shaders
  4901. /// that pick a view from the heap by a computed index are not seen by
  4902. /// `twin_use` and read the depth texture in lists that never name it
  4903. /// (in a captured frame of the title no table names a shadow
  4904. /// map for reading but the pass that fills the next one).
  4905. fn twins_to_depth(&self) {
  4906. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  4907. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  4908. let written: Vec<_> = twins
  4909. .values_mut()
  4910. .filter(|u| u.behind[0] == Some(true) || u.late)
  4911. .map(|u| {
  4912. // Not copied again if the list copied since the last write
  4913. // and only the depth plane's pass is left.
  4914. let copy = u.behind[0] == Some(true);
  4915. u.behind[0] = Some(false);
  4916. u.late = false;
  4917. (u.depth.clone(), u.twin.clone(), copy)
  4918. })
  4919. .collect();
  4920. drop(twins);
  4921. for (depth, twin, copy) in &written {
  4922. if *copy {
  4923. self.twin_copy(depth, twin, false);
  4924. }
  4925. // Nothing of the title's is recorded after this: the pass may
  4926. // leave its own pipeline and target set.
  4927. self.pass_plane(depth, twin);
  4928. self.settle(depth, SHADER_RESOURCE);
  4929. }
  4930. }
  4931. /// The draw or dispatch just prepared is recorded: the twins it writes
  4932. /// now hold what their depth textures lack.
  4933. pub(crate) fn twins_written(&self) {
  4934. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  4935. for u in twins.values_mut().filter(|u| u.writing) {
  4936. u.writing = false;
  4937. u.behind[0] = Some(true);
  4938. }
  4939. }
  4940. /// At submission: the list that moves each texture this list uses from
  4941. /// its real state to the one the list starts with; the textures' real
  4942. /// states become those the list ends with. For depth textures with a
  4943. /// colour twin it first copies the side the list uses as it finds it
  4944. /// from the other, if a list submitted earlier left it behind.
  4945. fn prelude(&self) -> Option<ID3D12CommandList> {
  4946. const COPY_DEST: u32 = 0x400;
  4947. const COPY_SOURCE: u32 = 0x800;
  4948. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  4949. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  4950. // The copies (depth texture, twin, whether into the twin); the
  4951. // sides are then as this list leaves them.
  4952. let mut syncs = Vec::new();
  4953. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  4954. for u in twins.values() {
  4955. let real = u.twin.behind.load(Ordering::Relaxed);
  4956. let mut behind = [real & 1 != 0, real & 2 != 0];
  4957. for side in [0, 1] {
  4958. if u.needs[side] && behind[side] {
  4959. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  4960. behind = [false; 2];
  4961. }
  4962. }
  4963. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  4964. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  4965. u.twin.behind.store(left, Ordering::Relaxed);
  4966. }
  4967. drop(twins);
  4968. // A copy runs with its textures in the copy states: each moves
  4969. // there from its real state, and from there to the state the list
  4970. // starts with (back to its real state if the list does not use it).
  4971. let mut to_copy = Vec::new();
  4972. let mut barriers = Vec::new();
  4973. let mut copying = std::collections::HashMap::new();
  4974. for (depth, twin, colour) in &syncs {
  4975. let (from, to) = if *colour {
  4976. (depth, &twin.colour)
  4977. } else {
  4978. (&twin.colour, depth)
  4979. };
  4980. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  4981. let key = std::sync::Arc::as_ptr(texture) as usize;
  4982. let real = texture.state.load(Ordering::Relaxed);
  4983. copying.insert(key, state);
  4984. if real != state {
  4985. to_copy.push(transition(
  4986. &texture.texture,
  4987. host_state(real),
  4988. host_state(state),
  4989. ));
  4990. if !states.contains_key(&key) {
  4991. barriers.push(transition(
  4992. &texture.texture,
  4993. host_state(state),
  4994. host_state(real),
  4995. ));
  4996. }
  4997. }
  4998. }
  4999. }
  5000. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5001. let real = copy.state.swap(*last, Ordering::Relaxed);
  5002. let real = copying.get(key).copied().unwrap_or(real);
  5003. (real != *first)
  5004. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5005. }));
  5006. if barriers.is_empty() && syncs.is_empty() {
  5007. return None;
  5008. }
  5009. let Some((allocator, list)) = self
  5010. .prelude
  5011. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5012. .as_ref()
  5013. else {
  5014. fail(format_args!("no host list for a state prelude"));
  5015. };
  5016. // SAFETY: the prelude is not executing (every submission is waited
  5017. // for); the textures are live.
  5018. let recorded = unsafe {
  5019. allocator.Reset().and_then(|()| {
  5020. list.Reset(allocator, None)?;
  5021. if !to_copy.is_empty() {
  5022. list.ResourceBarrier(&to_copy);
  5023. }
  5024. for (depth, twin, colour) in &syncs {
  5025. record_twin_copy(list, &depth.texture, twin, *colour);
  5026. }
  5027. if !barriers.is_empty() {
  5028. list.ResourceBarrier(&barriers);
  5029. }
  5030. list.Close()
  5031. })
  5032. };
  5033. if let Err(e) = recorded {
  5034. fail(format_args!("a host state prelude did not record ({e})"));
  5035. }
  5036. list.cast().ok()
  5037. }
  5038. /// Notes what the command about to be recorded does, as a marker
  5039. /// command whose text the list keeps (diagnostics, with device-removed
  5040. /// data on): the report pairs the breadcrumbs' marker commands with the
  5041. /// texts in order and names the commands a fault stopped among.
  5042. #[cfg(feature = "diagnostics")]
  5043. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5044. self.note(what, None);
  5045. }
  5046. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5047. /// `(address, bytes)`: the report places the faulting address in it.
  5048. #[cfg(feature = "diagnostics")]
  5049. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5050. self.note(what, Some(range));
  5051. }
  5052. #[cfg(feature = "diagnostics")]
  5053. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5054. if !dred_on() {
  5055. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5056. return;
  5057. }
  5058. {
  5059. let started = std::time::Instant::now();
  5060. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5061. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5062. // SAFETY: an open list and our query heap.
  5063. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5064. }
  5065. let what = what();
  5066. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5067. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5068. const UNICODE: u32 = 0;
  5069. // SAFETY: an open list; the marker is copied when recorded.
  5070. unsafe {
  5071. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5072. };
  5073. self.notes
  5074. .lock()
  5075. .unwrap_or_else(|e| e.into_inner())
  5076. .push((what, range));
  5077. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5078. }
  5079. }
  5080. /// Whether nothing recorded since the list was opened does any work:
  5081. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5082. /// upload or resolve (they defer a step or move a texture's state), no
  5083. /// bottom-of-pipe write. State set on the list does not count.
  5084. pub(crate) fn untouched(&self) -> bool {
  5085. {
  5086. let deferred = self.deferred();
  5087. if !(deferred.copies.is_empty()
  5088. && deferred.uploads.is_empty()
  5089. && deferred.kept.is_empty()
  5090. && deferred.textures.is_empty()
  5091. && deferred.writes.is_empty()
  5092. && deferred.backs.is_empty())
  5093. {
  5094. return false;
  5095. }
  5096. }
  5097. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5098. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5099. }
  5100. /// Notes a pipeline the list binds.
  5101. pub(crate) fn used_pipeline(&self, name: &str) {
  5102. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5103. if !pipelines.contains(name) {
  5104. pipelines.insert(name.to_owned());
  5105. }
  5106. }
  5107. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5108. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5109. }
  5110. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5111. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5112. let mut deferred = self.deferred();
  5113. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5114. // A copy that goes on where the one recorded just before it ended,
  5115. // source and destination both: with `join_copies` the two are one
  5116. // step.
  5117. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5118. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5119. {
  5120. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5121. if join_copies() {
  5122. *n += len;
  5123. return;
  5124. }
  5125. }
  5126. deferred
  5127. .copies
  5128. .push(Step::Copy(dst as usize, src as usize, len));
  5129. deferred.refreshed.clear();
  5130. }
  5131. /// Copies `len` bytes of title memory at `src` into the list's upload
  5132. /// memory at `dst` when the list is submitted.
  5133. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5134. self.deferred()
  5135. .copies
  5136. .push(Step::Fill(dst as usize, src as usize, len, None));
  5137. }
  5138. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5139. /// title heap's address, and the slot) shows.
  5140. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5141. self.deferred()
  5142. .copies
  5143. .push(Step::Fill(dst as usize, src as usize, len, Some(slot)));
  5144. }
  5145. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5146. /// when the list is submitted (once per range until a title copy
  5147. /// intervenes), keeping the copy alive until the list is reset.
  5148. pub(crate) fn defer_refresh(
  5149. &self,
  5150. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5151. address: usize,
  5152. len: usize,
  5153. ) {
  5154. let mut deferred = self.deferred();
  5155. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5156. if deferred.refreshed.insert(key) {
  5157. deferred
  5158. .copies
  5159. .push(Step::Refresh(shadow.clone(), address, len));
  5160. }
  5161. }
  5162. /// Shaders of the list write `[address, address + len)` of a buffer's
  5163. /// host copy: copied back into title memory once the list has run.
  5164. pub(crate) fn defer_gpu_write(
  5165. &self,
  5166. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5167. address: usize,
  5168. len: usize,
  5169. ) {
  5170. self.deferred()
  5171. .copies
  5172. .push(Step::GpuWrite(shadow.clone(), address, len));
  5173. }
  5174. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5175. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5176. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5177. /// the list is reset.
  5178. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5179. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5180. }
  5181. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5182. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5183. self.deferred().writes.push((dst as usize, what, bytes));
  5184. }
  5185. /// A mapped upload buffer of `size` bytes, alive until the list is
  5186. /// reset.
  5187. ///
  5188. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5189. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5190. let (buffer, data) = host.upload_buffer(size)?;
  5191. name(&buffer, || format!("list upload {size:#x}"));
  5192. self.deferred().hold_upload(buffer.clone(), size);
  5193. Some((buffer, data))
  5194. }
  5195. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5196. /// reset: the host GPU address and the CPU pointer.
  5197. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5198. let host = host()?;
  5199. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5200. let len = len.max(1).next_multiple_of(256);
  5201. if len > SCRATCH_CHUNK {
  5202. let (buffer, data) = host.upload_buffer(len)?;
  5203. name(&buffer, || format!("list scratch {len:#x}"));
  5204. // SAFETY: a live buffer.
  5205. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  5206. self.deferred().hold_upload(buffer, len);
  5207. return Some((gpu, data));
  5208. }
  5209. // The chunk in use while `len` fits in what is left of it, else the
  5210. // next one (a list's first chunk may be a small one).
  5211. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5212. (s.current, s.used) = (s.current + 1, 0);
  5213. }
  5214. if s.current == s.chunks.len() {
  5215. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  5216. SCRATCH_FIRST
  5217. } else {
  5218. SCRATCH_CHUNK
  5219. };
  5220. let chunk = take_chunk(host, size)?;
  5221. s.chunks.push((chunk, size));
  5222. s.used = 0;
  5223. }
  5224. let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu);
  5225. let at = s.used;
  5226. s.used += len;
  5227. Some((gpu + at, (data + at as usize) as *mut u8))
  5228. }
  5229. /// The bytes of scratch chunks the list holds now (after a reset:
  5230. /// none while lists share their chunks).
  5231. pub(crate) fn scratch_kept(&self) -> u64 {
  5232. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5233. scratch.chunks.iter().map(|c| c.1).sum()
  5234. }
  5235. /// The host address of the list's indirect-work budget, zeroed at each
  5236. /// submission of the list from the first use after a reset on.
  5237. pub(crate) fn budget(&self) -> Option<u64> {
  5238. let (buffer, data) = self
  5239. .budget
  5240. .get_or_init(|| {
  5241. let (b, d) = host()?.shared_buffer(256)?;
  5242. Some((b, d as usize))
  5243. })
  5244. .as_ref()?;
  5245. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5246. let mut deferred = self.deferred();
  5247. if !deferred.budget_zeroed {
  5248. deferred.budget_zeroed = true;
  5249. let at = *data;
  5250. // SAFETY: the list's own mapped words, written before it runs.
  5251. // The words after the budget hold what the clamp noted about the
  5252. // list's last run (mesh dispatches: the largest group count
  5253. // asked for, the groups asked in all; with the card's copy, as
  5254. // the list's end copied them here): taken, then zeroed.
  5255. let notes = Box::new(move || unsafe {
  5256. let words = at as *mut u32;
  5257. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  5258. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  5259. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  5260. for k in 0..3 {
  5261. words.add(k).write_volatile(0);
  5262. }
  5263. });
  5264. deferred.copies.push(Step::Host(notes, (0, 0)));
  5265. drop(deferred);
  5266. if let Some(card) = card {
  5267. self.zero_card_budget(card);
  5268. }
  5269. }
  5270. // SAFETY: a live buffer.
  5271. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  5272. }
  5273. /// The budget's words in the card's own memory ([`card_budget`]), if
  5274. /// the list can zero them itself (`WriteBufferImmediate`).
  5275. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  5276. if !card_budget() {
  5277. return None;
  5278. }
  5279. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  5280. let buffer = host()?.uav_buffer(256)?;
  5281. name(&buffer, || "indirect budget".to_owned());
  5282. Some(buffer)
  5283. }
  5284. /// Records, before the list's first clamp, the zeroing of the card's
  5285. /// copy of the budget: common, written as a copy, then left for
  5286. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  5287. fn zero_card_budget(&self, card: &ID3D12Resource) {
  5288. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  5289. return;
  5290. };
  5291. // SAFETY: a live buffer.
  5292. let at = unsafe { card.GetGPUVirtualAddress() };
  5293. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  5294. Dest: at + offset,
  5295. Value: 0,
  5296. });
  5297. // SAFETY: an open list; the buffer is the list's own and in the
  5298. // common state at the start of every recording.
  5299. unsafe {
  5300. self.list.ResourceBarrier(&[transition(
  5301. card,
  5302. D3D12_RESOURCE_STATE_COMMON,
  5303. D3D12_RESOURCE_STATE_COPY_DEST,
  5304. )]);
  5305. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  5306. self.list.ResourceBarrier(&[transition(
  5307. card,
  5308. D3D12_RESOURCE_STATE_COPY_DEST,
  5309. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5310. )]);
  5311. }
  5312. }
  5313. /// Before the list closes, if this recording charged the card's copy
  5314. /// of the budget: its notes on mesh records go to the mapped words
  5315. /// (read at the next submission), and it goes back to common.
  5316. fn card_budget_out(&self) {
  5317. if !self.deferred().budget_zeroed {
  5318. return;
  5319. }
  5320. let (Some(Some(card)), Some(Some((mapped, _)))) =
  5321. (self.card_budget.get(), self.budget.get())
  5322. else {
  5323. return;
  5324. };
  5325. // SAFETY: an open list; both buffers are the list's own. The
  5326. // mapped one is promoted from common to the copy destination.
  5327. unsafe {
  5328. self.list.ResourceBarrier(&[transition(
  5329. card,
  5330. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5331. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5332. )]);
  5333. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  5334. self.list.ResourceBarrier(&[transition(
  5335. card,
  5336. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5337. D3D12_RESOURCE_STATE_COMMON,
  5338. )]);
  5339. }
  5340. }
  5341. /// A device-local unordered-access buffer of at least `size` bytes for
  5342. /// clamped indirect arguments, reused across executions and resets of the
  5343. /// list. Smaller buffers replaced mid-list stay alive until
  5344. /// [`HostList::reset`].
  5345. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  5346. let needed = size.max(64 << 10);
  5347. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  5348. if let Some((buffer, cap)) = &*slot
  5349. && *cap >= needed
  5350. {
  5351. return Some(buffer.clone());
  5352. }
  5353. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  5354. let alloc = prev
  5355. .saturating_mul(2)
  5356. .max(needed)
  5357. .next_multiple_of(64 << 10);
  5358. let buffer = host()?.uav_buffer(alloc)?;
  5359. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  5360. let old = slot.replace((buffer.clone(), alloc));
  5361. drop(slot);
  5362. if let Some((old_buf, _)) = old {
  5363. // It ends the list common, as every scratch buffer does.
  5364. self.indirect_common(&old_buf);
  5365. self.keep(&old_buf);
  5366. }
  5367. Some(buffer)
  5368. }
  5369. /// Where the next batch of clamped records goes: a device-local buffer
  5370. /// the list keeps from recording to recording, the batch's place in it
  5371. /// and the state the buffer is in. Every batch of a recording has a place
  5372. /// of its own: the executions before it may still read theirs.
  5373. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  5374. use crate::indirect::batch::{JOBS, SLOT};
  5375. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5376. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  5377. if buffer == args.0.len() {
  5378. let size = u64::from(BATCHES * JOBS * SLOT);
  5379. let made = host()?.uav_buffer(size)?;
  5380. name(&made, || format!("indirect batches {size:#x}"));
  5381. args.0.push(made);
  5382. }
  5383. args.1 += 1;
  5384. // (Its first batch finds it as the recording before left it:
  5385. // `batches_common`.)
  5386. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  5387. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  5388. }
  5389. /// Before the list closes: the scratch buffers of the batched clamps go
  5390. /// back to the common state, where the next recording expects them.
  5391. fn batches_common(&self) {
  5392. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5393. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  5394. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  5395. .iter()
  5396. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  5397. .collect();
  5398. if !barriers.is_empty() {
  5399. // SAFETY: an open list and live buffers this recording left in
  5400. // `INDIRECT_ARGUMENT`.
  5401. unsafe { self.list.ResourceBarrier(&barriers) };
  5402. }
  5403. }
  5404. /// Moves `scratch` back to the common state if a clamp left it readable
  5405. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  5406. /// list's first clamp expects it. Done before the list closes and before
  5407. /// a bigger scratch buffer replaces it: one barrier per list (where
  5408. /// there was one per indirect execution), and the list ends as it
  5409. /// begins however it is submitted.
  5410. fn indirect_common(&self, scratch: &ID3D12Resource) {
  5411. {
  5412. let mut deferred = self.deferred();
  5413. if deferred.indirect_readable != scratch.as_raw() as usize {
  5414. return;
  5415. }
  5416. deferred.indirect_readable = 0;
  5417. }
  5418. let barrier = transition(
  5419. scratch,
  5420. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  5421. D3D12_RESOURCE_STATE_COMMON,
  5422. );
  5423. // SAFETY: an open list and a live buffer this recording left in
  5424. // `INDIRECT_ARGUMENT`.
  5425. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5426. }
  5427. /// The state the list's indirect scratch buffer `scratch` is in at this
  5428. /// point of the recording: indirect arguments if a clamp in this
  5429. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  5430. /// common: the state a buffer is made in, and the one a recording
  5431. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  5432. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  5433. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  5434. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  5435. } else {
  5436. D3D12_RESOURCE_STATE_COMMON
  5437. }
  5438. }
  5439. /// A clamp recorded in this list left `scratch` readable as indirect
  5440. /// arguments. It stays so for every execution that reads it, until the
  5441. /// next clamp moves it back to unordered access.
  5442. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  5443. self.deferred().indirect_readable = scratch.as_raw() as usize;
  5444. }
  5445. /// Keeps `object` alive until the list is reset.
  5446. pub(crate) fn keep(&self, object: &impl Interface) {
  5447. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  5448. self.deferred().kept.push(object);
  5449. }
  5450. }
  5451. /// Whether this is the first time since the reset that the list asks
  5452. /// about `key` (a texture to bring up to date).
  5453. pub(crate) fn first_use(&self, key: usize) -> bool {
  5454. self.deferred().textures.insert(key)
  5455. }
  5456. /// Runs `work` when the list is submitted, in order with its copies.
  5457. /// `work` may write title memory (refreshes after it copy again).
  5458. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  5459. self.deferred().copies.push(Step::Run(Box::new(work)));
  5460. self.deferred().refreshed.clear();
  5461. }
  5462. /// As [`HostList::defer`], for work that writes only host memory.
  5463. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  5464. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  5465. }
  5466. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  5467. /// memory at `from`.
  5468. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  5469. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  5470. }
  5471. /// Brings a texture's staging buffer up to date when the list is
  5472. /// submitted, keeping it alive until the list is reset.
  5473. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  5474. self.deferred().copies.push(Step::Texture(staging));
  5475. }
  5476. /// Runs the list's submission-time steps; refreshes go into `batch`
  5477. /// (the title's big buffers, a 174 MB one among them, are read by most
  5478. /// lists of a submission, through many ranges). Copies and fills that
  5479. /// `taken` names (by their place) are left out: they are done on the
  5480. /// card ([`card_steps`]).
  5481. fn run_deferred(&self, batch: &mut Batch, taken: impl Fn(usize) -> bool) {
  5482. #[cfg(feature = "diagnostics")]
  5483. use crate::copystat::{C, add};
  5484. for (i, step) in self.deferred().copies.iter().enumerate() {
  5485. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  5486. continue;
  5487. }
  5488. let started = std::time::Instant::now();
  5489. let copied = match step {
  5490. &Step::Copy(dst, src, len) => {
  5491. #[cfg(feature = "diagnostics")]
  5492. {
  5493. add(C::Copies, 1);
  5494. add(C::CopyBytes, len as u64);
  5495. }
  5496. batch.title_written();
  5497. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  5498. // With the submission's one asking: the journal learns it.
  5499. crate::watch::wrote(dst, len);
  5500. len
  5501. }
  5502. &Step::Fill(dst, src, len, _) => {
  5503. #[cfg(feature = "diagnostics")]
  5504. {
  5505. add(C::Copies, 1);
  5506. add(C::CopyBytes, len as u64);
  5507. }
  5508. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  5509. len
  5510. }
  5511. Step::Refresh(shadow, address, len) => {
  5512. #[cfg(feature = "diagnostics")]
  5513. {
  5514. add(C::Refreshes, 1);
  5515. add(C::RefreshBytes, *len as u64);
  5516. }
  5517. batch.add(shadow, *address, *len);
  5518. continue;
  5519. }
  5520. Step::Run(work) | Step::Host(work, _) => {
  5521. if matches!(step, Step::Run(_)) {
  5522. batch.title_written();
  5523. }
  5524. work();
  5525. // It wrote title memory, where is not known here: the
  5526. // submission's one asking ends, later refreshes ask anew.
  5527. if matches!(step, Step::Run(_)) {
  5528. crate::watch::ask_once_end();
  5529. }
  5530. #[cfg(feature = "diagnostics")]
  5531. {
  5532. add(C::Runs, 1);
  5533. add(C::RunUs, started.elapsed().as_micros() as u64);
  5534. }
  5535. continue;
  5536. }
  5537. Step::GpuWrite(shadow, address, len) => {
  5538. // The shaders start from the title's data: this copy's
  5539. // pending refresh first. The other copies' wait for
  5540. // the next flush of all (flushing all of them at every
  5541. // range a dispatch writes made thousands of write-watch
  5542. // askings a frame).
  5543. batch.flush_one(shadow);
  5544. #[cfg(feature = "diagnostics")]
  5545. let snapshot = std::time::Instant::now();
  5546. shadow.writing(*address, *len);
  5547. #[cfg(feature = "diagnostics")]
  5548. {
  5549. add(C::GpuWrites, 1);
  5550. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  5551. }
  5552. continue;
  5553. }
  5554. Step::Texture(staging) => {
  5555. if batch.texture_due(staging) {
  5556. staging.refresh();
  5557. }
  5558. continue;
  5559. }
  5560. };
  5561. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  5562. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  5563. }
  5564. }
  5565. }
  5566. /// Whether a submission's refreshes of host copies run on several threads,
  5567. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  5568. ///
  5569. /// A submission brings some sixty copies up to date, one after the other
  5570. /// on the submitting thread: for each, the pages the title wrote are asked
  5571. /// for and read through the kernel into the copy. That is the frame line's
  5572. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  5573. /// another: each refresh writes its own copy and its own notes, and reads
  5574. /// title memory. With the switch the copies of a flush (four or more) are
  5575. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  5576. /// The write-watch journal and the guards are behind their own locks, as
  5577. /// they are for the title's threads.
  5578. fn wide_refresh() -> bool {
  5579. static ON: OnceLock<bool> = OnceLock::new();
  5580. *ON.get_or_init(|| {
  5581. wide_refresh_enabled(
  5582. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  5583. std::thread::available_parallelism().ok().map(|n| n.get()),
  5584. )
  5585. })
  5586. }
  5587. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  5588. match setting {
  5589. Some("1") => true,
  5590. Some("0") => false,
  5591. _ => logical_cpus.is_some_and(|n| n >= 4),
  5592. }
  5593. }
  5594. #[cfg(test)]
  5595. mod wide_refresh_tests {
  5596. use super::wide_refresh_enabled;
  5597. #[test]
  5598. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  5599. assert!(wide_refresh_enabled(None, Some(4)));
  5600. assert!(wide_refresh_enabled(None, Some(16)));
  5601. assert!(!wide_refresh_enabled(None, Some(2)));
  5602. assert!(!wide_refresh_enabled(None, None));
  5603. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  5604. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  5605. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  5606. }
  5607. }
  5608. /// A submission's refreshes not done yet, merged per buffer copy into the
  5609. /// range that covers them: done before a step that writes title memory or
  5610. /// gives a range to shaders, and before the lists run.
  5611. ///
  5612. /// Also the textures brought up to date in the submission so far: most
  5613. /// lists of a world submission sample the same textures, and a texture in
  5614. /// physical-page memory is hashed whole each time it is checked. Checked
  5615. /// once, it is checked again only after a step that writes title memory.
  5616. #[derive(Default)]
  5617. struct Batch {
  5618. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  5619. /// Where each copy (by address) is in `refreshes`: the list that makes
  5620. /// the heap's buffers ready adds some 4,100 copies, and searching them
  5621. /// for every refresh of a submission was tens of millions of
  5622. /// comparisons a frame.
  5623. index: std::collections::HashMap<usize, usize>,
  5624. /// Staging buffers (by address) refreshed since the last title write.
  5625. textures: std::collections::HashSet<usize>,
  5626. }
  5627. impl Batch {
  5628. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  5629. let end = address + len;
  5630. let key = std::sync::Arc::as_ptr(shadow) as usize;
  5631. match self.index.get(&key) {
  5632. Some(&at) => {
  5633. let r = &mut self.refreshes[at];
  5634. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  5635. }
  5636. None => {
  5637. self.index.insert(key, self.refreshes.len());
  5638. self.refreshes.push((shadow.clone(), address, end));
  5639. }
  5640. }
  5641. }
  5642. /// Before shaders are given a range of `shadow`'s copy: its pending
  5643. /// refresh is done, the others stay pending.
  5644. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  5645. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  5646. return;
  5647. };
  5648. let (shadow, from, to) = self.refreshes.swap_remove(at);
  5649. // The last entry took its place.
  5650. if let Some(moved) = self.refreshes.get(at) {
  5651. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  5652. }
  5653. Self::update(&shadow, from, to);
  5654. }
  5655. /// Brings `[from, to)` of a copy up to date, timed.
  5656. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  5657. let started = std::time::Instant::now();
  5658. let copied = shadow.update(from, to - from);
  5659. let us = started.elapsed().as_micros() as u64;
  5660. #[cfg(feature = "diagnostics")]
  5661. crate::copystat::range(from, to - from, us, 0);
  5662. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  5663. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  5664. }
  5665. /// Whether `staging` is still to be refreshed in this submission (and
  5666. /// notes it refreshed).
  5667. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  5668. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  5669. }
  5670. /// Before a step that writes title memory: pending refreshes are done
  5671. /// first, and textures are checked again after it.
  5672. fn title_written(&mut self) {
  5673. self.flush();
  5674. self.textures.clear();
  5675. }
  5676. fn flush(&mut self) {
  5677. self.index.clear();
  5678. // One write-watch asking for the copies that lie close together,
  5679. // not one per copy.
  5680. let ahead = self.refreshes.len() > 1;
  5681. if ahead {
  5682. let started = std::time::Instant::now();
  5683. let ranges: Vec<(usize, usize)> = self
  5684. .refreshes
  5685. .iter()
  5686. .filter(|r| !r.0.unwatched())
  5687. .map(|r| (r.1, r.2))
  5688. .collect();
  5689. crate::watch::ask_ahead(&ranges);
  5690. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  5691. }
  5692. if wide_refresh() && self.refreshes.len() >= 4 {
  5693. // Each copy on its own, several at a time: a copy's refresh
  5694. // writes that copy and reads title memory, nothing of another's.
  5695. // The time counted is the time it took, not the threads' sum.
  5696. let started = std::time::Instant::now();
  5697. let before = PREPARING[0].load(Ordering::Relaxed);
  5698. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  5699. .refreshes
  5700. .drain(..)
  5701. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  5702. .collect();
  5703. crate::shadow::wide_run(jobs);
  5704. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  5705. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  5706. } else {
  5707. for (shadow, from, to) in self.refreshes.drain(..) {
  5708. Self::update(&shadow, from, to);
  5709. }
  5710. }
  5711. if ahead {
  5712. crate::watch::ask_ahead_done();
  5713. }
  5714. }
  5715. }
  5716. /// Copies title memory at submission. The ranges were checked against their
  5717. /// resources when recorded, but the title may since have unmapped pages of
  5718. /// them (tiled memory, page mappings), which read as zeros here; a title
  5719. /// destination (`title_dst`) that is not all mapped is left alone.
  5720. ///
  5721. /// The source is read through the kernel (`ReadProcessMemory`), which
  5722. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  5723. /// cost about 2 ms per copy in the title's big pools (it walks the page
  5724. /// tables to the region's end), which made copies run at 100-200 MB/s.
  5725. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  5726. #[cfg(feature = "diagnostics")]
  5727. match crate::copystat::mode() {
  5728. 1 => {
  5729. // SAFETY: timing only: the caller vouches for the source.
  5730. unsafe { std::ptr::copy(src, dst, len) };
  5731. return;
  5732. }
  5733. 2 => return,
  5734. _ => {}
  5735. }
  5736. if len == 0 {
  5737. return;
  5738. }
  5739. // A title destination that is not all mapped is left alone. Asking
  5740. // Windows first (`VirtualQuery`) walks the page tables to the end of
  5741. // the destination's region: in the title's big blocks that is
  5742. // milliseconds a copy, and it was a seventh of the submitting thread's
  5743. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  5744. // says the same when it fails, so the question is only asked then.
  5745. // `VICTORY_COPY_ASK=1` asks first, as before.
  5746. static ASK: OnceLock<bool> = OnceLock::new();
  5747. let ask_first = title_dst
  5748. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  5749. if ask_first && !crate::texture::committed(dst, len) {
  5750. return;
  5751. }
  5752. if title_dst {
  5753. // The kernel writes the destination: it must not be guarded.
  5754. crate::watch::writing(dst as usize, len);
  5755. }
  5756. #[cfg(feature = "diagnostics")]
  5757. let moved = std::time::Instant::now();
  5758. let whole = read(src, dst, len);
  5759. #[cfg(feature = "diagnostics")]
  5760. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  5761. if whole {
  5762. return;
  5763. }
  5764. // The copy failed: a source page is not there, or the destination is
  5765. // not all mapped. Then the destination stays as it is (the kernel may
  5766. // have written its first pages).
  5767. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  5768. return;
  5769. }
  5770. #[cfg(feature = "diagnostics")]
  5771. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  5772. #[cfg(feature = "diagnostics")]
  5773. let sparse = std::time::Instant::now();
  5774. if !title_dst && len >= 64 << 10 {
  5775. read_sparse(src, dst, len);
  5776. } else {
  5777. read_pieces(src, dst, len);
  5778. }
  5779. #[cfg(feature = "diagnostics")]
  5780. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  5781. }
  5782. /// After a failed bulk read into host memory, skip contiguous holes. Never
  5783. /// cache the query across copies: the title may remap the same address.
  5784. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  5785. use windows_sys::Win32::System::Memory::{
  5786. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  5787. };
  5788. let mut offset = 0;
  5789. while offset < len {
  5790. let at = src.wrapping_add(offset);
  5791. let to = dst.wrapping_add(offset);
  5792. let remaining = len - offset;
  5793. // SAFETY: the query inspects an address and fills a local structure.
  5794. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  5795. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  5796. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  5797. .saturating_sub(at as usize).min(remaining);
  5798. if size != size_of_val(&info) || n == 0 {
  5799. read_pieces(at, to, remaining);
  5800. break;
  5801. }
  5802. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  5803. #[cfg(feature = "diagnostics")]
  5804. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  5805. // SAFETY: this path is only used with a writable host destination.
  5806. unsafe { to.write_bytes(0, n) };
  5807. } else if !read(at, to, n) {
  5808. // A mapping may change between query and read.
  5809. read_pieces(at, to, n);
  5810. }
  5811. offset += n;
  5812. }
  5813. }
  5814. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  5815. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  5816. // that fails), zeros for what cannot be read.
  5817. for_pieces(src as usize, len, 64 << 10, |at, n| {
  5818. let to = dst.wrapping_add(at - src as usize);
  5819. if !read(at as *const u8, to, n) {
  5820. for_pieces(at, n, 4 << 10, |at, n| {
  5821. let to = dst.wrapping_add(at - src as usize);
  5822. if !read(at as *const u8, to, n) {
  5823. #[cfg(feature = "diagnostics")]
  5824. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  5825. // SAFETY: inside the destination, which is mapped.
  5826. unsafe { to.write_bytes(0, n) };
  5827. }
  5828. });
  5829. }
  5830. });
  5831. }
  5832. /// Reads title memory at `src` into `dst`; false if a page of it is not
  5833. /// readable.
  5834. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  5835. read(src, dst.as_mut_ptr(), dst.len())
  5836. }
  5837. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  5838. /// readable.
  5839. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  5840. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  5841. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  5842. if crate::safecopy::on() {
  5843. // SAFETY: the destination is mapped writable memory of `len` bytes;
  5844. // a source page that is not there fails the copy.
  5845. return unsafe { crate::safecopy::copy(dst, src, len) };
  5846. }
  5847. let mut done = 0;
  5848. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  5849. // kernel checks the source.
  5850. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  5851. }
  5852. #[link(name = "ntdll", kind = "raw-dylib")]
  5853. unsafe extern "system" {
  5854. /// The kernel's write into a process's memory, `(process, address,
  5855. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  5856. /// the range is not there or not writable. It changes no protection.
  5857. fn NtWriteVirtualMemory(
  5858. process: *mut std::ffi::c_void,
  5859. base: *mut std::ffi::c_void,
  5860. buffer: *const std::ffi::c_void,
  5861. size: usize,
  5862. written: *mut usize,
  5863. ) -> i32;
  5864. }
  5865. /// Whether title memory is written with the kernel's own call
  5866. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  5867. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  5868. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  5869. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  5870. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  5871. fn direct_writes() -> bool {
  5872. static ON: OnceLock<bool> = OnceLock::new();
  5873. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  5874. }
  5875. /// Copies host memory into title memory after a submission (what shaders
  5876. /// wrote), leaving pages that are not mapped alone.
  5877. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  5878. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  5879. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  5880. let direct = direct_writes();
  5881. let write = |at: usize, n: usize| {
  5882. let from = src.wrapping_add(at - dst as usize);
  5883. if crate::safecopy::on() {
  5884. // SAFETY: the source is ours; a destination page that is not
  5885. // there, or not writable, fails the copy.
  5886. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  5887. }
  5888. let mut done = 0;
  5889. if direct {
  5890. // SAFETY: as below; the kernel checks the destination and
  5891. // writes nothing it cannot (the caller opened its guards:
  5892. // `crate::watch::writing`).
  5893. return unsafe {
  5894. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  5895. };
  5896. }
  5897. // SAFETY: the source is our mapped host copy; the kernel checks the
  5898. // destination.
  5899. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  5900. };
  5901. if len == 0 || write(dst as usize, len) {
  5902. return;
  5903. }
  5904. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  5905. if !write(at, n) {
  5906. for_pieces(at, n, 4 << 10, |at, n| {
  5907. write(at, n);
  5908. });
  5909. }
  5910. });
  5911. }
  5912. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  5913. /// `step`.
  5914. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  5915. let end = start + len;
  5916. let mut at = start;
  5917. while at < end {
  5918. let next = ((at / step + 1) * step).min(end);
  5919. f(at, next - at);
  5920. at = next;
  5921. }
  5922. }
  5923. impl Host {
  5924. /// A buffer in the upload heap, mapped for writing.
  5925. /// A buffer of `size` bytes the card writes and we read (a read back),
  5926. /// in the state copies into it need.
  5927. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  5928. let heap = D3D12_HEAP_PROPERTIES {
  5929. Type: D3D12_HEAP_TYPE_READBACK,
  5930. ..Default::default()
  5931. };
  5932. let desc = D3D12_RESOURCE_DESC {
  5933. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5934. Width: size.max(1),
  5935. Height: 1,
  5936. DepthOrArraySize: 1,
  5937. MipLevels: 1,
  5938. SampleDesc: DXGI_SAMPLE_DESC {
  5939. Count: 1,
  5940. Quality: 0,
  5941. },
  5942. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5943. ..Default::default()
  5944. };
  5945. let mut buffer: Option<ID3D12Resource> = None;
  5946. // SAFETY: plain creation of a read-back buffer.
  5947. let made = unsafe {
  5948. self.device.CreateCommittedResource(
  5949. &heap,
  5950. D3D12_HEAP_FLAG_NONE,
  5951. &desc,
  5952. D3D12_RESOURCE_STATE_COPY_DEST,
  5953. None,
  5954. &mut buffer,
  5955. )
  5956. };
  5957. match made {
  5958. Ok(()) => buffer,
  5959. Err(e) => {
  5960. tracing::warn!(error = %e, size, "no read-back buffer");
  5961. None
  5962. }
  5963. }
  5964. }
  5965. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5966. MADE[0].fetch_add(1, Ordering::Relaxed);
  5967. MADE[1].fetch_add(size, Ordering::Relaxed);
  5968. let heap = D3D12_HEAP_PROPERTIES {
  5969. Type: D3D12_HEAP_TYPE_UPLOAD,
  5970. ..Default::default()
  5971. };
  5972. let desc = D3D12_RESOURCE_DESC {
  5973. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5974. Width: size.max(1),
  5975. Height: 1,
  5976. DepthOrArraySize: 1,
  5977. MipLevels: 1,
  5978. SampleDesc: DXGI_SAMPLE_DESC {
  5979. Count: 1,
  5980. Quality: 0,
  5981. },
  5982. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5983. ..Default::default()
  5984. };
  5985. let mut buffer: Option<ID3D12Resource> = None;
  5986. let mut data = std::ptr::null_mut();
  5987. // SAFETY: plain creation and mapping of an upload buffer.
  5988. let made = unsafe {
  5989. self.device
  5990. .CreateCommittedResource(
  5991. &heap,
  5992. D3D12_HEAP_FLAG_NONE,
  5993. &desc,
  5994. D3D12_RESOURCE_STATE_GENERIC_READ,
  5995. None,
  5996. &mut buffer,
  5997. )
  5998. .and_then(|()| {
  5999. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  6000. b.Map(0, None, Some(&mut data))
  6001. })
  6002. };
  6003. match made {
  6004. Ok(()) => Some((buffer?, data.cast())),
  6005. Err(e) => {
  6006. tracing::warn!(error = %e, size, "no upload buffer");
  6007. None
  6008. }
  6009. }
  6010. }
  6011. }
  6012. /// The swap chain formats a presented texture can be copied into: its own
  6013. /// family's.
  6014. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  6015. Some(match format.0 {
  6016. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  6017. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  6018. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  6019. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  6020. _ => return None,
  6021. })
  6022. }
  6023. const BUFFERS: u32 = 2;
  6024. struct Presenter {
  6025. swap_chain: IDXGISwapChain3,
  6026. width: u32,
  6027. height: u32,
  6028. format: DXGI_FORMAT,
  6029. copy: HostList,
  6030. /// With presents sent ahead ([`late_free_present`]): a list for each
  6031. /// present in the air, and the submission it last flew as (it is used
  6032. /// again once that one has finished).
  6033. ahead: Vec<(HostList, u64)>,
  6034. hwnd: HWND,
  6035. meter: Meter,
  6036. }
  6037. /// The frame rate, shown in the window's caption every second and logged
  6038. /// every few seconds.
  6039. struct Meter {
  6040. since: std::time::Instant,
  6041. frames: u32,
  6042. #[cfg(feature = "diagnostics")]
  6043. copy_stats_frames: u64,
  6044. drawn: u64,
  6045. logged: std::time::Instant,
  6046. /// The caption the window had, once read.
  6047. caption: Option<Vec<u16>>,
  6048. }
  6049. impl Meter {
  6050. fn new() -> Self {
  6051. let now = std::time::Instant::now();
  6052. Meter {
  6053. since: now,
  6054. frames: 0,
  6055. #[cfg(feature = "diagnostics")]
  6056. copy_stats_frames: 0,
  6057. drawn: crate::draw::drawn(),
  6058. logged: now,
  6059. caption: None,
  6060. }
  6061. }
  6062. /// Counts a presented frame.
  6063. fn frame(&mut self, hwnd: HWND) {
  6064. #[cfg(feature = "diagnostics")]
  6065. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  6066. #[cfg(feature = "diagnostics")]
  6067. crate::copystat::presented();
  6068. self.frames += 1;
  6069. #[cfg(feature = "diagnostics")]
  6070. {
  6071. self.copy_stats_frames += 1;
  6072. }
  6073. let elapsed = self.since.elapsed();
  6074. if elapsed < std::time::Duration::from_secs(1) {
  6075. return;
  6076. }
  6077. let drawn = crate::draw::drawn();
  6078. let frames = f64::from(self.frames);
  6079. let fps = frames / elapsed.as_secs_f64();
  6080. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  6081. let draws = (drawn - self.drawn) as f64 / frames;
  6082. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  6083. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  6084. let [cpu, gpu] = [0, 1].map(|i| {
  6085. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  6086. });
  6087. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  6088. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  6089. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  6090. });
  6091. let [back_ms, back_mb] = [0, 1].map(|i| {
  6092. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  6093. });
  6094. let dropped = crate::draw::take_dropped() as f64 / frames;
  6095. let indirect = crate::list::take_indirect() as f64 / frames;
  6096. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  6097. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  6098. tracing::info!(
  6099. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  6100. );
  6101. late_line(frames);
  6102. card_clock_line(frames, ms);
  6103. crate::shadow::back_line(frames);
  6104. {
  6105. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6106. if passes + compares > 0.0 {
  6107. tracing::info!(
  6108. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  6109. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  6110. if rehash_runs() { "on" } else { "off" }
  6111. );
  6112. }
  6113. }
  6114. {
  6115. let [own, asking, still, all] =
  6116. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  6117. if all >= 1.0 {
  6118. tracing::info!(
  6119. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  6120. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  6121. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  6122. );
  6123. }
  6124. let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6125. if through + left > 0.0 {
  6126. tracing::info!(
  6127. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  6128. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there)"
  6129. );
  6130. }
  6131. }
  6132. {
  6133. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6134. if copies > 0.0 {
  6135. tracing::info!(
  6136. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  6137. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  6138. if join_copies() { "on" } else { "off" }
  6139. );
  6140. }
  6141. }
  6142. // Passes over the heap's buffer views for shaders that pick them by index.
  6143. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  6144. let picked_ms =
  6145. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  6146. // Copies between depth textures and their colour twins, each way.
  6147. let [twin_to_depth, twin_to_colour] =
  6148. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6149. // Depth planes drawn from their twins.
  6150. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  6151. // Copies in the card's memory (`crate::shadow::cards`).
  6152. let card = crate::shadow::card_stats();
  6153. #[cfg(feature = "diagnostics")]
  6154. let slow = crate::watch::slow_asks();
  6155. // Over the same frames as the counts above.
  6156. #[cfg(feature = "diagnostics")]
  6157. let drops = crate::pipeline::take_drops();
  6158. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  6159. self.logged = std::time::Instant::now();
  6160. tracing::info!(
  6161. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  6162. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  6163. );
  6164. {
  6165. let [queued, due, away, partly, oldest] =
  6166. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  6167. let [same, parts, tails] =
  6168. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  6169. tracing::info!(
  6170. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  6171. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  6172. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  6173. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  6174. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  6175. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  6176. {} made slots found unmapped and made null",
  6177. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  6178. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  6179. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  6180. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  6181. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  6182. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  6183. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  6184. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  6185. );
  6186. }
  6187. #[cfg(feature = "diagnostics")]
  6188. tracing::info!(
  6189. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  6190. slow[0] as f64 / frames,
  6191. slow[1] as f64 / 1e3 / frames,
  6192. slow[2] as f64 / 1e3
  6193. );
  6194. if crate::shadow::cards() {
  6195. let per_frame = |i: usize| card[i] as f64 / frames;
  6196. tracing::info!(
  6197. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  6198. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  6199. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  6200. card[7],
  6201. card[8] >> 20,
  6202. card[9] >> 20,
  6203. per_frame(0) / 1e6,
  6204. per_frame(1),
  6205. per_frame(2),
  6206. per_frame(3),
  6207. per_frame(4) / 1e6,
  6208. per_frame(5),
  6209. per_frame(6) / 1e3
  6210. );
  6211. }
  6212. tracing::info!(
  6213. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  6214. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  6215. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  6216. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  6217. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  6218. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  6219. {picked_waiting} waiting, {picked_away} passed over unmapped; depth textures with unordered access: {du0} made, bound as depth {du1}x, cleared as depth {du2}x, unordered views refused {du3}x; buffer views left null as the host would refuse them: {refused}",
  6220. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  6221. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  6222. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  6223. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  6224. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  6225. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  6226. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  6227. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  6228. refused = format!(
  6229. "{}; depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass",
  6230. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  6231. crate::resource::TWINS[0].load(Ordering::Relaxed),
  6232. crate::resource::TWINS[1].load(Ordering::Relaxed),
  6233. crate::resource::PLANES[1].load(Ordering::Relaxed),
  6234. crate::resource::PLANES[2].load(Ordering::Relaxed)
  6235. ),
  6236. making = crate::pipeline::making(),
  6237. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  6238. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  6239. );
  6240. #[cfg(feature = "diagnostics")]
  6241. {
  6242. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6243. tracing::info!(
  6244. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  6245. put[0],
  6246. put[1],
  6247. put[2] / 1e6,
  6248. put[3]
  6249. );
  6250. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  6251. for (why, n) in drops.iter().take(40) {
  6252. tracing::info!(
  6253. "dropped {:.1}/frame without a host pipeline: {why}",
  6254. *n as f64 / frames
  6255. );
  6256. }
  6257. }
  6258. }
  6259. if self.caption.is_none() {
  6260. // The window's own text, read without a message.
  6261. let mut buffer = vec![0u16; 512];
  6262. // SAFETY: a window handle and a buffer of that length.
  6263. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  6264. buffer.truncate(n.max(0) as usize);
  6265. self.caption = Some(buffer);
  6266. }
  6267. let Some(caption) = &self.caption else { return };
  6268. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  6269. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  6270. text.push(0);
  6271. // Setting the text waits for the window's thread (a title thread,
  6272. // which may not pump for a while), so a thread of ours does it and
  6273. // presenting never waits; it takes the newest text when free.
  6274. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  6275. static SETTER: std::sync::Once = std::sync::Once::new();
  6276. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  6277. SETTER.call_once(|| {
  6278. let _ = std::thread::Builder::new()
  6279. .name("victory-caption".into())
  6280. .spawn(|| {
  6281. loop {
  6282. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  6283. match next {
  6284. // SAFETY: a window handle and a NUL-terminated text.
  6285. Some((hwnd, text)) => unsafe {
  6286. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  6287. },
  6288. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  6289. }
  6290. }
  6291. });
  6292. });
  6293. }
  6294. }
  6295. impl Host {
  6296. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  6297. /// as frame `frame` (saved if captures are on). `None` if nothing was
  6298. /// shown; else, in diagnostics builds, whether the frame was black.
  6299. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  6300. // SAFETY: a live resource.
  6301. let desc = unsafe { texture.GetDesc() };
  6302. let Some(format) = swap_format(desc.Format) else {
  6303. tracing::warn!(format = desc.Format.0, "cannot present this format");
  6304. return None;
  6305. };
  6306. let (width, height) = (desc.Width as u32, desc.Height);
  6307. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  6308. if presenter.is_none() {
  6309. *presenter = match self.presenter(width, height, format) {
  6310. Ok(p) => Some(p),
  6311. Err(e) => {
  6312. tracing::warn!(error = %e, "no swap chain");
  6313. return None;
  6314. }
  6315. };
  6316. }
  6317. let p = presenter.as_mut()?;
  6318. if (p.width, p.height, p.format) != (width, height, format) {
  6319. // Presents sent ahead hold back buffers until they have run.
  6320. settle_now(WHY_SYNC);
  6321. // SAFETY: no back buffer is held; every submission was waited for.
  6322. let resized = unsafe {
  6323. p.swap_chain
  6324. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  6325. };
  6326. match resized {
  6327. Ok(()) => {
  6328. (p.width, p.height, p.format) = (width, height, format);
  6329. tracing::info!(
  6330. width,
  6331. height,
  6332. format = format.0,
  6333. frame,
  6334. "the swap chain's buffers were made again for another size or format"
  6335. );
  6336. self.log_video_memory("right after the swap chain's buffers were made again");
  6337. }
  6338. Err(e) => {
  6339. tracing::warn!(error = %e, width, height, "swap chain not resized");
  6340. return None;
  6341. }
  6342. }
  6343. }
  6344. let state = D3D12_RESOURCE_STATES(state as i32);
  6345. // SAFETY: our swap chain, list and a live source texture.
  6346. unsafe {
  6347. let index = p.swap_chain.GetCurrentBackBufferIndex();
  6348. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  6349. return None;
  6350. };
  6351. // Sent ahead ([`late_free_present`]) unless the frame is to be
  6352. // read back at once (a saved or listed frame): then a list of
  6353. // its own, one whose last flight has finished or a new one.
  6354. #[cfg(feature = "diagnostics")]
  6355. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  6356. #[cfg(not(feature = "diagnostics"))]
  6357. let read_now = false;
  6358. let slot = if late_free_present() && !read_now {
  6359. let finished = FINISHED.load(Ordering::Acquire);
  6360. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  6361. let list = self.new_list().ok()?;
  6362. list.close();
  6363. p.ahead.push((list, 0));
  6364. Some(p.ahead.len() - 1)
  6365. })
  6366. } else {
  6367. None
  6368. };
  6369. let copy = match slot {
  6370. Some(i) => &p.ahead[i].0,
  6371. None => &p.copy,
  6372. };
  6373. copy.reset();
  6374. let list = &copy.list;
  6375. list.ResourceBarrier(&[
  6376. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  6377. transition(
  6378. &back,
  6379. D3D12_RESOURCE_STATE_PRESENT,
  6380. D3D12_RESOURCE_STATE_COPY_DEST,
  6381. ),
  6382. ]);
  6383. list.CopyResource(&back, texture);
  6384. #[cfg(feature = "diagnostics")]
  6385. let capture = crate::capture::wanted(frame)
  6386. .then(|| crate::capture::read_back(&self.device, list, texture))
  6387. .flatten();
  6388. #[cfg(feature = "diagnostics")]
  6389. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  6390. #[cfg(not(feature = "diagnostics"))]
  6391. let _ = frame;
  6392. list.ResourceBarrier(&[
  6393. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  6394. transition(
  6395. &back,
  6396. D3D12_RESOURCE_STATE_COPY_DEST,
  6397. D3D12_RESOURCE_STATE_PRESENT,
  6398. ),
  6399. ]);
  6400. copy.close();
  6401. match slot {
  6402. Some(i) => {
  6403. let flown = self.execute_own(copy);
  6404. p.ahead[i].1 = flown;
  6405. }
  6406. None => self.execute(&[copy]),
  6407. }
  6408. #[cfg(feature = "diagnostics")]
  6409. if let Some((buffer, footprint)) = capture {
  6410. crate::capture::save_read_back(frame, &buffer, &footprint);
  6411. }
  6412. #[cfg(feature = "diagnostics")]
  6413. crate::replay::record::present(texture, state);
  6414. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  6415. p.meter.frame(p.hwnd);
  6416. #[cfg(feature = "diagnostics")]
  6417. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  6418. #[cfg(not(feature = "diagnostics"))]
  6419. Some(false)
  6420. }
  6421. }
  6422. fn presenter(
  6423. &self,
  6424. width: u32,
  6425. height: u32,
  6426. format: DXGI_FORMAT,
  6427. ) -> windows::core::Result<Presenter> {
  6428. let hwnd = match title_window() {
  6429. Some(hwnd) => hwnd,
  6430. None => window(width, height)?,
  6431. };
  6432. self.log_video_memory("right before the swap chain is made");
  6433. // SAFETY: plain object creation for our window.
  6434. unsafe {
  6435. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  6436. let desc = DXGI_SWAP_CHAIN_DESC1 {
  6437. Width: width,
  6438. Height: height,
  6439. Format: format,
  6440. SampleDesc: DXGI_SAMPLE_DESC {
  6441. Count: 1,
  6442. Quality: 0,
  6443. },
  6444. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  6445. BufferCount: BUFFERS,
  6446. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  6447. ..Default::default()
  6448. };
  6449. let swap_chain = factory
  6450. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  6451. .cast::<IDXGISwapChain3>()?;
  6452. let copy = self.new_list()?;
  6453. copy.close();
  6454. tracing::info!(width, height, format = format.0, "presenting to a window");
  6455. self.log_video_memory("right after the swap chain is made");
  6456. Ok(Presenter {
  6457. swap_chain,
  6458. width,
  6459. height,
  6460. format,
  6461. copy,
  6462. ahead: Vec::new(),
  6463. hwnd,
  6464. meter: Meter::new(),
  6465. })
  6466. }
  6467. }
  6468. }
  6469. /// A visible top-level window of this process: the one the title made, if
  6470. /// it made one.
  6471. fn title_window() -> Option<HWND> {
  6472. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  6473. let mut process = 0;
  6474. // SAFETY: a window handle from the enumeration; `found` is ours.
  6475. unsafe {
  6476. GetWindowThreadProcessId(hwnd, Some(&mut process));
  6477. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  6478. && IsWindowVisible(hwnd).as_bool()
  6479. {
  6480. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  6481. return false.into();
  6482. }
  6483. }
  6484. true.into()
  6485. }
  6486. let mut found: Option<HWND> = None;
  6487. // SAFETY: the callback only writes `found`, which outlives the call.
  6488. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  6489. found
  6490. }
  6491. /// `state` without the bits the host texture's flags forbid: the console
  6492. /// lets the title name states its own resources allow (unordered access on
  6493. /// a depth target, whose host copy cannot have both).
  6494. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  6495. // SAFETY: a plain query.
  6496. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  6497. }
  6498. /// [`legal_state`] for a texture with resource flags `flags`.
  6499. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  6500. // (flag, set or clear forbids, state bits): render target, unordered
  6501. // access, depth, denied shader resource.
  6502. const FORBIDDEN: [(u32, bool, u32); 4] = [
  6503. (0x1, false, 0x4),
  6504. (0x4, false, 0x8),
  6505. (0x2, false, 0x10 | 0x20),
  6506. (0x8, true, 0x40 | 0x80),
  6507. ];
  6508. FORBIDDEN
  6509. .iter()
  6510. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  6511. .fold(state, |s, &(_, _, bits)| s & !bits)
  6512. }
  6513. impl Host {
  6514. /// The card's memory as the system accounts it to this process, in
  6515. /// bytes: the budget and the use of the card's own memory, then of the
  6516. /// PC's memory shared with the card (where the system moves what does
  6517. /// not fit on the card).
  6518. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  6519. let adapter = self.adapter.as_ref()?;
  6520. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  6521. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  6522. // SAFETY: plain queries that fill our structures.
  6523. unsafe {
  6524. adapter
  6525. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  6526. .ok()?;
  6527. adapter
  6528. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  6529. .ok()?;
  6530. }
  6531. // The card's budget moved by 256 MB or more since the last look:
  6532. // said at once, with what was in use at the last look, so the log
  6533. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  6534. // the first world frame in runs 179 to 185, and the memory line,
  6535. // seconds later, was the first to show it. We reserve nothing
  6536. // and make the swap chain once, at the start.)
  6537. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  6538. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  6539. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  6540. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  6541. tracing::info!(
  6542. "the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use",
  6543. last[0] >> 20,
  6544. own.Budget >> 20,
  6545. crate::frame::current(),
  6546. last[1] >> 20,
  6547. last[2] >> 20
  6548. );
  6549. self.log_video_memory("right after that change");
  6550. }
  6551. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  6552. }
  6553. /// Both of the system's memory groups for this process, in bytes: for
  6554. /// the card's own memory and then for the PC's memory shared with the
  6555. /// card, the budget, the use, what could still be reserved and what
  6556. /// is reserved (the layer reserves none).
  6557. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  6558. let adapter = self.adapter.as_ref()?;
  6559. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  6560. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  6561. // SAFETY: plain queries that fill our structures.
  6562. unsafe {
  6563. adapter
  6564. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  6565. .ok()?;
  6566. adapter
  6567. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  6568. .ok()?;
  6569. }
  6570. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  6571. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  6572. };
  6573. Some([all(&own), all(&shared)])
  6574. }
  6575. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  6576. pub(crate) fn log_video_memory(&self, when: &str) {
  6577. let Some([own, shared]) = self.video_memory_groups() else {
  6578. return;
  6579. };
  6580. tracing::info!(
  6581. "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)",
  6582. when,
  6583. own[0] >> 20,
  6584. own[1] >> 20,
  6585. own[2] >> 20,
  6586. own[3] >> 20,
  6587. shared[0] >> 20,
  6588. shared[1] >> 20,
  6589. shared[2] >> 20,
  6590. shared[3] >> 20
  6591. );
  6592. }
  6593. /// A buffer in system memory that the CPU maps (write-back, so reading
  6594. /// it is fast too) and shaders read and write: for host copies of title
  6595. /// memory that shaders write, which upload memory cannot be. Starts in
  6596. /// the common state (buffers move out of it implicitly).
  6597. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6598. MADE[2].fetch_add(1, Ordering::Relaxed);
  6599. MADE[3].fetch_add(size, Ordering::Relaxed);
  6600. let heap = D3D12_HEAP_PROPERTIES {
  6601. Type: D3D12_HEAP_TYPE_CUSTOM,
  6602. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  6603. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  6604. ..Default::default()
  6605. };
  6606. let desc = D3D12_RESOURCE_DESC {
  6607. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6608. Width: size.max(1),
  6609. Height: 1,
  6610. DepthOrArraySize: 1,
  6611. MipLevels: 1,
  6612. SampleDesc: DXGI_SAMPLE_DESC {
  6613. Count: 1,
  6614. Quality: 0,
  6615. },
  6616. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6617. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  6618. ..Default::default()
  6619. };
  6620. let mut buffer: Option<ID3D12Resource> = None;
  6621. let mut data = std::ptr::null_mut();
  6622. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  6623. let made = unsafe {
  6624. self.device
  6625. .CreateCommittedResource(
  6626. &heap,
  6627. D3D12_HEAP_FLAG_NONE,
  6628. &desc,
  6629. D3D12_RESOURCE_STATE_COMMON,
  6630. None,
  6631. &mut buffer,
  6632. )
  6633. .and_then(|()| {
  6634. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  6635. b.Map(0, None, Some(&mut data))
  6636. })
  6637. };
  6638. match made {
  6639. Ok(()) => Some((buffer?, data.cast())),
  6640. Err(e) => {
  6641. tracing::warn!(error = %e, size, "no shared buffer");
  6642. None
  6643. }
  6644. }
  6645. }
  6646. /// A device-local buffer shaders may write (unordered access) and indirect
  6647. /// execution may read, starting in the common state.
  6648. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  6649. MADE[4].fetch_add(1, Ordering::Relaxed);
  6650. MADE[5].fetch_add(size, Ordering::Relaxed);
  6651. let heap = D3D12_HEAP_PROPERTIES {
  6652. Type: D3D12_HEAP_TYPE_DEFAULT,
  6653. ..Default::default()
  6654. };
  6655. let desc = D3D12_RESOURCE_DESC {
  6656. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6657. Width: size.max(1),
  6658. Height: 1,
  6659. DepthOrArraySize: 1,
  6660. MipLevels: 1,
  6661. SampleDesc: DXGI_SAMPLE_DESC {
  6662. Count: 1,
  6663. Quality: 0,
  6664. },
  6665. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6666. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  6667. ..Default::default()
  6668. };
  6669. let mut buffer: Option<ID3D12Resource> = None;
  6670. // SAFETY: plain creation of a device-local buffer.
  6671. let made = unsafe {
  6672. self.device.CreateCommittedResource(
  6673. &heap,
  6674. D3D12_HEAP_FLAG_NONE,
  6675. &desc,
  6676. D3D12_RESOURCE_STATE_COMMON,
  6677. None,
  6678. &mut buffer,
  6679. )
  6680. };
  6681. match made {
  6682. Ok(()) => buffer,
  6683. Err(e) => {
  6684. tracing::warn!(error = %e, size, "no unordered-access buffer");
  6685. None
  6686. }
  6687. }
  6688. }
  6689. }
  6690. /// For adapters without device-removed data (the software one): the last
  6691. /// commands each list of the failed submission noted (diagnostics, with
  6692. /// `VICTORY_D3D12_DRED`).
  6693. fn last_notes(runs: &[&HostList]) -> String {
  6694. #[cfg(feature = "diagnostics")]
  6695. {
  6696. let mut text = String::new();
  6697. for (i, r) in runs.iter().enumerate() {
  6698. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  6699. for (n, _) in notes.iter().rev().take(6).rev() {
  6700. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  6701. }
  6702. }
  6703. text
  6704. }
  6705. #[cfg(not(feature = "diagnostics"))]
  6706. {
  6707. let _ = runs;
  6708. String::new()
  6709. }
  6710. }
  6711. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  6712. /// command reads (diagnostics).
  6713. #[cfg(feature = "diagnostics")]
  6714. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  6715. let end = start + bytes;
  6716. if va < start {
  6717. format!(" (fault {:#x} below its source)", start - va)
  6718. } else if va < end {
  6719. format!(" (fault at source +{:#x})", va - start)
  6720. } else {
  6721. format!(" (fault {:#x} past its source's end)", va - end)
  6722. }
  6723. }
  6724. /// The commands that may have been running where a list stopped at
  6725. /// command `done`: those between the barriers around it (work between
  6726. /// barriers overlaps on the GPU), by kind, and what the markers just
  6727. /// before them say (`HostList::note_op`: diagnostics builds with
  6728. /// device-removed data on).
  6729. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  6730. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  6731. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  6732. let to = history[done..]
  6733. .iter()
  6734. .position(barrier)
  6735. .map_or(history.len(), |b| (done + b).max(done + 1));
  6736. let mut text = format!(", commands {from}..{to} between its barriers:");
  6737. let mut shown = 0;
  6738. // From just before the command the GPU had not finished: the first
  6739. // twelve after the barrier named draws long done when a list of 79
  6740. // mesh draws stopped at its 45th (run 41).
  6741. for i in from.max(done.saturating_sub(4))..to {
  6742. let op = history[i];
  6743. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  6744. continue;
  6745. }
  6746. shown += 1;
  6747. let marker = i
  6748. .checked_sub(1)
  6749. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  6750. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  6751. .map_or("no marker", |(_, s)| s.as_str());
  6752. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  6753. }
  6754. text
  6755. }
  6756. pub(crate) fn transition(
  6757. resource: &ID3D12Resource,
  6758. before: D3D12_RESOURCE_STATES,
  6759. after: D3D12_RESOURCE_STATES,
  6760. ) -> D3D12_RESOURCE_BARRIER {
  6761. D3D12_RESOURCE_BARRIER {
  6762. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  6763. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  6764. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  6765. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  6766. // SAFETY: a borrowed pointer; the barrier never releases it.
  6767. pResource: unsafe { std::mem::transmute_copy(resource) },
  6768. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  6769. StateBefore: before,
  6770. StateAfter: after,
  6771. }),
  6772. },
  6773. }
  6774. }
  6775. /// A window of the given client size, owned by its own message thread.
  6776. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  6777. let (sender, receiver) = std::sync::mpsc::channel();
  6778. std::thread::Builder::new()
  6779. .name("victory-window".into())
  6780. .spawn(move || {
  6781. let made = make_window(width, height);
  6782. let ok = made.is_ok();
  6783. let _ = sender.send(made.map(|h| h.0 as usize));
  6784. if ok {
  6785. pump();
  6786. }
  6787. })
  6788. .map_err(|_| windows::core::Error::empty())?;
  6789. let hwnd = receiver
  6790. .recv()
  6791. .map_err(|_| windows::core::Error::empty())??;
  6792. Ok(HWND(hwnd as *mut _))
  6793. }
  6794. extern "system" fn window_proc(
  6795. hwnd: HWND,
  6796. message: u32,
  6797. wparam: WPARAM,
  6798. lparam: LPARAM,
  6799. ) -> LRESULT {
  6800. // SAFETY: the default handling for our window.
  6801. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  6802. }
  6803. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  6804. const CLASS: PCWSTR = w!("VIctory");
  6805. // SAFETY: registers our class once and creates a window of it.
  6806. unsafe {
  6807. let instance = GetModuleHandleW(None)?;
  6808. let class = WNDCLASSEXW {
  6809. cbSize: size_of::<WNDCLASSEXW>() as u32,
  6810. lpfnWndProc: Some(window_proc),
  6811. hInstance: instance.into(),
  6812. lpszClassName: CLASS,
  6813. hCursor: LoadCursorW(None, IDC_ARROW)?,
  6814. ..Default::default()
  6815. };
  6816. RegisterClassExW(&class);
  6817. let mut rect = RECT {
  6818. left: 0,
  6819. top: 0,
  6820. right: width as i32,
  6821. bottom: height as i32,
  6822. };
  6823. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  6824. CreateWindowExW(
  6825. WINDOW_EX_STYLE(0),
  6826. CLASS,
  6827. w!("VIctory"),
  6828. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  6829. CW_USEDEFAULT,
  6830. CW_USEDEFAULT,
  6831. rect.right - rect.left,
  6832. rect.bottom - rect.top,
  6833. None,
  6834. None,
  6835. Some(instance.into()),
  6836. None,
  6837. )
  6838. }
  6839. }
  6840. fn pump() {
  6841. let mut message = MSG::default();
  6842. // SAFETY: the standard message loop of this thread's window.
  6843. unsafe {
  6844. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  6845. let _ = TranslateMessage(&message);
  6846. DispatchMessageW(&message);
  6847. }
  6848. }
  6849. }
  6850. #[cfg(test)]
  6851. mod trail {
  6852. /// The trail keeps the newest things, and the report made when the
  6853. /// host device is removed says them and the pipeline library's state
  6854. /// (no card is asked for any of it).
  6855. #[test]
  6856. fn the_removal_report_says_the_newest_things_done() {
  6857. for n in 0..super::TRAIL_MOST + 5 {
  6858. super::trail(|| format!("thing {n} done"));
  6859. }
  6860. let text = super::removal_context();
  6861. assert!(text.contains("the submitting thread was"));
  6862. assert!(text.contains("pipeline library: no call running"));
  6863. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  6864. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  6865. }
  6866. }
  6867. #[cfg(test)]
  6868. mod spare {
  6869. use super::Spare;
  6870. /// Kept things come back by size, the last given first, and nothing is
  6871. /// kept past the limit.
  6872. #[test]
  6873. fn kept_things_come_back_by_size_within_the_limit() {
  6874. let mut spare: Spare<u32> = Spare::new();
  6875. assert_eq!(spare.take(4), None);
  6876. assert_eq!(spare.give(1, 4, 10), None);
  6877. assert_eq!(spare.give(2, 1, 10), None);
  6878. assert_eq!(spare.give(3, 4, 10), None);
  6879. assert_eq!(spare.bytes, 9);
  6880. // Past the limit: handed back, nothing changes.
  6881. assert_eq!(spare.give(4, 4, 10), Some(4));
  6882. assert_eq!(spare.bytes, 9);
  6883. assert_eq!(spare.take(2), None, "no thing of that size");
  6884. assert_eq!(spare.take(4), Some(3));
  6885. assert_eq!(spare.take(4), Some(1));
  6886. assert_eq!(spare.take(4), None);
  6887. assert_eq!(spare.take(1), Some(2));
  6888. assert_eq!(spare.bytes, 0);
  6889. assert!(spare.kept.is_empty());
  6890. }
  6891. }
  6892. #[cfg(test)]
  6893. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  6894. use super::Batch;
  6895. use std::sync::Arc;
  6896. #[test]
  6897. fn a_texture_is_checked_once_per_submission() {
  6898. let mut batch = Batch::default();
  6899. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  6900. // The first list sampling each texture checks it ...
  6901. assert!(batch.texture_due(&a));
  6902. assert!(batch.texture_due(&b));
  6903. // ... later lists of the same submission do not.
  6904. assert!(!batch.texture_due(&a));
  6905. assert!(!batch.texture_due(&a.clone()));
  6906. assert!(!batch.texture_due(&b));
  6907. }
  6908. #[test]
  6909. fn title_writes_make_textures_due_again() {
  6910. let mut batch = Batch::default();
  6911. let a = Arc::new(1u32);
  6912. assert!(batch.texture_due(&a));
  6913. assert!(!batch.texture_due(&a));
  6914. // A copy into title memory or work that may write it may have
  6915. // changed the texture's memory.
  6916. batch.title_written();
  6917. assert!(batch.texture_due(&a));
  6918. assert!(!batch.texture_due(&a));
  6919. // A fresh submission starts over.
  6920. let mut next = Batch::default();
  6921. assert!(next.texture_due(&a));
  6922. }
  6923. /// The hashing a submission does for textures in physical-page memory,
  6924. /// with every list checking the textures it samples (before) and with
  6925. /// each checked once (after). Run with
  6926. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  6927. #[test]
  6928. #[ignore = "benchmark"]
  6929. fn texture_checks_per_submission() {
  6930. const TEXTURES: usize = 48;
  6931. const SIZE: usize = 4 << 20;
  6932. const LISTS: usize = 12;
  6933. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  6934. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  6935. .collect();
  6936. let submit = |dedupe: bool| {
  6937. let mut batch = Batch::default();
  6938. let mut hashed = 0usize;
  6939. let started = std::time::Instant::now();
  6940. for _ in 0..LISTS {
  6941. for t in &textures {
  6942. if !dedupe || batch.texture_due(t) {
  6943. std::hint::black_box(blake3::hash(t));
  6944. hashed += 1;
  6945. }
  6946. }
  6947. }
  6948. (started.elapsed(), hashed)
  6949. };
  6950. submit(false); // warm up
  6951. let (before, n_before) = submit(false);
  6952. let (after, n_after) = submit(true);
  6953. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  6954. println!(
  6955. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  6956. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  6957. SIZE >> 20,
  6958. before.as_secs_f64() / after.as_secs_f64()
  6959. );
  6960. }
  6961. #[test]
  6962. fn vram_idle_ms_scales_with_pressure() {
  6963. use super::vram_idle_ms;
  6964. let gib = 1024 * 1024 * 1024;
  6965. // Normal (< 75%)
  6966. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  6967. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  6968. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  6969. // Moderate (75%..85%)
  6970. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  6971. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  6972. // High (>= 85%, including over-budget)
  6973. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  6974. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  6975. // Missing or zero budget falls back to normal
  6976. assert_eq!(vram_idle_ms(None), 5_000);
  6977. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  6978. }
  6979. #[test]
  6980. fn ram_idle_ms_scales_with_pressure() {
  6981. use super::ram_idle_ms;
  6982. let gib = 1024 * 1024 * 1024;
  6983. // Normal (>= 4 GiB)
  6984. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  6985. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  6986. // Moderate (2 GiB..4 GiB)
  6987. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  6988. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  6989. // High (< 2 GiB)
  6990. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  6991. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  6992. // Missing falls back to normal
  6993. assert_eq!(ram_idle_ms(None), 10_000);
  6994. }
  6995. }