host.rs 377 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631
  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. /// Zeros for a title destination that went meanwhile are no fault.
  656. #[test]
  657. fn zeros_where_nothing_is_are_lost() {
  658. use windows_sys::Win32::System::Memory::*;
  659. // SAFETY: a reservation of ours, its first page committed.
  660. unsafe {
  661. let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  662. assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
  663. at.write_bytes(7, 4096);
  664. super::zero(at, 4096);
  665. assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
  666. super::zero(at.add(4096), 4096);
  667. VirtualFree(at.cast(), 0, MEM_RELEASE);
  668. }
  669. }
  670. #[test]
  671. fn sparse_copies_preserve_islands_and_observe_remaps() {
  672. use windows_sys::Win32::System::Memory::*;
  673. const N: usize = 5 << 16;
  674. // SAFETY: we reserve a private region, commit selected pages inside it,
  675. // and only directly access the pages while they are writable.
  676. unsafe {
  677. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  678. assert!(!base.is_null());
  679. let mut expected = vec![0; N];
  680. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  681. let at = base.add(offset);
  682. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  683. at.write_bytes(value, 4096);
  684. expected[offset..offset + 4096].fill(value);
  685. }
  686. for remap in [false, true] {
  687. if remap {
  688. let mut old = 0;
  689. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  690. expected[..4096].fill(0);
  691. let at = base.add(1 << 16);
  692. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  693. at.write_bytes(0xc7, 4096);
  694. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  695. }
  696. let mut out = vec![0xee; N];
  697. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  698. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  699. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  700. }
  701. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  702. }
  703. }
  704. use super::*;
  705. #[test]
  706. fn warp_adapter_accepts_only_software() {
  707. // This probes DXGI without creating a D3D12 device or running a title.
  708. // SAFETY: plain DXGI adapter queries.
  709. let raw = unsafe {
  710. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  711. else {
  712. return;
  713. };
  714. factory.EnumWarpAdapter::<IDXGIAdapter>()
  715. };
  716. let Ok(raw) = raw else { return };
  717. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  718. // IDXGIAdapter1; `raw` owns that interface.
  719. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  720. eprintln!(
  721. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  722. desc.VendorId, desc.Flags
  723. );
  724. assert_eq!(
  725. warp_adapter().is_ok(),
  726. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  727. );
  728. }
  729. }
  730. /// The batches of clamped records in one scratch buffer
  731. /// ([`HostList::batch_place`]).
  732. const BATCHES: u32 = 8;
  733. /// A host command list and its allocator, always used together.
  734. pub(crate) struct HostList {
  735. allocator: ID3D12CommandAllocator,
  736. pub(crate) list: ID3D12GraphicsCommandList,
  737. /// Work for submission time, in recorded order.
  738. deferred: Mutex<Deferred>,
  739. /// Upload memory for data the list's draws make (expanded vertices),
  740. /// reused after a reset.
  741. scratch: Mutex<Scratch>,
  742. /// Host texture states the list assumes, by host copy: at its start and
  743. /// at its end. Lists are recorded on many threads and run in submission
  744. /// order, so the transitions from a texture's real state are made at
  745. /// submission, in `prelude`. Holding the copies keeps every texture the
  746. /// list names alive until it is reset, even if the title releases the
  747. /// resource first.
  748. states: Mutex<States>,
  749. /// What the list does with depth textures that have a colour twin, by
  750. /// twin ([`TwinUse`]).
  751. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  752. /// The list that runs those transitions just before this one, made
  753. /// when the list first has such transitions ([`lazy_prelude`]).
  754. prelude: OnceLock<Option<Prelude>>,
  755. /// The pipelines the list binds, for reports of slow submissions.
  756. pipelines: Mutex<std::collections::BTreeSet<String>>,
  757. /// The work its indirect executions may still do (`indirect`): a
  758. /// shader-writable word, zeroed when the list is submitted, and after
  759. /// it what the clamp notes about mesh records. In memory the CPU maps.
  760. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  761. /// The same words in the card's own memory ([`card_budget`]), which the
  762. /// clamp uses instead when there is one: zeroed in the list before its
  763. /// first clamp, its notes copied to `budget` when the list closes.
  764. card_budget: OnceLock<Option<ID3D12Resource>>,
  765. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  766. /// grown to the largest indirect execution recorded on the list.
  767. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  768. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  769. /// how many batches of this recording have a place in them.
  770. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  771. /// Counts the list in [`ALIVE`] while it lives.
  772. _alive: Counted,
  773. /// The texts of the markers `note_op` set, in order (for device-removed
  774. /// data without marker texts), with the host GPU range a copy reads.
  775. #[cfg(feature = "diagnostics")]
  776. notes: Mutex<Vec<Note>>,
  777. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  778. /// and at the end, and where they are read back.
  779. #[cfg(feature = "diagnostics")]
  780. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  781. }
  782. /// A list's prelude: an allocator and a closed list.
  783. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  784. /// Whether a host list's prelude is made when the list first needs one. A
  785. /// prelude runs the texture transitions and twin copies a list needs before
  786. /// it; lists that name no texture never have one, and every host list was
  787. /// made with one all the same: twice the host objects per list, for the
  788. /// title's 630 lists and for every list made anew.
  789. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  790. fn lazy_prelude() -> bool {
  791. static ON: OnceLock<bool> = OnceLock::new();
  792. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  793. }
  794. /// Timestamps per list (diagnostics); commands past them are not timed.
  795. #[cfg(feature = "diagnostics")]
  796. const STAMPS: u32 = 4096;
  797. /// A marker's text and the host range its command reads (diagnostics).
  798. #[cfg(feature = "diagnostics")]
  799. type Note = (String, Option<(u64, u64)>);
  800. type States = std::collections::HashMap<
  801. usize,
  802. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  803. >;
  804. /// What a list does with a depth texture that has a colour twin
  805. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  806. /// in submission order, so a list cannot know which side an earlier list
  807. /// leaves behind: it notes which sides it uses as it finds them, and its
  808. /// prelude copies one side into the other at submission if that side is
  809. /// behind then. From its first use of a side on, the list knows.
  810. struct TwinUse {
  811. /// The depth texture (the title resource's host copy) and its twin.
  812. depth: std::sync::Arc<crate::resource::HostTexture>,
  813. twin: std::sync::Arc<crate::resource::Twin>,
  814. /// The sides (depth texture, twin) the list uses as it finds them.
  815. needs: [bool; 2],
  816. /// Whether each side lacks what the other was written last, where the
  817. /// list is now; `None`: as the list found it.
  818. behind: [Option<bool>; 2],
  819. /// The draw or dispatch being prepared writes the twin.
  820. writing: bool,
  821. /// The depth plane's twin holds what the plane lacks although the list
  822. /// copied the twins since: the plane's pass waits for the list's close.
  823. late: bool,
  824. }
  825. /// The pass that draws the twin of a depth plane into the plane: one
  826. /// triangle over each mip of each slice, its pixel shader writing the
  827. /// twin's texel as the depth, with the depth test "always" and no stencil
  828. /// (the stencil plane is copied through a buffer and not touched here).
  829. ///
  830. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  831. /// the step times the float nearest 1/65535 (0x37800080). That is how
  832. /// The title's tiled lighting computes the depth of the
  833. /// rectangles it then draws with the test "equal", one class of materials
  834. /// a draw (all six of its vertex shaders multiply the class number by that
  835. /// constant), so the pass and the draw give the host the same float, and
  836. /// the host turns the same float into the same 24 bits. The step divided
  837. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  838. /// and lands in another 24-bit step for 127 of them (none under 385).
  839. const PLANE_CORNERS: &str = r#"
  840. float4 corner(uint i : SV_VertexID) : SV_Position {
  841. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  842. }
  843. "#;
  844. const PLANE_STEPS: &str = r#"
  845. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  846. Texture2DArray<uint> twin : register(t0);
  847. [RootSignature(RS)]
  848. float plane(float4 p : SV_Position) : SV_Depth {
  849. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  850. }
  851. "#;
  852. const PLANE_FLOATS: &str = r#"
  853. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  854. Texture2DArray<float> twin : register(t0);
  855. [RootSignature(RS)]
  856. float plane(float4 p : SV_Position) : SV_Depth {
  857. return twin.Load(int4(int2(p.xy), 0, 0));
  858. }
  859. "#;
  860. /// Views of twins the pass reads, in a heap of ours used as a ring.
  861. /// shortcut: a view must last until its list has run; with one or two
  862. /// passes a frame the ring is far from coming round.
  863. const PLANE_VIEWS: u32 = 256;
  864. /// What the pass draws with: the heap of its views of twins, and per kind
  865. /// of twin (16-bit steps or floats) and depth format the root signature
  866. /// and pipeline, made when first needed (`None`: the host refused).
  867. struct PlanePass {
  868. views: ID3D12DescriptorHeap,
  869. cpu: usize,
  870. gpu: u64,
  871. step: u32,
  872. next: AtomicU32,
  873. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  874. }
  875. /// The pass's root signature and pipeline for one kind of twin and one
  876. /// depth format.
  877. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  878. // SAFETY: D3D12 objects are free-threaded.
  879. unsafe impl Send for PlanePass {}
  880. // SAFETY: as above.
  881. unsafe impl Sync for PlanePass {}
  882. fn plane_pass() -> Option<&'static PlanePass> {
  883. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  884. PASS.get_or_init(|| {
  885. let host = host()?;
  886. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  887. // SAFETY: plain heap creation and queries.
  888. unsafe {
  889. let views: ID3D12DescriptorHeap = host
  890. .device
  891. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  892. Type: kind,
  893. NumDescriptors: PLANE_VIEWS,
  894. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  895. NodeMask: 0,
  896. })
  897. .ok()?;
  898. Some(PlanePass {
  899. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  900. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  901. step: host.device.GetDescriptorHandleIncrementSize(kind),
  902. views,
  903. next: AtomicU32::new(0),
  904. made: Mutex::default(),
  905. })
  906. }
  907. })
  908. .as_ref()
  909. }
  910. /// Compiles function `entry` of `source` for `target` with the system's
  911. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  912. pub(crate) fn compile(
  913. source: &str,
  914. entry: windows::core::PCSTR,
  915. target: windows::core::PCSTR,
  916. ) -> windows::core::Result<Vec<u8>> {
  917. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  918. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  919. let mut code: Option<ID3DBlob> = None;
  920. let mut errors: Option<ID3DBlob> = None;
  921. // SAFETY: the source and names live through the call; out pointers ours.
  922. let compiled = unsafe {
  923. D3DCompile(
  924. source.as_ptr().cast(),
  925. source.len(),
  926. windows::core::s!("victory"),
  927. None,
  928. None,
  929. entry,
  930. target,
  931. 0,
  932. 0,
  933. &mut code,
  934. Some(&mut errors),
  935. )
  936. };
  937. if let Err(e) = compiled {
  938. if let Some(errors) = errors {
  939. // SAFETY: the blob's own bytes.
  940. let text = unsafe {
  941. std::slice::from_raw_parts(
  942. errors.GetBufferPointer().cast::<u8>(),
  943. errors.GetBufferSize(),
  944. )
  945. };
  946. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  947. }
  948. return Err(e);
  949. }
  950. let code = code.ok_or_else(windows::core::Error::empty)?;
  951. // SAFETY: the blob's own bytes.
  952. let bytes = unsafe {
  953. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  954. };
  955. Ok(bytes.to_vec())
  956. }
  957. impl PlanePass {
  958. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  959. /// or of floats and the depth format `format`.
  960. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  961. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  962. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  963. return pipeline.clone();
  964. }
  965. let pipeline = match Self::make(steps, format) {
  966. Ok(pipeline) => Some(pipeline),
  967. Err(e) => {
  968. tracing::warn!(
  969. error = %e,
  970. steps,
  971. format = format.0,
  972. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  973. );
  974. None
  975. }
  976. };
  977. made.push((steps, format.0, pipeline.clone()));
  978. pipeline
  979. }
  980. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  981. use windows::core::s;
  982. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  983. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  984. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  985. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  986. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  987. pShaderBytecode: bytes.as_ptr().cast(),
  988. BytecodeLength: bytes.len(),
  989. };
  990. // SAFETY: the root signature is inside the pixel shader; the
  991. // description points at live data and never releases its pointer.
  992. unsafe {
  993. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  994. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  995. pRootSignature: std::mem::transmute_copy(&root),
  996. VS: code(&vs[..]),
  997. PS: code(&ps[..]),
  998. SampleMask: u32::MAX,
  999. RasterizerState: D3D12_RASTERIZER_DESC {
  1000. FillMode: D3D12_FILL_MODE_SOLID,
  1001. CullMode: D3D12_CULL_MODE_NONE,
  1002. DepthClipEnable: true.into(),
  1003. ..Default::default()
  1004. },
  1005. // Every texel is written; stencil stays off.
  1006. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1007. DepthEnable: true.into(),
  1008. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  1009. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1010. ..Default::default()
  1011. },
  1012. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1013. DSVFormat: format,
  1014. SampleDesc: DXGI_SAMPLE_DESC {
  1015. Count: 1,
  1016. Quality: 0,
  1017. },
  1018. ..Default::default()
  1019. };
  1020. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1021. Ok((root, pipeline))
  1022. }
  1023. }
  1024. }
  1025. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1026. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1027. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1028. /// heap, graphics root signature, pipeline, depth target, viewport,
  1029. /// scissor and topology and puts none of them back: it is for a list that
  1030. /// records nothing of the title's after it.
  1031. fn record_plane_pass(
  1032. list: &ID3D12GraphicsCommandList,
  1033. depth: &ID3D12Resource,
  1034. plane: &ID3D12Resource,
  1035. ) {
  1036. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1037. return;
  1038. };
  1039. // SAFETY: live resources.
  1040. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1041. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1042. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1043. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1044. let steps = twin.Format.0 == 53;
  1045. let format = DXGI_FORMAT(match of.Format.0 {
  1046. 44 => 45,
  1047. 19 => 20,
  1048. typed => typed,
  1049. });
  1050. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1051. return;
  1052. };
  1053. for slice in 0..u32::from(of.DepthOrArraySize) {
  1054. for mip in 0..u32::from(of.MipLevels) {
  1055. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1056. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1057. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1058. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1059. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1060. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1061. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1062. MostDetailedMip: mip,
  1063. MipLevels: 1,
  1064. FirstArraySlice: slice,
  1065. ArraySize: 1,
  1066. ..Default::default()
  1067. },
  1068. },
  1069. };
  1070. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1071. Format: format,
  1072. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1073. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1074. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1075. MipSlice: mip,
  1076. FirstArraySlice: slice,
  1077. ArraySize: 1,
  1078. },
  1079. },
  1080. ..Default::default()
  1081. };
  1082. let target = host.dsv(depth, Some(&target));
  1083. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1084. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1085. ptr: pass.cpu + (slot * pass.step) as usize,
  1086. };
  1087. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1088. ptr: pass.gpu + u64::from(slot * pass.step),
  1089. };
  1090. // SAFETY: an open list; a slot of our heap; live resources and
  1091. // objects (the pass's own live as long as the process).
  1092. unsafe {
  1093. host.device
  1094. .CreateShaderResourceView(plane, Some(&view), cpu);
  1095. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1096. list.SetGraphicsRootSignature(&root);
  1097. list.SetPipelineState(&pipeline);
  1098. list.SetGraphicsRootDescriptorTable(0, gpu);
  1099. list.OMSetRenderTargets(0, None, false, Some(&target));
  1100. list.RSSetViewports(&[D3D12_VIEWPORT {
  1101. TopLeftX: 0.0,
  1102. TopLeftY: 0.0,
  1103. Width: width as f32,
  1104. Height: height as f32,
  1105. MinDepth: 0.0,
  1106. MaxDepth: 1.0,
  1107. }]);
  1108. list.RSSetScissorRects(&[RECT {
  1109. left: 0,
  1110. top: 0,
  1111. right: width as i32,
  1112. bottom: height as i32,
  1113. }]);
  1114. list.IASetPrimitiveTopology(
  1115. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1116. );
  1117. list.DrawInstanced(3, 1, 0, 0);
  1118. }
  1119. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1120. }
  1121. }
  1122. }
  1123. /// Records into `list` the copy of a depth texture into its colour twin
  1124. /// (`colour`) or of the twin into the depth texture, both already in their
  1125. /// copy states: whole textures of one size in one format family, which the
  1126. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1127. /// alone, through the twin's buffer.
  1128. fn record_twin_copy(
  1129. list: &ID3D12GraphicsCommandList,
  1130. depth: &ID3D12Resource,
  1131. twin: &crate::resource::Twin,
  1132. colour: bool,
  1133. ) {
  1134. let (from, to) = if colour {
  1135. (depth, &twin.colour.texture)
  1136. } else {
  1137. (&twin.colour.texture, depth)
  1138. };
  1139. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1140. // shortcut: the depth plane's twin is not given the plane (that is a
  1141. // pass the other way: the plane read by a shader, the twin as its
  1142. // target). The twin then lacks what draws and clears wrote to the
  1143. // plane since shaders last wrote the twin. In the title
  1144. // nothing writes that plane but the twin's pass (its 192 draws against
  1145. // it only test, run 29), so the twin lacks nothing. Counted.
  1146. if colour && twin.plane.is_some() {
  1147. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1148. }
  1149. let Some(through) = &twin.through else {
  1150. // SAFETY: an open list and two live textures.
  1151. unsafe { list.CopyResource(to, from) };
  1152. return;
  1153. };
  1154. // A stencil plane and its twin: each mip and slice of the plane goes
  1155. // into the buffer, laid out as the host lays the plane out for copies,
  1156. // and from the buffer into the other texture, whole subresources both
  1157. // times. In the depth texture the stencil plane's subresources follow
  1158. // the depth plane's; the twin has the one plane.
  1159. let Some(host) = host() else { return };
  1160. // SAFETY: a live texture.
  1161. let of = unsafe { depth.GetDesc() };
  1162. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1163. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1164. // SAFETY: a plain query writing `planes` footprints.
  1165. unsafe {
  1166. host.device.GetCopyableFootprints(
  1167. &of,
  1168. planes,
  1169. planes,
  1170. 0,
  1171. Some(rows.as_mut_ptr()),
  1172. None,
  1173. None,
  1174. None,
  1175. );
  1176. }
  1177. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1178. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1179. // SAFETY: a borrowed pointer the location never releases.
  1180. pResource: unsafe { std::mem::transmute_copy(texture) },
  1181. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1182. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1183. SubresourceIndex: index,
  1184. },
  1185. };
  1186. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1187. // SAFETY: as above.
  1188. pResource: unsafe { std::mem::transmute_copy(through) },
  1189. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1190. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1191. PlacedFootprint: *row,
  1192. },
  1193. };
  1194. let (common, source, dest) = (
  1195. D3D12_RESOURCE_STATE_COMMON,
  1196. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1197. D3D12_RESOURCE_STATE_COPY_DEST,
  1198. );
  1199. // SAFETY: an open list and live resources; the buffer was made as big
  1200. // as these footprints, and rests in the common state between copies.
  1201. unsafe {
  1202. list.ResourceBarrier(&[transition(through, common, dest)]);
  1203. for (i, row) in rows.iter().enumerate() {
  1204. let index = first_from + i as u32;
  1205. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1206. }
  1207. list.ResourceBarrier(&[transition(through, dest, source)]);
  1208. for (i, row) in rows.iter().enumerate() {
  1209. let index = first_to + i as u32;
  1210. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1211. }
  1212. list.ResourceBarrier(&[transition(through, source, common)]);
  1213. }
  1214. }
  1215. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1216. /// builds).
  1217. pub(crate) fn dred_on() -> bool {
  1218. static ON: OnceLock<bool> = OnceLock::new();
  1219. *ON.get_or_init(|| {
  1220. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some()
  1221. })
  1222. }
  1223. /// Indirect mesh dispatches since the last frame line: the largest group
  1224. /// count a record asked for, and the groups asked in all (from the lists'
  1225. /// budget buffers, a run late).
  1226. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1227. /// Whether a list's indirect-work budget lives in the card's own memory
  1228. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1229. /// before). The clamp charges it with atomics, at least two in a row for
  1230. /// every clamp; in mapped memory on a card of its own each of them
  1231. /// crosses the bus.
  1232. fn card_budget() -> bool {
  1233. static ON: OnceLock<bool> = OnceLock::new();
  1234. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1235. }
  1236. /// Whether each list of a submission runs and is timed on its own, slow
  1237. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1238. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1239. #[cfg(feature = "diagnostics")]
  1240. fn timing() -> bool {
  1241. static ON: OnceLock<bool> = OnceLock::new();
  1242. *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some())
  1243. }
  1244. /// Names a host object for the device-removed report, which names the
  1245. /// allocations a page fault hit (only with device-removed data on), or for
  1246. /// the frame recorder (`VICTORY_RECORD`).
  1247. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1248. #[cfg(feature = "diagnostics")]
  1249. if crate::replay::record::on() {
  1250. let text = text();
  1251. crate::replay::record::name(object, &text);
  1252. if dred_on()
  1253. && let Ok(object) = object.cast::<ID3D12Object>()
  1254. {
  1255. // SAFETY: a plain call on a live object.
  1256. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1257. }
  1258. return;
  1259. }
  1260. if dred_on()
  1261. && let Ok(object) = object.cast::<ID3D12Object>()
  1262. {
  1263. // SAFETY: a plain call on a live object.
  1264. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1265. }
  1266. }
  1267. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1268. /// [`LISTS`]`[3]` until it is first reset.
  1269. struct Counted {
  1270. /// Not reset since it was made.
  1271. fresh: std::sync::atomic::AtomicBool,
  1272. }
  1273. impl Counted {
  1274. fn new() -> Counted {
  1275. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1276. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1277. Counted {
  1278. fresh: std::sync::atomic::AtomicBool::new(true),
  1279. }
  1280. }
  1281. /// The list is reset: it is in use.
  1282. fn used(&self) {
  1283. if self.fresh.swap(false, Ordering::Relaxed) {
  1284. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1285. }
  1286. }
  1287. }
  1288. impl Drop for Counted {
  1289. fn drop(&mut self) {
  1290. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1291. self.used();
  1292. }
  1293. }
  1294. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1295. /// mapping and its host GPU address.
  1296. struct Chunk {
  1297. _buffer: ID3D12Resource,
  1298. data: usize,
  1299. gpu: u64,
  1300. }
  1301. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1302. // written only by the list that holds the chunk.
  1303. unsafe impl Send for Chunk {}
  1304. /// Upload chunks handed out front to back: the chunks (each with its
  1305. /// bytes), the one in use and the bytes used in it.
  1306. #[derive(Default)]
  1307. struct Scratch {
  1308. chunks: Vec<(Chunk, u64)>,
  1309. current: usize,
  1310. used: u64,
  1311. }
  1312. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1313. unsafe impl Send for Scratch {}
  1314. impl Drop for Scratch {
  1315. fn drop(&mut self) {
  1316. give_chunks(std::mem::take(&mut self.chunks));
  1317. }
  1318. }
  1319. const SCRATCH_CHUNK: u64 = 4 << 20;
  1320. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1321. /// lists put a few constants or a rectangle's corners there, and every
  1322. /// list that did took 4 MiB of the PC's memory for it.
  1323. const SCRATCH_FIRST: u64 = 256 << 10;
  1324. /// The most bytes of chunks kept while no list holds them.
  1325. const SPARE_MOST: u64 = 128 << 20;
  1326. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1327. /// first needs one, a small one first, and gives all of them back when it
  1328. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1329. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1330. /// host lists of held submissions, which live for one submission, each
  1331. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1332. /// freed per frame of gameplay (run 60).
  1333. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1334. fn scratch_pool() -> bool {
  1335. static ON: OnceLock<bool> = OnceLock::new();
  1336. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1337. }
  1338. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1339. /// for one of the same size.
  1340. struct Spare<T> {
  1341. kept: Vec<(T, u64)>,
  1342. bytes: u64,
  1343. }
  1344. impl<T> Spare<T> {
  1345. const fn new() -> Self {
  1346. Spare { kept: Vec::new(), bytes: 0 }
  1347. }
  1348. /// A kept thing of `size` bytes, the one given last.
  1349. fn take(&mut self, size: u64) -> Option<T> {
  1350. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1351. self.bytes -= size;
  1352. Some(self.kept.remove(at).0)
  1353. }
  1354. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1355. /// `most`: then it comes back.
  1356. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1357. if self.bytes + size > most {
  1358. return Some(thing);
  1359. }
  1360. self.bytes += size;
  1361. self.kept.push((thing, size));
  1362. None
  1363. }
  1364. }
  1365. /// Scratch chunks no list holds.
  1366. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1367. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1368. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1369. if scratch_pool()
  1370. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1371. {
  1372. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1373. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1374. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1375. return Some(chunk);
  1376. }
  1377. let (buffer, data) = host.upload_buffer(size)?;
  1378. name(&buffer, || "list scratch".into());
  1379. // SAFETY: a live buffer.
  1380. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  1381. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1382. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1383. Some(Chunk {
  1384. _buffer: buffer,
  1385. data: data as usize,
  1386. gpu,
  1387. })
  1388. }
  1389. /// A list is done with `chunks` (it was reset after its submissions ran,
  1390. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1391. /// without the pool.
  1392. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1393. if chunks.is_empty() {
  1394. return;
  1395. }
  1396. let mut freed = Vec::new();
  1397. {
  1398. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1399. for (chunk, size) in chunks {
  1400. let back = if scratch_pool() {
  1401. spare.give(chunk, size, SPARE_MOST)
  1402. } else {
  1403. Some(chunk)
  1404. };
  1405. match back {
  1406. None => {
  1407. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1408. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1409. }
  1410. Some(chunk) => {
  1411. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1412. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1413. freed.push(chunk);
  1414. }
  1415. }
  1416. }
  1417. }
  1418. // Freed outside the lock.
  1419. drop(freed);
  1420. }
  1421. /// What the host keeps for copies in the card's own memory
  1422. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1423. struct CardWork {
  1424. /// Before a submission's lists: what changed on the copies' CPU side
  1425. /// goes to their card side. Those not in use: a plan takes one and
  1426. /// gives it back when its submission has run (`Host::card_done`), so
  1427. /// that submissions sent ahead ([`late`]) each have their own.
  1428. sync: Vec<Prelude>,
  1429. /// After them, in the same submission: the compare of the declared
  1430. /// ranges with their bytes from before. As `sync`.
  1431. check: Vec<Prelude>,
  1432. /// After it ran: the pieces that differ come down.
  1433. fetch: Prelude,
  1434. root: ID3D12RootSignature,
  1435. pso: ID3D12PipelineState,
  1436. /// One dword per piece compared, odd where the piece differs: PC
  1437. /// memory, mapped (buffer, mapping, bytes).
  1438. differs: (ID3D12Resource, usize, u64),
  1439. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1440. fetched: Option<(ID3D12Resource, usize, u64)>,
  1441. /// The dwords of `differs` taken by plans whose results were not read
  1442. /// yet.
  1443. taken: u32,
  1444. /// Plans made and not done with (`Host::card_done`).
  1445. out: u32,
  1446. }
  1447. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1448. // under the submission lock.
  1449. unsafe impl Send for CardWork {}
  1450. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1451. /// The compare of a declared range of a copy in the card's memory with
  1452. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1453. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1454. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1455. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1456. /// byte just outside the range costs a fetch that finds nothing.
  1457. ///
  1458. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1459. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1460. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1461. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1462. /// those steps.
  1463. pub(crate) const CARD_COMPARE: &str = r#"
  1464. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1465. cbuffer Span : register(b0) {
  1466. uint first; // the first piece
  1467. uint skew; // where the copy starts in its piece 0
  1468. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1469. uint pieces;
  1470. uint out_at; // the first piece's dword in `differs`, in bytes
  1471. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1472. };
  1473. ByteAddressBuffer now : register(t0);
  1474. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1475. // last sent up (or hashed whole, the first time).
  1476. RWByteAddressBuffer hashes : register(u0);
  1477. RWByteAddressBuffer differs : register(u1);
  1478. groupshared uint4 parts[64];
  1479. [RootSignature(RS)]
  1480. [numthreads(64, 1, 1)]
  1481. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1482. uint piece = first + id.x;
  1483. uint lo = piece * 65536u;
  1484. lo = lo > skew ? lo - skew : 0u;
  1485. uint hi = min((piece + 1u) * 65536u - skew, size);
  1486. lo = lo & ~15u;
  1487. hi = (hi + 15u) & ~15u;
  1488. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1489. [loop]
  1490. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1491. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1492. h = h.yzwx ^ (h >> 15);
  1493. }
  1494. parts[thread] = h;
  1495. GroupMemoryBarrierWithGroupSync();
  1496. if (thread != 0u) return;
  1497. h = parts[0];
  1498. [loop]
  1499. for (uint i = 1u; i < 64u; ++i) {
  1500. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1501. h = h.yzwx ^ (h >> 15);
  1502. }
  1503. if (compare != 0u) {
  1504. // The flag, and above it 31 bits of the hash (`torn`).
  1505. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1506. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1507. // With the copy-back on its own thread: the next compare of the
  1508. // piece finds what is written from here on.
  1509. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1510. } else {
  1511. hashes.Store4(piece * 16u, h);
  1512. }
  1513. }
  1514. "#;
  1515. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1516. #[cfg(test)]
  1517. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1518. torn::hash(bytes)
  1519. }
  1520. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1521. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1522. /// parts a dispatch can hold.
  1523. ///
  1524. /// # Safety
  1525. /// The list is open with the compare's root signature, pipeline and buffers
  1526. /// set, and the pieces lie in the buffer.
  1527. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1528. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1529. let mut done = 0;
  1530. while done < span.pieces {
  1531. let n = (span.pieces - done).min(MOST);
  1532. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1533. // SAFETY: the caller's.
  1534. unsafe {
  1535. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1536. list.Dispatch(n, 1, 1);
  1537. }
  1538. done += n;
  1539. }
  1540. }
  1541. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1542. /// the card's memory are hashed in runs of pieces that touch, each piece
  1543. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1544. /// per range sent up.
  1545. ///
  1546. /// These passes are ours, they run on the card before every submission's
  1547. /// lists: a pass takes the time of one piece however few its pieces are.
  1548. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1549. /// a piece hashed when it need not be, or not hashed when it should, costs
  1550. /// a fetch that finds nothing and loses no shader write.
  1551. fn rehash_runs() -> bool {
  1552. static ON: OnceLock<bool> = OnceLock::new();
  1553. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1554. }
  1555. /// Since the last frame-rate line, of our own passes over copies in the
  1556. /// card's memory: hash passes after ranges were sent up, the pieces they
  1557. /// hashed, and compare passes after the lists.
  1558. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1559. /// Whether what shaders wrote to copies in the card's memory is merged
  1560. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1561. /// default). The pieces the card's compare found differing come down in
  1562. /// one fetch and were then merged one after the other on the thread that
  1563. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1564. /// with the copy's CPU side byte by byte and put into title memory through
  1565. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1566. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1567. /// landings do not come here: `crate::land` has threads of its own.)
  1568. fn wide_merge() -> bool {
  1569. static ON: OnceLock<bool> = OnceLock::new();
  1570. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1571. }
  1572. /// One declared range of a copy in the card's memory, in a submission.
  1573. struct CardRange {
  1574. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1575. /// As declared (title addresses), for the statistics.
  1576. declared: (usize, usize),
  1577. span: crate::shadow::CardSpan,
  1578. /// Its first piece's dword in the compare's results.
  1579. at: u32,
  1580. /// Whether the card compares it; else every piece is fetched.
  1581. compared: bool,
  1582. /// Looked at by `crate::picked`, and not declared: what is found changed
  1583. /// there was written through a view nobody declared. Not landed.
  1584. picked: bool,
  1585. }
  1586. impl CardPlan {
  1587. /// `crate::picked` is told where what it looked at changed, by the
  1588. /// compare's results.
  1589. fn picked_found(&self, differs: &[u32]) {
  1590. for r in self.ranges.iter().filter(|r| r.picked) {
  1591. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1592. if let Some(p) = changed {
  1593. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1594. }
  1595. }
  1596. }
  1597. }
  1598. /// What a submission does for copies in the card's memory.
  1599. struct CardPlan {
  1600. ranges: Vec<CardRange>,
  1601. /// The compare, run after the submission's lists.
  1602. check: Option<ID3D12CommandList>,
  1603. /// The copies whose card side was brought up to date, alive until the
  1604. /// submission has run.
  1605. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1606. /// The lists of ours the plan recorded (whether the compare, the
  1607. /// list), given back by `Host::card_done`.
  1608. lists: Vec<(bool, Prelude)>,
  1609. /// With [`relay`]: the number of the send to copies in the card's memory
  1610. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1611. sent_as: u64,
  1612. /// With [`upcheck`]: the look at what it sent up.
  1613. looks: Option<upcheck::Looks>,
  1614. /// With [`send`]: the memory its sends come from.
  1615. sends: Option<send::Memory>,
  1616. }
  1617. /// One piece of submission-time work, in recorded order.
  1618. enum Step {
  1619. /// A copy into title memory (destination, source, bytes): the title's
  1620. /// buffer copies, which later refreshes must see.
  1621. Copy(usize, usize, usize),
  1622. /// A copy of title memory into the list's own upload memory, and how
  1623. /// the card could bring the bytes instead.
  1624. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  1625. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1626. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1627. /// intervenes.
  1628. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1629. /// Work that may write title memory.
  1630. Run(Box<dyn Fn() + Send>),
  1631. /// Work that writes host memory only, and the title memory it reads
  1632. /// (from, to; empty for none).
  1633. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1634. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1635. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1636. /// Brings a texture's staging buffer up to date: once per submission,
  1637. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1638. Texture(std::sync::Arc<crate::texture::Staging>),
  1639. }
  1640. /// What a list does on the CPU when it is submitted: copies between host
  1641. /// memory regions (title buffers, upload buffers and buffer copies), and
  1642. /// the upload buffers its GPU commands read, kept until the list is reset.
  1643. #[derive(Default)]
  1644. struct Deferred {
  1645. /// Destination, source, bytes.
  1646. copies: Vec<Step>,
  1647. uploads: Vec<ID3D12Resource>,
  1648. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1649. upload_bytes: u64,
  1650. /// Host objects the list's commands name (pipelines, root signatures,
  1651. /// descriptor heaps): the title may release its objects before it
  1652. /// submits the list.
  1653. kept: Vec<windows::core::IUnknown>,
  1654. /// Buffer ranges refreshed since the last title copy (host copy,
  1655. /// address, bytes): refreshing them again would find the same bytes.
  1656. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1657. /// Textures whose contents the list brings up to date.
  1658. textures: std::collections::HashSet<usize>,
  1659. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1660. /// bytes.
  1661. writes: Vec<(usize, crate::queue::Written, usize)>,
  1662. /// Textures read back (texture to buffer copies), done once the list
  1663. /// has run: the host buffer the list copies the texels into, the title
  1664. /// memory they go to, the bytes of a row, the rows, the title's row
  1665. /// pitch.
  1666. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1667. /// Whether the indirect-work budget is zeroed for this recording (a
  1668. /// step on the CPU, or in the list for the card's copy).
  1669. budget_zeroed: bool,
  1670. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1671. /// interface pointer) that a clamp in this recording left readable as
  1672. /// indirect arguments; 0 if none. It stays readable until the next
  1673. /// clamp into it ([`HostList::indirect_state`]).
  1674. indirect_readable: usize,
  1675. }
  1676. impl Deferred {
  1677. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1678. /// reset.
  1679. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1680. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1681. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1682. self.upload_bytes += size;
  1683. self.uploads.push(buffer);
  1684. }
  1685. }
  1686. impl Drop for Deferred {
  1687. fn drop(&mut self) {
  1688. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1689. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1690. }
  1691. }
  1692. /// Whether a queue's submissions go to the card without a wait for each
  1693. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1694. /// waits for every list on its own).
  1695. ///
  1696. /// Every submission was prepared, sent, waited for and copied back before
  1697. /// the next one was looked at, so the card stood idle while we prepared
  1698. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1699. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1700. /// other, on the one thread that submits.
  1701. ///
  1702. /// With the switch a queue's submission is sent and joins a line of
  1703. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1704. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1705. /// for the card, what their shaders wrote copied back once per byte, then
  1706. /// their bottom-of-pipe writes and the fence signals behind them, in
  1707. /// order) at the next point where the title, or our own preparing, can
  1708. /// observe what they do. Those points, exactly:
  1709. ///
  1710. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1711. /// read-back or map of a texture, a clear or upload run at once;
  1712. /// 2. the next submission reads title memory that a flight's shaders may
  1713. /// write: a title buffer copy, a fill of upload memory, a texture's
  1714. /// memory, any step that runs code of ours on title memory
  1715. /// ([`late_blocked`]);
  1716. /// 3. the next submission refreshes a range of a host copy that a flight's
  1717. /// shaders may write, and the title wrote a page of it since it was last
  1718. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1719. /// alone until the flight's writes are back, as it always did within a
  1720. /// submission;
  1721. /// 4. a queue stands at a wait for a memory value that no flight's
  1722. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1723. /// write ([`late_met`]);
  1724. /// 5. the title blocks on a fence without an event;
  1725. /// 6. the card has run every flight (a thread of ours waits for that:
  1726. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1727. ///
  1728. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1729. /// when the card has really run the work, later than before and never
  1730. /// earlier; a fence signalled on a queue while flights are in the air is
  1731. /// set behind them. A wait for a memory value that a flight's
  1732. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1733. /// the card behind that flight, which is the order the wait asks for.
  1734. ///
  1735. /// What it assumes beyond today: memory the title rewrites between two of
  1736. /// its submissions, without waiting for the first, may be seen by the
  1737. /// first's shaders (as on the console, where the card reads title memory
  1738. /// when it runs, not when the list is submitted).
  1739. pub(crate) fn late() -> bool {
  1740. late_stage() > 0
  1741. }
  1742. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1743. fn late_stage() -> u8 {
  1744. static STAGE: OnceLock<u8> = OnceLock::new();
  1745. *STAGE.get_or_init(|| {
  1746. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1747. return 0;
  1748. }
  1749. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1750. Ok("1") => 1,
  1751. Ok("2") => 2,
  1752. Ok("3") => 3,
  1753. // The relay alone: on top of stage 3.
  1754. Err(_) if crate::shadow::relay() => 3,
  1755. _ => 0,
  1756. }
  1757. })
  1758. }
  1759. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1760. /// longer a point. Where the title wrote a page that lies in a range a
  1761. /// flight's shaders may write, the bytes the title changed are found (the
  1762. /// page as it is now against what the copy held when the flight was
  1763. /// prepared) and put into the copy, and only those: what the flight's
  1764. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1765. /// flights are settled for it only where that cannot be done: memory that
  1766. /// is not write-watched, or a copy in the card's memory with more changed
  1767. /// runs than a submission should send up one by one.
  1768. ///
  1769. /// In run 92 (stage 1) this point settled the flights five times a frame
  1770. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1771. /// frame of waiting were left of 200.
  1772. ///
  1773. /// What differs from settling first: a byte both the title and a flight's
  1774. /// shader wrote is the title's if the shader wrote it first, the shader's
  1775. /// if it wrote it afterwards; settled first it was always the shader's.
  1776. /// The title writing a byte a shader of its own is writing is a race on
  1777. /// the console too.
  1778. fn late_exact() -> bool {
  1779. late_stage() > 1
  1780. }
  1781. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1782. /// no longer a point where flights are settled). The copy to the back
  1783. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1784. /// its own for each present in the air) and the swap chain is told to
  1785. /// present behind it; the queue's call returns, and the card finishes the
  1786. /// frame while the title records the next one. What the title is told
  1787. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1788. /// has run it, by the settling thread.
  1789. ///
  1790. /// What is left out with it: the look whether the presented frame is black
  1791. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1792. /// or listed is presented the old way. Once every second and a half a
  1793. /// submission settles the flights all the same, for the sweep that lets
  1794. /// idle host objects go (it needs nothing in the air).
  1795. pub(crate) fn late_free_present() -> bool {
  1796. late_stage() > 2
  1797. }
  1798. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1799. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1800. /// and is off with it, in the timing run and with kept snapshots).
  1801. ///
  1802. /// With [`late`] alone every settle does three things on the thread that
  1803. /// holds the submission lock: it waits for everything in the air, copies
  1804. /// back with the card standing, and only then goes on preparing. The frame
  1805. /// stays a relay: the card works about 242 ms of it and one thread
  1806. /// prepares, waits and copies back for about 220.
  1807. ///
  1808. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1809. /// soon as the card has run them, in the order they were sent and without
  1810. /// the submission lock: it fetches and merges what their shaders wrote to
  1811. /// copies in the card's memory, compares and merges the other copies,
  1812. /// frees the flights' ranges, and then does their read-backs, their
  1813. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1814. /// order. The submitting thread meanwhile prepares and sends the next
  1815. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  1816. /// that thread has landed everything in the air, at the same points as
  1817. /// before (the list in [`late`]), so whoever can observe title memory, a
  1818. /// fence or a present still does so only after the flights before it are
  1819. /// merged.
  1820. ///
  1821. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  1822. /// flight; a merge that never stores into memory the card may be writing;
  1823. /// sends to card copies numbered) and here: flights land in the order of
  1824. /// [`LINE`] by one thread, so a later flight's results never reach title
  1825. /// memory before an earlier flight's; the compare on the card stores the
  1826. /// hash it made, so each flight's compare flags exactly what changed since
  1827. /// the compare before it, however late the pieces are fetched; the fetch
  1828. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  1829. /// title bytes the card had received when it ran.
  1830. pub(crate) fn relay() -> bool {
  1831. static ON: OnceLock<bool> = OnceLock::new();
  1832. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  1833. }
  1834. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  1835. /// title memory a flight's shaders may write (a title buffer copy, a fill
  1836. /// of upload memory, a texture) waits only until the flights that declared
  1837. /// that memory have landed, not for everything in the air; and at
  1838. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  1839. /// both wait for everything.
  1840. fn relay_exact() -> bool {
  1841. static ON: OnceLock<bool> = OnceLock::new();
  1842. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  1843. // since the walls of the first room were found drawn in every run with
  1844. // this set and in fewer than half without it).
  1845. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  1846. }
  1847. /// Whether the pieces the relay fetches from the card's memory come over the
  1848. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  1849. /// draws.
  1850. ///
  1851. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  1852. /// and with the relay that is most of a frame: the thread that lands flights
  1853. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  1854. /// a few milliseconds of copying, and everything that waits for a landing
  1855. /// (the title's fences, reads of memory flights may write) waited with it.
  1856. ///
  1857. /// What changes: the fetch runs when its flights are done and beside later
  1858. /// submissions, so of the sends of title bytes it is only known to have run
  1859. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  1860. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  1861. /// the title's, newer than what the flights wrote. A later flight's bytes
  1862. /// may be in what is fetched, as before.
  1863. fn relay_copy() -> bool {
  1864. static ON: OnceLock<bool> = OnceLock::new();
  1865. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  1866. }
  1867. /// Told when something joins [`LINE`], for the thread that lands flights
  1868. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  1869. /// what queues hold.
  1870. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  1871. /// Told when flights have landed ([`relay`]): who waits for that looks
  1872. /// again.
  1873. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  1874. /// With [`relay`], the order of what we put on the queue: the number of
  1875. /// sends of changed ranges to copies in the card's memory so far
  1876. /// (`Host::card_before`). Held from the taking of the ranges until their
  1877. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  1878. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  1879. /// later one.
  1880. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  1881. /// Since the last frame-rate line, of the thread that lands flights
  1882. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  1883. /// card with nothing to land, microseconds it waited for fetches of card
  1884. /// copies' pieces, microseconds of landing in all.
  1885. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  1886. /// Of the line's things in order (a flight: the value signalled on the
  1887. /// host's fence behind it; a write or a signal behind a flight: `None`):
  1888. /// how many, from the front, can be landed when the card has reached
  1889. /// `completed`: everything ahead of the first flight it has not run. A
  1890. /// later flight never lands before an earlier one, and what follows a
  1891. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  1892. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  1893. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  1894. }
  1895. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  1896. /// holds, for every piece of every range of the plan, the copy, the
  1897. /// piece's number in the copy and whether the compare flagged it there (or
  1898. /// did not run). The pieces to fetch, under whichever range, in order: all
  1899. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  1900. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  1901. /// the hash, so the second of them may find it stored already and not
  1902. /// flag it.
  1903. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  1904. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  1905. pieces.sort_unstable();
  1906. pieces.dedup();
  1907. pieces
  1908. }
  1909. #[cfg(test)]
  1910. mod relay_tests {
  1911. use super::{flagged_pieces, landable};
  1912. /// Two flights and what follows each: nothing of the second lands
  1913. /// before the card has run it, and nothing behind a flight lands
  1914. /// before the flight.
  1915. #[test]
  1916. fn flights_land_in_the_order_they_were_sent() {
  1917. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  1918. let line = [Some(5), None, None, Some(6), None];
  1919. assert_eq!(landable(&line, 4), 0);
  1920. assert_eq!(landable(&line, 5), 3);
  1921. assert_eq!(landable(&line, 6), 5);
  1922. assert_eq!(landable(&line, u64::MAX), 5);
  1923. // Signals with no flight ahead land at once; behind one they wait.
  1924. assert_eq!(landable(&[None, None], 0), 2);
  1925. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  1926. assert_eq!(landable(&[], 3), 0);
  1927. // After the first three landed, the rest when its turn comes.
  1928. assert_eq!(landable(&line[3..], 5), 0);
  1929. assert_eq!(landable(&line[3..], 6), 2);
  1930. }
  1931. /// A piece flagged under one range of a plan is fetched under every
  1932. /// range that holds a part of it; pieces of other copies are not.
  1933. #[test]
  1934. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  1935. let (a, b) = (0x1000usize, 0x2000usize);
  1936. // Copy a: piece 3 under two ranges, flagged under the first only;
  1937. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  1938. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  1939. let fetch = flagged_pieces(&flags);
  1940. assert!(fetch.contains(&(a, 3)));
  1941. assert!(!fetch.contains(&(a, 4)));
  1942. assert!(!fetch.contains(&(b, 3)));
  1943. assert!(fetch.contains(&(b, 9)));
  1944. assert_eq!(fetch.len(), 2);
  1945. }
  1946. }
  1947. /// The most host lists in the air before the flights are settled
  1948. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  1949. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  1950. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  1951. /// 32 settled the flights three times a
  1952. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  1953. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  1954. /// descriptor slots, upload
  1955. /// memory and scratch chunks are held until then, and a frame's lists held
  1956. /// all at once ran the slots out before (run 45).
  1957. fn late_most() -> usize {
  1958. static MOST: OnceLock<usize> = OnceLock::new();
  1959. *MOST.get_or_init(|| {
  1960. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  1961. })
  1962. }
  1963. /// Whether a submission with bottom-of-pipe writes may fly
  1964. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  1965. /// the title is told at once, as before; for telling a title that polls
  1966. /// such a value from one that does not).
  1967. fn late_writes() -> bool {
  1968. static ON: OnceLock<bool> = OnceLock::new();
  1969. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  1970. }
  1971. /// Per host copy, the ranges a submission's shaders may write, as declared
  1972. /// (address, end).
  1973. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  1974. /// What [`Host::submit`] hands back for a submission it sent and did not
  1975. /// wait for.
  1976. struct Sent {
  1977. /// Its number among the submissions started.
  1978. number: u64,
  1979. card: Option<CardPlan>,
  1980. back: Vec<Declared>,
  1981. /// What was taken off it to be done on the card.
  1982. own: Option<card_steps::Taken>,
  1983. /// Its bottom-of-pipe writes.
  1984. writes: Vec<(usize, crate::queue::Written, usize)>,
  1985. }
  1986. /// A submission on the card that has not been waited for ([`late`]): its
  1987. /// host lists, taken from the title's (which it may reset meanwhile), and
  1988. /// what is to be done once it has run.
  1989. struct Flight {
  1990. number: u64,
  1991. /// The value signalled on the host's fence behind it.
  1992. fence: u64,
  1993. lists: Vec<crate::list::Detached>,
  1994. order: Vec<usize>,
  1995. card: Option<CardPlan>,
  1996. back: Vec<Declared>,
  1997. /// The list of ours that ran ahead of them ([`card_steps`]).
  1998. own: Option<card_steps::Taken>,
  1999. }
  2000. /// One thing in the line of what waits for the card, in order.
  2001. enum Late {
  2002. Run(Flight),
  2003. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  2004. Write(usize, crate::queue::Written, usize),
  2005. /// A fence (its address) signalled behind the flights before it.
  2006. Signal(usize, u64),
  2007. }
  2008. struct Line {
  2009. line: Vec<Late>,
  2010. /// The title memory the flights' shaders may write (address, end), in
  2011. /// order and joined.
  2012. written: Vec<(usize, usize)>,
  2013. /// Host lists in the flights.
  2014. lists: usize,
  2015. /// The value signalled on the host's fence behind the last flight.
  2016. target: u64,
  2017. /// A settle has taken the line and is not done: a signal still goes
  2018. /// behind it.
  2019. settling: bool,
  2020. /// Something was settled away from a queue's own calls: the helper
  2021. /// thread looks at what queues hold.
  2022. poke: bool,
  2023. /// Host lists of settled flights, reset and given back outside the
  2024. /// submission lock ([`land`]: a settle may run under a caller's own
  2025. /// locks).
  2026. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2027. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2028. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2029. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2030. /// With [`card_steps`]: what the flights being landed write.
  2031. landing: Vec<card_steps::Writer>,
  2032. }
  2033. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2034. // into; touched under the lock.
  2035. unsafe impl Send for Line {}
  2036. static LINE: Mutex<Line> = Mutex::new(Line {
  2037. line: Vec::new(),
  2038. written: Vec::new(),
  2039. lists: 0,
  2040. target: 0,
  2041. settling: false,
  2042. poke: false,
  2043. landed: Vec::new(),
  2044. in_hand: Vec::new(),
  2045. landing: Vec::new(),
  2046. });
  2047. /// Told when a flight joins [`LINE`] or it is poked.
  2048. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2049. fn line() -> std::sync::MutexGuard<'static, Line> {
  2050. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2051. }
  2052. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2053. const WHY_SYNC: usize = 2;
  2054. const WHY_CARD_DONE: usize = 3;
  2055. const WHY_VALUE: usize = 4;
  2056. const WHY_STALE: usize = 5;
  2057. const WHY_READ: usize = 6;
  2058. const WHY_RUN: usize = 7;
  2059. const WHY_MOST: usize = 8;
  2060. const WHY_WRITES: usize = 9;
  2061. const WHY_FENCE: usize = 10;
  2062. /// Since the last frame-rate line: submissions sent without a wait;
  2063. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2064. /// microseconds settles waited for the card; value waits met by a flight's
  2065. /// bottom-of-pipe write; fence signals set behind flights.
  2066. /// Then: the settles for title memory read, by what read it (a buffer
  2067. /// copy, a fill of upload memory, a texture).
  2068. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2069. /// Since the last frame-rate line: the microseconds settles waited for the
  2070. /// card, by why they settled (the `WHY_` places).
  2071. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2072. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2073. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2074. if from >= to {
  2075. return false;
  2076. }
  2077. let at = ranges.partition_point(|r| r.1 <= from);
  2078. ranges.get(at).is_some_and(|r| r.0 < to)
  2079. }
  2080. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2081. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2082. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2083. ranges.sort_unstable();
  2084. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2085. for &(from, to) in ranges.iter() {
  2086. match out.last_mut() {
  2087. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2088. _ => out.push((from, to)),
  2089. }
  2090. }
  2091. *ranges = out;
  2092. }
  2093. /// Whether anything is in the air.
  2094. fn flying() -> bool {
  2095. if !late() {
  2096. return false;
  2097. }
  2098. let line = line();
  2099. // (With the relay: also while flights are being landed.)
  2100. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2101. }
  2102. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2103. /// before they are settled, if so. Preparing reads title memory on the
  2104. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2105. /// runs steps of ours that may read or write it anywhere; what the
  2106. /// flights' shaders write is not there yet.
  2107. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2108. let (written, copies) = {
  2109. let line = line();
  2110. if line.written.is_empty() {
  2111. return None;
  2112. }
  2113. (line.written.clone(), card_steps::copies(&line))
  2114. };
  2115. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2116. }
  2117. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2118. /// flights when the title itself wrote the memory since they were given it
  2119. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2120. ///
  2121. /// The title's 174 MB heap is declared written as a whole (a root view has
  2122. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2123. /// bytes a frame, at a new place each time, waited for every flight's
  2124. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2125. /// named). The title writes those bytes just before the draw that reads
  2126. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2127. ///
  2128. /// Or no shader's write went into that page in the last 600 frames
  2129. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2130. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2131. /// before the page was taken.
  2132. ///
  2133. /// What can go wrong: a constant a flight's shader really writes, in a
  2134. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2135. /// for the first time, is read as it was before that flight.
  2136. fn fill_is_titles(src: usize, len: usize) -> bool {
  2137. const SMALL: usize = 64 << 10;
  2138. static ON: OnceLock<bool> = OnceLock::new();
  2139. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2140. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2141. }
  2142. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2143. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2144. /// in (start, bytes).
  2145. #[cfg(feature = "diagnostics")]
  2146. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2147. /// How often and how long, and the address the last one read.
  2148. #[cfg(feature = "diagnostics")]
  2149. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2150. /// What the wait that comes next is for, and why not on the card.
  2151. #[cfg(feature = "diagnostics")]
  2152. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2153. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2154. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2155. /// shaders.
  2156. #[cfg(feature = "diagnostics")]
  2157. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2158. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2159. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2160. /// raw address (1).
  2161. #[cfg(feature = "diagnostics")]
  2162. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2163. if len < 1 << 20 {
  2164. return;
  2165. }
  2166. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2167. let e = all
  2168. .get_or_insert_with(Default::default)
  2169. .entry((address as usize, (address + len) as usize, pipeline))
  2170. .or_insert_with(|| {
  2171. let shaders = match pipeline {
  2172. 0 => "a view in a table".into(),
  2173. 1 => "a raw address".into(),
  2174. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2175. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2176. }),
  2177. };
  2178. (0, shaders)
  2179. });
  2180. e.0 += 1;
  2181. }
  2182. #[cfg(feature = "diagnostics")]
  2183. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2184. let i = written.partition_point(|r| r.1 <= at);
  2185. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2186. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2187. let why = blamed.1;
  2188. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2189. }
  2190. /// Why [`card_steps`] left the submission to the wait that comes next.
  2191. #[cfg(feature = "diagnostics")]
  2192. fn refused(why: &'static str) {
  2193. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2194. }
  2195. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2196. #[cfg(feature = "diagnostics")]
  2197. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2198. if let Some((shadow, from, _)) = stale.first() {
  2199. let (start, len) = shadow.span();
  2200. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2201. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2202. }
  2203. }
  2204. /// The wait for what [`blame`] last named, or a wait of another reason than
  2205. /// title memory read, took `us`.
  2206. #[cfg(feature = "diagnostics")]
  2207. fn blamed(why: usize, us: u64) {
  2208. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2209. let (key, at) = match (why, named) {
  2210. (WHY_READ | WHY_STALE, Some(named)) => named,
  2211. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2212. _ => {
  2213. let kind = match why {
  2214. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2215. WHY_VALUE => "a memory value",
  2216. WHY_STALE => "title memory changed under shader writes",
  2217. WHY_RUN => "a step of ours",
  2218. WHY_MOST => "lists in the air",
  2219. WHY_FENCE => "a blocking fence wait",
  2220. _ => "another reason",
  2221. };
  2222. ((kind, "", 0, 0, 0), 0)
  2223. }
  2224. };
  2225. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2226. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2227. *e = (e.0 + 1, e.1 + us, at);
  2228. }
  2229. /// For the frame-rate line: the five that waited longest.
  2230. #[cfg(feature = "diagnostics")]
  2231. fn log_blame(frames: f64) {
  2232. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2233. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2234. let mut all: Vec<_> = all.into_iter().collect();
  2235. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2236. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2237. // The passes that declare it written, the ones that do so most.
  2238. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2239. for ((a, b, _), (n, shaders)) in &wide {
  2240. if *a < at + len && at < *b {
  2241. *passes.entry(shaders).or_default() += n;
  2242. }
  2243. }
  2244. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2245. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2246. let passes: Vec<String> =
  2247. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2248. tracing::info!(
  2249. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2250. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2251. us as f64 / 1e3 / frames,
  2252. n as f64 / frames,
  2253. passes.join(", "),
  2254. match (why.is_empty(), kind) {
  2255. (true, _) => "",
  2256. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2257. _ => "; not done on the card: ",
  2258. },
  2259. );
  2260. }
  2261. }
  2262. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2263. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2264. touches(written, src, src + len) && !fill_is_titles(src, len)
  2265. }
  2266. /// Whether they stop a title buffer copy, and if so whether by its source.
  2267. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2268. let read = read_blocked(written, src, len);
  2269. (read || touches(written, dst, dst + len)).then_some(read)
  2270. }
  2271. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2272. /// may write (in order, joined); `count` whether the kind of read is
  2273. /// counted for the frame line.
  2274. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2275. if written.is_empty() {
  2276. return None;
  2277. }
  2278. for list in runs {
  2279. for step in &list.deferred().copies {
  2280. match step {
  2281. &Step::Copy(dst, src, len) => {
  2282. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2283. if count {
  2284. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2285. #[cfg(feature = "diagnostics")]
  2286. if _read {
  2287. blame("a buffer copy's source", written, src, len);
  2288. } else {
  2289. blame("a buffer copy's destination", written, dst, len);
  2290. }
  2291. }
  2292. return Some(WHY_READ);
  2293. }
  2294. }
  2295. &Step::Fill(_, src, len, _) => {
  2296. if read_blocked(written, src, len) {
  2297. if count {
  2298. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2299. #[cfg(feature = "diagnostics")]
  2300. blame("a fill of upload memory", written, src, len);
  2301. }
  2302. return Some(WHY_READ);
  2303. }
  2304. }
  2305. Step::Texture(staging) => {
  2306. let (at, len) = staging.memory();
  2307. if touches(written, at, at + len) {
  2308. if count {
  2309. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2310. #[cfg(feature = "diagnostics")]
  2311. blame("a texture", written, at, len);
  2312. }
  2313. return Some(WHY_READ);
  2314. }
  2315. }
  2316. Step::Run(_) => return Some(WHY_RUN),
  2317. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2318. }
  2319. }
  2320. }
  2321. None
  2322. }
  2323. /// With flights in the air, after the submission's write-watch asking:
  2324. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2325. /// may write and that the title wrote since it was last copied. The
  2326. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2327. /// the title's bytes there would reach the card a submission late.
  2328. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2329. use std::sync::Arc;
  2330. // Per copy, the span of what is refreshed (a flush brings that much
  2331. // up to date at most).
  2332. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2333. // Where each copy is in it, if shaders may be writing it (none begins to
  2334. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2335. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2336. for list in runs {
  2337. for step in &list.deferred().copies {
  2338. if let Step::Refresh(shadow, address, len) = step {
  2339. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2340. shadow.writes_pending().then(|| {
  2341. spans.push((shadow.clone(), *address, *address + *len));
  2342. spans.len() - 1
  2343. })
  2344. });
  2345. if let Some(i) = *place {
  2346. let s = &mut spans[i];
  2347. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2348. }
  2349. }
  2350. }
  2351. }
  2352. if late_exact() {
  2353. // The title's bytes are put in beside the flights' writes; a
  2354. // settle is still due where that could not be done. At most this
  2355. // many changed runs go up to copies in the card's memory, each a
  2356. // copy of its own there. With [`card_steps`] the pages of the
  2357. // title's ring of constants come here too, which were waited for
  2358. // before: hundreds of short runs each, at about 1.5 us a run.
  2359. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2360. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2361. return spans;
  2362. }
  2363. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2364. spans
  2365. }
  2366. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2367. /// air, if there are any, and is set when they are settled. Whether it
  2368. /// did; if not the caller sets the fence now.
  2369. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2370. if !late() {
  2371. return false;
  2372. }
  2373. let mut line = line();
  2374. if line.line.is_empty() && !line.settling {
  2375. return false;
  2376. }
  2377. line.line.push(Late::Signal(fence, value));
  2378. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2379. drop(line);
  2380. // A signal alone (behind a settle under way) has no flight to wake
  2381. // the helper thread for it.
  2382. LINE_MOVED.notify_one();
  2383. RELAY_MOVED.notify_one();
  2384. true
  2385. }
  2386. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2387. /// whether it is met once the flights in the air have run. A flight's
  2388. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2389. /// for the card: the part behind the wait goes to the card behind that
  2390. /// flight, which is the order the wait asks for. If the flights may write
  2391. /// the value in a way not known here (shaders, a timestamp, another
  2392. /// width), they are settled and memory is asked again.
  2393. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2394. let (address, bytes) = wait.place();
  2395. {
  2396. let line = line();
  2397. if line.line.is_empty() && line.in_hand.is_empty() {
  2398. return false;
  2399. }
  2400. let mut unsure = touches(&line.written, address, address + bytes);
  2401. // (With the relay: first the writes of flights being landed.)
  2402. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2403. Late::Write(at, what, n) => Some((at, what, n)),
  2404. _ => None,
  2405. }));
  2406. for (at, what, n) in writes {
  2407. if *at >= address + bytes || address >= *at + *n {
  2408. continue;
  2409. }
  2410. match what {
  2411. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2412. if wait.holds_for(*v) {
  2413. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2414. return true;
  2415. }
  2416. }
  2417. _ => unsure = true,
  2418. }
  2419. }
  2420. if !unsure {
  2421. return false;
  2422. }
  2423. }
  2424. settle_now(WHY_VALUE);
  2425. wait.met()
  2426. }
  2427. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2428. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2429. pub(crate) fn settle_now(why: usize) {
  2430. if !late() {
  2431. return;
  2432. }
  2433. let Some(host) = host() else {
  2434. return;
  2435. };
  2436. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2437. host.settle(&mut submitted, why);
  2438. }
  2439. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2440. pub(crate) fn settle_for_present() {
  2441. settle_now(WHY_SYNC);
  2442. }
  2443. pub(crate) fn settle_for_fence() {
  2444. settle_now(WHY_FENCE);
  2445. }
  2446. /// Resets the host lists of settled flights and keeps them for reuse, as
  2447. /// a queue does for the lists it ran (`crate::list::recycle`).
  2448. fn land() {
  2449. let landed = std::mem::take(&mut line().landed);
  2450. for (lists, order) in landed {
  2451. crate::list::recycle(lists, &order);
  2452. }
  2453. }
  2454. /// The thread that settles the flights once the card has run them all
  2455. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2456. /// at the next call that settles, and a title thread that polls such a
  2457. /// value while the submitting thread waits for that thread would never
  2458. /// see it.
  2459. fn late_helper() {
  2460. let Some(host) = host() else {
  2461. return;
  2462. };
  2463. // SAFETY: a plain event of our own.
  2464. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2465. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2466. return;
  2467. };
  2468. loop {
  2469. let target = {
  2470. let mut line = line();
  2471. loop {
  2472. if line.poke {
  2473. line.poke = false;
  2474. break None;
  2475. }
  2476. // (With the relay the flights are another thread's.)
  2477. if !relay() && !line.line.is_empty() && !line.settling {
  2478. break Some(line.target);
  2479. }
  2480. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2481. }
  2482. };
  2483. let Some(target) = target else {
  2484. land();
  2485. crate::queue::release_held(false);
  2486. continue;
  2487. };
  2488. // The card first, without the submission lock: the submitting
  2489. // thread prepares and sends meanwhile.
  2490. // SAFETY: our fence and event.
  2491. unsafe {
  2492. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2493. WaitForSingleObject(event, INFINITE);
  2494. }
  2495. }
  2496. {
  2497. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2498. // Something newer went up meanwhile: the card is waited for
  2499. // again, the submitting thread is not held up for it.
  2500. if line().target != target {
  2501. continue;
  2502. }
  2503. host.settle(&mut submitted, WHY_CARD_DONE);
  2504. }
  2505. land();
  2506. crate::queue::release_held(false);
  2507. }
  2508. }
  2509. /// Starts the threads of [`late`], once: the one that settles flights when
  2510. /// the card has run them and looks at what queues hold, and with [`relay`]
  2511. /// the one that lands flights.
  2512. fn late_threads() {
  2513. static HELPER: std::sync::Once = std::sync::Once::new();
  2514. HELPER.call_once(|| {
  2515. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2516. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2517. }
  2518. tracing::info!(
  2519. most = late_most(),
  2520. writes = late_writes(),
  2521. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2522. );
  2523. if relay() {
  2524. // Without it nothing would ever land.
  2525. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2526. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2527. }
  2528. tracing::info!(
  2529. exact = relay_exact(),
  2530. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2531. );
  2532. }
  2533. });
  2534. }
  2535. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2536. /// time flights have landed. Counted as a settle for `why`, and its time
  2537. /// as waiting for the card. The caller may hold the submission lock: the
  2538. /// thread that lands flights never takes it.
  2539. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2540. let mut line = line();
  2541. if done(&line) {
  2542. return;
  2543. }
  2544. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2545. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2546. let was_working = working(false);
  2547. let waiting = std::time::Instant::now();
  2548. while !done(&line) {
  2549. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2550. }
  2551. drop(line);
  2552. stood(waiting);
  2553. working(was_working);
  2554. let us = waiting.elapsed().as_micros() as u64;
  2555. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2556. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2557. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2558. #[cfg(feature = "diagnostics")]
  2559. blamed(why, us);
  2560. }
  2561. /// What the thread that lands flights fetches card copies' pieces with
  2562. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2563. /// behind the submission lock), and the memory the pieces come down to.
  2564. struct RelayFetch {
  2565. list: Prelude,
  2566. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2567. queue: Option<ID3D12CommandQueue>,
  2568. fence: ID3D12Fence,
  2569. event: HANDLE,
  2570. /// The last value signalled on `fence`.
  2571. sent: u64,
  2572. /// Buffer, mapping, bytes.
  2573. buffer: Option<(ID3D12Resource, usize, u64)>,
  2574. /// Pieces caught while a later flight was writing them.
  2575. suspects: torn::Suspects,
  2576. /// What earlier fetches brought of flights not landed yet.
  2577. had: crate::land::Had,
  2578. }
  2579. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2580. /// the first flights of the line it takes them, with what follows them,
  2581. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2582. /// the card, or for a flight. It takes neither the submission lock nor
  2583. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2584. /// lists and looking at what queues hold are left to [`late_helper`].
  2585. fn relay_worker() {
  2586. let Some(host) = host() else {
  2587. return;
  2588. };
  2589. // SAFETY: a plain event of our own.
  2590. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2591. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2592. };
  2593. let mut fetch: Option<RelayFetch> = None;
  2594. loop {
  2595. let next = {
  2596. let mut line = line();
  2597. loop {
  2598. if line.line.is_empty() {
  2599. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2600. continue;
  2601. }
  2602. let fences: Vec<Option<u64>> = line
  2603. .line
  2604. .iter()
  2605. .map(|l| match l {
  2606. Late::Run(flight) => Some(flight.fence),
  2607. _ => None,
  2608. })
  2609. .collect();
  2610. // SAFETY: a plain query.
  2611. let completed = unsafe { host.fence.GetCompletedValue() };
  2612. let n = landable(&fences, completed);
  2613. if n == 0 {
  2614. // The first thing is a flight the card has not run.
  2615. break Err(fences[0].unwrap_or(0));
  2616. }
  2617. line.settling = true;
  2618. let items: Vec<Late> = line.line.drain(..n).collect();
  2619. line.in_hand = items
  2620. .iter()
  2621. .filter_map(|l| match l {
  2622. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2623. _ => None,
  2624. })
  2625. .collect();
  2626. if card_steps::stage() > 0 {
  2627. line.landing = card_steps::writers(&items);
  2628. }
  2629. break Ok(items);
  2630. }
  2631. };
  2632. match next {
  2633. Ok(items) => host.relay_land(items, &mut fetch),
  2634. Err(target) => {
  2635. let waiting = std::time::Instant::now();
  2636. // SAFETY: the host's fence and this thread's event.
  2637. let waited = unsafe {
  2638. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2639. WaitForSingleObject(event, INFINITE);
  2640. })
  2641. };
  2642. if waited.is_err() {
  2643. std::thread::sleep(std::time::Duration::from_millis(1));
  2644. }
  2645. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2646. }
  2647. }
  2648. }
  2649. }
  2650. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2651. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2652. /// once, the pieces that differ found on several threads; but the merge is
  2653. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2654. /// are not done with here (each flight's are, afterwards). In two steps:
  2655. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  2656. /// which needs nothing that the fetch from the card's memory brings), and
  2657. /// the merge.
  2658. struct RelayBack {
  2659. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  2660. found: Option<Vec<Vec<(usize, usize)>>>,
  2661. }
  2662. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  2663. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2664. for (shadow, declared) in back {
  2665. if shadow.carded() {
  2666. continue;
  2667. }
  2668. let mut spans: Vec<(usize, usize)> = Vec::new();
  2669. join_ranges(&mut spans, declared.iter().copied());
  2670. for &(from, to) in &spans {
  2671. shadow.relay_compared(from, to - from);
  2672. }
  2673. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2674. }
  2675. RelayBack { work, found: None }
  2676. }
  2677. impl RelayBack {
  2678. /// Looks the ranges through, once; its time counts as `stat`.
  2679. fn look(&mut self, stat: usize) {
  2680. if self.work.is_empty() || self.found.is_some() {
  2681. return;
  2682. }
  2683. let scanning = std::time::Instant::now();
  2684. // Looked through without a lock: a piece that changes meanwhile (a
  2685. // later flight writing, the title's bytes going in) is found now or
  2686. // by that flight's landing, and the merge looks again under the
  2687. // lock.
  2688. self.found = Some(crate::shadow::find_all(&self.work));
  2689. crate::land::spent(stat, scanning);
  2690. #[cfg(feature = "diagnostics")]
  2691. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2692. }
  2693. /// What differs goes into title memory.
  2694. fn merge(mut self) {
  2695. use crate::land;
  2696. self.look(land::stat::SCAN);
  2697. let Some(found) = self.found else {
  2698. return;
  2699. };
  2700. let merging = std::time::Instant::now();
  2701. let mut written: Vec<u64> = Vec::new();
  2702. if land::on() {
  2703. // Pieces in the same block of title memory in one job, in order.
  2704. let pieces: Vec<(usize, usize, usize)> =
  2705. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  2706. let start = |i: usize| self.work[i].0.span().0 as usize;
  2707. let mut order: Vec<usize> = (0..pieces.len()).collect();
  2708. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  2709. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  2710. let jobs = land::jobs(&cut);
  2711. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  2712. land::each(jobs.len(), &|j| {
  2713. let working = std::time::Instant::now();
  2714. let mut notes = land::Notes::default();
  2715. for &p in &order[jobs[j].clone()] {
  2716. let (i, at, n) = pieces[p];
  2717. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  2718. }
  2719. notes.flush();
  2720. land::spent(land::stat::BACK_ALL, working);
  2721. });
  2722. land::count(land::stat::JOBS, jobs.len() as u64);
  2723. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  2724. } else {
  2725. let (mut now, mut title) = (Vec::new(), Vec::new());
  2726. for ((shadow, ..), found) in self.work.iter().zip(found) {
  2727. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  2728. written.push(found.into_iter().map(merge).sum());
  2729. }
  2730. }
  2731. land::spent(land::stat::BACK, merging);
  2732. for ((_, from, to), written) in self.work.iter().zip(written) {
  2733. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  2734. #[cfg(feature = "diagnostics")]
  2735. crate::copystat::compared(*from, to - from, written as usize);
  2736. let _ = (from, to);
  2737. }
  2738. }
  2739. }
  2740. /// For the frame-rate line, with [`late`]: what the line of flights did
  2741. /// per frame since the last one.
  2742. fn late_line(frames: f64) {
  2743. if !late() {
  2744. return;
  2745. }
  2746. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2747. tracing::info!(
  2748. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2749. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2750. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2751. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2752. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2753. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2754. s[0],
  2755. s[1],
  2756. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2757. s[12] / 1000.0,
  2758. s[WHY_SYNC],
  2759. s[WHY_CARD_DONE],
  2760. s[WHY_VALUE],
  2761. s[WHY_STALE],
  2762. s[WHY_READ],
  2763. s[15],
  2764. s[16],
  2765. s[17],
  2766. s[WHY_RUN],
  2767. late_most(),
  2768. s[WHY_MOST],
  2769. s[WHY_WRITES],
  2770. s[WHY_FENCE],
  2771. s[13],
  2772. s[14],
  2773. );
  2774. {
  2775. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2776. tracing::info!(
  2777. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2778. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2779. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2780. w[WHY_SYNC],
  2781. w[WHY_CARD_DONE],
  2782. w[WHY_VALUE],
  2783. w[WHY_STALE],
  2784. w[WHY_READ],
  2785. w[WHY_RUN],
  2786. w[WHY_MOST],
  2787. w[WHY_WRITES],
  2788. w[WHY_FENCE],
  2789. );
  2790. }
  2791. if relay() {
  2792. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2793. tracing::info!(
  2794. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2795. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2796. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2797. \"settles\" above are waits of other threads for it)",
  2798. r[1],
  2799. r[0],
  2800. r[2] / 1000.0,
  2801. r[3] / 1000.0,
  2802. r[4] / 1000.0,
  2803. );
  2804. if send::own() {
  2805. let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2806. tracing::info!(
  2807. "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
  2808. taking them out of the CPU sides",
  2809. t[0] / (1 << 20) as f64,
  2810. t[1],
  2811. t[2],
  2812. t[3] / 1000.0,
  2813. );
  2814. }
  2815. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2816. if t[0] > 0.0 {
  2817. tracing::info!(
  2818. "fetched pieces checked per frame (VICTORY_FETCH_CHECK): {:.1}, of which {:.2} were not what their flight ended with (caught while a later flight was at them, or title bytes went up meanwhile); {:.2} were found whole when fetched again",
  2819. t[0],
  2820. t[1],
  2821. t[2],
  2822. );
  2823. }
  2824. }
  2825. crate::land::log(frames);
  2826. card_steps::log(frames);
  2827. crate::picked::log(frames);
  2828. #[cfg(feature = "diagnostics")]
  2829. log_blame(frames);
  2830. if late_exact() {
  2831. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  2832. tracing::info!(
  2833. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  2834. {runs:.0} changed runs, {:.2} MB",
  2835. bytes / (1 << 20) as f64
  2836. );
  2837. }
  2838. }
  2839. mod card_steps;
  2840. mod send;
  2841. mod torn;
  2842. pub(crate) mod upcheck;
  2843. #[cfg(test)]
  2844. mod late_tests {
  2845. use super::{continues, join_ranges, touches};
  2846. /// Copies join only when both ends continue and the whole does not
  2847. /// overlap itself.
  2848. #[test]
  2849. fn copies_join_only_end_to_end_and_apart() {
  2850. // (destination, source, bytes)
  2851. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  2852. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  2853. // A gap, or only one side continues.
  2854. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  2855. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  2856. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  2857. // Together they would overlap: the second reads what the first wrote.
  2858. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  2859. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  2860. // They touch without overlapping.
  2861. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  2862. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  2863. }
  2864. /// Ranges are found by what they hold, not by where they start, and a
  2865. /// range that only touches another's end does not touch it.
  2866. #[test]
  2867. fn ranges_touch_where_they_overlap() {
  2868. let mut ranges = Vec::new();
  2869. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  2870. assert_eq!(ranges, [(10, 25), (40, 60)]);
  2871. join_ranges(&mut ranges, [(25, 40)]);
  2872. assert_eq!(ranges, [(10, 60)]);
  2873. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  2874. for (from, to, hit) in [
  2875. (0, 10, false),
  2876. (0, 11, true),
  2877. (24, 25, true),
  2878. (25, 40, false),
  2879. (25, 41, true),
  2880. (59, 200, true),
  2881. (60, 100, false),
  2882. (100, 101, true),
  2883. (101, 500, false),
  2884. (30, 30, false),
  2885. (50, 50, false),
  2886. ] {
  2887. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  2888. }
  2889. assert!(!touches(&[], 0, usize::MAX));
  2890. }
  2891. }
  2892. /// Whether a title buffer copy that continues the one recorded before it
  2893. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  2894. /// default).
  2895. ///
  2896. /// Each copy is done at submission through the kernel, which reports a
  2897. /// page that is not there instead of faulting (`copy_mapped`), tells the
  2898. /// write watch and the guards, and ends the refreshes gathered so far: a
  2899. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  2900. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  2901. /// continue the one before is counted either way and said on its own line
  2902. /// with the frame rate; the switch is worth that many kernel calls.
  2903. ///
  2904. /// Joined, the same bytes move: [`continues`] joins only copies whose
  2905. /// ranges, taken together, do not overlap, and nothing is recorded between
  2906. /// two steps that follow each other. What differs: a page that is not
  2907. /// mapped now fails the joined copy as a whole (it then goes page by page,
  2908. /// zeros for what cannot be read, as a single copy does), where before
  2909. /// only the copy that held it did.
  2910. fn join_copies() -> bool {
  2911. static ON: OnceLock<bool> = OnceLock::new();
  2912. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  2913. }
  2914. /// Since the last frame-rate line: title buffer copies recorded, and those
  2915. /// that continue the one before ([`join_copies`]).
  2916. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  2917. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  2918. /// where `last` ended, source and destination both, and the two as one do
  2919. /// not overlap (source over destination): then one copy of both moves the
  2920. /// bytes the two would move in turn.
  2921. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  2922. let ((d, s, n), (dst, src, len)) = (last, next);
  2923. let Some(all) = n.checked_add(len) else {
  2924. return false;
  2925. };
  2926. d.checked_add(n) == Some(dst)
  2927. && s.checked_add(n) == Some(src)
  2928. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  2929. }
  2930. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  2931. /// One list's lock at a time: a submission may name a list twice.
  2932. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  2933. let mut back: Vec<Declared> = Vec::new();
  2934. // Where each copy is in it, and the ranges seen: dispatches declare the
  2935. // same ranges thousands of times a frame.
  2936. let mut places: ByCopy<usize> = ByCopy::default();
  2937. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  2938. for list in runs {
  2939. for step in &list.deferred().copies {
  2940. if let Step::GpuWrite(shadow, address, len) = step {
  2941. let key = std::sync::Arc::as_ptr(shadow) as usize;
  2942. if !seen.insert((key, *address, *len)) {
  2943. continue;
  2944. }
  2945. let i = *places.entry(key).or_insert_with(|| {
  2946. back.push((shadow.clone(), Vec::new()));
  2947. back.len() - 1
  2948. });
  2949. back[i].1.push((*address, *address + *len));
  2950. }
  2951. }
  2952. }
  2953. back
  2954. }
  2955. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  2956. /// lines that say what the title's CPU was given while it decided whether
  2957. /// the camera is in a room. The values of the small read-backs
  2958. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  2959. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  2960. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  2961. /// copies found stale after their refresh (`shadow.rs`), and, in the
  2962. /// runtime, the read requests that fail (with 2: every request).
  2963. pub(crate) fn walls_trace() -> bool {
  2964. static ON: OnceLock<bool> = OnceLock::new();
  2965. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  2966. }
  2967. /// After `list` has run: the texels its read-backs copied into host
  2968. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  2969. ///
  2970. /// A submission that is waited for did this itself. One sent ahead
  2971. /// ([`late`]) did not, at any stage: the flights' lists were settled
  2972. /// without it, so the title read a buffer nobody wrote, as before read-backs
  2973. /// were made (the exposure metering's two small float targets, every frame).
  2974. fn read_backs(list: &HostList) {
  2975. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  2976. let mut data = std::ptr::null_mut();
  2977. // SAFETY: a read-back buffer of ours, written by the list that has
  2978. // run; the title's destination holds every row (checked when the
  2979. // copy was recorded).
  2980. unsafe {
  2981. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  2982. let from = data.cast::<u8>().cast_const();
  2983. for line in 0..*rows {
  2984. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  2985. }
  2986. // The walls trace: what the title is handed (one row of at
  2987. // most 24 values: its 5x1 and 1x1 float targets).
  2988. if walls_trace() && *rows == 1 && *row <= 96 {
  2989. let mut values = [0f32; 24];
  2990. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  2991. tracing::info!(
  2992. frame = crate::frame::current(),
  2993. to = format_args!("{:#x}", *at),
  2994. bytes = *row,
  2995. values = ?&values[..*row / 4],
  2996. "walls trace: a read-back lands in title memory"
  2997. );
  2998. }
  2999. buffer.Unmap(0, None);
  3000. }
  3001. }
  3002. }
  3003. }
  3004. /// After the card ran what declared `back`: what shaders wrote there goes
  3005. /// into title memory, and the ranges are done with.
  3006. fn hand_back(back: &[Declared]) {
  3007. if crate::shadow::wide_back() {
  3008. // Every range first (the pieces that differ, found on several
  3009. // threads), then the merges, in order, as below.
  3010. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3011. for (shadow, declared) in back {
  3012. if shadow.carded() {
  3013. continue;
  3014. }
  3015. let mut sorted = declared.clone();
  3016. sorted.sort_unstable();
  3017. let mut spans: Vec<(usize, usize)> = Vec::new();
  3018. for (from, to) in sorted {
  3019. match spans.last_mut() {
  3020. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3021. _ => spans.push((from, to)),
  3022. }
  3023. }
  3024. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3025. }
  3026. #[cfg(feature = "diagnostics")]
  3027. let scanning = std::time::Instant::now();
  3028. let found = crate::shadow::find_all(&work);
  3029. #[cfg(feature = "diagnostics")]
  3030. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3031. for ((shadow, from, to), found) in work.iter().zip(found) {
  3032. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3033. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3034. #[cfg(feature = "diagnostics")]
  3035. crate::copystat::compared(*from, to - from, written);
  3036. }
  3037. for (shadow, declared) in back {
  3038. shadow.copy_back_done(declared);
  3039. }
  3040. return;
  3041. }
  3042. for (shadow, declared) in back {
  3043. if shadow.carded() {
  3044. // Done before (`Host::card_back`).
  3045. shadow.copy_back_done(declared);
  3046. continue;
  3047. }
  3048. // Each byte compared once: the world declares dozens of views
  3049. // of its 174 MB heap that overlap almost entirely, and comparing
  3050. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3051. // MB shaders wrote. Only ranges that overlap or touch are
  3052. // joined: what lies between two was not given to shaders (the
  3053. // snapshot does not hold it).
  3054. let mut sorted = declared.clone();
  3055. sorted.sort_unstable();
  3056. let mut spans: Vec<(usize, usize)> = Vec::new();
  3057. for (from, to) in sorted {
  3058. match spans.last_mut() {
  3059. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3060. _ => spans.push((from, to)),
  3061. }
  3062. }
  3063. for (from, to) in spans {
  3064. let written = shadow.copy_back(from, to - from);
  3065. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3066. #[cfg(feature = "diagnostics")]
  3067. crate::copystat::compared(from, to - from, written);
  3068. }
  3069. shadow.copy_back_done(declared);
  3070. }
  3071. }
  3072. impl Host {
  3073. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3074. /// mesh shaders need both); logged once.
  3075. pub(crate) fn mesh_shaders(&self) -> bool {
  3076. static MESH: OnceLock<bool> = OnceLock::new();
  3077. *MESH.get_or_init(|| {
  3078. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3079. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3080. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3081. };
  3082. // SAFETY: each query writes its own structure of the given size.
  3083. let ok = unsafe {
  3084. self.device
  3085. .CheckFeatureSupport(
  3086. D3D12_FEATURE_D3D12_OPTIONS7,
  3087. (&raw mut options).cast(),
  3088. size_of_val(&options) as u32,
  3089. )
  3090. .is_ok()
  3091. && self
  3092. .device
  3093. .CheckFeatureSupport(
  3094. D3D12_FEATURE_SHADER_MODEL,
  3095. (&raw mut model).cast(),
  3096. size_of_val(&model) as u32,
  3097. )
  3098. .is_ok()
  3099. };
  3100. let mesh = ok
  3101. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3102. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3103. tracing::info!(mesh, "host mesh shader support");
  3104. mesh
  3105. })
  3106. }
  3107. /// Whether the host GPU supports the depth bounds test; logged once.
  3108. pub(crate) fn depth_bounds(&self) -> bool {
  3109. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3110. *BOUNDS.get_or_init(|| {
  3111. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3112. // SAFETY: writes `options` of the given size.
  3113. let ok = unsafe {
  3114. self.device
  3115. .CheckFeatureSupport(
  3116. D3D12_FEATURE_D3D12_OPTIONS2,
  3117. (&raw mut options).cast(),
  3118. size_of_val(&options) as u32,
  3119. )
  3120. .is_ok()
  3121. };
  3122. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3123. tracing::info!(supported, "host depth bounds support");
  3124. supported
  3125. })
  3126. }
  3127. /// A new list, open for recording.
  3128. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3129. #[cfg(feature = "diagnostics")]
  3130. let started = std::time::Instant::now();
  3131. #[cfg(feature = "diagnostics")]
  3132. let before = private_bytes();
  3133. let list = self.make_list();
  3134. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3135. // (May shrink while a list is made, on another thread's account:
  3136. // added as it is, the sum is what counts.)
  3137. #[cfg(feature = "diagnostics")]
  3138. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3139. #[cfg(feature = "diagnostics")]
  3140. {
  3141. use crate::copystat::{C, add};
  3142. add(C::HostLists, 1);
  3143. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3144. }
  3145. list
  3146. }
  3147. /// An allocator and a closed list for a prelude.
  3148. fn make_prelude(&self) -> Option<Prelude> {
  3149. // SAFETY: plain object creation.
  3150. let made: windows::core::Result<Prelude> = unsafe {
  3151. (|| {
  3152. let allocator: ID3D12CommandAllocator =
  3153. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3154. let list: ID3D12GraphicsCommandList =
  3155. self.device
  3156. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3157. list.Close()?;
  3158. Ok((allocator, list))
  3159. })()
  3160. };
  3161. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3162. match made {
  3163. Ok(prelude) => Some(prelude),
  3164. Err(e) => {
  3165. tracing::warn!(error = %e, "no host list for a prelude");
  3166. None
  3167. }
  3168. }
  3169. }
  3170. fn make_list(&self) -> windows::core::Result<HostList> {
  3171. // SAFETY: plain object creation.
  3172. unsafe {
  3173. let allocator: ID3D12CommandAllocator = self
  3174. .device
  3175. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3176. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3177. 0,
  3178. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3179. &allocator,
  3180. None,
  3181. )?;
  3182. let prelude = OnceLock::new();
  3183. if !lazy_prelude() {
  3184. let _ = prelude.set(self.make_prelude());
  3185. }
  3186. Ok(HostList {
  3187. allocator,
  3188. list,
  3189. deferred: Mutex::default(),
  3190. scratch: Mutex::default(),
  3191. states: Mutex::default(),
  3192. twins: Mutex::default(),
  3193. prelude,
  3194. pipelines: Mutex::default(),
  3195. budget: OnceLock::new(),
  3196. card_budget: OnceLock::new(),
  3197. indirect_args: Mutex::default(),
  3198. batch_args: Mutex::default(),
  3199. _alive: Counted::new(),
  3200. #[cfg(feature = "diagnostics")]
  3201. notes: Mutex::default(),
  3202. #[cfg(feature = "diagnostics")]
  3203. stamps: OnceLock::new(),
  3204. })
  3205. }
  3206. }
  3207. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3208. fn card_clock(&self) -> Option<&'static CardClock> {
  3209. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3210. static WATCH: std::sync::Once = std::sync::Once::new();
  3211. let clock = CLOCK
  3212. .get_or_init(|| {
  3213. // SAFETY: a plain fence on our device.
  3214. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3215. Some(CardClock {
  3216. fence,
  3217. state: Mutex::new((0, None)),
  3218. sent: std::sync::Condvar::new(),
  3219. })
  3220. })
  3221. .as_ref()?;
  3222. WATCH.call_once(|| {
  3223. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3224. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3225. }
  3226. });
  3227. Some(clock)
  3228. }
  3229. /// Lists of ours just went to the queue: the clock's signal goes
  3230. /// behind them, and an idle stretch of the card, if one was under way,
  3231. /// ends here ([`CARD_CLOCK_US`]).
  3232. fn card_sent(&self) {
  3233. let Some(clock) = self.card_clock() else {
  3234. return;
  3235. };
  3236. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3237. state.0 += 1;
  3238. // SAFETY: our queue and the clock's fence.
  3239. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3240. if let Some((since, worked_then)) = state.1.take() {
  3241. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3242. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3243. }
  3244. drop(state);
  3245. clock.sent.notify_one();
  3246. }
  3247. /// Whether the host has what copies in the card's memory need (three
  3248. /// lists and the compare); made at the first ask. A copy goes to the
  3249. /// card's memory only if it has.
  3250. pub(crate) fn card_ready(&self) -> bool {
  3251. static READY: OnceLock<bool> = OnceLock::new();
  3252. *READY.get_or_init(|| match self.make_card_work() {
  3253. Ok(work) => {
  3254. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3255. true
  3256. }
  3257. Err(e) => {
  3258. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3259. false
  3260. }
  3261. })
  3262. }
  3263. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3264. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3265. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3266. let mut code: Option<ID3DBlob> = None;
  3267. // SAFETY: the source and names live through the call; the out
  3268. // pointer is ours.
  3269. unsafe {
  3270. D3DCompile(
  3271. CARD_COMPARE.as_ptr().cast(),
  3272. CARD_COMPARE.len(),
  3273. windows::core::s!("card compare"),
  3274. None,
  3275. None,
  3276. windows::core::s!("main"),
  3277. windows::core::s!("cs_5_1"),
  3278. 0,
  3279. 0,
  3280. &mut code,
  3281. None,
  3282. )?;
  3283. }
  3284. let code = code.ok_or_else(windows::core::Error::empty)?;
  3285. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3286. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3287. // in one submission.
  3288. const RESULTS: u64 = 1 << 20;
  3289. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3290. name(&differs, || "card compare results".into());
  3291. // SAFETY: the blob's own bytes; the root signature is inside the
  3292. // shader.
  3293. unsafe {
  3294. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3295. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3296. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3297. pRootSignature: std::mem::transmute_copy(&root),
  3298. CS: D3D12_SHADER_BYTECODE {
  3299. pShaderBytecode: bytes.as_ptr().cast(),
  3300. BytecodeLength: bytes.len(),
  3301. },
  3302. ..Default::default()
  3303. })?;
  3304. #[cfg(feature = "diagnostics")]
  3305. name(&pso, || crate::replay::play::COMPARE.into());
  3306. Ok(CardWork {
  3307. sync: vec![list()?],
  3308. check: vec![list()?],
  3309. fetch: list()?,
  3310. root,
  3311. pso,
  3312. differs: (differs, data as usize, RESULTS),
  3313. fetched: None,
  3314. taken: 0,
  3315. out: 0,
  3316. })
  3317. }
  3318. }
  3319. /// Before a submission's lists run, for copies in the card's memory
  3320. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3321. /// the last submission goes to their card side (a list of ours, run
  3322. /// now; the submission's lists follow it on the queue), and the ranges
  3323. /// this submission's shaders may write get a compare to run after its
  3324. /// lists. `None` if there is nothing to do.
  3325. ///
  3326. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3327. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3328. /// `relay`).
  3329. /// `picked`: ranges that may be written too, and ranges to look at
  3330. /// (`crate::picked`).
  3331. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3332. use std::sync::Arc;
  3333. if !crate::shadow::cards() {
  3334. return None;
  3335. }
  3336. // The ranges this submission's shaders may write, per copy.
  3337. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3338. for list in runs {
  3339. for step in &list.deferred().copies {
  3340. if let Step::GpuWrite(shadow, address, len) = step
  3341. && shadow.carded()
  3342. {
  3343. let range = (*address, *address + *len);
  3344. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3345. Some((_, ranges)) => {
  3346. if !ranges.contains(&range) {
  3347. ranges.push(range);
  3348. }
  3349. }
  3350. None => declared.push((shadow.clone(), vec![range])),
  3351. }
  3352. }
  3353. }
  3354. }
  3355. let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
  3356. // (Of a copy with a declared range here, that says it.)
  3357. let looked: Vec<&crate::picked::Range> =
  3358. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3359. // With the relay: the order of the queue is held from here until
  3360. // what is taken is on the queue, and the taking is numbered.
  3361. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3362. let sent_as = match order.as_mut() {
  3363. Some(order) => {
  3364. **order += 1;
  3365. **order
  3366. }
  3367. None => 0,
  3368. };
  3369. let mut dirty = crate::shadow::card_dirty(sent_as);
  3370. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3371. return None;
  3372. }
  3373. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3374. let work = work.as_mut()?;
  3375. // A copy whose shader writes are declared for the first time gets
  3376. // its bytes from before, whole.
  3377. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3378. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3379. if shadow.card_make_before(|size| {
  3380. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3381. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3382. Some(before)
  3383. }) {
  3384. whole.push(shadow.clone());
  3385. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3386. dirty.push((shadow.clone(), Vec::new()));
  3387. }
  3388. }
  3389. }
  3390. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3391. let mut looks = None;
  3392. // The bytes as they are now, whatever later submissions put there.
  3393. let own = if send::own() { send::take(self, &dirty) } else { None };
  3394. if !dirty.is_empty() {
  3395. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3396. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3397. };
  3398. let (allocator, list) = &sync;
  3399. // SAFETY: the list's last run finished (it ran ahead of a
  3400. // submission that was waited for, and came back after that);
  3401. // live buffers, and the ranges lie in them.
  3402. let recorded = unsafe {
  3403. (|| -> windows::core::Result<()> {
  3404. allocator.Reset()?;
  3405. list.Reset(allocator, None)?;
  3406. if upcheck::on() {
  3407. looks = upcheck::record(self, list, &dirty);
  3408. }
  3409. // Every copy first, then one barrier call, then every
  3410. // pass: a wait between each copy and its pass had the
  3411. // card do them one after the other.
  3412. let mut sent = Vec::new();
  3413. if let Some(own) = &own {
  3414. own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
  3415. }
  3416. for (shadow, ranges) in &dirty {
  3417. let Some((staging, before, _)) = shadow.card_sides() else {
  3418. continue;
  3419. };
  3420. for &(a, b) in ranges {
  3421. if own.is_none() {
  3422. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3423. }
  3424. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3425. }
  3426. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3427. if own.is_none() && before.is_some() && !ranges.is_empty() {
  3428. sent.push(transition(
  3429. &shadow.buffer,
  3430. D3D12_RESOURCE_STATE_COPY_DEST,
  3431. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3432. ));
  3433. }
  3434. }
  3435. if !sent.is_empty() {
  3436. list.ResourceBarrier(&sent);
  3437. }
  3438. list.SetComputeRootSignature(&work.root);
  3439. list.SetPipelineState(&work.pso);
  3440. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3441. for (shadow, ranges) in &dirty {
  3442. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3443. continue;
  3444. };
  3445. // No twin (it cost the card the copy's size again,
  3446. // 399 MB in run 75): `before` holds a 128-bit hash
  3447. // of each 64 KiB piece. The pieces just sent up are
  3448. // hashed again, all of them the first time; the
  3449. // compare after the lists hashes the declared
  3450. // pieces and flags those whose hash is another.
  3451. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3452. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3453. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3454. vec![shadow.card_run(0, usize::MAX)]
  3455. } else {
  3456. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3457. };
  3458. // The same pieces in fewer passes (`rehash_runs`).
  3459. let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3460. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3461. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3462. for run in runs {
  3463. card_pass(list, &run, size as u32, 0, 0);
  3464. }
  3465. }
  3466. list.Close()?;
  3467. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3468. Ok(())
  3469. })()
  3470. };
  3471. if let Err(e) = recorded {
  3472. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3473. }
  3474. used.push((false, sync));
  3475. }
  3476. drop(order);
  3477. let mut plan = CardPlan {
  3478. ranges: Vec::new(),
  3479. check: None,
  3480. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3481. lists: used,
  3482. sent_as,
  3483. looks,
  3484. sends: own.map(send::Own::memory),
  3485. };
  3486. // Each byte once, as the copy-back joins the declared ranges. The
  3487. // results go behind those of plans still in the air.
  3488. let mut at = work.taken;
  3489. for (shadow, ranges) in &declared {
  3490. let mut sorted = ranges.clone();
  3491. sorted.sort_unstable();
  3492. let mut spans: Vec<(usize, usize)> = Vec::new();
  3493. for (from, to) in sorted {
  3494. match spans.last_mut() {
  3495. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3496. _ => spans.push((from, to)),
  3497. }
  3498. }
  3499. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3500. for (from, to) in spans {
  3501. let Some(span) = shadow.card_span(from, to) else {
  3502. continue;
  3503. };
  3504. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3505. plan.ranges.push(CardRange {
  3506. shadow: shadow.clone(),
  3507. declared: (from, to),
  3508. span,
  3509. at,
  3510. compared,
  3511. picked: false,
  3512. });
  3513. if compared {
  3514. at += span.pieces;
  3515. }
  3516. }
  3517. }
  3518. for (shadow, from, len) in looked {
  3519. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3520. if let Some(span) = shadow.card_span(*from, from + len)
  3521. && twin
  3522. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3523. {
  3524. plan.ranges.push(CardRange {
  3525. shadow: shadow.clone(),
  3526. declared: (*from, from + len),
  3527. span,
  3528. at,
  3529. compared: true,
  3530. picked: true,
  3531. });
  3532. at += span.pieces;
  3533. }
  3534. }
  3535. work.taken = at;
  3536. if plan.ranges.iter().any(|r| r.compared) {
  3537. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3538. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3539. };
  3540. let (allocator, list) = &check;
  3541. // SAFETY: the list's last run finished (its submission was
  3542. // waited for, and it came back after that); live buffers; the
  3543. // compare's own root signature.
  3544. let recorded = unsafe {
  3545. (|| -> windows::core::Result<ID3D12CommandList> {
  3546. allocator.Reset()?;
  3547. list.Reset(allocator, None)?;
  3548. // What the submission's shaders wrote, first.
  3549. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3550. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3551. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3552. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3553. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3554. pResource: std::mem::ManuallyDrop::new(None),
  3555. }),
  3556. },
  3557. }]);
  3558. list.SetComputeRootSignature(&work.root);
  3559. list.SetPipelineState(&work.pso);
  3560. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3561. for r in plan.ranges.iter().filter(|r| r.compared) {
  3562. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3563. continue;
  3564. };
  3565. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3566. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3567. // (What is only looked at keeps its hashes: what
  3568. // changed there is the next declared range's to land.)
  3569. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  3570. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3571. }
  3572. list.Close()?;
  3573. list.cast()
  3574. })()
  3575. };
  3576. match recorded {
  3577. Ok(list) => plan.check = Some(list),
  3578. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3579. }
  3580. plan.lists.push((true, check));
  3581. }
  3582. work.out += 1;
  3583. Some(plan)
  3584. }
  3585. /// With [`relay`]: whether the compare's result area is half taken by
  3586. /// plans in the air. It starts from the beginning only when no plan is
  3587. /// out, so the caller lets the flights land first.
  3588. fn card_results_low(&self) -> bool {
  3589. CARD_WORK
  3590. .lock()
  3591. .unwrap_or_else(|e| e.into_inner())
  3592. .as_ref()
  3593. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3594. }
  3595. /// The plan's submission has run and its results were read
  3596. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3597. /// when nothing of ours is on the card, so the compare's results start
  3598. /// from the beginning again.
  3599. fn card_done(&self, plan: CardPlan) {
  3600. if let Some(looks) = plan.looks {
  3601. looks.read();
  3602. }
  3603. if let Some(memory) = plan.sends {
  3604. send::give_back(memory);
  3605. }
  3606. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3607. let Some(work) = work.as_mut() else {
  3608. return;
  3609. };
  3610. for (check, list) in plan.lists {
  3611. if check { work.check.push(list) } else { work.sync.push(list) }
  3612. }
  3613. work.out = work.out.saturating_sub(1);
  3614. // With the relay other plans may be on the card, their results
  3615. // not read yet: the area starts again only when none is out.
  3616. if !relay() || work.out == 0 {
  3617. work.taken = 0;
  3618. }
  3619. }
  3620. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3621. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3622. // SAFETY: plain object creation.
  3623. let copying = relay_copy().then(|| unsafe {
  3624. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3625. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3626. let list: ID3D12GraphicsCommandList =
  3627. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3628. list.Close()?;
  3629. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3630. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3631. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3632. ..Default::default()
  3633. })?;
  3634. Ok(((allocator, list), queue))
  3635. })()
  3636. });
  3637. let (list, queue) = match copying {
  3638. Some(Ok((list, queue))) => (list, Some(queue)),
  3639. Some(Err(e)) => {
  3640. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3641. (self.make_prelude()?, None)
  3642. }
  3643. None => (self.make_prelude()?, None),
  3644. };
  3645. // SAFETY: plain objects of our own.
  3646. unsafe {
  3647. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3648. let event = CreateEventW(None, false, false, None).ok()?;
  3649. Some(RelayFetch {
  3650. list,
  3651. queue,
  3652. fence,
  3653. event,
  3654. sent: 0,
  3655. buffer: None,
  3656. suspects: torn::Suspects::default(),
  3657. had: crate::land::Had::default(),
  3658. })
  3659. }
  3660. }
  3661. /// [`relay`], on the thread that lands flights: for the plans of the
  3662. /// flights being landed (the card has run them), the pieces their
  3663. /// compares flagged are fetched, once each, with a list and a wait of
  3664. /// this thread's own, and what shaders wrote in them goes into title
  3665. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3666. /// no submission lock; a piece flagged under one range of a plan is
  3667. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3668. /// whatever was sent meanwhile, so it may bring a later flight's
  3669. /// bytes, which that flight's landing then finds merged already; and
  3670. /// nothing is sent back up. `plans` come with the value signalled behind
  3671. /// their flight. `meanwhile` is called while the fetch is on its way, if
  3672. /// there is one.
  3673. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  3674. use crate::land;
  3675. let gathering = std::time::Instant::now();
  3676. let differs = {
  3677. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3678. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3679. };
  3680. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3681. let mut total = 0u64;
  3682. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  3683. fetch.had.landing(first);
  3684. }
  3685. // SAFETY: the mapping of the results. The compares of these plans
  3686. // have run, and their dwords are given to no other plan before these
  3687. // are done with (`card_done`).
  3688. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  3689. if let Some(differs) = differs {
  3690. // Pieces caught while a later flight was at them (`torn`).
  3691. let suspects = fetch.as_ref().map(|f| &f.suspects);
  3692. let mut seen = std::collections::HashSet::new();
  3693. for &(plan, behind) in plans {
  3694. plan.picked_found(differs);
  3695. let flags: Vec<(usize, u32, bool)> = plan
  3696. .ranges
  3697. .iter()
  3698. .filter(|r| !r.picked)
  3699. .flat_map(|r| {
  3700. (0..r.span.pieces).map(move |p| {
  3701. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  3702. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  3703. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  3704. })
  3705. })
  3706. .collect();
  3707. let fetched = flagged_pieces(&flags);
  3708. for r in plan.ranges.iter().filter(|r| !r.picked) {
  3709. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3710. if upcheck::on() {
  3711. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  3712. }
  3713. for p in 0..r.span.pieces {
  3714. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  3715. continue;
  3716. }
  3717. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3718. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  3719. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  3720. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  3721. land::count(land::stat::HAD, 1);
  3722. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  3723. if land::skip_on() {
  3724. continue;
  3725. }
  3726. }
  3727. if upcheck::on() {
  3728. upcheck::fetched(r.shadow.id(), lo);
  3729. }
  3730. seen.insert((copy, lo, hi));
  3731. pieces.push((r.shadow.clone(), lo, hi, total));
  3732. total += (hi - lo) as u64;
  3733. }
  3734. }
  3735. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3736. }
  3737. }
  3738. }
  3739. if land::on() {
  3740. // In the order they are landed, each byte of a copy once.
  3741. let keys: Vec<land::Piece> =
  3742. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  3743. total = 0;
  3744. pieces = land::ordered(&keys)
  3745. .into_iter()
  3746. .map(|(i, title, len)| {
  3747. let shadow = &pieces[i].0;
  3748. let lo = title - shadow.span().0 as usize;
  3749. let at = total;
  3750. total += len as u64;
  3751. (shadow.clone(), lo, lo + len, at)
  3752. })
  3753. .collect();
  3754. }
  3755. land::spent(land::stat::GATHER, gathering);
  3756. if fetch.is_none() {
  3757. *fetch = self.make_relay_fetch();
  3758. }
  3759. // On the copy queue a later flight may be at a piece while it is
  3760. // fetched: the pieces come down whole, to be hashed.
  3761. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  3762. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  3763. if let Some(check) = &check {
  3764. total = check.total;
  3765. }
  3766. // The sends these flights ran behind, all a fetch on the copy queue
  3767. // is known to have run behind.
  3768. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  3769. if pieces.is_empty() {
  3770. // Nothing to fetch: every send so far is older than the next
  3771. // fetch, if that goes to the queue the sends went to.
  3772. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  3773. true => behind,
  3774. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  3775. };
  3776. crate::shadow::relay_fetched(after);
  3777. return;
  3778. }
  3779. let Some(f) = fetch.as_mut() else {
  3780. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  3781. };
  3782. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  3783. let size = total.next_multiple_of(16 << 20);
  3784. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3785. }
  3786. let Some((buffer, data, _)) = f.buffer.clone() else {
  3787. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  3788. };
  3789. f.sent += 1;
  3790. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  3791. let copy_queue = f.queue.clone();
  3792. let waiting = std::time::Instant::now();
  3793. // The flights the fetch runs behind: those in the line by now have
  3794. // been given to the queue. On the copy queue, those landed here.
  3795. let ahead = match copy_queue {
  3796. Some(_) => 0,
  3797. None => line().target,
  3798. };
  3799. // SAFETY: the list's last run was waited for by this thread; live
  3800. // buffers (the copies are held by the plans); the fence and the
  3801. // event are this thread's.
  3802. let ran = unsafe {
  3803. (|| -> windows::core::Result<u64> {
  3804. allocator.Reset()?;
  3805. list.Reset(&allocator, None)?;
  3806. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  3807. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  3808. }
  3809. list.Close()?;
  3810. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  3811. if let Some(queue) = &copy_queue {
  3812. queue.ExecuteCommandLists(&lists);
  3813. queue.Signal(&fence, sent)?;
  3814. meanwhile();
  3815. fence.SetEventOnCompletion(sent, event)?;
  3816. WaitForSingleObject(event, INFINITE);
  3817. return Ok(behind);
  3818. }
  3819. // In the order of the queue: the sends of title bytes so
  3820. // far are ahead of this fetch, every later one behind it.
  3821. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  3822. self.queue.ExecuteCommandLists(&lists);
  3823. let after = *order;
  3824. drop(order);
  3825. self.card_sent();
  3826. self.queue.Signal(&fence, sent)?;
  3827. meanwhile();
  3828. fence.SetEventOnCompletion(sent, event)?;
  3829. WaitForSingleObject(event, INFINITE);
  3830. Ok(after)
  3831. })()
  3832. };
  3833. let after = match ran {
  3834. Ok(after) => after,
  3835. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  3836. };
  3837. let us = waiting.elapsed().as_micros() as u64;
  3838. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  3839. {
  3840. use crate::shadow::CARD_STATS;
  3841. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  3842. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  3843. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  3844. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  3845. }
  3846. let merging = std::time::Instant::now();
  3847. let mut written = 0;
  3848. if land::on() {
  3849. let titles: Vec<(usize, usize)> =
  3850. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  3851. let jobs = land::jobs(&titles);
  3852. let put = std::sync::atomic::AtomicU64::new(0);
  3853. land::each(jobs.len(), &|j| {
  3854. let working = std::time::Instant::now();
  3855. if let Some(check) = &check {
  3856. for i in jobs[j].clone() {
  3857. // SAFETY: as below.
  3858. unsafe { check.look(i, data) };
  3859. }
  3860. }
  3861. let mut notes = land::Notes::default();
  3862. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  3863. let addressed: Vec<(usize, usize, usize)> =
  3864. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  3865. // SAFETY: the mapping of the fetched bytes, `total` of
  3866. // them; the copy into it has run, and the next waits
  3867. // for this call.
  3868. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  3869. }
  3870. notes.flush();
  3871. land::spent(land::stat::CARD_ALL, working);
  3872. });
  3873. land::count(land::stat::JOBS, jobs.len() as u64);
  3874. written = put.into_inner();
  3875. } else {
  3876. let mut title = Vec::new();
  3877. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  3878. if let Some(check) = &check {
  3879. // SAFETY: as below.
  3880. unsafe { check.look(i, data) };
  3881. }
  3882. // SAFETY: the mapping of the fetched bytes, `total` of them;
  3883. // the copy into it has run.
  3884. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  3885. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  3886. shadow.walls_merged(gpu.len(), merged);
  3887. written += merged as u64;
  3888. }
  3889. }
  3890. land::spent(land::stat::CARD, merging);
  3891. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  3892. if let Some(f) = fetch.as_mut() {
  3893. if let Some(check) = &check {
  3894. check.done(&mut f.suspects);
  3895. }
  3896. f.had.fetched(
  3897. ahead,
  3898. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  3899. );
  3900. }
  3901. // Sends up to `after` are of no use to any later merge.
  3902. crate::shadow::relay_fetched(after);
  3903. }
  3904. /// [`relay`], on the thread that lands flights: `items` are the first
  3905. /// things of the line, flights the card has run and what follows them.
  3906. /// What their shaders wrote goes into title memory (copies in the
  3907. /// card's memory first, then the others, each byte once whichever
  3908. /// flights declared it); then every flight's ranges are done with;
  3909. /// then, in the line's order, each flight's read-backs, its
  3910. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  3911. /// is complete before the title is told anything.
  3912. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  3913. let landing = std::time::Instant::now();
  3914. {
  3915. let flights: Vec<&Flight> = items
  3916. .iter()
  3917. .filter_map(|l| match l {
  3918. Late::Run(flight) => Some(flight),
  3919. _ => None,
  3920. })
  3921. .collect();
  3922. if !flights.is_empty() {
  3923. // SAFETY: a plain query.
  3924. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  3925. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  3926. fail(format_args!(
  3927. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  3928. flights.len(),
  3929. runs.len(),
  3930. self.removal_data(&runs),
  3931. last_notes(&runs)
  3932. ));
  3933. }
  3934. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  3935. // (Each byte once: the ranges are joined.)
  3936. let mut back: Vec<Declared> = Vec::new();
  3937. for flight in &flights {
  3938. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  3939. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  3940. Some((_, all)) => all.extend_from_slice(ranges),
  3941. None => back.push((shadow.clone(), ranges.clone())),
  3942. }
  3943. }
  3944. }
  3945. let mut hand_back = relay_hand_back(&back);
  3946. self.relay_card_back(&plans, fetch, &mut || {
  3947. if crate::land::on() {
  3948. hand_back.look(crate::land::stat::SCAN_BESIDE);
  3949. }
  3950. });
  3951. hand_back.merge();
  3952. let finishing = std::time::Instant::now();
  3953. // Only now, and flight by flight: a range another flight
  3954. // in the air declared too stays closed to refreshes.
  3955. for flight in &flights {
  3956. for (shadow, ranges) in &flight.back {
  3957. shadow.copy_back_done(ranges);
  3958. }
  3959. }
  3960. crate::land::spent(crate::land::stat::DONE, finishing);
  3961. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  3962. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  3963. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  3964. }
  3965. }
  3966. // In the order given: what tells the title the card is done.
  3967. let mut last = 0;
  3968. let mut landed = Vec::new();
  3969. let mut telling = std::time::Instant::now();
  3970. for item in items {
  3971. telling = match item {
  3972. Late::Run(flight) => {
  3973. last = flight.number;
  3974. for &i in &flight.order {
  3975. read_backs(flight.lists[i].host());
  3976. }
  3977. if let Some(card) = flight.card {
  3978. self.card_done(card);
  3979. }
  3980. if let Some(own) = flight.own {
  3981. own.landed();
  3982. }
  3983. landed.push((flight.lists, flight.order));
  3984. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  3985. }
  3986. Late::Write(at, what, bytes) => {
  3987. what.write(at as *mut u8, bytes);
  3988. crate::land::spent(crate::land::stat::TOLD, telling)
  3989. }
  3990. Late::Signal(fence, value) => {
  3991. crate::fence::set(fence as crate::object::This, value);
  3992. crate::land::spent(crate::land::stat::TOLD, telling)
  3993. }
  3994. };
  3995. }
  3996. if last > 0 {
  3997. FINISHED.store(last, Ordering::Release);
  3998. bury(last);
  3999. }
  4000. self.log_messages();
  4001. crate::land::spent(crate::land::stat::REST, telling);
  4002. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4003. {
  4004. let mut line = line();
  4005. let Line {
  4006. line: items,
  4007. written,
  4008. lists,
  4009. settling,
  4010. poke,
  4011. landed: kept,
  4012. in_hand,
  4013. landing,
  4014. ..
  4015. } = &mut *line;
  4016. kept.extend(landed);
  4017. in_hand.clear();
  4018. landing.clear();
  4019. // What is still in the air, from the flights that are.
  4020. written.clear();
  4021. *lists = 0;
  4022. let mut ranges = Vec::new();
  4023. for item in items.iter() {
  4024. if let Late::Run(flight) = item {
  4025. *lists += flight.order.len().max(1);
  4026. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  4027. }
  4028. }
  4029. join_ranges(written, ranges);
  4030. *settling = false;
  4031. // The landed lists are reset, and what queues hold looked at,
  4032. // by the helper thread (they take locks a waiter may hold).
  4033. *poke = true;
  4034. }
  4035. LINE_MOVED.notify_all();
  4036. LINE_LANDED.notify_all();
  4037. }
  4038. /// After a submission ran, for copies in the card's memory: the pieces
  4039. /// of the declared ranges that the compare found differing (all of a
  4040. /// range it did not compare) are fetched, with one more wait for the
  4041. /// card, and what shaders wrote in them goes into title memory.
  4042. /// `submitted` is the last value signalled on the fence. `seen` holds
  4043. /// the pieces fetched already since the card was last waited for
  4044. /// (several submissions settled together name the same ones).
  4045. fn card_back(
  4046. &self,
  4047. plan: &CardPlan,
  4048. submitted: &mut u64,
  4049. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4050. ) {
  4051. if plan.ranges.is_empty() {
  4052. return;
  4053. }
  4054. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4055. let Some(work) = work.as_mut() else {
  4056. return;
  4057. };
  4058. // SAFETY: the mapping of the results, which the compare (it has
  4059. // run) wrote.
  4060. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4061. // The pieces to fetch: the range, the offsets in its copy, and
  4062. // where the bytes come down.
  4063. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4064. let mut total = 0u64;
  4065. plan.picked_found(differs);
  4066. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4067. for p in 0..r.span.pieces {
  4068. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4069. continue;
  4070. }
  4071. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4072. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4073. pieces.push((i, lo, hi, total));
  4074. total += (hi - lo) as u64;
  4075. }
  4076. }
  4077. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4078. }
  4079. let mut written = vec![0usize; plan.ranges.len()];
  4080. if !pieces.is_empty() {
  4081. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4082. let size = total.next_multiple_of(16 << 20);
  4083. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4084. }
  4085. let Some((fetched, data, _)) = &work.fetched else {
  4086. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4087. };
  4088. let waiting = std::time::Instant::now();
  4089. let (allocator, list) = &work.fetch;
  4090. // SAFETY: the list's last run was waited for; live buffers; the
  4091. // fence and event are ours, under the submission lock.
  4092. let ran = unsafe {
  4093. (|| -> windows::core::Result<()> {
  4094. allocator.Reset()?;
  4095. list.Reset(allocator, None)?;
  4096. for &(i, lo, hi, at) in &pieces {
  4097. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4098. }
  4099. list.Close()?;
  4100. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4101. self.card_sent();
  4102. *submitted += 1;
  4103. self.queue.Signal(&self.fence, *submitted)?;
  4104. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4105. let was_working = working(false);
  4106. WaitForSingleObject(self.event, INFINITE);
  4107. stood(waiting);
  4108. working(was_working);
  4109. Ok(())
  4110. })()
  4111. };
  4112. if let Err(e) = ran {
  4113. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4114. }
  4115. {
  4116. use crate::shadow::CARD_STATS;
  4117. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4118. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4119. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4120. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4121. }
  4122. if wide_merge() && pieces.len() >= 8 {
  4123. // The pieces are apart from one another (each its own bytes
  4124. // of its copy and of title memory): several at a time.
  4125. let fetched = *data;
  4126. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4127. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4128. let each = pieces.len().div_ceil(8);
  4129. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4130. .chunks(each)
  4131. .map(|chunk| {
  4132. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4133. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4134. let counts = counts.clone();
  4135. Box::new(move || {
  4136. let mut title = Vec::new();
  4137. for (shadow, i, lo, hi, at) in chunk {
  4138. // SAFETY: the mapping of the fetched bytes;
  4139. // the copy into it has run, and the caller
  4140. // waits for this job.
  4141. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4142. let merged = shadow.card_merge(lo, gpu, &mut title);
  4143. shadow.walls_merged(gpu.len(), merged);
  4144. counts[i].fetch_add(merged, Ordering::Relaxed);
  4145. }
  4146. }) as Box<dyn FnOnce() + Send>
  4147. })
  4148. .collect();
  4149. crate::shadow::wide_run(jobs);
  4150. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4151. *written += count.load(Ordering::Relaxed);
  4152. }
  4153. } else {
  4154. let mut title = Vec::new();
  4155. for &(i, lo, hi, at) in &pieces {
  4156. // SAFETY: the mapping of the fetched bytes, `total` of
  4157. // them; the copy into it has run.
  4158. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4159. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4160. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4161. written[i] += merged;
  4162. }
  4163. }
  4164. }
  4165. for (r, written) in plan.ranges.iter().zip(written) {
  4166. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4167. let (from, to) = r.declared;
  4168. #[cfg(feature = "diagnostics")]
  4169. crate::copystat::compared(from, to - from, written);
  4170. let _ = (from, to);
  4171. }
  4172. }
  4173. /// Runs closed lists and waits for them, and with [`late`] for
  4174. /// everything sent to the card before them, which is settled first.
  4175. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4176. let _ = self.submit(runs, false);
  4177. }
  4178. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4179. /// from the title's, go to the card in `order` and are not waited for.
  4180. /// They join the line of flights and are settled, with the others in
  4181. /// the air, at the next point where what they do can be observed
  4182. /// ([`late`] lists those points); their host lists are reset and kept
  4183. /// for reuse then, as a queue does for the lists it ran.
  4184. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4185. if order.is_empty() {
  4186. crate::list::recycle(lists, &order);
  4187. return;
  4188. }
  4189. late_threads();
  4190. let sent = {
  4191. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4192. self.submit(&runs, true)
  4193. };
  4194. let Some((mut submitted, sent)) = sent else {
  4195. // (Not reached: a submission sent ahead always comes back.)
  4196. crate::list::recycle(lists, &order);
  4197. return;
  4198. };
  4199. let told = !sent.writes.is_empty();
  4200. let most = {
  4201. let mut line = line();
  4202. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4203. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4204. *flying += order.len();
  4205. *target = *submitted;
  4206. items.push(Late::Run(Flight {
  4207. number: sent.number,
  4208. fence: *target,
  4209. lists,
  4210. order,
  4211. card: sent.card,
  4212. back: sent.back,
  4213. own: sent.own,
  4214. }));
  4215. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4216. *flying >= late_most()
  4217. };
  4218. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4219. RELAY_MOVED.notify_one();
  4220. if told && !late_writes() {
  4221. self.settle(&mut submitted, WHY_WRITES);
  4222. } else if most && relay_exact() {
  4223. // Until there are fewer, not until there are none.
  4224. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4225. } else if most {
  4226. self.settle(&mut submitted, WHY_MOST);
  4227. } else {
  4228. LINE_MOVED.notify_one();
  4229. }
  4230. drop(submitted);
  4231. land();
  4232. }
  4233. /// Sends `list`, a closed list of ours (the present's copy), as a
  4234. /// flight ([`late_free_present`]): not waited for, settled with the
  4235. /// others. The caller keeps the list and does not reset it before the
  4236. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4237. /// it ran and was waited for after all.
  4238. fn execute_own(&self, list: &HostList) -> u64 {
  4239. late_threads();
  4240. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4241. return 0;
  4242. };
  4243. let number = sent.number;
  4244. {
  4245. let mut line = line();
  4246. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4247. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4248. *flying += 1;
  4249. *target = *submitted;
  4250. items.push(Late::Run(Flight {
  4251. number,
  4252. fence: *target,
  4253. lists: Vec::new(),
  4254. order: Vec::new(),
  4255. card: sent.card,
  4256. back: sent.back,
  4257. own: sent.own,
  4258. }));
  4259. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4260. }
  4261. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4262. LINE_MOVED.notify_one();
  4263. RELAY_MOVED.notify_one();
  4264. drop(submitted);
  4265. number
  4266. }
  4267. /// Waits for the card to run every flight in the air ([`late`]) and
  4268. /// does what they left to do, as [`Host::execute`] does for one
  4269. /// submission after its wait: the pieces their shaders wrote in copies
  4270. /// in the card's memory are fetched and merged (each once), the ranges
  4271. /// they declared in the other copies are compared and copied back
  4272. /// (each byte once, whichever flights declared it), and then, in the
  4273. /// order they were given: their bottom-of-pipe writes and the fence
  4274. /// signals behind them. `submitted` is the submission lock's value;
  4275. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4276. ///
  4277. /// Everything in the air is settled, never the first flights alone:
  4278. /// the merge writes the copies' CPU side, which a flight still on the
  4279. /// card may be writing too.
  4280. fn settle(&self, submitted: &mut u64, why: usize) {
  4281. if !late() {
  4282. return;
  4283. }
  4284. if relay() {
  4285. // Nothing is settled here: the thread that lands flights does
  4286. // it, in order, and this waits until nothing is in the air and
  4287. // nothing is being landed. Every point that settled before
  4288. // comes here, so each still sees title memory, fences and
  4289. // bottom-of-pipe values as after a settle.
  4290. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4291. return;
  4292. }
  4293. let was_working = working(true);
  4294. let mut counted = false;
  4295. loop {
  4296. let items = {
  4297. let mut line = line();
  4298. if line.line.is_empty() {
  4299. line.settling = false;
  4300. break;
  4301. }
  4302. line.settling = true;
  4303. line.written.clear();
  4304. line.lists = 0;
  4305. std::mem::take(&mut line.line)
  4306. };
  4307. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4308. if !counted {
  4309. counted = true;
  4310. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4311. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4312. }
  4313. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4314. if flights > 0 {
  4315. submitting(2, flights);
  4316. let waiting = std::time::Instant::now();
  4317. // SAFETY: the fence and event are ours, under the
  4318. // submission lock; `submitted` is the last value signalled.
  4319. unsafe {
  4320. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4321. Ok(()) => {
  4322. working(false);
  4323. WaitForSingleObject(self.event, INFINITE);
  4324. stood(waiting);
  4325. working(true);
  4326. }
  4327. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4328. }
  4329. }
  4330. let gpu = waiting.elapsed();
  4331. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4332. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4333. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4334. #[cfg(feature = "diagnostics")]
  4335. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4336. format!("{flights} submissions sent ahead, settled together")
  4337. });
  4338. // SAFETY: a plain query.
  4339. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4340. let runs: Vec<&HostList> = items
  4341. .iter()
  4342. .filter_map(|i| match i {
  4343. Late::Run(f) => Some(f),
  4344. _ => None,
  4345. })
  4346. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4347. .collect();
  4348. fail(format_args!(
  4349. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4350. runs.len(),
  4351. self.removal_data(&runs),
  4352. last_notes(&runs)
  4353. ));
  4354. }
  4355. submitting(3, flights);
  4356. let copying = std::time::Instant::now();
  4357. let mut seen = std::collections::HashSet::new();
  4358. let mut back: Vec<Declared> = Vec::new();
  4359. for item in &items {
  4360. let Late::Run(flight) = item else {
  4361. continue;
  4362. };
  4363. if let Some(card) = &flight.card {
  4364. self.card_back(card, submitted, &mut seen);
  4365. }
  4366. for (shadow, ranges) in &flight.back {
  4367. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4368. Some((_, all)) => {
  4369. for range in ranges {
  4370. if !all.contains(range) {
  4371. all.push(*range);
  4372. }
  4373. }
  4374. }
  4375. None => back.push((shadow.clone(), ranges.clone())),
  4376. }
  4377. }
  4378. }
  4379. hand_back(&back);
  4380. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4381. }
  4382. // In the order given: what tells the title the card is done.
  4383. let mut last = 0;
  4384. let mut landed = Vec::new();
  4385. for item in items {
  4386. match item {
  4387. Late::Run(flight) => {
  4388. last = flight.number;
  4389. for &i in &flight.order {
  4390. read_backs(flight.lists[i].host());
  4391. }
  4392. if let Some(card) = flight.card {
  4393. self.card_done(card);
  4394. }
  4395. landed.push((flight.lists, flight.order));
  4396. }
  4397. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4398. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4399. }
  4400. }
  4401. if last > 0 {
  4402. FINISHED.store(last, Ordering::Release);
  4403. bury(last);
  4404. }
  4405. line().landed.extend(landed);
  4406. }
  4407. if counted {
  4408. self.log_messages();
  4409. submitting(0, 0);
  4410. // What was settled may be what a queue stands at, and the
  4411. // caller may not be one that looks (a read-back, a present).
  4412. if why != WHY_CARD_DONE {
  4413. line().poke = true;
  4414. LINE_MOVED.notify_one();
  4415. }
  4416. }
  4417. working(was_working);
  4418. }
  4419. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4420. /// copies, which flights may be writing and the title wrote too
  4421. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4422. /// those of the submission's one asking, which is made again.
  4423. ///
  4424. /// With [`card_steps`] only the flights that declared them: a range of
  4425. /// a copy nobody declared any more is refreshed like any other. What
  4426. /// they landed is title memory written, so everything is asked and
  4427. /// looked at again; what is left after three times waits as before.
  4428. fn settle_stale(
  4429. &self,
  4430. submitted: &mut u64,
  4431. runs: &[&HostList],
  4432. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4433. ranges: &[(usize, usize)],
  4434. ) {
  4435. if relay_exact() && card_steps::stage() > 0 {
  4436. for _ in 0..3 {
  4437. #[cfg(feature = "diagnostics")]
  4438. blame_stale(&stale);
  4439. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4440. crate::watch::ask_once(ranges);
  4441. stale = stale_under_flights(runs);
  4442. if stale.is_empty() {
  4443. return;
  4444. }
  4445. }
  4446. }
  4447. #[cfg(feature = "diagnostics")]
  4448. blame_stale(&stale);
  4449. self.settle(submitted, WHY_STALE);
  4450. crate::watch::ask_once(ranges);
  4451. }
  4452. /// [`Host::execute`], or with `late` the first half of
  4453. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4454. /// to be done once they have run comes back with the submission lock
  4455. /// still held.
  4456. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4457. #[cfg(feature = "diagnostics")]
  4458. let called = std::time::Instant::now();
  4459. #[cfg(feature = "diagnostics")]
  4460. crate::copystat::submission_begins();
  4461. // One submission at a time from preparation to copy-back: snapshots
  4462. // and the ranges shaders write are per host copy, not per submission.
  4463. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4464. let was_working = working(true);
  4465. submitting(1, runs.len());
  4466. // Flights in the air ([`late`]): a submission that is waited for
  4467. // settles them first, one sent ahead only if preparing it reads
  4468. // what they write.
  4469. // Or the reads are done on the card, behind the flights.
  4470. let own = if late { self.card_steps(runs) } else { None };
  4471. if !late {
  4472. self.settle(&mut submitted, WHY_SYNC);
  4473. } else if own.is_none()
  4474. && let Some(why) = late_blocked(runs)
  4475. {
  4476. if relay_exact() && why == WHY_READ {
  4477. // Only until the flights that may write what is read have
  4478. // landed: their copy-back's end, not the card's other work.
  4479. relay_wait(why, |line| {
  4480. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4481. });
  4482. } else {
  4483. self.settle(&mut submitted, why);
  4484. }
  4485. }
  4486. // That list runs first, and is one of the submission's from here on.
  4487. let with: Vec<&HostList>;
  4488. let runs = match &own {
  4489. Some(own) => {
  4490. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4491. &with[..]
  4492. }
  4493. None => runs,
  4494. };
  4495. let behind = late && flying();
  4496. // Before this submission counts as started: what the sweep lets go
  4497. // of is named by no list, and nothing runs now (behind flights the
  4498. // sweep waits for a submission that finds none in the air: there is
  4499. // one at every present).
  4500. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4501. if !behind {
  4502. if upcheck::on() {
  4503. upcheck::at_rest(self);
  4504. }
  4505. sweep();
  4506. SWEPT.store(now_ms(), Ordering::Relaxed);
  4507. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4508. // With the present sent ahead nothing else brings a moment
  4509. // with nothing in the air: one is made for the sweep.
  4510. self.settle(&mut submitted, WHY_SYNC);
  4511. if upcheck::on() {
  4512. upcheck::at_rest(self);
  4513. }
  4514. sweep();
  4515. SWEPT.store(now_ms(), Ordering::Relaxed);
  4516. }
  4517. let behind = late && flying();
  4518. // The slots that waited for a texture's host copy, before the
  4519. // lists that may read them run.
  4520. crate::descriptor::make_waiting();
  4521. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4522. // The ranges shaders write are counted for it (with the relay).
  4523. crate::shadow::preparing(this_submission);
  4524. let started = std::time::Instant::now();
  4525. #[cfg(feature = "diagnostics")]
  4526. let lock = (started - called).as_micros() as u64;
  4527. #[cfg(feature = "diagnostics")]
  4528. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4529. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4530. // Where each run's lists start in `lists`.
  4531. let mut firsts = Vec::with_capacity(runs.len());
  4532. let mut batch = Batch::default();
  4533. #[cfg(feature = "diagnostics")]
  4534. let split = Split::begin();
  4535. // The time a settle of flights takes inside this preparing: the
  4536. // wait for the card and the copy-back have their own places on the
  4537. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4538. let mut settled = std::time::Duration::ZERO;
  4539. // One write-watch asking for everything the submission refreshes
  4540. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4541. if crate::watch::once() {
  4542. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  4543. for list in runs {
  4544. for step in &list.deferred().copies {
  4545. if let Step::Refresh(shadow, address, len) = step
  4546. && shadow.asked_ahead()
  4547. {
  4548. let span = spans
  4549. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4550. .or_insert((*address, *address + *len));
  4551. *span = (span.0.min(*address), span.1.max(*address + *len));
  4552. }
  4553. }
  4554. }
  4555. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4556. #[cfg(feature = "diagnostics")]
  4557. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  4558. crate::watch::ask_once(&ranges);
  4559. #[cfg(feature = "diagnostics")]
  4560. split.part(0);
  4561. // Behind flights: the title wrote memory that a flight's shaders
  4562. // may write too, and this submission refreshes it. The flights
  4563. // are settled, and the asking made again: the copy-back wrote
  4564. // title memory, which other copies of it must see.
  4565. if upcheck::on() {
  4566. upcheck::order(runs);
  4567. if behind {
  4568. upcheck::reads(runs);
  4569. }
  4570. }
  4571. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  4572. if !stale.is_empty() {
  4573. let settling = std::time::Instant::now();
  4574. self.settle_stale(&mut submitted, runs, stale, &ranges);
  4575. settled += settling.elapsed();
  4576. }
  4577. } else if behind && !stale_under_flights(runs).is_empty() {
  4578. let settling = std::time::Instant::now();
  4579. self.settle(&mut submitted, WHY_STALE);
  4580. settled += settling.elapsed();
  4581. }
  4582. #[cfg(feature = "diagnostics")]
  4583. split.part(1);
  4584. for list in runs {
  4585. list.run_deferred(&mut batch, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4586. firsts.push(lists.len());
  4587. if let Some(prelude) = list.prelude() {
  4588. lists.push(Some(prelude));
  4589. }
  4590. lists.push(list.list.cast().ok());
  4591. }
  4592. batch.flush();
  4593. crate::watch::ask_once_end();
  4594. #[cfg(feature = "diagnostics")]
  4595. split.part(2);
  4596. // The snapshots of the ranges shaders may write, if they were left
  4597. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4598. // lists have not gone to the card.
  4599. {
  4600. #[cfg(feature = "diagnostics")]
  4601. let snapshots = std::time::Instant::now();
  4602. crate::shadow::take_snapshots();
  4603. #[cfg(feature = "diagnostics")]
  4604. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4605. }
  4606. #[cfg(feature = "diagnostics")]
  4607. split.part(3);
  4608. // Copies in the card's memory: what changed on their CPU side goes
  4609. // up ahead of the lists, and a compare of what the shaders may
  4610. // write follows them in the same submission.
  4611. let flown = late && relay();
  4612. if flown && self.card_results_low() {
  4613. let settling = std::time::Instant::now();
  4614. self.settle(&mut submitted, WHY_MOST);
  4615. settled += settling.elapsed();
  4616. }
  4617. // What shaders may write through views they pick: last, so that no
  4618. // refresh of this submission leaves it alone.
  4619. let picked = crate::picked::declare(runs);
  4620. for (shadow, at, len) in &picked.written {
  4621. shadow.writing(*at, *len);
  4622. }
  4623. let card = self.card_before(runs, &picked, flown);
  4624. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4625. lists.push(Some(check));
  4626. }
  4627. #[cfg(feature = "diagnostics")]
  4628. split.part(4);
  4629. let prepared = std::time::Instant::now();
  4630. if late {
  4631. *submitted += 1;
  4632. // SAFETY: closed lists; the fence is ours.
  4633. let signalled = unsafe {
  4634. self.queue.ExecuteCommandLists(&lists);
  4635. self.queue.Signal(&self.fence, *submitted)
  4636. };
  4637. self.card_sent();
  4638. if let Err(e) = signalled {
  4639. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4640. }
  4641. #[cfg(feature = "diagnostics")]
  4642. split.part(5);
  4643. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4644. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4645. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4646. submitting(0, 0);
  4647. #[cfg(feature = "diagnostics")]
  4648. crate::copystat::submission_ends(lock);
  4649. let sent = Sent {
  4650. number: this_submission,
  4651. card,
  4652. back,
  4653. own,
  4654. writes,
  4655. };
  4656. working(was_working);
  4657. return Some((submitted, sent));
  4658. }
  4659. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4660. #[cfg(feature = "diagnostics")]
  4661. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4662. firsts
  4663. .iter()
  4664. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4665. .map(|(&a, &b)| &lists[a..b])
  4666. .collect()
  4667. } else {
  4668. vec![&lists[..]]
  4669. };
  4670. #[cfg(not(feature = "diagnostics"))]
  4671. let groups = [&lists[..]];
  4672. submitting(2, runs.len());
  4673. for (i, group) in groups.iter().enumerate() {
  4674. *submitted += 1;
  4675. let started = std::time::Instant::now();
  4676. // SAFETY: closed lists; the fence and event are ours.
  4677. unsafe {
  4678. self.queue.ExecuteCommandLists(group);
  4679. self.card_sent();
  4680. let waited = self
  4681. .queue
  4682. .Signal(&self.fence, *submitted)
  4683. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4684. match waited {
  4685. Ok(()) => {
  4686. working(false);
  4687. WaitForSingleObject(self.event, INFINITE);
  4688. stood(started);
  4689. working(true);
  4690. }
  4691. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4692. }
  4693. }
  4694. // With timing on each group is one of `runs` (and the compare
  4695. // of copies in the card's memory, with the last): every
  4696. // command's time on the card goes to the sums by pipeline.
  4697. #[cfg(feature = "diagnostics")]
  4698. if timing() {
  4699. // SAFETY: a plain query.
  4700. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4701. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4702. crate::copystat::command_took(&op, ms);
  4703. }
  4704. }
  4705. // A submission of one list was never named here (`groups.len()
  4706. // > 1` was the test): the two 50 ms lists of the gameplay
  4707. // frame, each a submission of its own, printed nothing.
  4708. #[cfg(feature = "diagnostics")]
  4709. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4710. // SAFETY: a plain query.
  4711. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4712. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4713. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4714. for (ms, op) in runs[i].slowest(frequency, 6) {
  4715. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4716. }
  4717. }
  4718. let _ = (i, started);
  4719. }
  4720. let _ = &firsts;
  4721. FINISHED.store(this_submission, Ordering::Release);
  4722. bury(this_submission);
  4723. let gpu = prepared.elapsed();
  4724. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4725. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4726. #[cfg(feature = "diagnostics")]
  4727. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4728. let pipelines: std::collections::BTreeSet<String> = runs
  4729. .iter()
  4730. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4731. .collect();
  4732. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  4733. text.chars().take(1200).collect()
  4734. });
  4735. // The host resets a device whose submission runs for about 2 s.
  4736. if gpu > std::time::Duration::from_millis(250) {
  4737. let pipelines: std::collections::BTreeSet<String> = runs
  4738. .iter()
  4739. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4740. .collect();
  4741. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  4742. }
  4743. // SAFETY: a plain query.
  4744. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4745. fail(format_args!(
  4746. "host GPU device removed after a submission of {} lists{}{}",
  4747. runs.len(),
  4748. self.removal_data(runs),
  4749. last_notes(runs)
  4750. ));
  4751. }
  4752. submitting(3, runs.len());
  4753. // What shaders wrote goes back before the bottom-of-pipe writes,
  4754. // which tell the title the GPU is done; each range once per
  4755. // submission, however many dispatches declared it (the world's
  4756. // passes declare the same big ranges dozens of times).
  4757. let copying = std::time::Instant::now();
  4758. // For copies in the card's memory the compare has run there: the
  4759. // pieces that differ are fetched and merged.
  4760. if let Some(card) = &card {
  4761. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  4762. }
  4763. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4764. hand_back(&back);
  4765. if let Some(card) = card {
  4766. self.card_done(card);
  4767. }
  4768. #[cfg(feature = "diagnostics")]
  4769. if !back.is_empty() {
  4770. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  4771. }
  4772. // Nothing of this submission goes back to the title: no range of
  4773. // shader writes, no value written when it is done. The wait for
  4774. // such a one is only for order and for what the card still holds.
  4775. #[cfg(feature = "diagnostics")]
  4776. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  4777. use crate::copystat::{C, add};
  4778. add(C::NothingBack, 1);
  4779. add(C::NothingBackUs, gpu.as_micros() as u64);
  4780. }
  4781. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4782. for list in runs {
  4783. // Read backs first: a value written at the bottom of the pipe
  4784. // may be what tells the title that they are there.
  4785. read_backs(list);
  4786. for &(at, what, bytes) in &list.deferred().writes {
  4787. what.write(at as *mut u8, bytes);
  4788. }
  4789. }
  4790. self.log_messages();
  4791. submitting(0, 0);
  4792. #[cfg(feature = "diagnostics")]
  4793. crate::copystat::submission_ends(lock);
  4794. // With the relay: nothing is in the air now, so no fetch still to
  4795. // be merged is older than the sends to card copies so far, and
  4796. // their notes can go.
  4797. if relay() {
  4798. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  4799. }
  4800. working(was_working);
  4801. None
  4802. }
  4803. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  4804. /// it lies in (by the names we give them) or the title memory copy just
  4805. /// below it; for each list that did not finish, the command it stopped
  4806. /// at and what the draws and dispatches in flight there run (or, in
  4807. /// lists that never started, the pipelines they bind).
  4808. fn removal_data(&self, runs: &[&HostList]) -> String {
  4809. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  4810. return String::new();
  4811. };
  4812. let mut text = String::new();
  4813. let mut fault_va = None;
  4814. // SAFETY: the outputs are the runtime's, valid while the device
  4815. // lives; nodes are walked as linked, histories have their counts.
  4816. unsafe {
  4817. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  4818. && fault.PageFaultVA != 0
  4819. {
  4820. let va = fault.PageFaultVA;
  4821. fault_va = Some(va);
  4822. text.push_str(&format!("; page fault at {va:#x}"));
  4823. for (what, head) in [
  4824. ("inside", fault.pHeadExistingAllocationNode),
  4825. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  4826. ] {
  4827. let mut names = Vec::new();
  4828. let mut node = head;
  4829. while let Some(n) = node.as_ref()
  4830. && names.len() < 8
  4831. {
  4832. let name = if n.ObjectNameW.is_null() {
  4833. "unnamed".to_owned()
  4834. } else {
  4835. n.ObjectNameW.to_string().unwrap_or_default()
  4836. };
  4837. names.push(format!("{name} (type {})", n.AllocationType.0));
  4838. node = n.pNext;
  4839. }
  4840. if !names.is_empty() {
  4841. text.push_str(&format!("; {what} {names:?}"));
  4842. }
  4843. }
  4844. text.push_str(&crate::shadow::near(va));
  4845. text.push_str(&crate::descriptor::host::near_heaps(va));
  4846. }
  4847. // The plain output: the extended one (with marker texts) came
  4848. // back without stopped lists on this host.
  4849. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  4850. Ok(crumbs) => crumbs,
  4851. Err(e) => {
  4852. text.push_str(&format!("; no breadcrumbs ({e})"));
  4853. return text;
  4854. }
  4855. };
  4856. // Every list's progress (done/count), in the runtime's order.
  4857. let mut progress = Vec::new();
  4858. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  4859. while let Some(p) = node.as_ref() {
  4860. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4861. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  4862. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  4863. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  4864. node = p.pNext;
  4865. }
  4866. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  4867. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  4868. while let Some(p) = plain.as_ref() {
  4869. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4870. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  4871. let history =
  4872. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  4873. text.push_str(&format!(
  4874. "; a list stopped at command {done} of {} (op {})",
  4875. p.BreadcrumbCount, history[done as usize].0
  4876. ));
  4877. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  4878. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  4879. // The k-th marker command is the k-th note.
  4880. #[cfg(feature = "diagnostics")]
  4881. let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| {
  4882. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  4883. history
  4884. .iter()
  4885. .enumerate()
  4886. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  4887. .zip(notes.iter())
  4888. .map(|((at, _), (note, range))| {
  4889. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  4890. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  4891. })
  4892. .collect()
  4893. });
  4894. #[cfg(not(feature = "diagnostics"))]
  4895. let markers: Vec<(u32, String)> = Vec::new();
  4896. #[cfg(not(feature = "diagnostics"))]
  4897. let _ = fault_va;
  4898. if done > 0 {
  4899. text.push_str(&in_flight(history, &markers, done as usize));
  4900. } else if let Some(r) = run {
  4901. let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  4902. text.push_str(&format!(", its pipelines {pipelines:?}"));
  4903. }
  4904. }
  4905. plain = p.pNext;
  4906. }
  4907. }
  4908. text
  4909. }
  4910. /// Moves the debug layer's messages into our log; returns the first
  4911. /// error among them.
  4912. pub(crate) fn log_messages(&self) -> Option<String> {
  4913. let Some(queue) = &self.messages else {
  4914. return None;
  4915. };
  4916. let mut first_error = None;
  4917. // SAFETY: each message is read into a buffer of the size the queue
  4918. // reports, then the queue is emptied.
  4919. unsafe {
  4920. for i in 0..queue.GetNumStoredMessages() {
  4921. let mut size = 0;
  4922. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  4923. continue;
  4924. }
  4925. let mut buffer = vec![0u64; size.div_ceil(8)];
  4926. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  4927. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  4928. let m = &*message;
  4929. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  4930. let text = String::from_utf8_lossy(text);
  4931. let text = text.trim_end_matches('\0');
  4932. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  4933. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  4934. first_error = Some(text.to_owned());
  4935. }
  4936. }
  4937. }
  4938. queue.ClearStoredMessages();
  4939. }
  4940. first_error
  4941. }
  4942. /// A host render target view of `resource`, valid until it is recorded.
  4943. pub(crate) fn rtv(
  4944. &self,
  4945. resource: Option<&ID3D12Resource>,
  4946. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  4947. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4948. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4949. // SAFETY: a slot of our heap and a live resource, or none with a
  4950. // description (a typed null view).
  4951. unsafe {
  4952. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  4953. handle.ptr += (slot * self.rtv_size) as usize;
  4954. self.device
  4955. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  4956. handle
  4957. }
  4958. }
  4959. /// A host depth view of `resource`, valid until it is recorded.
  4960. pub(crate) fn dsv(
  4961. &self,
  4962. resource: &ID3D12Resource,
  4963. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  4964. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4965. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4966. // SAFETY: a slot of our heap and a live resource.
  4967. unsafe {
  4968. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  4969. handle.ptr += (slot * self.dsv_size) as usize;
  4970. self.device
  4971. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  4972. handle
  4973. }
  4974. }
  4975. }
  4976. impl HostList {
  4977. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  4978. #[cfg(feature = "diagnostics")]
  4979. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  4980. if !timing() {
  4981. return None;
  4982. }
  4983. self.stamps
  4984. .get_or_init(|| {
  4985. let device = &host()?.device;
  4986. let mut heap: Option<ID3D12QueryHeap> = None;
  4987. let mut back: Option<ID3D12Resource> = None;
  4988. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  4989. let desc = D3D12_RESOURCE_DESC {
  4990. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  4991. Width: u64::from(STAMPS) * 8,
  4992. Height: 1,
  4993. DepthOrArraySize: 1,
  4994. MipLevels: 1,
  4995. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  4996. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  4997. ..Default::default()
  4998. };
  4999. // SAFETY: plain object creation.
  5000. unsafe {
  5001. device
  5002. .CreateQueryHeap(
  5003. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  5004. &mut heap,
  5005. )
  5006. .ok()?;
  5007. device
  5008. .CreateCommittedResource(
  5009. &readback,
  5010. D3D12_HEAP_FLAG_NONE,
  5011. &desc,
  5012. D3D12_RESOURCE_STATE_COPY_DEST,
  5013. None,
  5014. &mut back,
  5015. )
  5016. .ok()?;
  5017. }
  5018. Some((heap?, back?))
  5019. })
  5020. .as_ref()
  5021. }
  5022. /// The noted commands that took longest on the GPU, longest first, as
  5023. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  5024. #[cfg(feature = "diagnostics")]
  5025. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  5026. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  5027. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  5028. return Vec::new();
  5029. };
  5030. let mut data = std::ptr::null_mut();
  5031. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  5032. // SAFETY: a read-back buffer the finished list resolved into.
  5033. let stamps: Vec<u64> = unsafe {
  5034. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  5035. return Vec::new();
  5036. }
  5037. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  5038. back.Unmap(0, None);
  5039. s
  5040. };
  5041. let mut times: Vec<(f64, String)> = (0..count)
  5042. .map(|i| {
  5043. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5044. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5045. })
  5046. .collect();
  5047. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5048. times.truncate(n);
  5049. times
  5050. }
  5051. pub(crate) fn close(&self) {
  5052. self.twins_to_depth();
  5053. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5054. if let Some((scratch, _)) = scratch {
  5055. self.indirect_common(&scratch);
  5056. }
  5057. self.batches_common();
  5058. self.card_budget_out();
  5059. #[cfg(feature = "diagnostics")]
  5060. if let Some((heap, back)) = self.stamps() {
  5061. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5062. // SAFETY: an open list, our heap and read-back buffer.
  5063. unsafe {
  5064. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5065. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5066. }
  5067. }
  5068. // SAFETY: our list.
  5069. if let Err(e) = unsafe { self.list.Close() } {
  5070. fail(format_args!(
  5071. "a host command list did not close ({e}): a command recorded into it was invalid"
  5072. ));
  5073. }
  5074. }
  5075. /// Only after the list's last submission finished (every one is waited
  5076. /// for).
  5077. pub(crate) fn reset(&self) {
  5078. #[cfg(feature = "diagnostics")]
  5079. let started = std::time::Instant::now();
  5080. self._alive.used();
  5081. *self.deferred() = Deferred::default();
  5082. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5083. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5084. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5085. #[cfg(feature = "diagnostics")]
  5086. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5087. {
  5088. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5089. (scratch.current, scratch.used) = (0, 0);
  5090. // Every submission of the list has run: nothing reads its
  5091. // scratch memory any more, and the next list to ask takes it.
  5092. if scratch_pool() {
  5093. give_chunks(std::mem::take(&mut scratch.chunks));
  5094. }
  5095. }
  5096. // SAFETY: the list is not executing.
  5097. let reset = unsafe {
  5098. self.allocator
  5099. .Reset()
  5100. .and_then(|()| self.list.Reset(&self.allocator, None))
  5101. };
  5102. if let Err(e) = reset {
  5103. fail(format_args!("a host command list did not reset ({e})"));
  5104. }
  5105. #[cfg(feature = "diagnostics")]
  5106. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5107. }
  5108. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5109. /// list: the host texture and the state it leaves, if that is a change.
  5110. /// The list's first use of a texture records nothing: its prelude brings
  5111. /// the texture there at submission.
  5112. pub(crate) fn transition(
  5113. &self,
  5114. resource: crate::object::This,
  5115. wanted: u32,
  5116. ) -> Option<(&'static ID3D12Resource, u32)> {
  5117. let texture = crate::resource::host_resource(resource)?;
  5118. let copy = crate::resource::host_copy(resource)?;
  5119. let wanted = legal_state(texture, wanted);
  5120. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5121. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5122. std::collections::hash_map::Entry::Vacant(v) => {
  5123. v.insert((wanted, wanted, copy));
  5124. None
  5125. }
  5126. std::collections::hash_map::Entry::Occupied(mut o) => {
  5127. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5128. (before != wanted).then_some((texture, before))
  5129. }
  5130. }
  5131. }
  5132. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5133. /// as [`HostList::transition`] does a title resource's host copy, and
  5134. /// records the barrier: for textures that are not a title resource's
  5135. /// host copy (colour twins) and for the copies between the two.
  5136. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5137. let wanted = legal_state(&copy.texture, wanted);
  5138. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5139. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5140. std::collections::hash_map::Entry::Vacant(v) => {
  5141. v.insert((wanted, wanted, copy.clone()));
  5142. None
  5143. }
  5144. std::collections::hash_map::Entry::Occupied(mut o) => {
  5145. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5146. (before != wanted).then_some(before)
  5147. }
  5148. };
  5149. drop(states);
  5150. if let Some(before) = before {
  5151. let barrier = transition(
  5152. &copy.texture,
  5153. D3D12_RESOURCE_STATES(before as i32),
  5154. D3D12_RESOURCE_STATES(wanted as i32),
  5155. );
  5156. // SAFETY: an open list and a live texture.
  5157. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5158. }
  5159. }
  5160. /// A use of title texture `resource` about to be recorded, if it is a
  5161. /// depth texture with a colour twin (false if it is not): of the twin
  5162. /// (`colour`: unordered access) or of the depth texture (depth target,
  5163. /// clear, shader read, copy, resolve), writing it or only reading. The
  5164. /// side used is first brought up to date: by a copy recorded here if
  5165. /// this list wrote the other side since, by the list's prelude if the
  5166. /// list uses the side as it finds it. The twin is left in the
  5167. /// unordered access state; the caller moves the depth texture to the
  5168. /// state its use needs, as for any texture. A twin still ahead when the
  5169. /// list closes is copied then (`twins_to_depth`).
  5170. /// shortcut: every depth target bound for a draw counts as written
  5171. /// (also when the draw only tests), and every unordered access view a
  5172. /// shader names as written; views a shader picks from the heap by a
  5173. /// computed index are not seen here at all.
  5174. pub(crate) fn twin_use(
  5175. &self,
  5176. resource: crate::object::This,
  5177. colour: bool,
  5178. write: bool,
  5179. ) -> bool {
  5180. const UNORDERED_ACCESS: u32 = 0x8;
  5181. // Asked for every texture a draw reads: most have no twin.
  5182. let Some(twin) = crate::resource::twin(resource) else {
  5183. return false;
  5184. };
  5185. let Some(depth) = crate::resource::host_copy(resource) else {
  5186. return false;
  5187. };
  5188. let side = usize::from(colour);
  5189. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5190. let u = twins
  5191. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5192. .or_insert_with(|| TwinUse {
  5193. depth: depth.clone(),
  5194. twin: twin.clone(),
  5195. needs: [false; 2],
  5196. behind: [None; 2],
  5197. writing: false,
  5198. late: false,
  5199. });
  5200. let copy = match u.behind[side] {
  5201. Some(behind) => behind,
  5202. None => {
  5203. u.needs[side] = true;
  5204. false
  5205. }
  5206. };
  5207. u.behind[side] = Some(false);
  5208. match (write, colour) {
  5209. // Shaders write the twin when the draw or dispatch runs: what
  5210. // the same one reads of the depth texture is prepared before
  5211. // (`twins_written`).
  5212. (true, true) => u.writing = true,
  5213. (true, false) => u.behind[1] = Some(true),
  5214. (false, _) => {}
  5215. }
  5216. // shortcut: the depth plane's twin is not drawn into the plane
  5217. // here: the pass sets a pipeline and a target of ours, which a list
  5218. // still recording the title's commands cannot take. This use sees
  5219. // the plane as it was; the pass runs when the list closes
  5220. // (`twins_to_depth`). Counted.
  5221. if copy && !colour && twin.plane.is_some() {
  5222. u.late = true;
  5223. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5224. }
  5225. drop(twins);
  5226. if copy {
  5227. self.twin_copy(&depth, &twin, colour);
  5228. } else if colour {
  5229. self.settle(&twin.colour, UNORDERED_ACCESS);
  5230. }
  5231. // The depth plane's twin is written through unordered access too.
  5232. if colour && let Some(plane) = &twin.plane {
  5233. self.settle(plane, UNORDERED_ACCESS);
  5234. }
  5235. true
  5236. }
  5237. /// Records the pass that draws the twin of the depth plane of `depth`
  5238. /// into the plane, if `twin` has one, with the moves to the states the
  5239. /// pass needs; the twin is left in the unordered access state. Only
  5240. /// for a list that records nothing of the title's afterwards
  5241. /// (`record_plane_pass`).
  5242. fn pass_plane(
  5243. &self,
  5244. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5245. twin: &crate::resource::Twin,
  5246. ) {
  5247. const UNORDERED_ACCESS: u32 = 0x8;
  5248. const DEPTH_WRITE: u32 = 0x10;
  5249. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5250. let Some(plane) = &twin.plane else { return };
  5251. self.settle(depth, DEPTH_WRITE);
  5252. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5253. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5254. self.settle(plane, UNORDERED_ACCESS);
  5255. }
  5256. /// Records the copy of a depth texture into its colour twin (`colour`)
  5257. /// or of the twin into the depth texture, with the moves to the copy
  5258. /// states. The twin is left in the unordered access state.
  5259. fn twin_copy(
  5260. &self,
  5261. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5262. twin: &crate::resource::Twin,
  5263. colour: bool,
  5264. ) {
  5265. const UNORDERED_ACCESS: u32 = 0x8;
  5266. const COPY_DEST: u32 = 0x400;
  5267. const COPY_SOURCE: u32 = 0x800;
  5268. let (from, to) = if colour {
  5269. (depth, &twin.colour)
  5270. } else {
  5271. (&twin.colour, depth)
  5272. };
  5273. self.settle(from, COPY_SOURCE);
  5274. self.settle(to, COPY_DEST);
  5275. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5276. self.settle(&twin.colour, UNORDERED_ACCESS);
  5277. }
  5278. /// Before the list closes: the depth textures whose twins it wrote last
  5279. /// are given what was written, and left readable by shaders. Shaders
  5280. /// that pick a view from the heap by a computed index are not seen by
  5281. /// `twin_use` and read the depth texture in lists that never name it
  5282. /// (in a captured frame of the title no table names a shadow
  5283. /// map for reading but the pass that fills the next one).
  5284. fn twins_to_depth(&self) {
  5285. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5286. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5287. let written: Vec<_> = twins
  5288. .values_mut()
  5289. .filter(|u| u.behind[0] == Some(true) || u.late)
  5290. .map(|u| {
  5291. // Not copied again if the list copied since the last write
  5292. // and only the depth plane's pass is left.
  5293. let copy = u.behind[0] == Some(true);
  5294. u.behind[0] = Some(false);
  5295. u.late = false;
  5296. (u.depth.clone(), u.twin.clone(), copy)
  5297. })
  5298. .collect();
  5299. drop(twins);
  5300. for (depth, twin, copy) in &written {
  5301. if *copy {
  5302. self.twin_copy(depth, twin, false);
  5303. }
  5304. // Nothing of the title's is recorded after this: the pass may
  5305. // leave its own pipeline and target set.
  5306. self.pass_plane(depth, twin);
  5307. self.settle(depth, SHADER_RESOURCE);
  5308. }
  5309. }
  5310. /// The draw or dispatch just prepared is recorded: the twins it writes
  5311. /// now hold what their depth textures lack.
  5312. pub(crate) fn twins_written(&self) {
  5313. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5314. for u in twins.values_mut().filter(|u| u.writing) {
  5315. u.writing = false;
  5316. u.behind[0] = Some(true);
  5317. }
  5318. }
  5319. /// At submission: the list that moves each texture this list uses from
  5320. /// its real state to the one the list starts with; the textures' real
  5321. /// states become those the list ends with. For depth textures with a
  5322. /// colour twin it first copies the side the list uses as it finds it
  5323. /// from the other, if a list submitted earlier left it behind.
  5324. fn prelude(&self) -> Option<ID3D12CommandList> {
  5325. const COPY_DEST: u32 = 0x400;
  5326. const COPY_SOURCE: u32 = 0x800;
  5327. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5328. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5329. // The copies (depth texture, twin, whether into the twin); the
  5330. // sides are then as this list leaves them.
  5331. let mut syncs = Vec::new();
  5332. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5333. for u in twins.values() {
  5334. let real = u.twin.behind.load(Ordering::Relaxed);
  5335. let mut behind = [real & 1 != 0, real & 2 != 0];
  5336. for side in [0, 1] {
  5337. if u.needs[side] && behind[side] {
  5338. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5339. behind = [false; 2];
  5340. }
  5341. }
  5342. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5343. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5344. u.twin.behind.store(left, Ordering::Relaxed);
  5345. }
  5346. drop(twins);
  5347. // A copy runs with its textures in the copy states: each moves
  5348. // there from its real state, and from there to the state the list
  5349. // starts with (back to its real state if the list does not use it).
  5350. let mut to_copy = Vec::new();
  5351. let mut barriers = Vec::new();
  5352. let mut copying = std::collections::HashMap::new();
  5353. for (depth, twin, colour) in &syncs {
  5354. let (from, to) = if *colour {
  5355. (depth, &twin.colour)
  5356. } else {
  5357. (&twin.colour, depth)
  5358. };
  5359. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  5360. let key = std::sync::Arc::as_ptr(texture) as usize;
  5361. let real = texture.state.load(Ordering::Relaxed);
  5362. copying.insert(key, state);
  5363. if real != state {
  5364. to_copy.push(transition(
  5365. &texture.texture,
  5366. host_state(real),
  5367. host_state(state),
  5368. ));
  5369. if !states.contains_key(&key) {
  5370. barriers.push(transition(
  5371. &texture.texture,
  5372. host_state(state),
  5373. host_state(real),
  5374. ));
  5375. }
  5376. }
  5377. }
  5378. }
  5379. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5380. let real = copy.state.swap(*last, Ordering::Relaxed);
  5381. let real = copying.get(key).copied().unwrap_or(real);
  5382. (real != *first)
  5383. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5384. }));
  5385. if barriers.is_empty() && syncs.is_empty() {
  5386. return None;
  5387. }
  5388. let Some((allocator, list)) = self
  5389. .prelude
  5390. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5391. .as_ref()
  5392. else {
  5393. fail(format_args!("no host list for a state prelude"));
  5394. };
  5395. // SAFETY: the prelude is not executing (every submission is waited
  5396. // for); the textures are live.
  5397. let recorded = unsafe {
  5398. allocator.Reset().and_then(|()| {
  5399. list.Reset(allocator, None)?;
  5400. if !to_copy.is_empty() {
  5401. list.ResourceBarrier(&to_copy);
  5402. }
  5403. for (depth, twin, colour) in &syncs {
  5404. record_twin_copy(list, &depth.texture, twin, *colour);
  5405. }
  5406. if !barriers.is_empty() {
  5407. list.ResourceBarrier(&barriers);
  5408. }
  5409. list.Close()
  5410. })
  5411. };
  5412. if let Err(e) = recorded {
  5413. fail(format_args!("a host state prelude did not record ({e})"));
  5414. }
  5415. list.cast().ok()
  5416. }
  5417. /// Notes what the command about to be recorded does, as a marker
  5418. /// command whose text the list keeps (diagnostics, with device-removed
  5419. /// data on): the report pairs the breadcrumbs' marker commands with the
  5420. /// texts in order and names the commands a fault stopped among.
  5421. #[cfg(feature = "diagnostics")]
  5422. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5423. self.note(what, None);
  5424. }
  5425. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5426. /// `(address, bytes)`: the report places the faulting address in it.
  5427. #[cfg(feature = "diagnostics")]
  5428. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5429. self.note(what, Some(range));
  5430. }
  5431. #[cfg(feature = "diagnostics")]
  5432. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5433. if !dred_on() {
  5434. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5435. return;
  5436. }
  5437. {
  5438. let started = std::time::Instant::now();
  5439. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5440. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5441. // SAFETY: an open list and our query heap.
  5442. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5443. }
  5444. let what = what();
  5445. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5446. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5447. const UNICODE: u32 = 0;
  5448. // SAFETY: an open list; the marker is copied when recorded.
  5449. unsafe {
  5450. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5451. };
  5452. self.notes
  5453. .lock()
  5454. .unwrap_or_else(|e| e.into_inner())
  5455. .push((what, range));
  5456. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5457. }
  5458. }
  5459. /// Whether nothing recorded since the list was opened does any work:
  5460. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5461. /// upload or resolve (they defer a step or move a texture's state), no
  5462. /// bottom-of-pipe write. State set on the list does not count.
  5463. pub(crate) fn untouched(&self) -> bool {
  5464. {
  5465. let deferred = self.deferred();
  5466. if !(deferred.copies.is_empty()
  5467. && deferred.uploads.is_empty()
  5468. && deferred.kept.is_empty()
  5469. && deferred.textures.is_empty()
  5470. && deferred.writes.is_empty()
  5471. && deferred.backs.is_empty())
  5472. {
  5473. return false;
  5474. }
  5475. }
  5476. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5477. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5478. }
  5479. /// Notes a pipeline the list binds.
  5480. pub(crate) fn used_pipeline(&self, name: &str) {
  5481. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5482. if !pipelines.contains(name) {
  5483. pipelines.insert(name.to_owned());
  5484. }
  5485. }
  5486. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5487. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5488. }
  5489. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5490. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5491. let mut deferred = self.deferred();
  5492. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5493. // A copy that goes on where the one recorded just before it ended,
  5494. // source and destination both: with `join_copies` the two are one
  5495. // step.
  5496. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5497. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5498. {
  5499. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5500. if join_copies() {
  5501. *n += len;
  5502. return;
  5503. }
  5504. }
  5505. deferred
  5506. .copies
  5507. .push(Step::Copy(dst as usize, src as usize, len));
  5508. deferred.refreshed.clear();
  5509. }
  5510. /// Copies `len` bytes of title memory at `src` into the list's upload
  5511. /// memory at `dst` when the list is submitted.
  5512. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5513. self.deferred()
  5514. .copies
  5515. .push(Step::Fill(dst as usize, src as usize, len, None));
  5516. }
  5517. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5518. /// title heap's address, and the slot) shows.
  5519. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5520. self.deferred()
  5521. .copies
  5522. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  5523. }
  5524. /// As [`HostList::defer_fill`], for the beginning of a buffer
  5525. /// [`HostList::upload`] made.
  5526. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  5527. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  5528. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  5529. }
  5530. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5531. /// when the list is submitted (once per range until a title copy
  5532. /// intervenes), keeping the copy alive until the list is reset.
  5533. pub(crate) fn defer_refresh(
  5534. &self,
  5535. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5536. address: usize,
  5537. len: usize,
  5538. ) {
  5539. let mut deferred = self.deferred();
  5540. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5541. if deferred.refreshed.insert(key) {
  5542. deferred
  5543. .copies
  5544. .push(Step::Refresh(shadow.clone(), address, len));
  5545. }
  5546. }
  5547. /// Shaders of the list write `[address, address + len)` of a buffer's
  5548. /// host copy: copied back into title memory once the list has run.
  5549. pub(crate) fn defer_gpu_write(
  5550. &self,
  5551. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5552. address: usize,
  5553. len: usize,
  5554. ) {
  5555. self.deferred()
  5556. .copies
  5557. .push(Step::GpuWrite(shadow.clone(), address, len));
  5558. }
  5559. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5560. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5561. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5562. /// the list is reset.
  5563. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5564. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5565. }
  5566. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5567. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5568. self.deferred().writes.push((dst as usize, what, bytes));
  5569. }
  5570. /// A mapped upload buffer of `size` bytes, alive until the list is
  5571. /// reset.
  5572. ///
  5573. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5574. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5575. // With [`card_steps`] the card may be the one that fills it.
  5576. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  5577. name(&buffer, || format!("list upload {size:#x}"));
  5578. self.deferred().hold_upload(buffer.clone(), size);
  5579. Some((buffer, data))
  5580. }
  5581. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5582. /// reset: the host GPU address and the CPU pointer.
  5583. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5584. let host = host()?;
  5585. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5586. let len = len.max(1).next_multiple_of(256);
  5587. if len > SCRATCH_CHUNK {
  5588. let (buffer, data) = host.upload_buffer(len)?;
  5589. name(&buffer, || format!("list scratch {len:#x}"));
  5590. // SAFETY: a live buffer.
  5591. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  5592. self.deferred().hold_upload(buffer, len);
  5593. return Some((gpu, data));
  5594. }
  5595. // The chunk in use while `len` fits in what is left of it, else the
  5596. // next one (a list's first chunk may be a small one).
  5597. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5598. (s.current, s.used) = (s.current + 1, 0);
  5599. }
  5600. if s.current == s.chunks.len() {
  5601. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  5602. SCRATCH_FIRST
  5603. } else {
  5604. SCRATCH_CHUNK
  5605. };
  5606. let chunk = take_chunk(host, size)?;
  5607. s.chunks.push((chunk, size));
  5608. s.used = 0;
  5609. }
  5610. let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu);
  5611. let at = s.used;
  5612. s.used += len;
  5613. Some((gpu + at, (data + at as usize) as *mut u8))
  5614. }
  5615. /// The bytes of scratch chunks the list holds now (after a reset:
  5616. /// none while lists share their chunks).
  5617. pub(crate) fn scratch_kept(&self) -> u64 {
  5618. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5619. scratch.chunks.iter().map(|c| c.1).sum()
  5620. }
  5621. /// The host address of the list's indirect-work budget, zeroed at each
  5622. /// submission of the list from the first use after a reset on.
  5623. pub(crate) fn budget(&self) -> Option<u64> {
  5624. let (buffer, data) = self
  5625. .budget
  5626. .get_or_init(|| {
  5627. let (b, d) = host()?.shared_buffer(256)?;
  5628. Some((b, d as usize))
  5629. })
  5630. .as_ref()?;
  5631. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5632. let mut deferred = self.deferred();
  5633. if !deferred.budget_zeroed {
  5634. deferred.budget_zeroed = true;
  5635. let at = *data;
  5636. // SAFETY: the list's own mapped words, written before it runs.
  5637. // The words after the budget hold what the clamp noted about the
  5638. // list's last run (mesh dispatches: the largest group count
  5639. // asked for, the groups asked in all; with the card's copy, as
  5640. // the list's end copied them here): taken, then zeroed.
  5641. let notes = Box::new(move || unsafe {
  5642. let words = at as *mut u32;
  5643. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  5644. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  5645. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  5646. for k in 0..3 {
  5647. words.add(k).write_volatile(0);
  5648. }
  5649. });
  5650. deferred.copies.push(Step::Host(notes, (0, 0)));
  5651. drop(deferred);
  5652. if let Some(card) = card {
  5653. self.zero_card_budget(card);
  5654. }
  5655. }
  5656. // SAFETY: a live buffer.
  5657. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  5658. }
  5659. /// The budget's words in the card's own memory ([`card_budget`]), if
  5660. /// the list can zero them itself (`WriteBufferImmediate`).
  5661. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  5662. if !card_budget() {
  5663. return None;
  5664. }
  5665. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  5666. let buffer = host()?.uav_buffer(256)?;
  5667. name(&buffer, || "indirect budget".to_owned());
  5668. Some(buffer)
  5669. }
  5670. /// Records, before the list's first clamp, the zeroing of the card's
  5671. /// copy of the budget: common, written as a copy, then left for
  5672. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  5673. fn zero_card_budget(&self, card: &ID3D12Resource) {
  5674. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  5675. return;
  5676. };
  5677. // SAFETY: a live buffer.
  5678. let at = unsafe { card.GetGPUVirtualAddress() };
  5679. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  5680. Dest: at + offset,
  5681. Value: 0,
  5682. });
  5683. // SAFETY: an open list; the buffer is the list's own and in the
  5684. // common state at the start of every recording.
  5685. unsafe {
  5686. self.list.ResourceBarrier(&[transition(
  5687. card,
  5688. D3D12_RESOURCE_STATE_COMMON,
  5689. D3D12_RESOURCE_STATE_COPY_DEST,
  5690. )]);
  5691. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  5692. self.list.ResourceBarrier(&[transition(
  5693. card,
  5694. D3D12_RESOURCE_STATE_COPY_DEST,
  5695. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5696. )]);
  5697. }
  5698. }
  5699. /// Before the list closes, if this recording charged the card's copy
  5700. /// of the budget: its notes on mesh records go to the mapped words
  5701. /// (read at the next submission), and it goes back to common.
  5702. fn card_budget_out(&self) {
  5703. if !self.deferred().budget_zeroed {
  5704. return;
  5705. }
  5706. let (Some(Some(card)), Some(Some((mapped, _)))) =
  5707. (self.card_budget.get(), self.budget.get())
  5708. else {
  5709. return;
  5710. };
  5711. // SAFETY: an open list; both buffers are the list's own. The
  5712. // mapped one is promoted from common to the copy destination.
  5713. unsafe {
  5714. self.list.ResourceBarrier(&[transition(
  5715. card,
  5716. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5717. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5718. )]);
  5719. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  5720. self.list.ResourceBarrier(&[transition(
  5721. card,
  5722. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5723. D3D12_RESOURCE_STATE_COMMON,
  5724. )]);
  5725. }
  5726. }
  5727. /// A device-local unordered-access buffer of at least `size` bytes for
  5728. /// clamped indirect arguments, reused across executions and resets of the
  5729. /// list. Smaller buffers replaced mid-list stay alive until
  5730. /// [`HostList::reset`].
  5731. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  5732. let needed = size.max(64 << 10);
  5733. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  5734. if let Some((buffer, cap)) = &*slot
  5735. && *cap >= needed
  5736. {
  5737. return Some(buffer.clone());
  5738. }
  5739. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  5740. let alloc = prev
  5741. .saturating_mul(2)
  5742. .max(needed)
  5743. .next_multiple_of(64 << 10);
  5744. let buffer = host()?.uav_buffer(alloc)?;
  5745. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  5746. let old = slot.replace((buffer.clone(), alloc));
  5747. drop(slot);
  5748. if let Some((old_buf, _)) = old {
  5749. // It ends the list common, as every scratch buffer does.
  5750. self.indirect_common(&old_buf);
  5751. self.keep(&old_buf);
  5752. }
  5753. Some(buffer)
  5754. }
  5755. /// Where the next batch of clamped records goes: a device-local buffer
  5756. /// the list keeps from recording to recording, the batch's place in it
  5757. /// and the state the buffer is in. Every batch of a recording has a place
  5758. /// of its own: the executions before it may still read theirs.
  5759. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  5760. use crate::indirect::batch::{JOBS, SLOT};
  5761. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5762. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  5763. if buffer == args.0.len() {
  5764. let size = u64::from(BATCHES * JOBS * SLOT);
  5765. let made = host()?.uav_buffer(size)?;
  5766. name(&made, || format!("indirect batches {size:#x}"));
  5767. args.0.push(made);
  5768. }
  5769. args.1 += 1;
  5770. // (Its first batch finds it as the recording before left it:
  5771. // `batches_common`.)
  5772. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  5773. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  5774. }
  5775. /// Before the list closes: the scratch buffers of the batched clamps go
  5776. /// back to the common state, where the next recording expects them.
  5777. fn batches_common(&self) {
  5778. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5779. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  5780. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  5781. .iter()
  5782. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  5783. .collect();
  5784. if !barriers.is_empty() {
  5785. // SAFETY: an open list and live buffers this recording left in
  5786. // `INDIRECT_ARGUMENT`.
  5787. unsafe { self.list.ResourceBarrier(&barriers) };
  5788. }
  5789. }
  5790. /// Moves `scratch` back to the common state if a clamp left it readable
  5791. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  5792. /// list's first clamp expects it. Done before the list closes and before
  5793. /// a bigger scratch buffer replaces it: one barrier per list (where
  5794. /// there was one per indirect execution), and the list ends as it
  5795. /// begins however it is submitted.
  5796. fn indirect_common(&self, scratch: &ID3D12Resource) {
  5797. {
  5798. let mut deferred = self.deferred();
  5799. if deferred.indirect_readable != scratch.as_raw() as usize {
  5800. return;
  5801. }
  5802. deferred.indirect_readable = 0;
  5803. }
  5804. let barrier = transition(
  5805. scratch,
  5806. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  5807. D3D12_RESOURCE_STATE_COMMON,
  5808. );
  5809. // SAFETY: an open list and a live buffer this recording left in
  5810. // `INDIRECT_ARGUMENT`.
  5811. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5812. }
  5813. /// The state the list's indirect scratch buffer `scratch` is in at this
  5814. /// point of the recording: indirect arguments if a clamp in this
  5815. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  5816. /// common: the state a buffer is made in, and the one a recording
  5817. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  5818. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  5819. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  5820. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  5821. } else {
  5822. D3D12_RESOURCE_STATE_COMMON
  5823. }
  5824. }
  5825. /// A clamp recorded in this list left `scratch` readable as indirect
  5826. /// arguments. It stays so for every execution that reads it, until the
  5827. /// next clamp moves it back to unordered access.
  5828. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  5829. self.deferred().indirect_readable = scratch.as_raw() as usize;
  5830. }
  5831. /// Keeps `object` alive until the list is reset.
  5832. pub(crate) fn keep(&self, object: &impl Interface) {
  5833. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  5834. self.deferred().kept.push(object);
  5835. }
  5836. }
  5837. /// Whether this is the first time since the reset that the list asks
  5838. /// about `key` (a texture to bring up to date).
  5839. pub(crate) fn first_use(&self, key: usize) -> bool {
  5840. self.deferred().textures.insert(key)
  5841. }
  5842. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  5843. /// reset.
  5844. pub(crate) fn used(&self, key: usize) -> bool {
  5845. self.deferred().textures.contains(&key)
  5846. }
  5847. /// Runs `work` when the list is submitted, in order with its copies.
  5848. /// `work` may write title memory (refreshes after it copy again).
  5849. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  5850. self.deferred().copies.push(Step::Run(Box::new(work)));
  5851. self.deferred().refreshed.clear();
  5852. }
  5853. /// As [`HostList::defer`], for work that writes only host memory.
  5854. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  5855. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  5856. }
  5857. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  5858. /// memory at `from`.
  5859. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  5860. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  5861. }
  5862. /// Brings a texture's staging buffer up to date when the list is
  5863. /// submitted, keeping it alive until the list is reset.
  5864. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  5865. self.deferred().copies.push(Step::Texture(staging));
  5866. }
  5867. /// Runs the list's submission-time steps; refreshes go into `batch`
  5868. /// (the title's big buffers, a 174 MB one among them, are read by most
  5869. /// lists of a submission, through many ranges). Copies and fills that
  5870. /// `taken` names (by their place) are left out: they are done on the
  5871. /// card ([`card_steps`]).
  5872. fn run_deferred(&self, batch: &mut Batch, taken: impl Fn(usize) -> bool) {
  5873. #[cfg(feature = "diagnostics")]
  5874. use crate::copystat::{C, add};
  5875. // The time and the bytes of the copies and fills, some 13,000 a
  5876. // frame between 20,000 refreshes: summed here and added once.
  5877. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  5878. #[cfg(feature = "diagnostics")]
  5879. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  5880. for (i, step) in self.deferred().copies.iter().enumerate() {
  5881. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  5882. continue;
  5883. }
  5884. let (started, copied) = match step {
  5885. &Step::Copy(dst, src, len) => {
  5886. let started = std::time::Instant::now();
  5887. #[cfg(feature = "diagnostics")]
  5888. {
  5889. copies += 1;
  5890. }
  5891. batch.title_written();
  5892. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  5893. // With the submission's one asking: the journal learns it.
  5894. crate::watch::wrote(dst, len);
  5895. // What the card holds there may be another value although
  5896. // ours did not change.
  5897. if send::own() {
  5898. crate::shadow::send_copied(dst, len);
  5899. }
  5900. (started, len)
  5901. }
  5902. &Step::Fill(dst, src, len, _) => {
  5903. let started = std::time::Instant::now();
  5904. #[cfg(feature = "diagnostics")]
  5905. {
  5906. copies += 1;
  5907. }
  5908. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  5909. (started, len)
  5910. }
  5911. Step::Refresh(shadow, address, len) => {
  5912. #[cfg(feature = "diagnostics")]
  5913. {
  5914. refreshes += 1;
  5915. refreshed += *len as u64;
  5916. }
  5917. batch.add(shadow, *address, *len);
  5918. continue;
  5919. }
  5920. Step::Run(work) | Step::Host(work, _) => {
  5921. #[cfg(feature = "diagnostics")]
  5922. let started = std::time::Instant::now();
  5923. if matches!(step, Step::Run(_)) {
  5924. batch.title_written();
  5925. }
  5926. work();
  5927. // It wrote title memory, where is not known here: the
  5928. // submission's one asking ends, later refreshes ask anew.
  5929. if matches!(step, Step::Run(_)) {
  5930. crate::watch::ask_once_end();
  5931. }
  5932. #[cfg(feature = "diagnostics")]
  5933. {
  5934. add(C::Runs, 1);
  5935. add(C::RunUs, started.elapsed().as_micros() as u64);
  5936. }
  5937. continue;
  5938. }
  5939. Step::GpuWrite(shadow, address, len) => {
  5940. // The shaders start from the title's data: this copy's
  5941. // pending refresh first. The other copies' wait for
  5942. // the next flush of all (flushing all of them at every
  5943. // range a dispatch writes made thousands of write-watch
  5944. // askings a frame).
  5945. batch.flush_one(shadow);
  5946. #[cfg(feature = "diagnostics")]
  5947. let snapshot = std::time::Instant::now();
  5948. shadow.writing(*address, *len);
  5949. #[cfg(feature = "diagnostics")]
  5950. {
  5951. add(C::GpuWrites, 1);
  5952. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  5953. }
  5954. continue;
  5955. }
  5956. Step::Texture(staging) => {
  5957. if batch.texture_due(staging) {
  5958. batch.due.push(staging.clone());
  5959. if !wide_textures() {
  5960. batch.refresh_textures();
  5961. }
  5962. }
  5963. continue;
  5964. }
  5965. };
  5966. us += started.elapsed();
  5967. bytes += copied as u64;
  5968. }
  5969. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  5970. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  5971. #[cfg(feature = "diagnostics")]
  5972. {
  5973. add(C::Copies, copies);
  5974. add(C::CopyBytes, bytes);
  5975. add(C::Refreshes, refreshes);
  5976. add(C::RefreshBytes, refreshed);
  5977. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  5978. }
  5979. }
  5980. }
  5981. /// A table by a copy's address.
  5982. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  5983. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  5984. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  5985. /// but our own.
  5986. #[derive(Default)]
  5987. pub(crate) struct AddressHash(u64);
  5988. impl std::hash::Hasher for AddressHash {
  5989. fn finish(&self) -> u64 {
  5990. self.0
  5991. }
  5992. fn write(&mut self, bytes: &[u8]) {
  5993. for &b in bytes {
  5994. self.write_usize(usize::from(b));
  5995. }
  5996. }
  5997. fn write_usize(&mut self, n: usize) {
  5998. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  5999. self.0 = h ^ (h >> 32);
  6000. }
  6001. }
  6002. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  6003. /// preparing: the write-watch asking for a submission; the title's bytes put
  6004. /// in under flights' writes; the lists' steps, the refreshes among them; the
  6005. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  6006. /// of the steps: the refreshes, and the copies and fills (those with the
  6007. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  6008. /// is of. Of the refreshes, those before ranges are given to shaders, one
  6009. /// copy at a time: nanoseconds, and how many.
  6010. #[cfg(feature = "diagnostics")]
  6011. static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  6012. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  6013. /// those known to copy nothing, and those done on several threads.
  6014. #[cfg(feature = "diagnostics")]
  6015. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  6016. /// Counts into [`SPLIT`].
  6017. #[cfg(feature = "diagnostics")]
  6018. struct Split(std::cell::Cell<std::time::Instant>);
  6019. #[cfg(feature = "diagnostics")]
  6020. impl Split {
  6021. fn begin() -> Split {
  6022. Split(std::cell::Cell::new(std::time::Instant::now()))
  6023. }
  6024. /// Nanoseconds since the last part.
  6025. fn so_far(&self) -> u64 {
  6026. self.0.get().elapsed().as_nanos() as u64
  6027. }
  6028. /// What came since the last part was part `i`.
  6029. fn part(&self, i: usize) {
  6030. let now = std::time::Instant::now();
  6031. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  6032. }
  6033. }
  6034. /// The split of the preparing, per frame, for the frame-rate line.
  6035. #[cfg(feature = "diagnostics")]
  6036. fn split_line(frames: f64) {
  6037. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6038. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  6039. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  6040. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6041. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
  6042. tracing::info!(
  6043. "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \
  6044. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  6045. several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \
  6046. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
  6047. ms[0],
  6048. ms[8],
  6049. ms[1],
  6050. ms[2],
  6051. ms[6],
  6052. f[0],
  6053. f[1],
  6054. f[2],
  6055. f[3],
  6056. ms[9],
  6057. ms[10] * 1e6,
  6058. ms[7],
  6059. ms[3],
  6060. ms[4],
  6061. ms[5],
  6062. if crate::watch::light() { "on" } else { "off" },
  6063. );
  6064. tracing::info!(
  6065. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6066. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6067. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6068. waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
  6069. as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
  6070. a[0],
  6071. a[1] / 1024.0,
  6072. a[11] / 1e6,
  6073. a[12],
  6074. a[10],
  6075. a[9],
  6076. a[2],
  6077. a[3],
  6078. a[4],
  6079. a[5],
  6080. a[6],
  6081. a[7] / 1e6,
  6082. a[8] / 1e6,
  6083. s[0] / 1048576.0,
  6084. s[1] / 1048576.0,
  6085. s[2] / 1048576.0,
  6086. s[3],
  6087. );
  6088. tracing::info!(
  6089. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures",
  6090. h[0],
  6091. h[1],
  6092. h[2],
  6093. );
  6094. }
  6095. /// Whether a submission's refreshes of host copies run on several threads,
  6096. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6097. ///
  6098. /// A submission brings some sixty copies up to date, one after the other
  6099. /// on the submitting thread: for each, the pages the title wrote are asked
  6100. /// for and read through the kernel into the copy. That is the frame line's
  6101. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6102. /// another: each refresh writes its own copy and its own notes, and reads
  6103. /// title memory. With the switch the copies of a flush (four or more) are
  6104. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6105. /// The write-watch journal and the guards are behind their own locks, as
  6106. /// they are for the title's threads.
  6107. fn wide_refresh() -> bool {
  6108. static ON: OnceLock<bool> = OnceLock::new();
  6109. *ON.get_or_init(|| {
  6110. wide_refresh_enabled(
  6111. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6112. std::thread::available_parallelism().ok().map(|n| n.get()),
  6113. )
  6114. })
  6115. }
  6116. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6117. match setting {
  6118. Some("1") => true,
  6119. Some("0") => false,
  6120. _ => logical_cpus.is_some_and(|n| n >= 4),
  6121. }
  6122. }
  6123. #[cfg(test)]
  6124. mod wide_refresh_tests {
  6125. use super::wide_refresh_enabled;
  6126. #[test]
  6127. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6128. assert!(wide_refresh_enabled(None, Some(4)));
  6129. assert!(wide_refresh_enabled(None, Some(16)));
  6130. assert!(!wide_refresh_enabled(None, Some(2)));
  6131. assert!(!wide_refresh_enabled(None, None));
  6132. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6133. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6134. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6135. }
  6136. }
  6137. /// A submission's refreshes not done yet, merged per buffer copy into the
  6138. /// range that covers them: done before a step that writes title memory or
  6139. /// gives a range to shaders, and before the lists run.
  6140. ///
  6141. /// Also the textures brought up to date in the submission so far: most
  6142. /// lists of a world submission sample the same textures, and a texture in
  6143. /// physical-page memory is hashed whole each time it is checked. Checked
  6144. /// once, it is checked again only after a step that writes title memory.
  6145. #[derive(Default)]
  6146. struct Batch {
  6147. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6148. /// Where each copy (by address) is in `refreshes`: the list that makes
  6149. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6150. /// for every refresh of a submission was tens of millions of
  6151. /// comparisons a frame.
  6152. index: ByCopy<usize>,
  6153. /// Staging buffers (by address) refreshed since the last title write,
  6154. /// or due to be.
  6155. textures: std::collections::HashSet<usize>,
  6156. /// Those due ([`Batch::refresh_textures`]).
  6157. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6158. }
  6159. /// Whether a submission's textures are brought up to date on several
  6160. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6161. /// name them, as before).
  6162. ///
  6163. /// They are read, hashed and, if they changed, detiled into their staging
  6164. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6165. /// its own buffer, notes and lock, and is refreshed by the title's own
  6166. /// threads as it is. They are done before the next step that writes title
  6167. /// memory, as the copies' refreshes are, and before the lists go to the
  6168. /// card. What is new: the note of a list that its upload takes what the
  6169. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6170. /// an earlier list of the submission asked for, not behind it. The texture
  6171. /// is then uploaded by a later list too, once more than needed.
  6172. fn wide_textures() -> bool {
  6173. static ON: OnceLock<bool> = OnceLock::new();
  6174. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6175. }
  6176. impl Batch {
  6177. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6178. let end = address + len;
  6179. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6180. match self.index.get(&key) {
  6181. Some(&at) => {
  6182. let r = &mut self.refreshes[at];
  6183. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6184. }
  6185. None => {
  6186. self.index.insert(key, self.refreshes.len());
  6187. self.refreshes.push((shadow.clone(), address, end));
  6188. }
  6189. }
  6190. }
  6191. /// Before shaders are given a range of `shadow`'s copy: its pending
  6192. /// refresh is done, the others stay pending.
  6193. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  6194. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  6195. return;
  6196. };
  6197. let (shadow, from, to) = self.refreshes.swap_remove(at);
  6198. // The last entry took its place.
  6199. if let Some(moved) = self.refreshes.get(at) {
  6200. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  6201. }
  6202. #[cfg(feature = "diagnostics")]
  6203. let started = std::time::Instant::now();
  6204. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  6205. Self::update(&shadow, from, to);
  6206. }
  6207. #[cfg(feature = "diagnostics")]
  6208. {
  6209. let ns = started.elapsed().as_nanos() as u64;
  6210. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6211. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6212. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  6213. }
  6214. }
  6215. /// Brings `[from, to)` of a copy up to date, timed.
  6216. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  6217. let started = std::time::Instant::now();
  6218. let copied = shadow.update(from, to - from);
  6219. let us = started.elapsed().as_micros() as u64;
  6220. #[cfg(feature = "diagnostics")]
  6221. crate::copystat::range(from, to - from, us, 0);
  6222. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  6223. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  6224. }
  6225. /// Whether `staging` is still to be refreshed in this submission (and
  6226. /// notes it refreshed).
  6227. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  6228. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  6229. }
  6230. /// Before a step that writes title memory: pending refreshes are done
  6231. /// first, and textures are checked again after it.
  6232. fn title_written(&mut self) {
  6233. self.flush();
  6234. self.textures.clear();
  6235. }
  6236. /// The textures due are brought up to date.
  6237. fn refresh_textures(&mut self) {
  6238. if self.due.len() < 2 || !wide_textures() {
  6239. self.due.drain(..).for_each(|staging| staging.refresh());
  6240. return;
  6241. }
  6242. // The time counted is the time it took, not the threads' sum.
  6243. let started = std::time::Instant::now();
  6244. let before = PREPARING[2].load(Ordering::Relaxed);
  6245. let due = std::mem::take(&mut self.due);
  6246. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  6247. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  6248. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6249. }
  6250. fn flush(&mut self) {
  6251. self.refresh_textures();
  6252. self.index.clear();
  6253. if self.refreshes.is_empty() {
  6254. return;
  6255. }
  6256. #[cfg(feature = "diagnostics")]
  6257. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  6258. self.flush_all();
  6259. #[cfg(feature = "diagnostics")]
  6260. {
  6261. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6262. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  6263. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  6264. }
  6265. }
  6266. fn flush_all(&mut self) {
  6267. // Most of a flush's copies are as they were: they are told so here,
  6268. // from what the submission's asking found, before anything is asked
  6269. // and any thread woken. (Thousands of them, the heap's buffer views
  6270. // once a frame: on the threads, below.)
  6271. const FEW: usize = 256;
  6272. let light = crate::watch::light();
  6273. if light && self.refreshes.len() <= FEW {
  6274. let started = std::time::Instant::now();
  6275. #[cfg(feature = "diagnostics")]
  6276. let all = self.refreshes.len();
  6277. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  6278. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6279. #[cfg(feature = "diagnostics")]
  6280. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  6281. }
  6282. // One write-watch asking for the copies that lie close together,
  6283. // not one per copy.
  6284. let ahead = self.refreshes.len() > 1;
  6285. if ahead {
  6286. let started = std::time::Instant::now();
  6287. let ranges: Vec<(usize, usize)> = self
  6288. .refreshes
  6289. .iter()
  6290. .filter(|r| r.0.asked_ahead())
  6291. .map(|r| (r.1, r.2))
  6292. .collect();
  6293. crate::watch::ask_ahead(&ranges);
  6294. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6295. }
  6296. if wide_refresh() && self.refreshes.len() >= 4 {
  6297. // Each copy on its own, several at a time: a copy's refresh
  6298. // writes that copy and reads title memory, nothing of another's.
  6299. // The time counted is the time it took, not the threads' sum.
  6300. let started = std::time::Instant::now();
  6301. let before = PREPARING[0].load(Ordering::Relaxed);
  6302. #[cfg(feature = "diagnostics")]
  6303. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  6304. if light {
  6305. // A number to a free thread, not a job to each copy.
  6306. let refreshes = std::mem::take(&mut self.refreshes);
  6307. crate::shadow::wide_each(refreshes.len(), move |i| {
  6308. let (shadow, from, to) = &refreshes[i];
  6309. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  6310. #[cfg(feature = "diagnostics")]
  6311. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  6312. return;
  6313. }
  6314. Self::update(shadow, *from, *to);
  6315. });
  6316. } else {
  6317. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  6318. .refreshes
  6319. .drain(..)
  6320. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  6321. .collect();
  6322. crate::shadow::wide_run(jobs);
  6323. }
  6324. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6325. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6326. } else {
  6327. for (shadow, from, to) in self.refreshes.drain(..) {
  6328. Self::update(&shadow, from, to);
  6329. }
  6330. }
  6331. if ahead {
  6332. crate::watch::ask_ahead_done();
  6333. }
  6334. }
  6335. }
  6336. /// Copies title memory at submission. The ranges were checked against their
  6337. /// resources when recorded, but the title may since have unmapped pages of
  6338. /// them (tiled memory, page mappings), which read as zeros here; a title
  6339. /// destination (`title_dst`) that is not all mapped is left alone.
  6340. ///
  6341. /// The source is read through the kernel (`ReadProcessMemory`), which
  6342. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  6343. /// cost about 2 ms per copy in the title's big pools (it walks the page
  6344. /// tables to the region's end), which made copies run at 100-200 MB/s.
  6345. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  6346. #[cfg(feature = "diagnostics")]
  6347. match crate::copystat::mode() {
  6348. 1 => {
  6349. // SAFETY: timing only: the caller vouches for the source.
  6350. unsafe { std::ptr::copy(src, dst, len) };
  6351. return;
  6352. }
  6353. 2 => return,
  6354. _ => {}
  6355. }
  6356. if len == 0 {
  6357. return;
  6358. }
  6359. // A title destination that is not all mapped is left alone. Asking
  6360. // Windows first (`VirtualQuery`) walks the page tables to the end of
  6361. // the destination's region: in the title's big blocks that is
  6362. // milliseconds a copy, and it was a seventh of the submitting thread's
  6363. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  6364. // says the same when it fails, so the question is only asked then.
  6365. // `VICTORY_COPY_ASK=1` asks first, as before.
  6366. static ASK: OnceLock<bool> = OnceLock::new();
  6367. let ask_first = title_dst
  6368. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  6369. if ask_first && !crate::texture::committed(dst, len) {
  6370. return;
  6371. }
  6372. if title_dst {
  6373. // The kernel writes the destination: it must not be guarded.
  6374. crate::watch::writing(dst as usize, len);
  6375. }
  6376. #[cfg(feature = "diagnostics")]
  6377. let moved = std::time::Instant::now();
  6378. let since = crate::watch::changes();
  6379. // (A title destination that is away only while the runtime changes a
  6380. // mapping beside it is written when that is done.)
  6381. let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
  6382. #[cfg(feature = "diagnostics")]
  6383. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  6384. if whole {
  6385. return;
  6386. }
  6387. // The copy failed: a source page is not there, or the destination is
  6388. // not all mapped. Then the destination stays as it is (the kernel may
  6389. // have written its first pages).
  6390. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  6391. crate::watch::lost("a copy of the title's", dst as usize, len);
  6392. return;
  6393. }
  6394. #[cfg(feature = "diagnostics")]
  6395. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  6396. #[cfg(feature = "diagnostics")]
  6397. let sparse = std::time::Instant::now();
  6398. if !title_dst && len >= 64 << 10 {
  6399. read_sparse(src, dst, len);
  6400. } else {
  6401. read_pieces(src, dst, len);
  6402. }
  6403. #[cfg(feature = "diagnostics")]
  6404. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  6405. }
  6406. /// After a failed bulk read into host memory, skip contiguous holes. Never
  6407. /// cache the query across copies: the title may remap the same address.
  6408. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  6409. use windows_sys::Win32::System::Memory::{
  6410. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  6411. };
  6412. let mut offset = 0;
  6413. while offset < len {
  6414. let at = src.wrapping_add(offset);
  6415. let to = dst.wrapping_add(offset);
  6416. let remaining = len - offset;
  6417. // SAFETY: the query inspects an address and fills a local structure.
  6418. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  6419. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  6420. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  6421. .saturating_sub(at as usize).min(remaining);
  6422. if size != size_of_val(&info) || n == 0 {
  6423. read_pieces(at, to, remaining);
  6424. break;
  6425. }
  6426. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  6427. #[cfg(feature = "diagnostics")]
  6428. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6429. // SAFETY: this path is only used with a writable host destination.
  6430. unsafe { to.write_bytes(0, n) };
  6431. } else if !read(at, to, n) {
  6432. // A mapping may change between query and read.
  6433. read_pieces(at, to, n);
  6434. }
  6435. offset += n;
  6436. }
  6437. }
  6438. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  6439. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  6440. // that fails), zeros for what cannot be read.
  6441. for_pieces(src as usize, len, 64 << 10, |at, n| {
  6442. let to = dst.wrapping_add(at - src as usize);
  6443. if !read(at as *const u8, to, n) {
  6444. for_pieces(at, n, 4 << 10, |at, n| {
  6445. let to = dst.wrapping_add(at - src as usize);
  6446. if !read(at as *const u8, to, n) {
  6447. #[cfg(feature = "diagnostics")]
  6448. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6449. zero(to, n);
  6450. }
  6451. });
  6452. }
  6453. });
  6454. }
  6455. /// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
  6456. /// destination of a title's copy), which can go between the question whether
  6457. /// it is there and this.
  6458. fn zero(to: *mut u8, n: usize) {
  6459. static ZEROS: [u8; 4096] = [0; 4096];
  6460. if n <= ZEROS.len() && crate::safecopy::on() {
  6461. // SAFETY: a destination that is not there fails the copy.
  6462. if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
  6463. crate::watch::lost("zeros", to as usize, n);
  6464. }
  6465. return;
  6466. }
  6467. // SAFETY: inside the destination, which is mapped.
  6468. unsafe { to.write_bytes(0, n) };
  6469. }
  6470. /// Reads title memory at `src` into `dst`; false if a page of it is not
  6471. /// readable.
  6472. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  6473. read(src, dst.as_mut_ptr(), dst.len())
  6474. }
  6475. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  6476. /// readable.
  6477. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  6478. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  6479. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6480. if crate::safecopy::on() {
  6481. // SAFETY: the destination is mapped writable memory of `len` bytes;
  6482. // a source page that is not there fails the copy.
  6483. return unsafe { crate::safecopy::copy(dst, src, len) };
  6484. }
  6485. let mut done = 0;
  6486. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  6487. // kernel checks the source.
  6488. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  6489. }
  6490. #[link(name = "ntdll", kind = "raw-dylib")]
  6491. unsafe extern "system" {
  6492. /// The kernel's write into a process's memory, `(process, address,
  6493. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  6494. /// the range is not there or not writable. It changes no protection.
  6495. fn NtWriteVirtualMemory(
  6496. process: *mut std::ffi::c_void,
  6497. base: *mut std::ffi::c_void,
  6498. buffer: *const std::ffi::c_void,
  6499. size: usize,
  6500. written: *mut usize,
  6501. ) -> i32;
  6502. }
  6503. /// Whether title memory is written with the kernel's own call
  6504. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  6505. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  6506. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  6507. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  6508. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  6509. fn direct_writes() -> bool {
  6510. static ON: OnceLock<bool> = OnceLock::new();
  6511. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  6512. }
  6513. /// Copies host memory into title memory after a submission (what shaders
  6514. /// wrote), leaving pages that are not mapped alone.
  6515. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  6516. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  6517. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6518. let direct = direct_writes();
  6519. let since = crate::watch::changes();
  6520. let write = |at: usize, n: usize| {
  6521. let from = src.wrapping_add(at - dst as usize);
  6522. if crate::safecopy::on() {
  6523. // SAFETY: the source is ours; a destination page that is not
  6524. // there, or not writable, fails the copy.
  6525. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  6526. }
  6527. let mut done = 0;
  6528. if direct {
  6529. // SAFETY: as below; the kernel checks the destination and
  6530. // writes nothing it cannot (the caller opened its guards:
  6531. // `crate::watch::writing`).
  6532. return unsafe {
  6533. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  6534. };
  6535. }
  6536. // SAFETY: the source is our mapped host copy; the kernel checks the
  6537. // destination.
  6538. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  6539. };
  6540. if len == 0 || write(dst as usize, len) {
  6541. return;
  6542. }
  6543. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  6544. if !write(at, n) {
  6545. for_pieces(at, n, 4 << 10, |at, n| {
  6546. if write(at, n) {
  6547. return;
  6548. }
  6549. // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
  6550. // refresh guarded the block again since the caller opened
  6551. // it; and any where the runtime was changing a mapping.
  6552. crate::watch::writing(at, n);
  6553. if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
  6554. crate::watch::lost("a host copy's bytes", at, n);
  6555. }
  6556. });
  6557. }
  6558. });
  6559. }
  6560. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  6561. /// `step`.
  6562. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  6563. let end = start + len;
  6564. let mut at = start;
  6565. while at < end {
  6566. let next = ((at / step + 1) * step).min(end);
  6567. f(at, next - at);
  6568. at = next;
  6569. }
  6570. }
  6571. impl Host {
  6572. /// A buffer in the upload heap, mapped for writing.
  6573. /// A buffer of `size` bytes the card writes and we read (a read back),
  6574. /// in the state copies into it need.
  6575. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  6576. let heap = D3D12_HEAP_PROPERTIES {
  6577. Type: D3D12_HEAP_TYPE_READBACK,
  6578. ..Default::default()
  6579. };
  6580. let desc = D3D12_RESOURCE_DESC {
  6581. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6582. Width: size.max(1),
  6583. Height: 1,
  6584. DepthOrArraySize: 1,
  6585. MipLevels: 1,
  6586. SampleDesc: DXGI_SAMPLE_DESC {
  6587. Count: 1,
  6588. Quality: 0,
  6589. },
  6590. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6591. ..Default::default()
  6592. };
  6593. let mut buffer: Option<ID3D12Resource> = None;
  6594. // SAFETY: plain creation of a read-back buffer.
  6595. let made = unsafe {
  6596. self.device.CreateCommittedResource(
  6597. &heap,
  6598. D3D12_HEAP_FLAG_NONE,
  6599. &desc,
  6600. D3D12_RESOURCE_STATE_COPY_DEST,
  6601. None,
  6602. &mut buffer,
  6603. )
  6604. };
  6605. match made {
  6606. Ok(()) => buffer,
  6607. Err(e) => {
  6608. tracing::warn!(error = %e, size, "no read-back buffer");
  6609. None
  6610. }
  6611. }
  6612. }
  6613. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6614. MADE[0].fetch_add(1, Ordering::Relaxed);
  6615. MADE[1].fetch_add(size, Ordering::Relaxed);
  6616. let heap = D3D12_HEAP_PROPERTIES {
  6617. Type: D3D12_HEAP_TYPE_UPLOAD,
  6618. ..Default::default()
  6619. };
  6620. let desc = D3D12_RESOURCE_DESC {
  6621. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6622. Width: size.max(1),
  6623. Height: 1,
  6624. DepthOrArraySize: 1,
  6625. MipLevels: 1,
  6626. SampleDesc: DXGI_SAMPLE_DESC {
  6627. Count: 1,
  6628. Quality: 0,
  6629. },
  6630. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6631. ..Default::default()
  6632. };
  6633. let mut buffer: Option<ID3D12Resource> = None;
  6634. let mut data = std::ptr::null_mut();
  6635. // SAFETY: plain creation and mapping of an upload buffer.
  6636. let made = unsafe {
  6637. self.device
  6638. .CreateCommittedResource(
  6639. &heap,
  6640. D3D12_HEAP_FLAG_NONE,
  6641. &desc,
  6642. D3D12_RESOURCE_STATE_GENERIC_READ,
  6643. None,
  6644. &mut buffer,
  6645. )
  6646. .and_then(|()| {
  6647. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  6648. b.Map(0, None, Some(&mut data))
  6649. })
  6650. };
  6651. match made {
  6652. Ok(()) => Some((buffer?, data.cast())),
  6653. Err(e) => {
  6654. tracing::warn!(error = %e, size, "no upload buffer");
  6655. None
  6656. }
  6657. }
  6658. }
  6659. }
  6660. /// The swap chain formats a presented texture can be copied into: its own
  6661. /// family's.
  6662. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  6663. Some(match format.0 {
  6664. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  6665. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  6666. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  6667. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  6668. _ => return None,
  6669. })
  6670. }
  6671. const BUFFERS: u32 = 2;
  6672. struct Presenter {
  6673. swap_chain: IDXGISwapChain3,
  6674. width: u32,
  6675. height: u32,
  6676. format: DXGI_FORMAT,
  6677. copy: HostList,
  6678. /// With presents sent ahead ([`late_free_present`]): a list for each
  6679. /// present in the air, and the submission it last flew as (it is used
  6680. /// again once that one has finished).
  6681. ahead: Vec<(HostList, u64)>,
  6682. hwnd: HWND,
  6683. meter: Meter,
  6684. }
  6685. /// The frame rate, shown in the window's caption every second and logged
  6686. /// every few seconds.
  6687. struct Meter {
  6688. since: std::time::Instant,
  6689. frames: u32,
  6690. #[cfg(feature = "diagnostics")]
  6691. copy_stats_frames: u64,
  6692. drawn: u64,
  6693. logged: std::time::Instant,
  6694. /// The caption the window had, once read.
  6695. caption: Option<Vec<u16>>,
  6696. }
  6697. impl Meter {
  6698. fn new() -> Self {
  6699. let now = std::time::Instant::now();
  6700. Meter {
  6701. since: now,
  6702. frames: 0,
  6703. #[cfg(feature = "diagnostics")]
  6704. copy_stats_frames: 0,
  6705. drawn: crate::draw::drawn(),
  6706. logged: now,
  6707. caption: None,
  6708. }
  6709. }
  6710. /// Counts a presented frame.
  6711. fn frame(&mut self, hwnd: HWND) {
  6712. #[cfg(feature = "diagnostics")]
  6713. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  6714. #[cfg(feature = "diagnostics")]
  6715. crate::copystat::presented();
  6716. self.frames += 1;
  6717. #[cfg(feature = "diagnostics")]
  6718. {
  6719. self.copy_stats_frames += 1;
  6720. }
  6721. let elapsed = self.since.elapsed();
  6722. if elapsed < std::time::Duration::from_secs(1) {
  6723. return;
  6724. }
  6725. let drawn = crate::draw::drawn();
  6726. let frames = f64::from(self.frames);
  6727. let fps = frames / elapsed.as_secs_f64();
  6728. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  6729. let draws = (drawn - self.drawn) as f64 / frames;
  6730. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  6731. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  6732. let [cpu, gpu] = [0, 1].map(|i| {
  6733. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  6734. });
  6735. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  6736. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  6737. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  6738. });
  6739. let [back_ms, back_mb] = [0, 1].map(|i| {
  6740. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  6741. });
  6742. let dropped = crate::draw::take_dropped() as f64 / frames;
  6743. let indirect = crate::list::take_indirect() as f64 / frames;
  6744. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  6745. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  6746. tracing::info!(
  6747. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  6748. );
  6749. late_line(frames);
  6750. card_clock_line(frames, ms);
  6751. crate::shadow::back_line(frames);
  6752. #[cfg(feature = "diagnostics")]
  6753. split_line(frames);
  6754. {
  6755. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6756. if passes + compares > 0.0 {
  6757. tracing::info!(
  6758. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  6759. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  6760. if rehash_runs() { "on" } else { "off" }
  6761. );
  6762. }
  6763. }
  6764. {
  6765. let [own, asking, still, all] =
  6766. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  6767. if all >= 1.0 {
  6768. tracing::info!(
  6769. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  6770. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  6771. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  6772. );
  6773. }
  6774. let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6775. if through + left > 0.0 {
  6776. tracing::info!(
  6777. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  6778. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there)"
  6779. );
  6780. }
  6781. }
  6782. {
  6783. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6784. if copies > 0.0 {
  6785. tracing::info!(
  6786. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  6787. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  6788. if join_copies() { "on" } else { "off" }
  6789. );
  6790. }
  6791. }
  6792. // Passes over the heap's buffer views for shaders that pick them by index.
  6793. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  6794. let picked_ms =
  6795. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  6796. // Copies between depth textures and their colour twins, each way.
  6797. let [twin_to_depth, twin_to_colour] =
  6798. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6799. // Depth planes drawn from their twins.
  6800. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  6801. // Copies in the card's memory (`crate::shadow::cards`).
  6802. let card = crate::shadow::card_stats();
  6803. #[cfg(feature = "diagnostics")]
  6804. let slow = crate::watch::slow_asks();
  6805. // Over the same frames as the counts above.
  6806. #[cfg(feature = "diagnostics")]
  6807. let drops = crate::pipeline::take_drops();
  6808. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  6809. self.logged = std::time::Instant::now();
  6810. tracing::info!(
  6811. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  6812. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  6813. );
  6814. {
  6815. let [queued, due, away, partly, oldest] =
  6816. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  6817. let [same, parts, tails] =
  6818. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  6819. tracing::info!(
  6820. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  6821. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  6822. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  6823. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  6824. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  6825. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  6826. {} made slots found unmapped and made null",
  6827. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  6828. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  6829. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  6830. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  6831. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  6832. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  6833. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  6834. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  6835. );
  6836. }
  6837. #[cfg(feature = "diagnostics")]
  6838. tracing::info!(
  6839. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  6840. slow[0] as f64 / frames,
  6841. slow[1] as f64 / 1e3 / frames,
  6842. slow[2] as f64 / 1e3
  6843. );
  6844. if crate::shadow::cards() {
  6845. let per_frame = |i: usize| card[i] as f64 / frames;
  6846. tracing::info!(
  6847. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  6848. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  6849. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  6850. card[7],
  6851. card[8] >> 20,
  6852. card[9] >> 20,
  6853. per_frame(0) / 1e6,
  6854. per_frame(1),
  6855. per_frame(2),
  6856. per_frame(3),
  6857. per_frame(4) / 1e6,
  6858. per_frame(5),
  6859. per_frame(6) / 1e3
  6860. );
  6861. }
  6862. tracing::info!(
  6863. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  6864. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  6865. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  6866. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  6867. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  6868. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  6869. {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}",
  6870. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  6871. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  6872. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  6873. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  6874. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  6875. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  6876. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  6877. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  6878. refused = format!(
  6879. "{} ({} copies made of views off their buffer's elements); 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",
  6880. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  6881. crate::shadow::OWN_MADE.load(Ordering::Relaxed),
  6882. crate::resource::TWINS[0].load(Ordering::Relaxed),
  6883. crate::resource::TWINS[1].load(Ordering::Relaxed),
  6884. crate::resource::PLANES[1].load(Ordering::Relaxed),
  6885. crate::resource::PLANES[2].load(Ordering::Relaxed)
  6886. ),
  6887. making = crate::pipeline::making(),
  6888. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  6889. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  6890. );
  6891. #[cfg(feature = "diagnostics")]
  6892. {
  6893. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6894. tracing::info!(
  6895. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  6896. put[0],
  6897. put[1],
  6898. put[2] / 1e6,
  6899. put[3]
  6900. );
  6901. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  6902. for (why, n) in drops.iter().take(40) {
  6903. tracing::info!(
  6904. "dropped {:.1}/frame without a host pipeline: {why}",
  6905. *n as f64 / frames
  6906. );
  6907. }
  6908. }
  6909. }
  6910. if self.caption.is_none() {
  6911. // The window's own text, read without a message.
  6912. let mut buffer = vec![0u16; 512];
  6913. // SAFETY: a window handle and a buffer of that length.
  6914. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  6915. buffer.truncate(n.max(0) as usize);
  6916. self.caption = Some(buffer);
  6917. }
  6918. let Some(caption) = &self.caption else { return };
  6919. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  6920. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  6921. text.push(0);
  6922. // Setting the text waits for the window's thread (a title thread,
  6923. // which may not pump for a while), so a thread of ours does it and
  6924. // presenting never waits; it takes the newest text when free.
  6925. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  6926. static SETTER: std::sync::Once = std::sync::Once::new();
  6927. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  6928. SETTER.call_once(|| {
  6929. let _ = std::thread::Builder::new()
  6930. .name("victory-caption".into())
  6931. .spawn(|| {
  6932. loop {
  6933. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  6934. match next {
  6935. // SAFETY: a window handle and a NUL-terminated text.
  6936. Some((hwnd, text)) => unsafe {
  6937. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  6938. },
  6939. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  6940. }
  6941. }
  6942. });
  6943. });
  6944. }
  6945. }
  6946. impl Host {
  6947. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  6948. /// as frame `frame` (saved if captures are on). `None` if nothing was
  6949. /// shown; else, in diagnostics builds, whether the frame was black.
  6950. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  6951. // SAFETY: a live resource.
  6952. let desc = unsafe { texture.GetDesc() };
  6953. let Some(format) = swap_format(desc.Format) else {
  6954. tracing::warn!(format = desc.Format.0, "cannot present this format");
  6955. return None;
  6956. };
  6957. let (width, height) = (desc.Width as u32, desc.Height);
  6958. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  6959. if presenter.is_none() {
  6960. *presenter = match self.presenter(width, height, format) {
  6961. Ok(p) => Some(p),
  6962. Err(e) => {
  6963. tracing::warn!(error = %e, "no swap chain");
  6964. return None;
  6965. }
  6966. };
  6967. }
  6968. let p = presenter.as_mut()?;
  6969. if (p.width, p.height, p.format) != (width, height, format) {
  6970. // Presents sent ahead hold back buffers until they have run.
  6971. settle_now(WHY_SYNC);
  6972. // SAFETY: no back buffer is held; every submission was waited for.
  6973. let resized = unsafe {
  6974. p.swap_chain
  6975. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  6976. };
  6977. match resized {
  6978. Ok(()) => {
  6979. (p.width, p.height, p.format) = (width, height, format);
  6980. tracing::info!(
  6981. width,
  6982. height,
  6983. format = format.0,
  6984. frame,
  6985. "the swap chain's buffers were made again for another size or format"
  6986. );
  6987. self.log_video_memory("right after the swap chain's buffers were made again");
  6988. }
  6989. Err(e) => {
  6990. tracing::warn!(error = %e, width, height, "swap chain not resized");
  6991. return None;
  6992. }
  6993. }
  6994. }
  6995. let state = D3D12_RESOURCE_STATES(state as i32);
  6996. // SAFETY: our swap chain, list and a live source texture.
  6997. unsafe {
  6998. let index = p.swap_chain.GetCurrentBackBufferIndex();
  6999. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  7000. return None;
  7001. };
  7002. // Sent ahead ([`late_free_present`]) unless the frame is to be
  7003. // read back at once (a saved or listed frame): then a list of
  7004. // its own, one whose last flight has finished or a new one.
  7005. #[cfg(feature = "diagnostics")]
  7006. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  7007. #[cfg(not(feature = "diagnostics"))]
  7008. let read_now = false;
  7009. let slot = if late_free_present() && !read_now {
  7010. let finished = FINISHED.load(Ordering::Acquire);
  7011. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  7012. let list = self.new_list().ok()?;
  7013. list.close();
  7014. p.ahead.push((list, 0));
  7015. Some(p.ahead.len() - 1)
  7016. })
  7017. } else {
  7018. None
  7019. };
  7020. let copy = match slot {
  7021. Some(i) => &p.ahead[i].0,
  7022. None => &p.copy,
  7023. };
  7024. copy.reset();
  7025. let list = &copy.list;
  7026. list.ResourceBarrier(&[
  7027. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  7028. transition(
  7029. &back,
  7030. D3D12_RESOURCE_STATE_PRESENT,
  7031. D3D12_RESOURCE_STATE_COPY_DEST,
  7032. ),
  7033. ]);
  7034. list.CopyResource(&back, texture);
  7035. #[cfg(feature = "diagnostics")]
  7036. let capture = crate::capture::wanted(frame)
  7037. .then(|| crate::capture::read_back(&self.device, list, texture))
  7038. .flatten();
  7039. #[cfg(feature = "diagnostics")]
  7040. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  7041. #[cfg(not(feature = "diagnostics"))]
  7042. let _ = frame;
  7043. list.ResourceBarrier(&[
  7044. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  7045. transition(
  7046. &back,
  7047. D3D12_RESOURCE_STATE_COPY_DEST,
  7048. D3D12_RESOURCE_STATE_PRESENT,
  7049. ),
  7050. ]);
  7051. copy.close();
  7052. match slot {
  7053. Some(i) => {
  7054. let flown = self.execute_own(copy);
  7055. p.ahead[i].1 = flown;
  7056. }
  7057. None => self.execute(&[copy]),
  7058. }
  7059. #[cfg(feature = "diagnostics")]
  7060. if let Some((buffer, footprint)) = capture {
  7061. crate::capture::save_read_back(frame, &buffer, &footprint);
  7062. }
  7063. #[cfg(feature = "diagnostics")]
  7064. crate::replay::record::present(texture, state);
  7065. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  7066. p.meter.frame(p.hwnd);
  7067. #[cfg(feature = "diagnostics")]
  7068. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  7069. #[cfg(not(feature = "diagnostics"))]
  7070. Some(false)
  7071. }
  7072. }
  7073. fn presenter(
  7074. &self,
  7075. width: u32,
  7076. height: u32,
  7077. format: DXGI_FORMAT,
  7078. ) -> windows::core::Result<Presenter> {
  7079. let hwnd = match title_window() {
  7080. Some(hwnd) => hwnd,
  7081. None => window(width, height)?,
  7082. };
  7083. self.log_video_memory("right before the swap chain is made");
  7084. // SAFETY: plain object creation for our window.
  7085. unsafe {
  7086. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  7087. let desc = DXGI_SWAP_CHAIN_DESC1 {
  7088. Width: width,
  7089. Height: height,
  7090. Format: format,
  7091. SampleDesc: DXGI_SAMPLE_DESC {
  7092. Count: 1,
  7093. Quality: 0,
  7094. },
  7095. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  7096. BufferCount: BUFFERS,
  7097. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  7098. ..Default::default()
  7099. };
  7100. let swap_chain = factory
  7101. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  7102. .cast::<IDXGISwapChain3>()?;
  7103. let copy = self.new_list()?;
  7104. copy.close();
  7105. tracing::info!(width, height, format = format.0, "presenting to a window");
  7106. self.log_video_memory("right after the swap chain is made");
  7107. Ok(Presenter {
  7108. swap_chain,
  7109. width,
  7110. height,
  7111. format,
  7112. copy,
  7113. ahead: Vec::new(),
  7114. hwnd,
  7115. meter: Meter::new(),
  7116. })
  7117. }
  7118. }
  7119. }
  7120. /// A visible top-level window of this process: the one the title made, if
  7121. /// it made one.
  7122. fn title_window() -> Option<HWND> {
  7123. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  7124. let mut process = 0;
  7125. // SAFETY: a window handle from the enumeration; `found` is ours.
  7126. unsafe {
  7127. GetWindowThreadProcessId(hwnd, Some(&mut process));
  7128. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  7129. && IsWindowVisible(hwnd).as_bool()
  7130. {
  7131. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  7132. return false.into();
  7133. }
  7134. }
  7135. true.into()
  7136. }
  7137. let mut found: Option<HWND> = None;
  7138. // SAFETY: the callback only writes `found`, which outlives the call.
  7139. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  7140. found
  7141. }
  7142. /// `state` without the bits the host texture's flags forbid: the console
  7143. /// lets the title name states its own resources allow (unordered access on
  7144. /// a depth target, whose host copy cannot have both).
  7145. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  7146. // SAFETY: a plain query.
  7147. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  7148. }
  7149. /// [`legal_state`] for a texture with resource flags `flags`.
  7150. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  7151. // (flag, set or clear forbids, state bits): render target, unordered
  7152. // access, depth, denied shader resource.
  7153. const FORBIDDEN: [(u32, bool, u32); 4] = [
  7154. (0x1, false, 0x4),
  7155. (0x4, false, 0x8),
  7156. (0x2, false, 0x10 | 0x20),
  7157. (0x8, true, 0x40 | 0x80),
  7158. ];
  7159. FORBIDDEN
  7160. .iter()
  7161. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  7162. .fold(state, |s, &(_, _, bits)| s & !bits)
  7163. }
  7164. impl Host {
  7165. /// The card's memory as the system accounts it to this process, in
  7166. /// bytes: the budget and the use of the card's own memory, then of the
  7167. /// PC's memory shared with the card (where the system moves what does
  7168. /// not fit on the card).
  7169. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  7170. let adapter = self.adapter.as_ref()?;
  7171. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7172. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7173. // SAFETY: plain queries that fill our structures.
  7174. unsafe {
  7175. adapter
  7176. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7177. .ok()?;
  7178. adapter
  7179. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7180. .ok()?;
  7181. }
  7182. // The card's budget moved by 256 MB or more since the last look:
  7183. // said at once, with what was in use at the last look, so the log
  7184. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  7185. // the first world frame in runs 179 to 185, and the memory line,
  7186. // seconds later, was the first to show it. We reserve nothing
  7187. // and make the swap chain once, at the start.)
  7188. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  7189. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  7190. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  7191. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  7192. tracing::info!(
  7193. "the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use",
  7194. last[0] >> 20,
  7195. own.Budget >> 20,
  7196. crate::frame::current(),
  7197. last[1] >> 20,
  7198. last[2] >> 20
  7199. );
  7200. self.log_video_memory("right after that change");
  7201. }
  7202. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  7203. }
  7204. /// Both of the system's memory groups for this process, in bytes: for
  7205. /// the card's own memory and then for the PC's memory shared with the
  7206. /// card, the budget, the use, what could still be reserved and what
  7207. /// is reserved (the layer reserves none).
  7208. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  7209. let adapter = self.adapter.as_ref()?;
  7210. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7211. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7212. // SAFETY: plain queries that fill our structures.
  7213. unsafe {
  7214. adapter
  7215. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7216. .ok()?;
  7217. adapter
  7218. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7219. .ok()?;
  7220. }
  7221. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  7222. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  7223. };
  7224. Some([all(&own), all(&shared)])
  7225. }
  7226. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  7227. pub(crate) fn log_video_memory(&self, when: &str) {
  7228. let Some([own, shared]) = self.video_memory_groups() else {
  7229. return;
  7230. };
  7231. tracing::info!(
  7232. "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)",
  7233. when,
  7234. own[0] >> 20,
  7235. own[1] >> 20,
  7236. own[2] >> 20,
  7237. own[3] >> 20,
  7238. shared[0] >> 20,
  7239. shared[1] >> 20,
  7240. shared[2] >> 20,
  7241. shared[3] >> 20
  7242. );
  7243. }
  7244. /// A buffer in system memory that the CPU maps (write-back, so reading
  7245. /// it is fast too) and shaders read and write: for host copies of title
  7246. /// memory that shaders write, which upload memory cannot be. Starts in
  7247. /// the common state (buffers move out of it implicitly).
  7248. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7249. MADE[2].fetch_add(1, Ordering::Relaxed);
  7250. MADE[3].fetch_add(size, Ordering::Relaxed);
  7251. let heap = D3D12_HEAP_PROPERTIES {
  7252. Type: D3D12_HEAP_TYPE_CUSTOM,
  7253. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  7254. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  7255. ..Default::default()
  7256. };
  7257. let desc = D3D12_RESOURCE_DESC {
  7258. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7259. Width: size.max(1),
  7260. Height: 1,
  7261. DepthOrArraySize: 1,
  7262. MipLevels: 1,
  7263. SampleDesc: DXGI_SAMPLE_DESC {
  7264. Count: 1,
  7265. Quality: 0,
  7266. },
  7267. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7268. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7269. ..Default::default()
  7270. };
  7271. let mut buffer: Option<ID3D12Resource> = None;
  7272. let mut data = std::ptr::null_mut();
  7273. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7274. let made = unsafe {
  7275. self.device
  7276. .CreateCommittedResource(
  7277. &heap,
  7278. D3D12_HEAP_FLAG_NONE,
  7279. &desc,
  7280. D3D12_RESOURCE_STATE_COMMON,
  7281. None,
  7282. &mut buffer,
  7283. )
  7284. .and_then(|()| {
  7285. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7286. b.Map(0, None, Some(&mut data))
  7287. })
  7288. };
  7289. match made {
  7290. Ok(()) => Some((buffer?, data.cast())),
  7291. Err(e) => {
  7292. tracing::warn!(error = %e, size, "no shared buffer");
  7293. None
  7294. }
  7295. }
  7296. }
  7297. /// A device-local buffer shaders may write (unordered access) and indirect
  7298. /// execution may read, starting in the common state.
  7299. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7300. MADE[4].fetch_add(1, Ordering::Relaxed);
  7301. MADE[5].fetch_add(size, Ordering::Relaxed);
  7302. let heap = D3D12_HEAP_PROPERTIES {
  7303. Type: D3D12_HEAP_TYPE_DEFAULT,
  7304. ..Default::default()
  7305. };
  7306. let desc = D3D12_RESOURCE_DESC {
  7307. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7308. Width: size.max(1),
  7309. Height: 1,
  7310. DepthOrArraySize: 1,
  7311. MipLevels: 1,
  7312. SampleDesc: DXGI_SAMPLE_DESC {
  7313. Count: 1,
  7314. Quality: 0,
  7315. },
  7316. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7317. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7318. ..Default::default()
  7319. };
  7320. let mut buffer: Option<ID3D12Resource> = None;
  7321. // SAFETY: plain creation of a device-local buffer.
  7322. let made = unsafe {
  7323. self.device.CreateCommittedResource(
  7324. &heap,
  7325. D3D12_HEAP_FLAG_NONE,
  7326. &desc,
  7327. D3D12_RESOURCE_STATE_COMMON,
  7328. None,
  7329. &mut buffer,
  7330. )
  7331. };
  7332. match made {
  7333. Ok(()) => buffer,
  7334. Err(e) => {
  7335. tracing::warn!(error = %e, size, "no unordered-access buffer");
  7336. None
  7337. }
  7338. }
  7339. }
  7340. }
  7341. /// For adapters without device-removed data (the software one): the last
  7342. /// commands each list of the failed submission noted (diagnostics, with
  7343. /// `VICTORY_D3D12_DRED`).
  7344. fn last_notes(runs: &[&HostList]) -> String {
  7345. #[cfg(feature = "diagnostics")]
  7346. {
  7347. let mut text = String::new();
  7348. for (i, r) in runs.iter().enumerate() {
  7349. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  7350. for (n, _) in notes.iter().rev().take(6).rev() {
  7351. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  7352. }
  7353. }
  7354. text
  7355. }
  7356. #[cfg(not(feature = "diagnostics"))]
  7357. {
  7358. let _ = runs;
  7359. String::new()
  7360. }
  7361. }
  7362. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  7363. /// command reads (diagnostics).
  7364. #[cfg(feature = "diagnostics")]
  7365. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  7366. let end = start + bytes;
  7367. if va < start {
  7368. format!(" (fault {:#x} below its source)", start - va)
  7369. } else if va < end {
  7370. format!(" (fault at source +{:#x})", va - start)
  7371. } else {
  7372. format!(" (fault {:#x} past its source's end)", va - end)
  7373. }
  7374. }
  7375. /// The commands that may have been running where a list stopped at
  7376. /// command `done`: those between the barriers around it (work between
  7377. /// barriers overlaps on the GPU), by kind, and what the markers just
  7378. /// before them say (`HostList::note_op`: diagnostics builds with
  7379. /// device-removed data on).
  7380. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  7381. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  7382. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  7383. let to = history[done..]
  7384. .iter()
  7385. .position(barrier)
  7386. .map_or(history.len(), |b| (done + b).max(done + 1));
  7387. let mut text = format!(", commands {from}..{to} between its barriers:");
  7388. let mut shown = 0;
  7389. // From just before the command the GPU had not finished: the first
  7390. // twelve after the barrier named draws long done when a list of 79
  7391. // mesh draws stopped at its 45th (run 41).
  7392. for i in from.max(done.saturating_sub(4))..to {
  7393. let op = history[i];
  7394. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  7395. continue;
  7396. }
  7397. shown += 1;
  7398. let marker = i
  7399. .checked_sub(1)
  7400. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  7401. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  7402. .map_or("no marker", |(_, s)| s.as_str());
  7403. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  7404. }
  7405. text
  7406. }
  7407. pub(crate) fn transition(
  7408. resource: &ID3D12Resource,
  7409. before: D3D12_RESOURCE_STATES,
  7410. after: D3D12_RESOURCE_STATES,
  7411. ) -> D3D12_RESOURCE_BARRIER {
  7412. D3D12_RESOURCE_BARRIER {
  7413. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  7414. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  7415. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  7416. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  7417. // SAFETY: a borrowed pointer; the barrier never releases it.
  7418. pResource: unsafe { std::mem::transmute_copy(resource) },
  7419. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  7420. StateBefore: before,
  7421. StateAfter: after,
  7422. }),
  7423. },
  7424. }
  7425. }
  7426. /// A window of the given client size, owned by its own message thread.
  7427. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7428. let (sender, receiver) = std::sync::mpsc::channel();
  7429. std::thread::Builder::new()
  7430. .name("victory-window".into())
  7431. .spawn(move || {
  7432. let made = make_window(width, height);
  7433. let ok = made.is_ok();
  7434. let _ = sender.send(made.map(|h| h.0 as usize));
  7435. if ok {
  7436. pump();
  7437. }
  7438. })
  7439. .map_err(|_| windows::core::Error::empty())?;
  7440. let hwnd = receiver
  7441. .recv()
  7442. .map_err(|_| windows::core::Error::empty())??;
  7443. Ok(HWND(hwnd as *mut _))
  7444. }
  7445. extern "system" fn window_proc(
  7446. hwnd: HWND,
  7447. message: u32,
  7448. wparam: WPARAM,
  7449. lparam: LPARAM,
  7450. ) -> LRESULT {
  7451. // SAFETY: the default handling for our window.
  7452. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  7453. }
  7454. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7455. const CLASS: PCWSTR = w!("VIctory");
  7456. // SAFETY: registers our class once and creates a window of it.
  7457. unsafe {
  7458. let instance = GetModuleHandleW(None)?;
  7459. let class = WNDCLASSEXW {
  7460. cbSize: size_of::<WNDCLASSEXW>() as u32,
  7461. lpfnWndProc: Some(window_proc),
  7462. hInstance: instance.into(),
  7463. lpszClassName: CLASS,
  7464. hCursor: LoadCursorW(None, IDC_ARROW)?,
  7465. ..Default::default()
  7466. };
  7467. RegisterClassExW(&class);
  7468. let mut rect = RECT {
  7469. left: 0,
  7470. top: 0,
  7471. right: width as i32,
  7472. bottom: height as i32,
  7473. };
  7474. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  7475. CreateWindowExW(
  7476. WINDOW_EX_STYLE(0),
  7477. CLASS,
  7478. w!("VIctory"),
  7479. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  7480. CW_USEDEFAULT,
  7481. CW_USEDEFAULT,
  7482. rect.right - rect.left,
  7483. rect.bottom - rect.top,
  7484. None,
  7485. None,
  7486. Some(instance.into()),
  7487. None,
  7488. )
  7489. }
  7490. }
  7491. fn pump() {
  7492. let mut message = MSG::default();
  7493. // SAFETY: the standard message loop of this thread's window.
  7494. unsafe {
  7495. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  7496. let _ = TranslateMessage(&message);
  7497. DispatchMessageW(&message);
  7498. }
  7499. }
  7500. }
  7501. #[cfg(test)]
  7502. mod trail {
  7503. /// The trail keeps the newest things, and the report made when the
  7504. /// host device is removed says them and the pipeline library's state
  7505. /// (no card is asked for any of it).
  7506. #[test]
  7507. fn the_removal_report_says_the_newest_things_done() {
  7508. for n in 0..super::TRAIL_MOST + 5 {
  7509. super::trail(|| format!("thing {n} done"));
  7510. }
  7511. let text = super::removal_context();
  7512. assert!(text.contains("the submitting thread was"));
  7513. assert!(text.contains("pipeline library: no call running"));
  7514. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  7515. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  7516. }
  7517. }
  7518. #[cfg(test)]
  7519. mod spare {
  7520. use super::Spare;
  7521. /// Kept things come back by size, the last given first, and nothing is
  7522. /// kept past the limit.
  7523. #[test]
  7524. fn kept_things_come_back_by_size_within_the_limit() {
  7525. let mut spare: Spare<u32> = Spare::new();
  7526. assert_eq!(spare.take(4), None);
  7527. assert_eq!(spare.give(1, 4, 10), None);
  7528. assert_eq!(spare.give(2, 1, 10), None);
  7529. assert_eq!(spare.give(3, 4, 10), None);
  7530. assert_eq!(spare.bytes, 9);
  7531. // Past the limit: handed back, nothing changes.
  7532. assert_eq!(spare.give(4, 4, 10), Some(4));
  7533. assert_eq!(spare.bytes, 9);
  7534. assert_eq!(spare.take(2), None, "no thing of that size");
  7535. assert_eq!(spare.take(4), Some(3));
  7536. assert_eq!(spare.take(4), Some(1));
  7537. assert_eq!(spare.take(4), None);
  7538. assert_eq!(spare.take(1), Some(2));
  7539. assert_eq!(spare.bytes, 0);
  7540. assert!(spare.kept.is_empty());
  7541. }
  7542. }
  7543. #[cfg(test)]
  7544. mod refresh_tests {
  7545. use super::Batch;
  7546. use crate::shadow::Shadow;
  7547. use std::sync::Arc;
  7548. use windows_sys::Win32::System::Memory::{
  7549. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  7550. VirtualAlloc,
  7551. };
  7552. const PAGE: usize = 64 << 10;
  7553. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  7554. /// Title memory for the tests (never given back: copies of it stay in
  7555. /// the guards): write-watched, or a view of a section.
  7556. fn title(len: usize, view: bool) -> usize {
  7557. // SAFETY: plain allocations.
  7558. let at = unsafe {
  7559. if view {
  7560. let section =
  7561. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  7562. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  7563. // As the runtime tells of it.
  7564. crate::title_memory_section(section as usize, len as u64, true);
  7565. crate::title_memory_remapped(at, len);
  7566. crate::title_memory_view(at, len, section as usize, 0);
  7567. at
  7568. } else {
  7569. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  7570. }
  7571. };
  7572. assert_ne!(at, 0);
  7573. at
  7574. }
  7575. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  7576. /// and every fourth page not there: as a title that streams has it.
  7577. fn with_holes(blocks: usize) -> usize {
  7578. use windows_sys::Win32::System::Memory::{
  7579. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  7580. VirtualAlloc2, VirtualFree,
  7581. };
  7582. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7583. // SAFETY: a placeholder and a section of our own.
  7584. unsafe {
  7585. let at = VirtualAlloc2(
  7586. GetCurrentProcess(),
  7587. std::ptr::null(),
  7588. blocks * PAGE,
  7589. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  7590. PAGE_NOACCESS,
  7591. std::ptr::null_mut(),
  7592. 0,
  7593. ) as usize;
  7594. assert_ne!(at, 0);
  7595. let len = blocks * PAGE;
  7596. let section =
  7597. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  7598. for block in (0..blocks).filter(|b| b % 4 != 3) {
  7599. let to = at + block * PAGE;
  7600. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  7601. let view = MapViewOfFile3(
  7602. section,
  7603. GetCurrentProcess(),
  7604. to as *const _,
  7605. (block * PAGE) as u64,
  7606. PAGE,
  7607. MEM_REPLACE_PLACEHOLDER,
  7608. PAGE_READWRITE,
  7609. std::ptr::null_mut(),
  7610. 0,
  7611. );
  7612. assert_eq!(view.Value as usize, to);
  7613. crate::title_memory_remapped(to, PAGE);
  7614. }
  7615. at
  7616. }
  7617. }
  7618. fn memory(len: usize) -> *mut u8 {
  7619. // SAFETY: a plain allocation.
  7620. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  7621. }
  7622. struct Random(u64);
  7623. impl Random {
  7624. fn below(&mut self, n: usize) -> usize {
  7625. self.0 ^= self.0 << 13;
  7626. self.0 ^= self.0 >> 7;
  7627. self.0 ^= self.0 << 17;
  7628. (self.0 >> 11) as usize % n
  7629. }
  7630. }
  7631. /// Prepares as a submission does: one asking for all the ranges, the
  7632. /// refreshes in several flushes, the asking's end.
  7633. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  7634. // One at a time, as submissions are.
  7635. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  7636. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  7637. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  7638. crate::watch::ask_once(&asked);
  7639. let mut batch = Batch::default();
  7640. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  7641. for (shadow, at, len) in part {
  7642. batch.add(shadow, *at, *len);
  7643. }
  7644. batch.flush();
  7645. }
  7646. crate::watch::ask_once_end();
  7647. }
  7648. /// Whatever is written where, by the title or by us, and whichever
  7649. /// copies (of both kinds of memory, over one another, none on a page
  7650. /// line) are refreshed in which ranges: a refreshed range holds what
  7651. /// title memory holds.
  7652. #[test]
  7653. fn refreshed_ranges_hold_title_memory() {
  7654. // SAFETY (all blocks): title memory and copies of the test's own,
  7655. // written by this thread and, in `Batch::flush`, by the threads that
  7656. // refresh, which are done when it returns.
  7657. let mut random = Random(0x1234_5678_9ABC_DEF1);
  7658. const LEN: usize = 24 * PAGE;
  7659. let regions = [title(LEN, false), title(LEN, true)];
  7660. let mut copies = Vec::new();
  7661. for &region in &regions {
  7662. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  7663. let data = memory(to - from);
  7664. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  7665. }
  7666. }
  7667. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  7668. for round in 0..600 {
  7669. for _ in 0..random.below(4) {
  7670. let at = regions[random.below(2)] + random.below(LEN - 64);
  7671. let n = 1 + random.below(60);
  7672. if random.below(3) == 0 {
  7673. // What shaders wrote.
  7674. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  7675. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  7676. Shadow::put(at, &was, &now);
  7677. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  7678. continue;
  7679. }
  7680. for i in 0..n {
  7681. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  7682. }
  7683. }
  7684. let mut ranges = Vec::new();
  7685. for (shadow, _) in &copies {
  7686. if random.below(3) == 0 {
  7687. continue;
  7688. }
  7689. let (start, len) = shadow.span();
  7690. let (start, len) = (start as usize, len as usize);
  7691. // Often the range of the time before, as a list's is.
  7692. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  7693. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  7694. ranges.push((shadow.clone(), start + from, n));
  7695. }
  7696. if ranges.is_empty() {
  7697. continue;
  7698. }
  7699. let flushes = 1 + random.below(3);
  7700. submission(&ranges, flushes);
  7701. for (shadow, at, n) in &ranges {
  7702. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  7703. let start = shadow.span().0 as usize;
  7704. let same = unsafe {
  7705. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  7706. };
  7707. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  7708. }
  7709. }
  7710. }
  7711. /// A copy in the card's memory, with the card's side and the sends to it
  7712. /// played by the test.
  7713. struct Carded {
  7714. shadow: Arc<Shadow>,
  7715. data: usize,
  7716. start: usize,
  7717. len: usize,
  7718. /// The last send, the last send every fetch to come is behind, and
  7719. /// the card's bytes: the queue's order is the order it is locked in.
  7720. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  7721. /// Whether a flight that writes it has not landed.
  7722. flying: std::sync::atomic::AtomicBool,
  7723. /// The dword of each eight its shaders write.
  7724. class: usize,
  7725. }
  7726. impl Carded {
  7727. fn new(start: usize, len: usize, class: usize) -> Carded {
  7728. let data = memory(len);
  7729. Carded {
  7730. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  7731. data: data as usize,
  7732. start,
  7733. len,
  7734. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  7735. flying: std::sync::atomic::AtomicBool::new(false),
  7736. class,
  7737. }
  7738. }
  7739. /// What changed on the CPU's side goes up.
  7740. fn send(&self) {
  7741. let mut card = self.card.lock().unwrap();
  7742. card.0 += 1;
  7743. let (number, merged) = (card.0, card.1);
  7744. for (a, b) in self.shadow.send_up(number, merged) {
  7745. // SAFETY: the copy's bytes; nothing writes those that are to
  7746. // go up.
  7747. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  7748. }
  7749. }
  7750. }
  7751. /// Everything at once: the title writes its memory on two threads, the
  7752. /// submitting thread puts its bytes in under shader writes
  7753. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  7754. /// the card's memory, one not), sends up what changed and declares what
  7755. /// the next flight's shaders write, and what flights wrote is landed
  7756. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  7757. /// still and the copies are refreshed once more, each of them, and the
  7758. /// card's side of those that have one, hold what title memory holds, and
  7759. /// title memory what was written last.
  7760. ///
  7761. /// Into the first copy shaders write besides through a view nobody
  7762. /// declared, words the title does not write: nothing that goes up ever
  7763. /// puts an older value over those.
  7764. ///
  7765. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  7766. /// only takes the block out of the guards' clean ones and leaves its bit,
  7767. /// or if a fault leaves the bit; in some thousand rounds,
  7768. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  7769. #[test]
  7770. fn landings_title_writes_and_light_refreshes_at_once() {
  7771. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  7772. assert!(crate::safecopy::on());
  7773. const LEN: usize = 24 * PAGE;
  7774. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  7775. let region = title(LEN, true);
  7776. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  7777. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  7778. let plain = {
  7779. let (start, len) = (region + 700, LEN - 9000);
  7780. let data = memory(len);
  7781. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  7782. };
  7783. // What was last written so, by offset.
  7784. let mut undeclared = std::collections::HashMap::new();
  7785. let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0");
  7786. let stop = AtomicBool::new(false);
  7787. // Also when an assertion fails on one of the threads.
  7788. struct Stop<'a>(&'a AtomicBool);
  7789. impl Drop for Stop<'_> {
  7790. fn drop(&mut self) {
  7791. self.0.store(true, Ordering::Relaxed);
  7792. }
  7793. }
  7794. // Held shared by who writes title memory, alone while it is looked at.
  7795. let still = std::sync::RwLock::new(());
  7796. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  7797. std::thread::scope(|s| {
  7798. for t in 0..2usize {
  7799. let (stop, still) = (&stop, &still);
  7800. s.spawn(move || {
  7801. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  7802. let mut value = 0u32;
  7803. while !stop.load(Ordering::Relaxed) {
  7804. {
  7805. let _moving = still.read().unwrap();
  7806. for _ in 0..3 {
  7807. value += 1;
  7808. // Of each eight dwords, one a thread.
  7809. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  7810. dword(at).store(value, Ordering::Relaxed);
  7811. }
  7812. }
  7813. std::thread::sleep(std::time::Duration::from_micros(20));
  7814. }
  7815. });
  7816. }
  7817. // Lands flights.
  7818. {
  7819. let (carded, stop) = (&carded, &stop);
  7820. s.spawn(move || {
  7821. let _stop = Stop(stop);
  7822. while let Ok((which, ranges, value)) = flights.recv() {
  7823. let c = &carded[which];
  7824. // Fetched: the card's bytes, behind every send so far.
  7825. let (after, now) = {
  7826. let card = c.card.lock().unwrap();
  7827. (card.0, card.2.clone())
  7828. };
  7829. // By piece: 64 KiB of title memory.
  7830. let mut pieces = Vec::new();
  7831. for &(from, to) in &ranges {
  7832. let mut at = from;
  7833. while at < to {
  7834. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  7835. pieces.push((at, next, now.as_ptr() as usize + at));
  7836. at = next;
  7837. }
  7838. }
  7839. let parts: Vec<_> = pieces.chunks(3).collect();
  7840. crate::land::each(parts.len(), &|i| {
  7841. let mut notes = crate::land::Notes::default();
  7842. // SAFETY: the bytes of `now`; each piece once.
  7843. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  7844. notes.flush();
  7845. });
  7846. for &(from, to) in &ranges {
  7847. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  7848. // (The next fetch may have brought more.)
  7849. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  7850. }
  7851. }
  7852. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  7853. c.shadow.copy_back_done(&done);
  7854. c.card.lock().unwrap().1 = after;
  7855. c.flying.store(false, Ordering::Release);
  7856. }
  7857. });
  7858. }
  7859. let _stop = Stop(&stop);
  7860. let mut random = Random(0xABCD_EF01_2345_6789);
  7861. let check = |round: usize, random: &mut Random, quiet: bool| {
  7862. for c in &carded {
  7863. if c.shadow.writes_pending() {
  7864. let mut runs = usize::MAX;
  7865. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  7866. }
  7867. }
  7868. let mut ranges = Vec::new();
  7869. for (shadow, start, len) in
  7870. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  7871. {
  7872. // All of it, or a part; often the same part.
  7873. let (from, n) = match random.below(3) {
  7874. _ if quiet => (0, len),
  7875. 0 => (0, len),
  7876. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  7877. _ => {
  7878. let from = random.below(len / 4) * 4;
  7879. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  7880. }
  7881. };
  7882. ranges.push((shadow.clone(), start + from, n));
  7883. }
  7884. submission(&ranges, 1 + random.below(3));
  7885. carded.iter().for_each(Carded::send);
  7886. };
  7887. let mut value = 1u32;
  7888. for round in 0..rounds {
  7889. check(round, &mut random, false);
  7890. if exact {
  7891. let c = &carded[0];
  7892. let mut card = c.card.lock().unwrap();
  7893. for _ in 0..40 {
  7894. value += 1;
  7895. let at = random.below(LEN / 32) * 32 + 4 * 6;
  7896. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  7897. undeclared.insert(at, value);
  7898. }
  7899. }
  7900. // The flight of this submission: its shaders' writes.
  7901. for (which, c) in carded.iter().enumerate() {
  7902. if c.flying.swap(true, Ordering::Acquire) {
  7903. continue;
  7904. }
  7905. value += 1;
  7906. let mut ranges: Vec<(usize, usize)> = Vec::new();
  7907. let first = random.below(6) * PAGE / 2;
  7908. for k in 0..2 {
  7909. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  7910. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  7911. if from < to {
  7912. ranges.push((from, to));
  7913. }
  7914. }
  7915. for &(from, to) in &ranges {
  7916. c.shadow.writing(c.start + from, to - from);
  7917. }
  7918. {
  7919. let mut card = c.card.lock().unwrap();
  7920. for &(from, to) in &ranges {
  7921. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  7922. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  7923. }
  7924. }
  7925. }
  7926. fly.send((which, ranges, value)).unwrap();
  7927. }
  7928. if round % 20 != 19 {
  7929. continue;
  7930. }
  7931. // Still: no flight in the air, no title write.
  7932. let _still = still.write().unwrap();
  7933. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  7934. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  7935. std::thread::yield_now();
  7936. }
  7937. check(round, &mut random, true);
  7938. // SAFETY: the test's own memory, written by nobody now.
  7939. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  7940. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  7941. for c in &carded {
  7942. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  7943. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  7944. let card = c.card.lock().unwrap();
  7945. let mut side = card.2.clone();
  7946. if c.class == carded[0].class {
  7947. // (They may have been landed meanwhile, by a flight
  7948. // that declared their range, and may not.)
  7949. for (&at, &value) in &undeclared {
  7950. let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
  7951. assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
  7952. side[at..at + 4].copy_from_slice(&there[at..at + 4]);
  7953. }
  7954. }
  7955. assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
  7956. }
  7957. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  7958. }
  7959. drop(fly);
  7960. });
  7961. }
  7962. /// The title's bytes put in under shader writes, for a copy of 174 MB
  7963. /// whose shader writes were declared as 40 ranges that overlap, with 12
  7964. /// pages written since. Run with `--ignored --nocapture`, and with
  7965. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  7966. #[test]
  7967. #[ignore]
  7968. fn bytes_under_overlapping_ranges() {
  7969. const BIG: usize = 174 << 20;
  7970. let big = title(BIG, true);
  7971. // SAFETY (both): the test's own memory.
  7972. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  7973. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  7974. copy.update(big, BIG);
  7975. copy.take_dirty();
  7976. for i in 0..40 {
  7977. copy.writing(big + i * 5920, BIG - i * 5920);
  7978. }
  7979. let mut best = f64::MAX;
  7980. for round in 0..30 {
  7981. for i in 0..12 {
  7982. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  7983. }
  7984. let started = std::time::Instant::now();
  7985. let mut runs = usize::MAX;
  7986. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  7987. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  7988. copy.take_dirty();
  7989. }
  7990. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  7991. }
  7992. /// A range nothing wrote is known to be as it was, at its ends too, and
  7993. /// is so no more once something wrote it.
  7994. #[test]
  7995. fn unchanged_ranges_are_known() {
  7996. for view in [false, true] {
  7997. let region = title(8 * PAGE, view);
  7998. // (A page read for the first time counts as written.)
  7999. // SAFETY: the test's own memory.
  8000. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  8001. let data = memory(8 * PAGE);
  8002. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  8003. // Ends in the middle of pages.
  8004. let (at, len) = (region + 500, 5 * PAGE);
  8005. let look = |expected: bool, what: &str| {
  8006. // The submission's one asking, which takes two ranges. (Again
  8007. // if a submission of another test ended it.)
  8008. let mut known = false;
  8009. for _ in 0..100 {
  8010. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  8011. known = copy.nothing_new(at, len);
  8012. if known || !expected {
  8013. break;
  8014. }
  8015. }
  8016. assert_eq!(known, expected, "view {view}: {what}");
  8017. let copied = copy.update(at, len);
  8018. crate::watch::ask_once_end();
  8019. copied
  8020. };
  8021. assert_eq!(look(false, "never taken"), len);
  8022. assert_eq!(look(true, "taken"), 0);
  8023. assert_eq!(look(true, "taken"), 0);
  8024. // SAFETY: the test's own memory.
  8025. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  8026. assert_eq!(look(false, "written at its end"), PAGE - 500);
  8027. assert_eq!(look(true, "taken again"), 0);
  8028. // Outside the range, on its last page.
  8029. // SAFETY: as above.
  8030. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  8031. assert_eq!(look(false, "written on its last page"), 500);
  8032. // A longer range was never taken whole.
  8033. assert!(!copy.nothing_new(region, 6 * PAGE));
  8034. }
  8035. }
  8036. /// Of a copy in the card's memory only the dwords title memory changed go
  8037. /// up, and none beside them, not even between two in 64 bytes; a page
  8038. /// never taken goes up whole.
  8039. #[test]
  8040. fn only_what_differs_goes_up() {
  8041. let region = title(4 * PAGE, true);
  8042. let data = memory(4 * PAGE);
  8043. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  8044. copy.update(region, 4 * PAGE);
  8045. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  8046. // What the relay does: shader writes into title memory, and into the
  8047. // CPU's side.
  8048. crate::watch::landing(region + PAGE + 640, 64);
  8049. // SAFETY: the test's own memory.
  8050. unsafe {
  8051. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  8052. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  8053. }
  8054. copy.update(region, 4 * PAGE);
  8055. let again = copy.take_dirty();
  8056. // SAFETY: as above.
  8057. unsafe {
  8058. ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
  8059. ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
  8060. ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
  8061. // The value that was there.
  8062. ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
  8063. }
  8064. copy.update(region, 4 * PAGE);
  8065. let written = copy.take_dirty();
  8066. if std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0") {
  8067. assert_eq!(again, []);
  8068. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
  8069. } else {
  8070. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  8071. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  8072. }
  8073. // SAFETY: as above.
  8074. assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
  8075. }
  8076. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  8077. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  8078. /// big copy that 55 landed pieces and 9 title writes opened, while a
  8079. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  8080. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8081. #[test]
  8082. #[ignore]
  8083. fn frame_of_refreshes() {
  8084. let mut random = Random(0x9876_5432_1234_5671);
  8085. const EACH: usize = 224 << 10;
  8086. const BIG: usize = 174 << 20;
  8087. let watched = title(3000 * EACH, false);
  8088. // `VICTORY_BENCH_HOLES=0`: views without holes.
  8089. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  8090. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  8091. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  8092. let big = title(BIG, true);
  8093. // SAFETY: the test's own memory.
  8094. unsafe {
  8095. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  8096. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  8097. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  8098. }
  8099. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  8100. }
  8101. let mut small = Vec::new();
  8102. for i in 0..4400 {
  8103. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  8104. let data = memory(EACH);
  8105. // The range views read, not all of the copy.
  8106. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  8107. }
  8108. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  8109. // The same memory, as another copy: what is landed is landed through
  8110. // it, and the refreshes are of the first.
  8111. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8112. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  8113. let (mut sum, mut landing) = (0.0, 0.0);
  8114. const FRAMES: usize = 12;
  8115. for frame in 0..FRAMES {
  8116. let mut took = [0f64; 2];
  8117. for i in 0..30 {
  8118. // The title's writes, and the relay's beside the submission.
  8119. for _ in 0..9 {
  8120. let at = views + random.below(1400 * EACH / 8) * 8;
  8121. if there(at) {
  8122. // SAFETY: the test's own memory.
  8123. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8124. }
  8125. }
  8126. for _ in 0..60 {
  8127. let at = watched + random.below(3000 * EACH / 8) * 8;
  8128. // SAFETY: the test's own memory.
  8129. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8130. }
  8131. let first = random.below(BIG / PAGE - 60);
  8132. let lands = lands.clone();
  8133. let land = std::thread::spawn(move || {
  8134. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  8135. let started = std::time::Instant::now();
  8136. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  8137. let pieces: Vec<_> =
  8138. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  8139. let mut notes = crate::land::Notes::default();
  8140. // SAFETY: the bytes of `now`; nothing else lands here.
  8141. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  8142. notes.flush();
  8143. }
  8144. started.elapsed().as_secs_f64() * 1e3
  8145. });
  8146. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  8147. small.iter().cloned().chain([heap.clone()]).collect()
  8148. } else {
  8149. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  8150. };
  8151. let started = std::time::Instant::now();
  8152. submission(&ranges, 3);
  8153. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  8154. let put = land.join().unwrap();
  8155. if frame >= 2 {
  8156. landing += put;
  8157. }
  8158. heap.0.take_dirty();
  8159. }
  8160. if frame >= 2 {
  8161. sum += took[0] + took[1];
  8162. for k in 0..2 {
  8163. best[k] = best[k].min(took[k]);
  8164. asking[k] += took[k];
  8165. }
  8166. }
  8167. }
  8168. println!(
  8169. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  8170. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  8171. crate::watch::light(),
  8172. sum / (FRAMES - 2) as f64,
  8173. asking[0] / (FRAMES - 2) as f64,
  8174. best[0],
  8175. asking[1] / (FRAMES - 2) as f64,
  8176. best[1],
  8177. landing / (FRAMES - 2) as f64,
  8178. );
  8179. #[cfg(feature = "diagnostics")]
  8180. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  8181. }
  8182. }
  8183. #[cfg(test)]
  8184. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  8185. use super::Batch;
  8186. use std::sync::Arc;
  8187. #[test]
  8188. fn a_texture_is_checked_once_per_submission() {
  8189. let mut batch = Batch::default();
  8190. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  8191. // The first list sampling each texture checks it ...
  8192. assert!(batch.texture_due(&a));
  8193. assert!(batch.texture_due(&b));
  8194. // ... later lists of the same submission do not.
  8195. assert!(!batch.texture_due(&a));
  8196. assert!(!batch.texture_due(&a.clone()));
  8197. assert!(!batch.texture_due(&b));
  8198. }
  8199. #[test]
  8200. fn title_writes_make_textures_due_again() {
  8201. let mut batch = Batch::default();
  8202. let a = Arc::new(1u32);
  8203. assert!(batch.texture_due(&a));
  8204. assert!(!batch.texture_due(&a));
  8205. // A copy into title memory or work that may write it may have
  8206. // changed the texture's memory.
  8207. batch.title_written();
  8208. assert!(batch.texture_due(&a));
  8209. assert!(!batch.texture_due(&a));
  8210. // A fresh submission starts over.
  8211. let mut next = Batch::default();
  8212. assert!(next.texture_due(&a));
  8213. }
  8214. /// The hashing a submission does for textures in physical-page memory,
  8215. /// with every list checking the textures it samples (before) and with
  8216. /// each checked once (after). Run with
  8217. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  8218. #[test]
  8219. #[ignore = "benchmark"]
  8220. fn texture_checks_per_submission() {
  8221. const TEXTURES: usize = 48;
  8222. const SIZE: usize = 4 << 20;
  8223. const LISTS: usize = 12;
  8224. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  8225. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  8226. .collect();
  8227. let submit = |dedupe: bool| {
  8228. let mut batch = Batch::default();
  8229. let mut hashed = 0usize;
  8230. let started = std::time::Instant::now();
  8231. for _ in 0..LISTS {
  8232. for t in &textures {
  8233. if !dedupe || batch.texture_due(t) {
  8234. std::hint::black_box(blake3::hash(t));
  8235. hashed += 1;
  8236. }
  8237. }
  8238. }
  8239. (started.elapsed(), hashed)
  8240. };
  8241. submit(false); // warm up
  8242. let (before, n_before) = submit(false);
  8243. let (after, n_after) = submit(true);
  8244. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  8245. println!(
  8246. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  8247. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  8248. SIZE >> 20,
  8249. before.as_secs_f64() / after.as_secs_f64()
  8250. );
  8251. }
  8252. #[test]
  8253. fn vram_idle_ms_scales_with_pressure() {
  8254. use super::vram_idle_ms;
  8255. let gib = 1024 * 1024 * 1024;
  8256. // Normal (< 75%)
  8257. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  8258. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  8259. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  8260. // Moderate (75%..85%)
  8261. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  8262. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  8263. // High (>= 85%, including over-budget)
  8264. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  8265. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  8266. // Missing or zero budget falls back to normal
  8267. assert_eq!(vram_idle_ms(None), 5_000);
  8268. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  8269. }
  8270. #[test]
  8271. fn ram_idle_ms_scales_with_pressure() {
  8272. use super::ram_idle_ms;
  8273. let gib = 1024 * 1024 * 1024;
  8274. // Normal (>= 4 GiB)
  8275. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  8276. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  8277. // Moderate (2 GiB..4 GiB)
  8278. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  8279. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  8280. // High (< 2 GiB)
  8281. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  8282. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  8283. // Missing falls back to normal
  8284. assert_eq!(ram_idle_ms(None), 10_000);
  8285. }
  8286. }