host.rs 306 KB

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