host.rs 371 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517
  1. //! The host GPU: one D3D12 device and direct queue (decision 0007), and a
  2. //! window to present on.
  3. //!
  4. //! shortcut: every submission is waited for, so CPU and GPU never overlap
  5. //! (unless `VICTORY_LATE_WAIT=1`, see [`late`]);
  6. //! overlap them with per-submission fences once more than clears run.
  7. use std::sync::atomic::{AtomicU32, Ordering};
  8. use std::sync::{Mutex, OnceLock};
  9. use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
  10. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  11. use windows::Win32::Graphics::Direct3D12::*;
  12. use windows::Win32::Graphics::Dxgi::Common::*;
  13. use windows::Win32::Graphics::Dxgi::*;
  14. use windows::Win32::System::LibraryLoader::GetModuleHandleW;
  15. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  16. use windows::Win32::UI::WindowsAndMessaging::*;
  17. use windows::core::{Interface, PCWSTR, w};
  18. /// Resource states without the console's own bits (compression hints from
  19. /// bit 25 up), which the host rejects.
  20. pub(crate) fn pc_state(state: u32) -> u32 {
  21. state & 0x01ff_ffff
  22. }
  23. /// A console state as a host texture state: PC bits only, and none of the
  24. /// buffer-only ones the console allows on textures (vertex, constant and
  25. /// index buffer, stream out, indirect arguments, as in "generic read").
  26. pub(crate) fn texture_state(state: u32) -> u32 {
  27. const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
  28. pc_state(state) & !BUFFER_ONLY
  29. }
  30. /// Render target views live only until their command is recorded, so a
  31. /// ring of host descriptors is enough.
  32. const RTV_RING: u32 = 1024;
  33. pub(crate) struct Host {
  34. pub(crate) device: ID3D12Device,
  35. queue: ID3D12CommandQueue,
  36. fence: ID3D12Fence,
  37. /// The last value signalled on `fence`, behind the submission lock.
  38. submitted: Mutex<u64>,
  39. event: HANDLE,
  40. rtvs: ID3D12DescriptorHeap,
  41. rtv_size: u32,
  42. /// A ring of depth views, used as `rtvs`.
  43. dsvs: ID3D12DescriptorHeap,
  44. dsv_size: u32,
  45. next_dsv: AtomicU32,
  46. /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug
  47. /// layer's messages.
  48. messages: Option<ID3D12InfoQueue>,
  49. next_rtv: AtomicU32,
  50. presenter: Mutex<Option<Presenter>>,
  51. /// The adapter the device is on, for its memory budget
  52. /// ([`Host::video_memory`]); `None` if the system does not name it.
  53. adapter: Option<IDXGIAdapter3>,
  54. }
  55. // SAFETY: D3D12 devices, queues, fences and descriptor heaps are
  56. // free-threaded; the event handle is only waited on under `submitted`.
  57. unsafe impl Send for Host {}
  58. // SAFETY: as above.
  59. unsafe impl Sync for Host {}
  60. /// Host objects the title let go of while a submission may still use them
  61. /// (a texture its descriptors name, a descriptor slot's old resource), by
  62. /// the submission count they wait for. The title's descriptor writes and
  63. /// releases reach the host at once, from its own threads, while the host
  64. /// runs a submission: freeing there is a GPU page fault on the freed
  65. /// texture (a device hang).
  66. static RETIRED: Mutex<Vec<(u64, Retired)>> = Mutex::new(Vec::new());
  67. /// Submissions started and finished (waited for).
  68. static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  69. static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  70. /// A retired object, dropped on whatever thread finishes the submission.
  71. struct Retired(#[allow(dead_code)] Box<dyn std::any::Any>);
  72. // SAFETY: what is retired is D3D12 objects (free-threaded) and the
  73. // reference-counted wrappers holding them, dropped once.
  74. unsafe impl Send for Retired {}
  75. /// Milliseconds since the first call.
  76. pub(crate) fn now_ms() -> u64 {
  77. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  78. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  79. }
  80. /// This moment, for telling later how long ago it was ([`long_ago`]): the
  81. /// frames begun so far (high half, `crate::frame::current`) and tenths of a
  82. /// second since the start. Host copies of title memory, staging buffers and
  83. /// host textures note when they were last used with it.
  84. pub(crate) fn moment() -> u64 {
  85. (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff)
  86. }
  87. /// Whether `moment` lies at least `ms` milliseconds and `frames` frames
  88. /// back. Both: at seconds per frame, what every frame uses is not touched
  89. /// for seconds, and at many frames per second not for many frames. (A title
  90. /// that never waits for frames has no frame count: nothing is then idle.)
  91. pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
  92. let now = self::moment();
  93. let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
  94. (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
  95. }
  96. /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
  97. pub(crate) fn available_physical_ram() -> Option<u64> {
  98. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  99. // SAFETY: plain data the call fills in.
  100. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  101. m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
  102. // SAFETY: a sized structure.
  103. let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
  104. ok.then_some(m.ullAvailPhys)
  105. }
  106. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  107. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  108. /// handles not yet recorded into a list or slot remain protected.
  109. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  110. const NORMAL_MS: u64 = 5_000;
  111. const MODERATE_MS: u64 = 2_500;
  112. const HIGH_MS: u64 = 1_000;
  113. let Some([budget, used, ..]) = video_memory else {
  114. return NORMAL_MS;
  115. };
  116. if budget == 0 {
  117. return NORMAL_MS;
  118. }
  119. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  120. if used_pct >= 85 {
  121. HIGH_MS
  122. } else if used_pct >= 75 {
  123. MODERATE_MS
  124. } else {
  125. NORMAL_MS
  126. }
  127. }
  128. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  129. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  130. /// when free physical RAM is low. Never returns less than 2,000 ms.
  131. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  132. const GIB: u64 = 1024 * 1024 * 1024;
  133. const NORMAL_MS: u64 = 10_000;
  134. const MODERATE_MS: u64 = 5_000;
  135. const HIGH_MS: u64 = 2_000;
  136. let Some(avail) = avail_phys else {
  137. return NORMAL_MS;
  138. };
  139. if avail < 2 * GIB {
  140. HIGH_MS
  141. } else if avail < 4 * GIB {
  142. MODERATE_MS
  143. } else {
  144. NORMAL_MS
  145. }
  146. }
  147. /// How many references are held on a host object (its COM count): ours
  148. /// all, since the host's views and commands hold none. A buffer or texture
  149. /// with one is held by its owner alone: no descriptor slot keeps it
  150. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  151. pub(crate) fn references(object: &impl Interface) -> u32 {
  152. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  153. let raw = object.as_raw();
  154. // SAFETY: a live COM object, whose first three methods are those of
  155. // `IUnknown` (query, add a reference, release one); the pair leaves the
  156. // count as it was, and the release returns it. The first is not called.
  157. unsafe {
  158. let methods = *raw.cast::<*const [Method; 3]>();
  159. ((*methods)[1])(raw);
  160. ((*methods)[2])(raw)
  161. }
  162. }
  163. /// Once a second, before a submission starts: lets go of what nothing
  164. /// names any more (copies of windows of title memory, staging buffers,
  165. /// host copies of textures the title fills).
  166. /// `VICTORY_SWEEP=0` keeps everything, as before.
  167. fn sweep() {
  168. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  169. crate::inplace::tick();
  170. static ON: OnceLock<bool> = OnceLock::new();
  171. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  172. return;
  173. }
  174. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  175. let now = now_ms();
  176. let last = LAST.load(Ordering::Relaxed);
  177. if now < last + 1000
  178. || LAST
  179. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  180. .is_err()
  181. {
  182. return;
  183. }
  184. crate::pipeline::trim_library();
  185. crate::shadow::let_go_idle();
  186. crate::texture::let_go_idle();
  187. crate::resource::let_go_idle();
  188. }
  189. /// Drops `object` once every submission running now has finished: at once
  190. /// if none is.
  191. pub(crate) fn retire<T: 'static>(object: T) {
  192. let started = STARTED.load(Ordering::Acquire);
  193. if started <= FINISHED.load(Ordering::Acquire) {
  194. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  195. drop(object);
  196. return;
  197. }
  198. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  199. RETIRED
  200. .lock()
  201. .unwrap_or_else(|e| e.into_inner())
  202. .push((started, Retired(Box::new(object))));
  203. }
  204. /// Drops what waited for submissions up to `finished`.
  205. fn bury(finished: u64) {
  206. let done: Vec<(u64, Retired)> = {
  207. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  208. if retired.is_empty() {
  209. return;
  210. }
  211. let (done, keep) = std::mem::take(&mut *retired)
  212. .into_iter()
  213. .partition(|(at, _)| *at <= finished);
  214. *retired = keep;
  215. done
  216. };
  217. drop(done);
  218. }
  219. /// Objects [`retire`] dropped at once (no submission was running) and
  220. /// kept until a running submission finished, since the start.
  221. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  222. /// What the layer did to the host's objects lately, newest last (sweeps
  223. /// that let host copies go, pipeline library calls, saves and trims): said
  224. /// once when the host device is removed ([`log_removal_context`]), with
  225. /// what the submitting thread and the pipeline workers were doing at that
  226. /// moment. A device the driver removes "internally" names no command, and
  227. /// the pass that happens to notice first names only the view it was at:
  228. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  229. /// pipeline library call that no line of the log tied to them.
  230. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  231. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  232. /// The entries kept.
  233. const TRAIL_MOST: usize = 96;
  234. fn trail_on() -> bool {
  235. static ON: OnceLock<bool> = OnceLock::new();
  236. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  237. }
  238. /// Microseconds since the first call.
  239. pub(crate) fn now_us() -> u64 {
  240. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  241. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  242. }
  243. /// The calling thread, as the log's other lines name threads.
  244. pub(crate) fn thread_id() -> u32 {
  245. // SAFETY: a plain query.
  246. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  247. }
  248. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  249. /// run when the trail is kept.
  250. pub(crate) fn trail(what: impl FnOnce() -> String) {
  251. if !trail_on() {
  252. return;
  253. }
  254. let entry = (now_us(), thread_id(), what());
  255. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  256. if trail.len() >= TRAIL_MOST {
  257. trail.pop_front();
  258. }
  259. trail.push_back(entry);
  260. }
  261. /// What the submitting thread is doing (0 nothing: between submissions,
  262. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  263. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  264. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  265. fn submitting(phase: u64, lists: usize) {
  266. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  267. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  268. SUBMITTING[0].store(phase, Ordering::Relaxed);
  269. }
  270. /// What was going on when the host device went: whether a submission was
  271. /// on the card, the pipeline library's state and the calls running in it,
  272. /// and the trail.
  273. pub(crate) fn removal_context() -> String {
  274. use std::fmt::Write;
  275. let now = now_us();
  276. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  277. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  278. 0 => "between submissions (nothing of ours was running on the card)",
  279. 1 => "preparing a submission (nothing of ours was running on the card)",
  280. 2 => "waiting for the card to run a submission",
  281. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  282. };
  283. let mut text = format!(
  284. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  285. SUBMITTING[1].load(Ordering::Relaxed),
  286. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  287. crate::pipeline::library_removal_note(),
  288. RETIREMENTS[0].load(Ordering::Relaxed),
  289. RETIREMENTS[1].load(Ordering::Relaxed),
  290. STARTED.load(Ordering::Relaxed),
  291. FINISHED.load(Ordering::Relaxed),
  292. );
  293. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  294. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  295. for (at, thread, what) in trail.iter() {
  296. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  297. }
  298. text
  299. }
  300. /// Says [`removal_context`] in the log, once: called by whoever finds the
  301. /// host device removed.
  302. pub(crate) fn log_removal_context() {
  303. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  304. if !trail_on() || SAID.swap(true, Ordering::Relaxed) {
  305. return;
  306. }
  307. tracing::error!("when the host device went: {}", removal_context());
  308. }
  309. /// Time spent in submissions since the last frame-rate line, in
  310. /// microseconds: preparing them on the CPU (title memory copies, texture
  311. /// detiling), then waiting for the GPU.
  312. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  313. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  314. /// After submissions: shader-written ranges compared and copied back into
  315. /// title memory (microseconds, bytes that differed), since the last
  316. /// frame-rate line.
  317. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  318. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  319. /// The card's clock, for the frame line of every run, in microseconds since
  320. /// the last one: how long the card had nothing of ours queued; how much of
  321. /// that while the thread that holds the submission lock was working (the
  322. /// card idle behind us: preparing and copying back are done with the card
  323. /// standing); and how long that thread stood waiting for the card.
  324. ///
  325. /// Every send of lists to the queue is followed by a signal on a fence of
  326. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  327. /// the newest signal and notes the moment the card reached it with nothing
  328. /// newer sent; the next send ends that idle stretch.
  329. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  330. /// Of the thread that holds the submission lock: the microseconds it has
  331. /// worked so far (preparing, copying back; not its waits for the card), and
  332. /// since when it works now ([`now_us`] plus one; 0: it does not).
  333. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  334. /// The thread that holds the submission lock starts (`on`) or stops
  335. /// working; whether it worked until now.
  336. fn working(on: bool) -> bool {
  337. let now = now_us() + 1;
  338. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  339. if since != 0 {
  340. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  341. }
  342. since != 0
  343. }
  344. /// [`WORKING`] as of now: microseconds worked so far.
  345. fn worked() -> u64 {
  346. let since = WORKING[1].load(Ordering::Relaxed);
  347. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  348. WORKING[0].load(Ordering::Relaxed) + now
  349. }
  350. /// The thread that holds the submission lock stood waiting for the card
  351. /// from `since` until now ([`CARD_CLOCK_US`]).
  352. fn stood(since: std::time::Instant) {
  353. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  354. }
  355. /// What [`CARD_CLOCK_US`] is measured with.
  356. struct CardClock {
  357. fence: ID3D12Fence,
  358. /// Signals sent so far; and, while the card has reached the last of
  359. /// them, since when and what [`worked`] said then.
  360. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  361. sent: std::sync::Condvar,
  362. }
  363. // SAFETY: a fence (free-threaded) behind a lock.
  364. unsafe impl Send for CardClock {}
  365. // SAFETY: as above.
  366. unsafe impl Sync for CardClock {}
  367. /// The clock's thread: waits for the newest signal sent and notes when the
  368. /// card got there with nothing newer behind it.
  369. fn card_clock_watch(clock: &'static CardClock) {
  370. // SAFETY: a plain event of our own.
  371. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  372. return;
  373. };
  374. let mut seen = 0;
  375. loop {
  376. let target = {
  377. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  378. while state.0 == seen {
  379. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  380. }
  381. state.0
  382. };
  383. // SAFETY: the clock's fence and this thread's event.
  384. unsafe {
  385. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  386. WaitForSingleObject(event, INFINITE);
  387. }
  388. }
  389. seen = target;
  390. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  391. if state.0 == target && state.1.is_none() {
  392. state.1 = Some((std::time::Instant::now(), worked()));
  393. }
  394. }
  395. }
  396. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  397. /// frame's time.
  398. fn card_clock_line(frames: f64, ms: f64) {
  399. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  400. tracing::info!(
  401. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  402. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  403. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  404. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  405. );
  406. }
  407. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  408. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  409. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  410. std::sync::atomic::AtomicU64::new(0),
  411. std::sync::atomic::AtomicU64::new(0),
  412. std::sync::atomic::AtomicU64::new(0),
  413. std::sync::atomic::AtomicU64::new(0),
  414. ];
  415. /// Host buffers made since the start, as (count, bytes): in the upload heap
  416. /// (staging, list scratch), shared with the processor (host copies of title
  417. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  418. /// For the memory line: against what is alive, they show what was let go.
  419. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  420. /// What of that is alive now, for the memory line (`MADE` counts what was
  421. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  422. /// and nothing said how many were alive): host lists; the lists' scratch
  423. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  424. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  425. /// instead of made, since the start; and the lists' other upload buffers
  426. /// (texture data copied from buffers, scratch too big for a chunk) and
  427. /// their bytes.
  428. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  429. /// About host lists, for the memory line: lists made by the host since the
  430. /// start; preludes made (a list's second allocator and list, made when it
  431. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  432. /// bytes the process's private memory grew by while lists were being made
  433. /// (what a list costs: host objects with the driver's command memory; 631
  434. /// lists were alive in run 65, each with a prelude it may never use).
  435. /// Then the lists alive that were never reset since they were made: the
  436. /// host sides of title lists the title made and has not used (a host list
  437. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  438. /// makes at its start).
  439. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  440. /// The process's private bytes (diagnostics: around the making of lists).
  441. #[cfg(feature = "diagnostics")]
  442. fn private_bytes() -> u64 {
  443. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  444. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  445. let mut c = PROCESS_MEMORY_COUNTERS {
  446. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  447. ..Default::default()
  448. };
  449. // SAFETY: our own process and a sized structure.
  450. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  451. c.PagefileUsage as u64
  452. }
  453. /// What the runtime does when the host GPU fails for good: report it like a
  454. /// crash and end the run. The console has no such state, and carrying on
  455. /// draws nothing at seconds per frame.
  456. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  457. /// Sets what a host GPU failure does (the runtime's crash report).
  458. pub fn on_failure(report: fn(&str) -> !) {
  459. let _ = ON_FAILURE.set(report);
  460. }
  461. /// Ends the run on a host GPU failure: what failed, the removal reason and
  462. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  463. /// diagnostics build names the command).
  464. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  465. let mut text = what.to_string();
  466. if let Some(host) = host() {
  467. // SAFETY: a plain query.
  468. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  469. text.push_str(&format!("; device removed: {e}"));
  470. log_removal_context();
  471. }
  472. match host.log_messages() {
  473. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  474. None if host.messages.is_none() => text.push_str(
  475. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  476. ),
  477. None => {}
  478. }
  479. }
  480. tracing::error!("{text}");
  481. // Tests have no log: the reason goes to their output.
  482. #[cfg(test)]
  483. eprintln!("host GPU failure: {text}");
  484. match ON_FAILURE.get() {
  485. Some(report) => report(&text),
  486. None => std::process::abort(),
  487. }
  488. }
  489. /// The host GPU, created on first use; `None` without one (a run then
  490. /// behaves as before: nothing executes).
  491. pub(crate) fn host() -> Option<&'static Host> {
  492. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  493. HOST.get_or_init(|| match create() {
  494. Ok(host) => Some(host),
  495. Err(e) => {
  496. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  497. None
  498. }
  499. })
  500. .as_ref()
  501. }
  502. fn create() -> windows::core::Result<Host> {
  503. // SAFETY: plain D3D12 object creation with valid descriptions.
  504. unsafe {
  505. // The debug layer only in builds with diagnostics.
  506. let debug =
  507. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some();
  508. if debug {
  509. let mut layer: Option<ID3D12Debug> = None;
  510. match D3D12GetDebugInterface(&mut layer) {
  511. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  512. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  513. }
  514. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  515. // descriptor heap indices and the like become messages naming
  516. // the command instead of page faults. Without state tracking
  517. // (directly indexed textures are not transitioned).
  518. if std::env::var_os("VICTORY_D3D12_GBV").is_some()
  519. && let Some(l) = &layer
  520. {
  521. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  522. d1.SetEnableGPUBasedValidation(true);
  523. }
  524. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  525. d2.SetGPUBasedValidationFlags(
  526. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  527. );
  528. }
  529. tracing::info!("GPU-based validation on");
  530. }
  531. }
  532. // Diagnostics: device-removed data (the command that faulted, the
  533. // faulting address), read when the device is removed.
  534. if dred_on() {
  535. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  536. if D3D12GetDebugInterface(&mut dred).is_ok()
  537. && let Some(dred) = dred
  538. {
  539. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  540. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  541. }
  542. }
  543. let mut device: Option<ID3D12Device> = None;
  544. // Diagnostics: the software adapter, on which a shader's wild access
  545. // is an access violation in this process (a crash report with the
  546. // address and instruction) instead of a GPU fault and driver reset.
  547. if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() {
  548. let adapter = warp_adapter()?;
  549. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  550. tracing::info!("host device on the software adapter (WARP)");
  551. } else {
  552. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  553. }
  554. let device = device.ok_or_else(windows::core::Error::empty)?;
  555. // Before anything is made with it (`VICTORY_RECORD`).
  556. #[cfg(feature = "diagnostics")]
  557. crate::replay::record::from_env(&device);
  558. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  559. // driver compiling shaders again on the "D3D Background Thread"s,
  560. // for minutes after pipelines were made or loaded) is switched off.
  561. // An experiment: while those threads ran, the same shot took
  562. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  563. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  564. // whether the card is slower with the shaders it then keeps is not
  565. // known.
  566. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  567. && let Ok(device6) = device.cast::<ID3D12Device6>()
  568. {
  569. let set = device6.SetBackgroundProcessingMode(
  570. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  571. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  572. None,
  573. None,
  574. );
  575. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  576. }
  577. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  578. // cross-lane code stays in 32-lane halves translated for waves of 32
  579. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  580. if device
  581. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  582. .is_ok()
  583. {
  584. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  585. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  586. }
  587. let messages = debug
  588. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  589. .flatten();
  590. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  591. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  592. ..Default::default()
  593. })?;
  594. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  595. let event = CreateEventW(None, false, false, None)?;
  596. let rtvs: ID3D12DescriptorHeap =
  597. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  598. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  599. NumDescriptors: RTV_RING,
  600. ..Default::default()
  601. })?;
  602. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  603. let dsvs: ID3D12DescriptorHeap =
  604. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  605. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  606. NumDescriptors: RTV_RING,
  607. ..Default::default()
  608. })?;
  609. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  610. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  611. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  612. .ok();
  613. tracing::info!("host D3D12 device ready");
  614. Ok(Host {
  615. device,
  616. queue,
  617. fence,
  618. submitted: Mutex::new(0),
  619. event,
  620. rtvs,
  621. rtv_size,
  622. dsvs,
  623. dsv_size,
  624. next_dsv: AtomicU32::new(0),
  625. messages,
  626. next_rtv: AtomicU32::new(0),
  627. presenter: Mutex::new(None),
  628. adapter,
  629. })
  630. }
  631. }
  632. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  633. /// Reject it before creating a device in diagnostics' software-only mode.
  634. fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  635. // SAFETY: plain DXGI adapter queries.
  636. unsafe {
  637. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  638. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  639. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  640. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  641. tracing::warn!(
  642. vendor = format_args!("{:#x}", desc.VendorId),
  643. flags = format_args!("{:#x}", desc.Flags),
  644. "DXGI did not identify the WARP adapter as software; refusing device"
  645. );
  646. return Err(windows::core::Error::from_hresult(
  647. windows::Win32::Foundation::E_FAIL,
  648. ));
  649. }
  650. Ok(adapter)
  651. }
  652. }
  653. #[cfg(test)]
  654. mod tests {
  655. #[test]
  656. fn sparse_copies_preserve_islands_and_observe_remaps() {
  657. use windows_sys::Win32::System::Memory::*;
  658. const N: usize = 5 << 16;
  659. // SAFETY: we reserve a private region, commit selected pages inside it,
  660. // and only directly access the pages while they are writable.
  661. unsafe {
  662. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  663. assert!(!base.is_null());
  664. let mut expected = vec![0; N];
  665. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  666. let at = base.add(offset);
  667. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  668. at.write_bytes(value, 4096);
  669. expected[offset..offset + 4096].fill(value);
  670. }
  671. for remap in [false, true] {
  672. if remap {
  673. let mut old = 0;
  674. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  675. expected[..4096].fill(0);
  676. let at = base.add(1 << 16);
  677. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  678. at.write_bytes(0xc7, 4096);
  679. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  680. }
  681. let mut out = vec![0xee; N];
  682. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  683. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  684. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  685. }
  686. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  687. }
  688. }
  689. use super::*;
  690. #[test]
  691. fn warp_adapter_accepts_only_software() {
  692. // This probes DXGI without creating a D3D12 device or running a title.
  693. // SAFETY: plain DXGI adapter queries.
  694. let raw = unsafe {
  695. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  696. else {
  697. return;
  698. };
  699. factory.EnumWarpAdapter::<IDXGIAdapter>()
  700. };
  701. let Ok(raw) = raw else { return };
  702. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  703. // IDXGIAdapter1; `raw` owns that interface.
  704. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  705. eprintln!(
  706. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  707. desc.VendorId, desc.Flags
  708. );
  709. assert_eq!(
  710. warp_adapter().is_ok(),
  711. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  712. );
  713. }
  714. }
  715. /// The batches of clamped records in one scratch buffer
  716. /// ([`HostList::batch_place`]).
  717. const BATCHES: u32 = 8;
  718. /// A host command list and its allocator, always used together.
  719. pub(crate) struct HostList {
  720. allocator: ID3D12CommandAllocator,
  721. pub(crate) list: ID3D12GraphicsCommandList,
  722. /// Work for submission time, in recorded order.
  723. deferred: Mutex<Deferred>,
  724. /// Upload memory for data the list's draws make (expanded vertices),
  725. /// reused after a reset.
  726. scratch: Mutex<Scratch>,
  727. /// Host texture states the list assumes, by host copy: at its start and
  728. /// at its end. Lists are recorded on many threads and run in submission
  729. /// order, so the transitions from a texture's real state are made at
  730. /// submission, in `prelude`. Holding the copies keeps every texture the
  731. /// list names alive until it is reset, even if the title releases the
  732. /// resource first.
  733. states: Mutex<States>,
  734. /// What the list does with depth textures that have a colour twin, by
  735. /// twin ([`TwinUse`]).
  736. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  737. /// The list that runs those transitions just before this one, made
  738. /// when the list first has such transitions ([`lazy_prelude`]).
  739. prelude: OnceLock<Option<Prelude>>,
  740. /// The pipelines the list binds, for reports of slow submissions.
  741. pipelines: Mutex<std::collections::BTreeSet<String>>,
  742. /// The work its indirect executions may still do (`indirect`): a
  743. /// shader-writable word, zeroed when the list is submitted, and after
  744. /// it what the clamp notes about mesh records. In memory the CPU maps.
  745. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  746. /// The same words in the card's own memory ([`card_budget`]), which the
  747. /// clamp uses instead when there is one: zeroed in the list before its
  748. /// first clamp, its notes copied to `budget` when the list closes.
  749. card_budget: OnceLock<Option<ID3D12Resource>>,
  750. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  751. /// grown to the largest indirect execution recorded on the list.
  752. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  753. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  754. /// how many batches of this recording have a place in them.
  755. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  756. /// Counts the list in [`ALIVE`] while it lives.
  757. _alive: Counted,
  758. /// The texts of the markers `note_op` set, in order (for device-removed
  759. /// data without marker texts), with the host GPU range a copy reads.
  760. #[cfg(feature = "diagnostics")]
  761. notes: Mutex<Vec<Note>>,
  762. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  763. /// and at the end, and where they are read back.
  764. #[cfg(feature = "diagnostics")]
  765. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  766. }
  767. /// A list's prelude: an allocator and a closed list.
  768. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  769. /// Whether a host list's prelude is made when the list first needs one. A
  770. /// prelude runs the texture transitions and twin copies a list needs before
  771. /// it; lists that name no texture never have one, and every host list was
  772. /// made with one all the same: twice the host objects per list, for the
  773. /// title's 630 lists and for every list made anew.
  774. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  775. fn lazy_prelude() -> bool {
  776. static ON: OnceLock<bool> = OnceLock::new();
  777. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  778. }
  779. /// Timestamps per list (diagnostics); commands past them are not timed.
  780. #[cfg(feature = "diagnostics")]
  781. const STAMPS: u32 = 4096;
  782. /// A marker's text and the host range its command reads (diagnostics).
  783. #[cfg(feature = "diagnostics")]
  784. type Note = (String, Option<(u64, u64)>);
  785. type States = std::collections::HashMap<
  786. usize,
  787. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  788. >;
  789. /// What a list does with a depth texture that has a colour twin
  790. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  791. /// in submission order, so a list cannot know which side an earlier list
  792. /// leaves behind: it notes which sides it uses as it finds them, and its
  793. /// prelude copies one side into the other at submission if that side is
  794. /// behind then. From its first use of a side on, the list knows.
  795. struct TwinUse {
  796. /// The depth texture (the title resource's host copy) and its twin.
  797. depth: std::sync::Arc<crate::resource::HostTexture>,
  798. twin: std::sync::Arc<crate::resource::Twin>,
  799. /// The sides (depth texture, twin) the list uses as it finds them.
  800. needs: [bool; 2],
  801. /// Whether each side lacks what the other was written last, where the
  802. /// list is now; `None`: as the list found it.
  803. behind: [Option<bool>; 2],
  804. /// The draw or dispatch being prepared writes the twin.
  805. writing: bool,
  806. /// The depth plane's twin holds what the plane lacks although the list
  807. /// copied the twins since: the plane's pass waits for the list's close.
  808. late: bool,
  809. }
  810. /// The pass that draws the twin of a depth plane into the plane: one
  811. /// triangle over each mip of each slice, its pixel shader writing the
  812. /// twin's texel as the depth, with the depth test "always" and no stencil
  813. /// (the stencil plane is copied through a buffer and not touched here).
  814. ///
  815. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  816. /// the step times the float nearest 1/65535 (0x37800080). That is how
  817. /// The title's tiled lighting computes the depth of the
  818. /// rectangles it then draws with the test "equal", one class of materials
  819. /// a draw (all six of its vertex shaders multiply the class number by that
  820. /// constant), so the pass and the draw give the host the same float, and
  821. /// the host turns the same float into the same 24 bits. The step divided
  822. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  823. /// and lands in another 24-bit step for 127 of them (none under 385).
  824. const PLANE_CORNERS: &str = r#"
  825. float4 corner(uint i : SV_VertexID) : SV_Position {
  826. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  827. }
  828. "#;
  829. const PLANE_STEPS: &str = r#"
  830. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  831. Texture2DArray<uint> twin : register(t0);
  832. [RootSignature(RS)]
  833. float plane(float4 p : SV_Position) : SV_Depth {
  834. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  835. }
  836. "#;
  837. const PLANE_FLOATS: &str = r#"
  838. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  839. Texture2DArray<float> twin : register(t0);
  840. [RootSignature(RS)]
  841. float plane(float4 p : SV_Position) : SV_Depth {
  842. return twin.Load(int4(int2(p.xy), 0, 0));
  843. }
  844. "#;
  845. /// Views of twins the pass reads, in a heap of ours used as a ring.
  846. /// shortcut: a view must last until its list has run; with one or two
  847. /// passes a frame the ring is far from coming round.
  848. const PLANE_VIEWS: u32 = 256;
  849. /// What the pass draws with: the heap of its views of twins, and per kind
  850. /// of twin (16-bit steps or floats) and depth format the root signature
  851. /// and pipeline, made when first needed (`None`: the host refused).
  852. struct PlanePass {
  853. views: ID3D12DescriptorHeap,
  854. cpu: usize,
  855. gpu: u64,
  856. step: u32,
  857. next: AtomicU32,
  858. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  859. }
  860. /// The pass's root signature and pipeline for one kind of twin and one
  861. /// depth format.
  862. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  863. // SAFETY: D3D12 objects are free-threaded.
  864. unsafe impl Send for PlanePass {}
  865. // SAFETY: as above.
  866. unsafe impl Sync for PlanePass {}
  867. fn plane_pass() -> Option<&'static PlanePass> {
  868. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  869. PASS.get_or_init(|| {
  870. let host = host()?;
  871. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  872. // SAFETY: plain heap creation and queries.
  873. unsafe {
  874. let views: ID3D12DescriptorHeap = host
  875. .device
  876. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  877. Type: kind,
  878. NumDescriptors: PLANE_VIEWS,
  879. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  880. NodeMask: 0,
  881. })
  882. .ok()?;
  883. Some(PlanePass {
  884. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  885. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  886. step: host.device.GetDescriptorHandleIncrementSize(kind),
  887. views,
  888. next: AtomicU32::new(0),
  889. made: Mutex::default(),
  890. })
  891. }
  892. })
  893. .as_ref()
  894. }
  895. /// Compiles function `entry` of `source` for `target` with the system's
  896. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  897. pub(crate) fn compile(
  898. source: &str,
  899. entry: windows::core::PCSTR,
  900. target: windows::core::PCSTR,
  901. ) -> windows::core::Result<Vec<u8>> {
  902. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  903. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  904. let mut code: Option<ID3DBlob> = None;
  905. let mut errors: Option<ID3DBlob> = None;
  906. // SAFETY: the source and names live through the call; out pointers ours.
  907. let compiled = unsafe {
  908. D3DCompile(
  909. source.as_ptr().cast(),
  910. source.len(),
  911. windows::core::s!("victory"),
  912. None,
  913. None,
  914. entry,
  915. target,
  916. 0,
  917. 0,
  918. &mut code,
  919. Some(&mut errors),
  920. )
  921. };
  922. if let Err(e) = compiled {
  923. if let Some(errors) = errors {
  924. // SAFETY: the blob's own bytes.
  925. let text = unsafe {
  926. std::slice::from_raw_parts(
  927. errors.GetBufferPointer().cast::<u8>(),
  928. errors.GetBufferSize(),
  929. )
  930. };
  931. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  932. }
  933. return Err(e);
  934. }
  935. let code = code.ok_or_else(windows::core::Error::empty)?;
  936. // SAFETY: the blob's own bytes.
  937. let bytes = unsafe {
  938. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  939. };
  940. Ok(bytes.to_vec())
  941. }
  942. impl PlanePass {
  943. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  944. /// or of floats and the depth format `format`.
  945. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  946. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  947. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  948. return pipeline.clone();
  949. }
  950. let pipeline = match Self::make(steps, format) {
  951. Ok(pipeline) => Some(pipeline),
  952. Err(e) => {
  953. tracing::warn!(
  954. error = %e,
  955. steps,
  956. format = format.0,
  957. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  958. );
  959. None
  960. }
  961. };
  962. made.push((steps, format.0, pipeline.clone()));
  963. pipeline
  964. }
  965. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  966. use windows::core::s;
  967. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  968. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  969. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  970. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  971. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  972. pShaderBytecode: bytes.as_ptr().cast(),
  973. BytecodeLength: bytes.len(),
  974. };
  975. // SAFETY: the root signature is inside the pixel shader; the
  976. // description points at live data and never releases its pointer.
  977. unsafe {
  978. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  979. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  980. pRootSignature: std::mem::transmute_copy(&root),
  981. VS: code(&vs[..]),
  982. PS: code(&ps[..]),
  983. SampleMask: u32::MAX,
  984. RasterizerState: D3D12_RASTERIZER_DESC {
  985. FillMode: D3D12_FILL_MODE_SOLID,
  986. CullMode: D3D12_CULL_MODE_NONE,
  987. DepthClipEnable: true.into(),
  988. ..Default::default()
  989. },
  990. // Every texel is written; stencil stays off.
  991. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  992. DepthEnable: true.into(),
  993. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  994. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  995. ..Default::default()
  996. },
  997. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  998. DSVFormat: format,
  999. SampleDesc: DXGI_SAMPLE_DESC {
  1000. Count: 1,
  1001. Quality: 0,
  1002. },
  1003. ..Default::default()
  1004. };
  1005. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1006. Ok((root, pipeline))
  1007. }
  1008. }
  1009. }
  1010. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1011. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1012. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1013. /// heap, graphics root signature, pipeline, depth target, viewport,
  1014. /// scissor and topology and puts none of them back: it is for a list that
  1015. /// records nothing of the title's after it.
  1016. fn record_plane_pass(
  1017. list: &ID3D12GraphicsCommandList,
  1018. depth: &ID3D12Resource,
  1019. plane: &ID3D12Resource,
  1020. ) {
  1021. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1022. return;
  1023. };
  1024. // SAFETY: live resources.
  1025. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1026. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1027. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1028. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1029. let steps = twin.Format.0 == 53;
  1030. let format = DXGI_FORMAT(match of.Format.0 {
  1031. 44 => 45,
  1032. 19 => 20,
  1033. typed => typed,
  1034. });
  1035. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1036. return;
  1037. };
  1038. for slice in 0..u32::from(of.DepthOrArraySize) {
  1039. for mip in 0..u32::from(of.MipLevels) {
  1040. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1041. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1042. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1043. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1044. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1045. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1046. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1047. MostDetailedMip: mip,
  1048. MipLevels: 1,
  1049. FirstArraySlice: slice,
  1050. ArraySize: 1,
  1051. ..Default::default()
  1052. },
  1053. },
  1054. };
  1055. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1056. Format: format,
  1057. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1058. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1059. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1060. MipSlice: mip,
  1061. FirstArraySlice: slice,
  1062. ArraySize: 1,
  1063. },
  1064. },
  1065. ..Default::default()
  1066. };
  1067. let target = host.dsv(depth, Some(&target));
  1068. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1069. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1070. ptr: pass.cpu + (slot * pass.step) as usize,
  1071. };
  1072. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1073. ptr: pass.gpu + u64::from(slot * pass.step),
  1074. };
  1075. // SAFETY: an open list; a slot of our heap; live resources and
  1076. // objects (the pass's own live as long as the process).
  1077. unsafe {
  1078. host.device
  1079. .CreateShaderResourceView(plane, Some(&view), cpu);
  1080. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1081. list.SetGraphicsRootSignature(&root);
  1082. list.SetPipelineState(&pipeline);
  1083. list.SetGraphicsRootDescriptorTable(0, gpu);
  1084. list.OMSetRenderTargets(0, None, false, Some(&target));
  1085. list.RSSetViewports(&[D3D12_VIEWPORT {
  1086. TopLeftX: 0.0,
  1087. TopLeftY: 0.0,
  1088. Width: width as f32,
  1089. Height: height as f32,
  1090. MinDepth: 0.0,
  1091. MaxDepth: 1.0,
  1092. }]);
  1093. list.RSSetScissorRects(&[RECT {
  1094. left: 0,
  1095. top: 0,
  1096. right: width as i32,
  1097. bottom: height as i32,
  1098. }]);
  1099. list.IASetPrimitiveTopology(
  1100. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1101. );
  1102. list.DrawInstanced(3, 1, 0, 0);
  1103. }
  1104. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1105. }
  1106. }
  1107. }
  1108. /// Records into `list` the copy of a depth texture into its colour twin
  1109. /// (`colour`) or of the twin into the depth texture, both already in their
  1110. /// copy states: whole textures of one size in one format family, which the
  1111. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1112. /// alone, through the twin's buffer.
  1113. fn record_twin_copy(
  1114. list: &ID3D12GraphicsCommandList,
  1115. depth: &ID3D12Resource,
  1116. twin: &crate::resource::Twin,
  1117. colour: bool,
  1118. ) {
  1119. let (from, to) = if colour {
  1120. (depth, &twin.colour.texture)
  1121. } else {
  1122. (&twin.colour.texture, depth)
  1123. };
  1124. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1125. // shortcut: the depth plane's twin is not given the plane (that is a
  1126. // pass the other way: the plane read by a shader, the twin as its
  1127. // target). The twin then lacks what draws and clears wrote to the
  1128. // plane since shaders last wrote the twin. In the title
  1129. // nothing writes that plane but the twin's pass (its 192 draws against
  1130. // it only test, run 29), so the twin lacks nothing. Counted.
  1131. if colour && twin.plane.is_some() {
  1132. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1133. }
  1134. let Some(through) = &twin.through else {
  1135. // SAFETY: an open list and two live textures.
  1136. unsafe { list.CopyResource(to, from) };
  1137. return;
  1138. };
  1139. // A stencil plane and its twin: each mip and slice of the plane goes
  1140. // into the buffer, laid out as the host lays the plane out for copies,
  1141. // and from the buffer into the other texture, whole subresources both
  1142. // times. In the depth texture the stencil plane's subresources follow
  1143. // the depth plane's; the twin has the one plane.
  1144. let Some(host) = host() else { return };
  1145. // SAFETY: a live texture.
  1146. let of = unsafe { depth.GetDesc() };
  1147. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1148. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1149. // SAFETY: a plain query writing `planes` footprints.
  1150. unsafe {
  1151. host.device.GetCopyableFootprints(
  1152. &of,
  1153. planes,
  1154. planes,
  1155. 0,
  1156. Some(rows.as_mut_ptr()),
  1157. None,
  1158. None,
  1159. None,
  1160. );
  1161. }
  1162. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1163. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1164. // SAFETY: a borrowed pointer the location never releases.
  1165. pResource: unsafe { std::mem::transmute_copy(texture) },
  1166. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1167. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1168. SubresourceIndex: index,
  1169. },
  1170. };
  1171. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1172. // SAFETY: as above.
  1173. pResource: unsafe { std::mem::transmute_copy(through) },
  1174. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1175. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1176. PlacedFootprint: *row,
  1177. },
  1178. };
  1179. let (common, source, dest) = (
  1180. D3D12_RESOURCE_STATE_COMMON,
  1181. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1182. D3D12_RESOURCE_STATE_COPY_DEST,
  1183. );
  1184. // SAFETY: an open list and live resources; the buffer was made as big
  1185. // as these footprints, and rests in the common state between copies.
  1186. unsafe {
  1187. list.ResourceBarrier(&[transition(through, common, dest)]);
  1188. for (i, row) in rows.iter().enumerate() {
  1189. let index = first_from + i as u32;
  1190. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1191. }
  1192. list.ResourceBarrier(&[transition(through, dest, source)]);
  1193. for (i, row) in rows.iter().enumerate() {
  1194. let index = first_to + i as u32;
  1195. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1196. }
  1197. list.ResourceBarrier(&[transition(through, source, common)]);
  1198. }
  1199. }
  1200. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1201. /// builds).
  1202. pub(crate) fn dred_on() -> bool {
  1203. static ON: OnceLock<bool> = OnceLock::new();
  1204. *ON.get_or_init(|| {
  1205. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some()
  1206. })
  1207. }
  1208. /// Indirect mesh dispatches since the last frame line: the largest group
  1209. /// count a record asked for, and the groups asked in all (from the lists'
  1210. /// budget buffers, a run late).
  1211. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1212. /// Whether a list's indirect-work budget lives in the card's own memory
  1213. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1214. /// before). The clamp charges it with atomics, at least two in a row for
  1215. /// every clamp; in mapped memory on a card of its own each of them
  1216. /// crosses the bus.
  1217. fn card_budget() -> bool {
  1218. static ON: OnceLock<bool> = OnceLock::new();
  1219. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1220. }
  1221. /// Whether each list of a submission runs and is timed on its own, slow
  1222. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1223. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1224. #[cfg(feature = "diagnostics")]
  1225. fn timing() -> bool {
  1226. static ON: OnceLock<bool> = OnceLock::new();
  1227. *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some())
  1228. }
  1229. /// Names a host object for the device-removed report, which names the
  1230. /// allocations a page fault hit (only with device-removed data on), or for
  1231. /// the frame recorder (`VICTORY_RECORD`).
  1232. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1233. #[cfg(feature = "diagnostics")]
  1234. if crate::replay::record::on() {
  1235. let text = text();
  1236. crate::replay::record::name(object, &text);
  1237. if dred_on()
  1238. && let Ok(object) = object.cast::<ID3D12Object>()
  1239. {
  1240. // SAFETY: a plain call on a live object.
  1241. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1242. }
  1243. return;
  1244. }
  1245. if dred_on()
  1246. && let Ok(object) = object.cast::<ID3D12Object>()
  1247. {
  1248. // SAFETY: a plain call on a live object.
  1249. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1250. }
  1251. }
  1252. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1253. /// [`LISTS`]`[3]` until it is first reset.
  1254. struct Counted {
  1255. /// Not reset since it was made.
  1256. fresh: std::sync::atomic::AtomicBool,
  1257. }
  1258. impl Counted {
  1259. fn new() -> Counted {
  1260. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1261. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1262. Counted {
  1263. fresh: std::sync::atomic::AtomicBool::new(true),
  1264. }
  1265. }
  1266. /// The list is reset: it is in use.
  1267. fn used(&self) {
  1268. if self.fresh.swap(false, Ordering::Relaxed) {
  1269. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1270. }
  1271. }
  1272. }
  1273. impl Drop for Counted {
  1274. fn drop(&mut self) {
  1275. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1276. self.used();
  1277. }
  1278. }
  1279. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1280. /// mapping and its host GPU address.
  1281. struct Chunk {
  1282. _buffer: ID3D12Resource,
  1283. data: usize,
  1284. gpu: u64,
  1285. }
  1286. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1287. // written only by the list that holds the chunk.
  1288. unsafe impl Send for Chunk {}
  1289. /// Upload chunks handed out front to back: the chunks (each with its
  1290. /// bytes), the one in use and the bytes used in it.
  1291. #[derive(Default)]
  1292. struct Scratch {
  1293. chunks: Vec<(Chunk, u64)>,
  1294. current: usize,
  1295. used: u64,
  1296. }
  1297. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1298. unsafe impl Send for Scratch {}
  1299. impl Drop for Scratch {
  1300. fn drop(&mut self) {
  1301. give_chunks(std::mem::take(&mut self.chunks));
  1302. }
  1303. }
  1304. const SCRATCH_CHUNK: u64 = 4 << 20;
  1305. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1306. /// lists put a few constants or a rectangle's corners there, and every
  1307. /// list that did took 4 MiB of the PC's memory for it.
  1308. const SCRATCH_FIRST: u64 = 256 << 10;
  1309. /// The most bytes of chunks kept while no list holds them.
  1310. const SPARE_MOST: u64 = 128 << 20;
  1311. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1312. /// first needs one, a small one first, and gives all of them back when it
  1313. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1314. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1315. /// host lists of held submissions, which live for one submission, each
  1316. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1317. /// freed per frame of gameplay (run 60).
  1318. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1319. fn scratch_pool() -> bool {
  1320. static ON: OnceLock<bool> = OnceLock::new();
  1321. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1322. }
  1323. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1324. /// for one of the same size.
  1325. struct Spare<T> {
  1326. kept: Vec<(T, u64)>,
  1327. bytes: u64,
  1328. }
  1329. impl<T> Spare<T> {
  1330. const fn new() -> Self {
  1331. Spare { kept: Vec::new(), bytes: 0 }
  1332. }
  1333. /// A kept thing of `size` bytes, the one given last.
  1334. fn take(&mut self, size: u64) -> Option<T> {
  1335. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1336. self.bytes -= size;
  1337. Some(self.kept.remove(at).0)
  1338. }
  1339. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1340. /// `most`: then it comes back.
  1341. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1342. if self.bytes + size > most {
  1343. return Some(thing);
  1344. }
  1345. self.bytes += size;
  1346. self.kept.push((thing, size));
  1347. None
  1348. }
  1349. }
  1350. /// Scratch chunks no list holds.
  1351. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1352. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1353. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1354. if scratch_pool()
  1355. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1356. {
  1357. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1358. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1359. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1360. return Some(chunk);
  1361. }
  1362. let (buffer, data) = host.upload_buffer(size)?;
  1363. name(&buffer, || "list scratch".into());
  1364. // SAFETY: a live buffer.
  1365. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  1366. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1367. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1368. Some(Chunk {
  1369. _buffer: buffer,
  1370. data: data as usize,
  1371. gpu,
  1372. })
  1373. }
  1374. /// A list is done with `chunks` (it was reset after its submissions ran,
  1375. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1376. /// without the pool.
  1377. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1378. if chunks.is_empty() {
  1379. return;
  1380. }
  1381. let mut freed = Vec::new();
  1382. {
  1383. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1384. for (chunk, size) in chunks {
  1385. let back = if scratch_pool() {
  1386. spare.give(chunk, size, SPARE_MOST)
  1387. } else {
  1388. Some(chunk)
  1389. };
  1390. match back {
  1391. None => {
  1392. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1393. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1394. }
  1395. Some(chunk) => {
  1396. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1397. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1398. freed.push(chunk);
  1399. }
  1400. }
  1401. }
  1402. }
  1403. // Freed outside the lock.
  1404. drop(freed);
  1405. }
  1406. /// What the host keeps for copies in the card's own memory
  1407. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1408. struct CardWork {
  1409. /// Before a submission's lists: what changed on the copies' CPU side
  1410. /// goes to their card side. Those not in use: a plan takes one and
  1411. /// gives it back when its submission has run (`Host::card_done`), so
  1412. /// that submissions sent ahead ([`late`]) each have their own.
  1413. sync: Vec<Prelude>,
  1414. /// After them, in the same submission: the compare of the declared
  1415. /// ranges with their bytes from before. As `sync`.
  1416. check: Vec<Prelude>,
  1417. /// After it ran: the pieces that differ come down.
  1418. fetch: Prelude,
  1419. root: ID3D12RootSignature,
  1420. pso: ID3D12PipelineState,
  1421. /// One dword per piece compared, odd where the piece differs: PC
  1422. /// memory, mapped (buffer, mapping, bytes).
  1423. differs: (ID3D12Resource, usize, u64),
  1424. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1425. fetched: Option<(ID3D12Resource, usize, u64)>,
  1426. /// The dwords of `differs` taken by plans whose results were not read
  1427. /// yet.
  1428. taken: u32,
  1429. /// Plans made and not done with (`Host::card_done`).
  1430. out: u32,
  1431. }
  1432. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1433. // under the submission lock.
  1434. unsafe impl Send for CardWork {}
  1435. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1436. /// The compare of a declared range of a copy in the card's memory with
  1437. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1438. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1439. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1440. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1441. /// byte just outside the range costs a fetch that finds nothing.
  1442. ///
  1443. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1444. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1445. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1446. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1447. /// those steps.
  1448. pub(crate) const CARD_COMPARE: &str = r#"
  1449. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1450. cbuffer Span : register(b0) {
  1451. uint first; // the first piece
  1452. uint skew; // where the copy starts in its piece 0
  1453. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1454. uint pieces;
  1455. uint out_at; // the first piece's dword in `differs`, in bytes
  1456. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1457. };
  1458. ByteAddressBuffer now : register(t0);
  1459. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1460. // last sent up (or hashed whole, the first time).
  1461. RWByteAddressBuffer hashes : register(u0);
  1462. RWByteAddressBuffer differs : register(u1);
  1463. groupshared uint4 parts[64];
  1464. [RootSignature(RS)]
  1465. [numthreads(64, 1, 1)]
  1466. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1467. uint piece = first + id.x;
  1468. uint lo = piece * 65536u;
  1469. lo = lo > skew ? lo - skew : 0u;
  1470. uint hi = min((piece + 1u) * 65536u - skew, size);
  1471. lo = lo & ~15u;
  1472. hi = (hi + 15u) & ~15u;
  1473. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1474. [loop]
  1475. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1476. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1477. h = h.yzwx ^ (h >> 15);
  1478. }
  1479. parts[thread] = h;
  1480. GroupMemoryBarrierWithGroupSync();
  1481. if (thread != 0u) return;
  1482. h = parts[0];
  1483. [loop]
  1484. for (uint i = 1u; i < 64u; ++i) {
  1485. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1486. h = h.yzwx ^ (h >> 15);
  1487. }
  1488. if (compare != 0u) {
  1489. // The flag, and above it 31 bits of the hash (`torn`).
  1490. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1491. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1492. // With the copy-back on its own thread: the next compare of the
  1493. // piece finds what is written from here on.
  1494. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1495. } else {
  1496. hashes.Store4(piece * 16u, h);
  1497. }
  1498. }
  1499. "#;
  1500. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1501. #[cfg(test)]
  1502. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1503. torn::hash(bytes)
  1504. }
  1505. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1506. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1507. /// parts a dispatch can hold.
  1508. ///
  1509. /// # Safety
  1510. /// The list is open with the compare's root signature, pipeline and buffers
  1511. /// set, and the pieces lie in the buffer.
  1512. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1513. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1514. let mut done = 0;
  1515. while done < span.pieces {
  1516. let n = (span.pieces - done).min(MOST);
  1517. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1518. // SAFETY: the caller's.
  1519. unsafe {
  1520. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1521. list.Dispatch(n, 1, 1);
  1522. }
  1523. done += n;
  1524. }
  1525. }
  1526. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1527. /// the card's memory are hashed in runs of pieces that touch, each piece
  1528. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1529. /// per range sent up.
  1530. ///
  1531. /// These passes are ours, they run on the card before every submission's
  1532. /// lists: a pass takes the time of one piece however few its pieces are.
  1533. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1534. /// a piece hashed when it need not be, or not hashed when it should, costs
  1535. /// a fetch that finds nothing and loses no shader write.
  1536. fn rehash_runs() -> bool {
  1537. static ON: OnceLock<bool> = OnceLock::new();
  1538. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1539. }
  1540. /// Since the last frame-rate line, of our own passes over copies in the
  1541. /// card's memory: hash passes after ranges were sent up, the pieces they
  1542. /// hashed, and compare passes after the lists.
  1543. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1544. /// Whether what shaders wrote to copies in the card's memory is merged
  1545. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1546. /// default). The pieces the card's compare found differing come down in
  1547. /// one fetch and were then merged one after the other on the thread that
  1548. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1549. /// with the copy's CPU side byte by byte and put into title memory through
  1550. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1551. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1552. /// landings do not come here: `crate::land` has threads of its own.)
  1553. fn wide_merge() -> bool {
  1554. static ON: OnceLock<bool> = OnceLock::new();
  1555. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1556. }
  1557. /// One declared range of a copy in the card's memory, in a submission.
  1558. struct CardRange {
  1559. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1560. /// As declared (title addresses), for the statistics.
  1561. declared: (usize, usize),
  1562. span: crate::shadow::CardSpan,
  1563. /// Its first piece's dword in the compare's results.
  1564. at: u32,
  1565. /// Whether the card compares it; else every piece is fetched.
  1566. compared: bool,
  1567. /// Looked at by `crate::picked`, and not declared: what is found changed
  1568. /// there was written through a view nobody declared. Not landed.
  1569. picked: bool,
  1570. }
  1571. impl CardPlan {
  1572. /// `crate::picked` is told where what it looked at changed, by the
  1573. /// compare's results.
  1574. fn picked_found(&self, differs: &[u32]) {
  1575. for r in self.ranges.iter().filter(|r| r.picked) {
  1576. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1577. if let Some(p) = changed {
  1578. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. /// What a submission does for copies in the card's memory.
  1584. struct CardPlan {
  1585. ranges: Vec<CardRange>,
  1586. /// The compare, run after the submission's lists.
  1587. check: Option<ID3D12CommandList>,
  1588. /// The copies whose card side was brought up to date, alive until the
  1589. /// submission has run.
  1590. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1591. /// The lists of ours the plan recorded (whether the compare, the
  1592. /// list), given back by `Host::card_done`.
  1593. lists: Vec<(bool, Prelude)>,
  1594. /// With [`relay`]: the number of the send to copies in the card's memory
  1595. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1596. sent_as: u64,
  1597. /// With [`upcheck`]: the look at what it sent up.
  1598. looks: Option<upcheck::Looks>,
  1599. }
  1600. /// One piece of submission-time work, in recorded order.
  1601. enum Step {
  1602. /// A copy into title memory (destination, source, bytes): the title's
  1603. /// buffer copies, which later refreshes must see.
  1604. Copy(usize, usize, usize),
  1605. /// A copy of title memory into the list's own upload memory, and how
  1606. /// the card could bring the bytes instead.
  1607. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  1608. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1609. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1610. /// intervenes.
  1611. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1612. /// Work that may write title memory.
  1613. Run(Box<dyn Fn() + Send>),
  1614. /// Work that writes host memory only, and the title memory it reads
  1615. /// (from, to; empty for none).
  1616. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1617. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1618. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1619. /// Brings a texture's staging buffer up to date: once per submission,
  1620. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1621. Texture(std::sync::Arc<crate::texture::Staging>),
  1622. }
  1623. /// What a list does on the CPU when it is submitted: copies between host
  1624. /// memory regions (title buffers, upload buffers and buffer copies), and
  1625. /// the upload buffers its GPU commands read, kept until the list is reset.
  1626. #[derive(Default)]
  1627. struct Deferred {
  1628. /// Destination, source, bytes.
  1629. copies: Vec<Step>,
  1630. uploads: Vec<ID3D12Resource>,
  1631. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1632. upload_bytes: u64,
  1633. /// Host objects the list's commands name (pipelines, root signatures,
  1634. /// descriptor heaps): the title may release its objects before it
  1635. /// submits the list.
  1636. kept: Vec<windows::core::IUnknown>,
  1637. /// Buffer ranges refreshed since the last title copy (host copy,
  1638. /// address, bytes): refreshing them again would find the same bytes.
  1639. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1640. /// Textures whose contents the list brings up to date.
  1641. textures: std::collections::HashSet<usize>,
  1642. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1643. /// bytes.
  1644. writes: Vec<(usize, crate::queue::Written, usize)>,
  1645. /// Textures read back (texture to buffer copies), done once the list
  1646. /// has run: the host buffer the list copies the texels into, the title
  1647. /// memory they go to, the bytes of a row, the rows, the title's row
  1648. /// pitch.
  1649. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1650. /// Whether the indirect-work budget is zeroed for this recording (a
  1651. /// step on the CPU, or in the list for the card's copy).
  1652. budget_zeroed: bool,
  1653. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1654. /// interface pointer) that a clamp in this recording left readable as
  1655. /// indirect arguments; 0 if none. It stays readable until the next
  1656. /// clamp into it ([`HostList::indirect_state`]).
  1657. indirect_readable: usize,
  1658. }
  1659. impl Deferred {
  1660. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1661. /// reset.
  1662. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1663. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1664. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1665. self.upload_bytes += size;
  1666. self.uploads.push(buffer);
  1667. }
  1668. }
  1669. impl Drop for Deferred {
  1670. fn drop(&mut self) {
  1671. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1672. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1673. }
  1674. }
  1675. /// Whether a queue's submissions go to the card without a wait for each
  1676. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1677. /// waits for every list on its own).
  1678. ///
  1679. /// Every submission was prepared, sent, waited for and copied back before
  1680. /// the next one was looked at, so the card stood idle while we prepared
  1681. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1682. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1683. /// other, on the one thread that submits.
  1684. ///
  1685. /// With the switch a queue's submission is sent and joins a line of
  1686. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1687. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1688. /// for the card, what their shaders wrote copied back once per byte, then
  1689. /// their bottom-of-pipe writes and the fence signals behind them, in
  1690. /// order) at the next point where the title, or our own preparing, can
  1691. /// observe what they do. Those points, exactly:
  1692. ///
  1693. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1694. /// read-back or map of a texture, a clear or upload run at once;
  1695. /// 2. the next submission reads title memory that a flight's shaders may
  1696. /// write: a title buffer copy, a fill of upload memory, a texture's
  1697. /// memory, any step that runs code of ours on title memory
  1698. /// ([`late_blocked`]);
  1699. /// 3. the next submission refreshes a range of a host copy that a flight's
  1700. /// shaders may write, and the title wrote a page of it since it was last
  1701. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1702. /// alone until the flight's writes are back, as it always did within a
  1703. /// submission;
  1704. /// 4. a queue stands at a wait for a memory value that no flight's
  1705. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1706. /// write ([`late_met`]);
  1707. /// 5. the title blocks on a fence without an event;
  1708. /// 6. the card has run every flight (a thread of ours waits for that:
  1709. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1710. ///
  1711. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1712. /// when the card has really run the work, later than before and never
  1713. /// earlier; a fence signalled on a queue while flights are in the air is
  1714. /// set behind them. A wait for a memory value that a flight's
  1715. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1716. /// the card behind that flight, which is the order the wait asks for.
  1717. ///
  1718. /// What it assumes beyond today: memory the title rewrites between two of
  1719. /// its submissions, without waiting for the first, may be seen by the
  1720. /// first's shaders (as on the console, where the card reads title memory
  1721. /// when it runs, not when the list is submitted).
  1722. pub(crate) fn late() -> bool {
  1723. late_stage() > 0
  1724. }
  1725. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1726. fn late_stage() -> u8 {
  1727. static STAGE: OnceLock<u8> = OnceLock::new();
  1728. *STAGE.get_or_init(|| {
  1729. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1730. return 0;
  1731. }
  1732. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1733. Ok("1") => 1,
  1734. Ok("2") => 2,
  1735. Ok("3") => 3,
  1736. // The relay alone: on top of stage 3.
  1737. Err(_) if crate::shadow::relay() => 3,
  1738. _ => 0,
  1739. }
  1740. })
  1741. }
  1742. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1743. /// longer a point. Where the title wrote a page that lies in a range a
  1744. /// flight's shaders may write, the bytes the title changed are found (the
  1745. /// page as it is now against what the copy held when the flight was
  1746. /// prepared) and put into the copy, and only those: what the flight's
  1747. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1748. /// flights are settled for it only where that cannot be done: memory that
  1749. /// is not write-watched, or a copy in the card's memory with more changed
  1750. /// runs than a submission should send up one by one.
  1751. ///
  1752. /// In run 92 (stage 1) this point settled the flights five times a frame
  1753. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1754. /// frame of waiting were left of 200.
  1755. ///
  1756. /// What differs from settling first: a byte both the title and a flight's
  1757. /// shader wrote is the title's if the shader wrote it first, the shader's
  1758. /// if it wrote it afterwards; settled first it was always the shader's.
  1759. /// The title writing a byte a shader of its own is writing is a race on
  1760. /// the console too.
  1761. fn late_exact() -> bool {
  1762. late_stage() > 1
  1763. }
  1764. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1765. /// no longer a point where flights are settled). The copy to the back
  1766. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1767. /// its own for each present in the air) and the swap chain is told to
  1768. /// present behind it; the queue's call returns, and the card finishes the
  1769. /// frame while the title records the next one. What the title is told
  1770. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1771. /// has run it, by the settling thread.
  1772. ///
  1773. /// What is left out with it: the look whether the presented frame is black
  1774. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1775. /// or listed is presented the old way. Once every second and a half a
  1776. /// submission settles the flights all the same, for the sweep that lets
  1777. /// idle host objects go (it needs nothing in the air).
  1778. pub(crate) fn late_free_present() -> bool {
  1779. late_stage() > 2
  1780. }
  1781. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1782. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1783. /// and is off with it, in the timing run and with kept snapshots).
  1784. ///
  1785. /// With [`late`] alone every settle does three things on the thread that
  1786. /// holds the submission lock: it waits for everything in the air, copies
  1787. /// back with the card standing, and only then goes on preparing. The frame
  1788. /// stays a relay: the card works about 242 ms of it and one thread
  1789. /// prepares, waits and copies back for about 220.
  1790. ///
  1791. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1792. /// soon as the card has run them, in the order they were sent and without
  1793. /// the submission lock: it fetches and merges what their shaders wrote to
  1794. /// copies in the card's memory, compares and merges the other copies,
  1795. /// frees the flights' ranges, and then does their read-backs, their
  1796. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1797. /// order. The submitting thread meanwhile prepares and sends the next
  1798. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  1799. /// that thread has landed everything in the air, at the same points as
  1800. /// before (the list in [`late`]), so whoever can observe title memory, a
  1801. /// fence or a present still does so only after the flights before it are
  1802. /// merged.
  1803. ///
  1804. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  1805. /// flight; a merge that never stores into memory the card may be writing;
  1806. /// sends to card copies numbered) and here: flights land in the order of
  1807. /// [`LINE`] by one thread, so a later flight's results never reach title
  1808. /// memory before an earlier flight's; the compare on the card stores the
  1809. /// hash it made, so each flight's compare flags exactly what changed since
  1810. /// the compare before it, however late the pieces are fetched; the fetch
  1811. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  1812. /// title bytes the card had received when it ran.
  1813. pub(crate) fn relay() -> bool {
  1814. static ON: OnceLock<bool> = OnceLock::new();
  1815. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  1816. }
  1817. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  1818. /// title memory a flight's shaders may write (a title buffer copy, a fill
  1819. /// of upload memory, a texture) waits only until the flights that declared
  1820. /// that memory have landed, not for everything in the air; and at
  1821. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  1822. /// both wait for everything.
  1823. fn relay_exact() -> bool {
  1824. static ON: OnceLock<bool> = OnceLock::new();
  1825. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  1826. // since the walls of the first room were found drawn in every run with
  1827. // this set and in fewer than half without it).
  1828. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  1829. }
  1830. /// Whether the pieces the relay fetches from the card's memory come over the
  1831. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  1832. /// draws.
  1833. ///
  1834. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  1835. /// and with the relay that is most of a frame: the thread that lands flights
  1836. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  1837. /// a few milliseconds of copying, and everything that waits for a landing
  1838. /// (the title's fences, reads of memory flights may write) waited with it.
  1839. ///
  1840. /// What changes: the fetch runs when its flights are done and beside later
  1841. /// submissions, so of the sends of title bytes it is only known to have run
  1842. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  1843. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  1844. /// the title's, newer than what the flights wrote. A later flight's bytes
  1845. /// may be in what is fetched, as before.
  1846. fn relay_copy() -> bool {
  1847. static ON: OnceLock<bool> = OnceLock::new();
  1848. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  1849. }
  1850. /// Told when something joins [`LINE`], for the thread that lands flights
  1851. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  1852. /// what queues hold.
  1853. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  1854. /// Told when flights have landed ([`relay`]): who waits for that looks
  1855. /// again.
  1856. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  1857. /// With [`relay`], the order of what we put on the queue: the number of
  1858. /// sends of changed ranges to copies in the card's memory so far
  1859. /// (`Host::card_before`). Held from the taking of the ranges until their
  1860. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  1861. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  1862. /// later one.
  1863. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  1864. /// Since the last frame-rate line, of the thread that lands flights
  1865. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  1866. /// card with nothing to land, microseconds it waited for fetches of card
  1867. /// copies' pieces, microseconds of landing in all.
  1868. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  1869. /// Of the line's things in order (a flight: the value signalled on the
  1870. /// host's fence behind it; a write or a signal behind a flight: `None`):
  1871. /// how many, from the front, can be landed when the card has reached
  1872. /// `completed`: everything ahead of the first flight it has not run. A
  1873. /// later flight never lands before an earlier one, and what follows a
  1874. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  1875. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  1876. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  1877. }
  1878. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  1879. /// holds, for every piece of every range of the plan, the copy, the
  1880. /// piece's number in the copy and whether the compare flagged it there (or
  1881. /// did not run). The pieces to fetch, under whichever range, in order: all
  1882. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  1883. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  1884. /// the hash, so the second of them may find it stored already and not
  1885. /// flag it.
  1886. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  1887. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  1888. pieces.sort_unstable();
  1889. pieces.dedup();
  1890. pieces
  1891. }
  1892. #[cfg(test)]
  1893. mod relay_tests {
  1894. use super::{flagged_pieces, landable};
  1895. /// Two flights and what follows each: nothing of the second lands
  1896. /// before the card has run it, and nothing behind a flight lands
  1897. /// before the flight.
  1898. #[test]
  1899. fn flights_land_in_the_order_they_were_sent() {
  1900. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  1901. let line = [Some(5), None, None, Some(6), None];
  1902. assert_eq!(landable(&line, 4), 0);
  1903. assert_eq!(landable(&line, 5), 3);
  1904. assert_eq!(landable(&line, 6), 5);
  1905. assert_eq!(landable(&line, u64::MAX), 5);
  1906. // Signals with no flight ahead land at once; behind one they wait.
  1907. assert_eq!(landable(&[None, None], 0), 2);
  1908. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  1909. assert_eq!(landable(&[], 3), 0);
  1910. // After the first three landed, the rest when its turn comes.
  1911. assert_eq!(landable(&line[3..], 5), 0);
  1912. assert_eq!(landable(&line[3..], 6), 2);
  1913. }
  1914. /// A piece flagged under one range of a plan is fetched under every
  1915. /// range that holds a part of it; pieces of other copies are not.
  1916. #[test]
  1917. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  1918. let (a, b) = (0x1000usize, 0x2000usize);
  1919. // Copy a: piece 3 under two ranges, flagged under the first only;
  1920. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  1921. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  1922. let fetch = flagged_pieces(&flags);
  1923. assert!(fetch.contains(&(a, 3)));
  1924. assert!(!fetch.contains(&(a, 4)));
  1925. assert!(!fetch.contains(&(b, 3)));
  1926. assert!(fetch.contains(&(b, 9)));
  1927. assert_eq!(fetch.len(), 2);
  1928. }
  1929. }
  1930. /// The most host lists in the air before the flights are settled
  1931. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  1932. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  1933. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  1934. /// 32 settled the flights three times a
  1935. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  1936. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  1937. /// descriptor slots, upload
  1938. /// memory and scratch chunks are held until then, and a frame's lists held
  1939. /// all at once ran the slots out before (run 45).
  1940. fn late_most() -> usize {
  1941. static MOST: OnceLock<usize> = OnceLock::new();
  1942. *MOST.get_or_init(|| {
  1943. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  1944. })
  1945. }
  1946. /// Whether a submission with bottom-of-pipe writes may fly
  1947. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  1948. /// the title is told at once, as before; for telling a title that polls
  1949. /// such a value from one that does not).
  1950. fn late_writes() -> bool {
  1951. static ON: OnceLock<bool> = OnceLock::new();
  1952. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  1953. }
  1954. /// Per host copy, the ranges a submission's shaders may write, as declared
  1955. /// (address, end).
  1956. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  1957. /// What [`Host::submit`] hands back for a submission it sent and did not
  1958. /// wait for.
  1959. struct Sent {
  1960. /// Its number among the submissions started.
  1961. number: u64,
  1962. card: Option<CardPlan>,
  1963. back: Vec<Declared>,
  1964. /// What was taken off it to be done on the card.
  1965. own: Option<card_steps::Taken>,
  1966. /// Its bottom-of-pipe writes.
  1967. writes: Vec<(usize, crate::queue::Written, usize)>,
  1968. }
  1969. /// A submission on the card that has not been waited for ([`late`]): its
  1970. /// host lists, taken from the title's (which it may reset meanwhile), and
  1971. /// what is to be done once it has run.
  1972. struct Flight {
  1973. number: u64,
  1974. /// The value signalled on the host's fence behind it.
  1975. fence: u64,
  1976. lists: Vec<crate::list::Detached>,
  1977. order: Vec<usize>,
  1978. card: Option<CardPlan>,
  1979. back: Vec<Declared>,
  1980. /// The list of ours that ran ahead of them ([`card_steps`]).
  1981. own: Option<card_steps::Taken>,
  1982. }
  1983. /// One thing in the line of what waits for the card, in order.
  1984. enum Late {
  1985. Run(Flight),
  1986. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  1987. Write(usize, crate::queue::Written, usize),
  1988. /// A fence (its address) signalled behind the flights before it.
  1989. Signal(usize, u64),
  1990. }
  1991. struct Line {
  1992. line: Vec<Late>,
  1993. /// The title memory the flights' shaders may write (address, end), in
  1994. /// order and joined.
  1995. written: Vec<(usize, usize)>,
  1996. /// Host lists in the flights.
  1997. lists: usize,
  1998. /// The value signalled on the host's fence behind the last flight.
  1999. target: u64,
  2000. /// A settle has taken the line and is not done: a signal still goes
  2001. /// behind it.
  2002. settling: bool,
  2003. /// Something was settled away from a queue's own calls: the helper
  2004. /// thread looks at what queues hold.
  2005. poke: bool,
  2006. /// Host lists of settled flights, reset and given back outside the
  2007. /// submission lock ([`land`]: a settle may run under a caller's own
  2008. /// locks).
  2009. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2010. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2011. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2012. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2013. /// With [`card_steps`]: what the flights being landed write.
  2014. landing: Vec<card_steps::Writer>,
  2015. }
  2016. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2017. // into; touched under the lock.
  2018. unsafe impl Send for Line {}
  2019. static LINE: Mutex<Line> = Mutex::new(Line {
  2020. line: Vec::new(),
  2021. written: Vec::new(),
  2022. lists: 0,
  2023. target: 0,
  2024. settling: false,
  2025. poke: false,
  2026. landed: Vec::new(),
  2027. in_hand: Vec::new(),
  2028. landing: Vec::new(),
  2029. });
  2030. /// Told when a flight joins [`LINE`] or it is poked.
  2031. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2032. fn line() -> std::sync::MutexGuard<'static, Line> {
  2033. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2034. }
  2035. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2036. const WHY_SYNC: usize = 2;
  2037. const WHY_CARD_DONE: usize = 3;
  2038. const WHY_VALUE: usize = 4;
  2039. const WHY_STALE: usize = 5;
  2040. const WHY_READ: usize = 6;
  2041. const WHY_RUN: usize = 7;
  2042. const WHY_MOST: usize = 8;
  2043. const WHY_WRITES: usize = 9;
  2044. const WHY_FENCE: usize = 10;
  2045. /// Since the last frame-rate line: submissions sent without a wait;
  2046. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2047. /// microseconds settles waited for the card; value waits met by a flight's
  2048. /// bottom-of-pipe write; fence signals set behind flights.
  2049. /// Then: the settles for title memory read, by what read it (a buffer
  2050. /// copy, a fill of upload memory, a texture).
  2051. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2052. /// Since the last frame-rate line: the microseconds settles waited for the
  2053. /// card, by why they settled (the `WHY_` places).
  2054. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2055. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2056. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2057. if from >= to {
  2058. return false;
  2059. }
  2060. let at = ranges.partition_point(|r| r.1 <= from);
  2061. ranges.get(at).is_some_and(|r| r.0 < to)
  2062. }
  2063. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2064. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2065. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2066. ranges.sort_unstable();
  2067. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2068. for &(from, to) in ranges.iter() {
  2069. match out.last_mut() {
  2070. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2071. _ => out.push((from, to)),
  2072. }
  2073. }
  2074. *ranges = out;
  2075. }
  2076. /// Whether anything is in the air.
  2077. fn flying() -> bool {
  2078. if !late() {
  2079. return false;
  2080. }
  2081. let line = line();
  2082. // (With the relay: also while flights are being landed.)
  2083. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2084. }
  2085. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2086. /// before they are settled, if so. Preparing reads title memory on the
  2087. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2088. /// runs steps of ours that may read or write it anywhere; what the
  2089. /// flights' shaders write is not there yet.
  2090. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2091. let (written, copies) = {
  2092. let line = line();
  2093. if line.written.is_empty() {
  2094. return None;
  2095. }
  2096. (line.written.clone(), card_steps::copies(&line))
  2097. };
  2098. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2099. }
  2100. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2101. /// flights when the title itself wrote the memory since they were given it
  2102. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2103. ///
  2104. /// The title's 174 MB heap is declared written as a whole (a root view has
  2105. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2106. /// bytes a frame, at a new place each time, waited for every flight's
  2107. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2108. /// named). The title writes those bytes just before the draw that reads
  2109. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2110. ///
  2111. /// Or no shader's write went into that page in the last 600 frames
  2112. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2113. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2114. /// before the page was taken.
  2115. ///
  2116. /// What can go wrong: a constant a flight's shader really writes, in a
  2117. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2118. /// for the first time, is read as it was before that flight.
  2119. fn fill_is_titles(src: usize, len: usize) -> bool {
  2120. const SMALL: usize = 64 << 10;
  2121. static ON: OnceLock<bool> = OnceLock::new();
  2122. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2123. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2124. }
  2125. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2126. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2127. /// in (start, bytes).
  2128. #[cfg(feature = "diagnostics")]
  2129. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2130. /// How often and how long, and the address the last one read.
  2131. #[cfg(feature = "diagnostics")]
  2132. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2133. /// What the wait that comes next is for, and why not on the card.
  2134. #[cfg(feature = "diagnostics")]
  2135. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2136. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2137. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2138. /// shaders.
  2139. #[cfg(feature = "diagnostics")]
  2140. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2141. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2142. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2143. /// raw address (1).
  2144. #[cfg(feature = "diagnostics")]
  2145. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2146. if len < 1 << 20 {
  2147. return;
  2148. }
  2149. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2150. let e = all
  2151. .get_or_insert_with(Default::default)
  2152. .entry((address as usize, (address + len) as usize, pipeline))
  2153. .or_insert_with(|| {
  2154. let shaders = match pipeline {
  2155. 0 => "a view in a table".into(),
  2156. 1 => "a raw address".into(),
  2157. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2158. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2159. }),
  2160. };
  2161. (0, shaders)
  2162. });
  2163. e.0 += 1;
  2164. }
  2165. #[cfg(feature = "diagnostics")]
  2166. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2167. let i = written.partition_point(|r| r.1 <= at);
  2168. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2169. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2170. let why = blamed.1;
  2171. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2172. }
  2173. /// Why [`card_steps`] left the submission to the wait that comes next.
  2174. #[cfg(feature = "diagnostics")]
  2175. fn refused(why: &'static str) {
  2176. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2177. }
  2178. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2179. #[cfg(feature = "diagnostics")]
  2180. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2181. if let Some((shadow, from, _)) = stale.first() {
  2182. let (start, len) = shadow.span();
  2183. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2184. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2185. }
  2186. }
  2187. /// The wait for what [`blame`] last named, or a wait of another reason than
  2188. /// title memory read, took `us`.
  2189. #[cfg(feature = "diagnostics")]
  2190. fn blamed(why: usize, us: u64) {
  2191. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2192. let (key, at) = match (why, named) {
  2193. (WHY_READ | WHY_STALE, Some(named)) => named,
  2194. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2195. _ => {
  2196. let kind = match why {
  2197. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2198. WHY_VALUE => "a memory value",
  2199. WHY_STALE => "title memory changed under shader writes",
  2200. WHY_RUN => "a step of ours",
  2201. WHY_MOST => "lists in the air",
  2202. WHY_FENCE => "a blocking fence wait",
  2203. _ => "another reason",
  2204. };
  2205. ((kind, "", 0, 0, 0), 0)
  2206. }
  2207. };
  2208. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2209. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2210. *e = (e.0 + 1, e.1 + us, at);
  2211. }
  2212. /// For the frame-rate line: the five that waited longest.
  2213. #[cfg(feature = "diagnostics")]
  2214. fn log_blame(frames: f64) {
  2215. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2216. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2217. let mut all: Vec<_> = all.into_iter().collect();
  2218. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2219. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2220. // The passes that declare it written, the ones that do so most.
  2221. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2222. for ((a, b, _), (n, shaders)) in &wide {
  2223. if *a < at + len && at < *b {
  2224. *passes.entry(shaders).or_default() += n;
  2225. }
  2226. }
  2227. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2228. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2229. let passes: Vec<String> =
  2230. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2231. tracing::info!(
  2232. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2233. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2234. us as f64 / 1e3 / frames,
  2235. n as f64 / frames,
  2236. passes.join(", "),
  2237. match (why.is_empty(), kind) {
  2238. (true, _) => "",
  2239. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2240. _ => "; not done on the card: ",
  2241. },
  2242. );
  2243. }
  2244. }
  2245. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2246. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2247. touches(written, src, src + len) && !fill_is_titles(src, len)
  2248. }
  2249. /// Whether they stop a title buffer copy, and if so whether by its source.
  2250. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2251. let read = read_blocked(written, src, len);
  2252. (read || touches(written, dst, dst + len)).then_some(read)
  2253. }
  2254. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2255. /// may write (in order, joined); `count` whether the kind of read is
  2256. /// counted for the frame line.
  2257. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2258. if written.is_empty() {
  2259. return None;
  2260. }
  2261. for list in runs {
  2262. for step in &list.deferred().copies {
  2263. match step {
  2264. &Step::Copy(dst, src, len) => {
  2265. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2266. if count {
  2267. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2268. #[cfg(feature = "diagnostics")]
  2269. if _read {
  2270. blame("a buffer copy's source", written, src, len);
  2271. } else {
  2272. blame("a buffer copy's destination", written, dst, len);
  2273. }
  2274. }
  2275. return Some(WHY_READ);
  2276. }
  2277. }
  2278. &Step::Fill(_, src, len, _) => {
  2279. if read_blocked(written, src, len) {
  2280. if count {
  2281. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2282. #[cfg(feature = "diagnostics")]
  2283. blame("a fill of upload memory", written, src, len);
  2284. }
  2285. return Some(WHY_READ);
  2286. }
  2287. }
  2288. Step::Texture(staging) => {
  2289. let (at, len) = staging.memory();
  2290. if touches(written, at, at + len) {
  2291. if count {
  2292. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2293. #[cfg(feature = "diagnostics")]
  2294. blame("a texture", written, at, len);
  2295. }
  2296. return Some(WHY_READ);
  2297. }
  2298. }
  2299. Step::Run(_) => return Some(WHY_RUN),
  2300. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2301. }
  2302. }
  2303. }
  2304. None
  2305. }
  2306. /// With flights in the air, after the submission's write-watch asking:
  2307. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2308. /// may write and that the title wrote since it was last copied. The
  2309. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2310. /// the title's bytes there would reach the card a submission late.
  2311. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2312. use std::sync::Arc;
  2313. // Per copy, the span of what is refreshed (a flush brings that much
  2314. // up to date at most).
  2315. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2316. // Where each copy is in it, if shaders may be writing it (none begins to
  2317. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2318. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2319. for list in runs {
  2320. for step in &list.deferred().copies {
  2321. if let Step::Refresh(shadow, address, len) = step {
  2322. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2323. shadow.writes_pending().then(|| {
  2324. spans.push((shadow.clone(), *address, *address + *len));
  2325. spans.len() - 1
  2326. })
  2327. });
  2328. if let Some(i) = *place {
  2329. let s = &mut spans[i];
  2330. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2331. }
  2332. }
  2333. }
  2334. }
  2335. if late_exact() {
  2336. // The title's bytes are put in beside the flights' writes; a
  2337. // settle is still due where that could not be done. At most this
  2338. // many changed runs go up to copies in the card's memory, each a
  2339. // copy of its own there. With [`card_steps`] the pages of the
  2340. // title's ring of constants come here too, which were waited for
  2341. // before: hundreds of short runs each, at about 1.5 us a run.
  2342. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2343. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2344. return spans;
  2345. }
  2346. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2347. spans
  2348. }
  2349. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2350. /// air, if there are any, and is set when they are settled. Whether it
  2351. /// did; if not the caller sets the fence now.
  2352. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2353. if !late() {
  2354. return false;
  2355. }
  2356. let mut line = line();
  2357. if line.line.is_empty() && !line.settling {
  2358. return false;
  2359. }
  2360. line.line.push(Late::Signal(fence, value));
  2361. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2362. drop(line);
  2363. // A signal alone (behind a settle under way) has no flight to wake
  2364. // the helper thread for it.
  2365. LINE_MOVED.notify_one();
  2366. RELAY_MOVED.notify_one();
  2367. true
  2368. }
  2369. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2370. /// whether it is met once the flights in the air have run. A flight's
  2371. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2372. /// for the card: the part behind the wait goes to the card behind that
  2373. /// flight, which is the order the wait asks for. If the flights may write
  2374. /// the value in a way not known here (shaders, a timestamp, another
  2375. /// width), they are settled and memory is asked again.
  2376. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2377. let (address, bytes) = wait.place();
  2378. {
  2379. let line = line();
  2380. if line.line.is_empty() && line.in_hand.is_empty() {
  2381. return false;
  2382. }
  2383. let mut unsure = touches(&line.written, address, address + bytes);
  2384. // (With the relay: first the writes of flights being landed.)
  2385. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2386. Late::Write(at, what, n) => Some((at, what, n)),
  2387. _ => None,
  2388. }));
  2389. for (at, what, n) in writes {
  2390. if *at >= address + bytes || address >= *at + *n {
  2391. continue;
  2392. }
  2393. match what {
  2394. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2395. if wait.holds_for(*v) {
  2396. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2397. return true;
  2398. }
  2399. }
  2400. _ => unsure = true,
  2401. }
  2402. }
  2403. if !unsure {
  2404. return false;
  2405. }
  2406. }
  2407. settle_now(WHY_VALUE);
  2408. wait.met()
  2409. }
  2410. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2411. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2412. pub(crate) fn settle_now(why: usize) {
  2413. if !late() {
  2414. return;
  2415. }
  2416. let Some(host) = host() else {
  2417. return;
  2418. };
  2419. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2420. host.settle(&mut submitted, why);
  2421. }
  2422. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2423. pub(crate) fn settle_for_present() {
  2424. settle_now(WHY_SYNC);
  2425. }
  2426. pub(crate) fn settle_for_fence() {
  2427. settle_now(WHY_FENCE);
  2428. }
  2429. /// Resets the host lists of settled flights and keeps them for reuse, as
  2430. /// a queue does for the lists it ran (`crate::list::recycle`).
  2431. fn land() {
  2432. let landed = std::mem::take(&mut line().landed);
  2433. for (lists, order) in landed {
  2434. crate::list::recycle(lists, &order);
  2435. }
  2436. }
  2437. /// The thread that settles the flights once the card has run them all
  2438. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2439. /// at the next call that settles, and a title thread that polls such a
  2440. /// value while the submitting thread waits for that thread would never
  2441. /// see it.
  2442. fn late_helper() {
  2443. let Some(host) = host() else {
  2444. return;
  2445. };
  2446. // SAFETY: a plain event of our own.
  2447. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2448. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2449. return;
  2450. };
  2451. loop {
  2452. let target = {
  2453. let mut line = line();
  2454. loop {
  2455. if line.poke {
  2456. line.poke = false;
  2457. break None;
  2458. }
  2459. // (With the relay the flights are another thread's.)
  2460. if !relay() && !line.line.is_empty() && !line.settling {
  2461. break Some(line.target);
  2462. }
  2463. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2464. }
  2465. };
  2466. let Some(target) = target else {
  2467. land();
  2468. crate::queue::release_held(false);
  2469. continue;
  2470. };
  2471. // The card first, without the submission lock: the submitting
  2472. // thread prepares and sends meanwhile.
  2473. // SAFETY: our fence and event.
  2474. unsafe {
  2475. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2476. WaitForSingleObject(event, INFINITE);
  2477. }
  2478. }
  2479. {
  2480. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2481. // Something newer went up meanwhile: the card is waited for
  2482. // again, the submitting thread is not held up for it.
  2483. if line().target != target {
  2484. continue;
  2485. }
  2486. host.settle(&mut submitted, WHY_CARD_DONE);
  2487. }
  2488. land();
  2489. crate::queue::release_held(false);
  2490. }
  2491. }
  2492. /// Starts the threads of [`late`], once: the one that settles flights when
  2493. /// the card has run them and looks at what queues hold, and with [`relay`]
  2494. /// the one that lands flights.
  2495. fn late_threads() {
  2496. static HELPER: std::sync::Once = std::sync::Once::new();
  2497. HELPER.call_once(|| {
  2498. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2499. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2500. }
  2501. tracing::info!(
  2502. most = late_most(),
  2503. writes = late_writes(),
  2504. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2505. );
  2506. if relay() {
  2507. // Without it nothing would ever land.
  2508. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2509. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2510. }
  2511. tracing::info!(
  2512. exact = relay_exact(),
  2513. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2514. );
  2515. }
  2516. });
  2517. }
  2518. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2519. /// time flights have landed. Counted as a settle for `why`, and its time
  2520. /// as waiting for the card. The caller may hold the submission lock: the
  2521. /// thread that lands flights never takes it.
  2522. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2523. let mut line = line();
  2524. if done(&line) {
  2525. return;
  2526. }
  2527. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2528. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2529. let was_working = working(false);
  2530. let waiting = std::time::Instant::now();
  2531. while !done(&line) {
  2532. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2533. }
  2534. drop(line);
  2535. stood(waiting);
  2536. working(was_working);
  2537. let us = waiting.elapsed().as_micros() as u64;
  2538. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2539. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2540. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2541. #[cfg(feature = "diagnostics")]
  2542. blamed(why, us);
  2543. }
  2544. /// What the thread that lands flights fetches card copies' pieces with
  2545. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2546. /// behind the submission lock), and the memory the pieces come down to.
  2547. struct RelayFetch {
  2548. list: Prelude,
  2549. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2550. queue: Option<ID3D12CommandQueue>,
  2551. fence: ID3D12Fence,
  2552. event: HANDLE,
  2553. /// The last value signalled on `fence`.
  2554. sent: u64,
  2555. /// Buffer, mapping, bytes.
  2556. buffer: Option<(ID3D12Resource, usize, u64)>,
  2557. /// Pieces caught while a later flight was writing them.
  2558. suspects: torn::Suspects,
  2559. /// What earlier fetches brought of flights not landed yet.
  2560. had: crate::land::Had,
  2561. }
  2562. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2563. /// the first flights of the line it takes them, with what follows them,
  2564. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2565. /// the card, or for a flight. It takes neither the submission lock nor
  2566. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2567. /// lists and looking at what queues hold are left to [`late_helper`].
  2568. fn relay_worker() {
  2569. let Some(host) = host() else {
  2570. return;
  2571. };
  2572. // SAFETY: a plain event of our own.
  2573. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2574. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2575. };
  2576. let mut fetch: Option<RelayFetch> = None;
  2577. loop {
  2578. let next = {
  2579. let mut line = line();
  2580. loop {
  2581. if line.line.is_empty() {
  2582. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2583. continue;
  2584. }
  2585. let fences: Vec<Option<u64>> = line
  2586. .line
  2587. .iter()
  2588. .map(|l| match l {
  2589. Late::Run(flight) => Some(flight.fence),
  2590. _ => None,
  2591. })
  2592. .collect();
  2593. // SAFETY: a plain query.
  2594. let completed = unsafe { host.fence.GetCompletedValue() };
  2595. let n = landable(&fences, completed);
  2596. if n == 0 {
  2597. // The first thing is a flight the card has not run.
  2598. break Err(fences[0].unwrap_or(0));
  2599. }
  2600. line.settling = true;
  2601. let items: Vec<Late> = line.line.drain(..n).collect();
  2602. line.in_hand = items
  2603. .iter()
  2604. .filter_map(|l| match l {
  2605. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2606. _ => None,
  2607. })
  2608. .collect();
  2609. if card_steps::stage() > 0 {
  2610. line.landing = card_steps::writers(&items);
  2611. }
  2612. break Ok(items);
  2613. }
  2614. };
  2615. match next {
  2616. Ok(items) => host.relay_land(items, &mut fetch),
  2617. Err(target) => {
  2618. let waiting = std::time::Instant::now();
  2619. // SAFETY: the host's fence and this thread's event.
  2620. let waited = unsafe {
  2621. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2622. WaitForSingleObject(event, INFINITE);
  2623. })
  2624. };
  2625. if waited.is_err() {
  2626. std::thread::sleep(std::time::Duration::from_millis(1));
  2627. }
  2628. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2629. }
  2630. }
  2631. }
  2632. }
  2633. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2634. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2635. /// once, the pieces that differ found on several threads; but the merge is
  2636. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2637. /// are not done with here (each flight's are, afterwards). In two steps:
  2638. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  2639. /// which needs nothing that the fetch from the card's memory brings), and
  2640. /// the merge.
  2641. struct RelayBack {
  2642. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  2643. found: Option<Vec<Vec<(usize, usize)>>>,
  2644. }
  2645. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  2646. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2647. for (shadow, declared) in back {
  2648. if shadow.carded() {
  2649. continue;
  2650. }
  2651. let mut spans: Vec<(usize, usize)> = Vec::new();
  2652. join_ranges(&mut spans, declared.iter().copied());
  2653. for &(from, to) in &spans {
  2654. shadow.relay_compared(from, to - from);
  2655. }
  2656. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2657. }
  2658. RelayBack { work, found: None }
  2659. }
  2660. impl RelayBack {
  2661. /// Looks the ranges through, once; its time counts as `stat`.
  2662. fn look(&mut self, stat: usize) {
  2663. if self.work.is_empty() || self.found.is_some() {
  2664. return;
  2665. }
  2666. let scanning = std::time::Instant::now();
  2667. // Looked through without a lock: a piece that changes meanwhile (a
  2668. // later flight writing, the title's bytes going in) is found now or
  2669. // by that flight's landing, and the merge looks again under the
  2670. // lock.
  2671. self.found = Some(crate::shadow::find_all(&self.work));
  2672. crate::land::spent(stat, scanning);
  2673. #[cfg(feature = "diagnostics")]
  2674. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2675. }
  2676. /// What differs goes into title memory.
  2677. fn merge(mut self) {
  2678. use crate::land;
  2679. self.look(land::stat::SCAN);
  2680. let Some(found) = self.found else {
  2681. return;
  2682. };
  2683. let merging = std::time::Instant::now();
  2684. let mut written: Vec<u64> = Vec::new();
  2685. if land::on() {
  2686. // Pieces in the same block of title memory in one job, in order.
  2687. let pieces: Vec<(usize, usize, usize)> =
  2688. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  2689. let start = |i: usize| self.work[i].0.span().0 as usize;
  2690. let mut order: Vec<usize> = (0..pieces.len()).collect();
  2691. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  2692. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  2693. let jobs = land::jobs(&cut);
  2694. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  2695. land::each(jobs.len(), &|j| {
  2696. let working = std::time::Instant::now();
  2697. let mut notes = land::Notes::default();
  2698. for &p in &order[jobs[j].clone()] {
  2699. let (i, at, n) = pieces[p];
  2700. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  2701. }
  2702. notes.flush();
  2703. land::spent(land::stat::BACK_ALL, working);
  2704. });
  2705. land::count(land::stat::JOBS, jobs.len() as u64);
  2706. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  2707. } else {
  2708. let (mut now, mut title) = (Vec::new(), Vec::new());
  2709. for ((shadow, ..), found) in self.work.iter().zip(found) {
  2710. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  2711. written.push(found.into_iter().map(merge).sum());
  2712. }
  2713. }
  2714. land::spent(land::stat::BACK, merging);
  2715. for ((_, from, to), written) in self.work.iter().zip(written) {
  2716. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  2717. #[cfg(feature = "diagnostics")]
  2718. crate::copystat::compared(*from, to - from, written as usize);
  2719. let _ = (from, to);
  2720. }
  2721. }
  2722. }
  2723. /// For the frame-rate line, with [`late`]: what the line of flights did
  2724. /// per frame since the last one.
  2725. fn late_line(frames: f64) {
  2726. if !late() {
  2727. return;
  2728. }
  2729. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2730. tracing::info!(
  2731. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2732. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2733. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2734. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2735. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2736. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2737. s[0],
  2738. s[1],
  2739. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2740. s[12] / 1000.0,
  2741. s[WHY_SYNC],
  2742. s[WHY_CARD_DONE],
  2743. s[WHY_VALUE],
  2744. s[WHY_STALE],
  2745. s[WHY_READ],
  2746. s[15],
  2747. s[16],
  2748. s[17],
  2749. s[WHY_RUN],
  2750. late_most(),
  2751. s[WHY_MOST],
  2752. s[WHY_WRITES],
  2753. s[WHY_FENCE],
  2754. s[13],
  2755. s[14],
  2756. );
  2757. {
  2758. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2759. tracing::info!(
  2760. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2761. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2762. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2763. w[WHY_SYNC],
  2764. w[WHY_CARD_DONE],
  2765. w[WHY_VALUE],
  2766. w[WHY_STALE],
  2767. w[WHY_READ],
  2768. w[WHY_RUN],
  2769. w[WHY_MOST],
  2770. w[WHY_WRITES],
  2771. w[WHY_FENCE],
  2772. );
  2773. }
  2774. if relay() {
  2775. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2776. tracing::info!(
  2777. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2778. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2779. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2780. \"settles\" above are waits of other threads for it)",
  2781. r[1],
  2782. r[0],
  2783. r[2] / 1000.0,
  2784. r[3] / 1000.0,
  2785. r[4] / 1000.0,
  2786. );
  2787. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2788. if t[0] > 0.0 {
  2789. tracing::info!(
  2790. "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",
  2791. t[0],
  2792. t[1],
  2793. t[2],
  2794. );
  2795. }
  2796. }
  2797. crate::land::log(frames);
  2798. card_steps::log(frames);
  2799. crate::picked::log(frames);
  2800. #[cfg(feature = "diagnostics")]
  2801. log_blame(frames);
  2802. if late_exact() {
  2803. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  2804. tracing::info!(
  2805. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  2806. {runs:.0} changed runs, {:.2} MB",
  2807. bytes / (1 << 20) as f64
  2808. );
  2809. }
  2810. }
  2811. mod card_steps;
  2812. mod torn;
  2813. pub(crate) mod upcheck;
  2814. #[cfg(test)]
  2815. mod late_tests {
  2816. use super::{continues, join_ranges, touches};
  2817. /// Copies join only when both ends continue and the whole does not
  2818. /// overlap itself.
  2819. #[test]
  2820. fn copies_join_only_end_to_end_and_apart() {
  2821. // (destination, source, bytes)
  2822. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  2823. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  2824. // A gap, or only one side continues.
  2825. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  2826. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  2827. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  2828. // Together they would overlap: the second reads what the first wrote.
  2829. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  2830. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  2831. // They touch without overlapping.
  2832. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  2833. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  2834. }
  2835. /// Ranges are found by what they hold, not by where they start, and a
  2836. /// range that only touches another's end does not touch it.
  2837. #[test]
  2838. fn ranges_touch_where_they_overlap() {
  2839. let mut ranges = Vec::new();
  2840. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  2841. assert_eq!(ranges, [(10, 25), (40, 60)]);
  2842. join_ranges(&mut ranges, [(25, 40)]);
  2843. assert_eq!(ranges, [(10, 60)]);
  2844. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  2845. for (from, to, hit) in [
  2846. (0, 10, false),
  2847. (0, 11, true),
  2848. (24, 25, true),
  2849. (25, 40, false),
  2850. (25, 41, true),
  2851. (59, 200, true),
  2852. (60, 100, false),
  2853. (100, 101, true),
  2854. (101, 500, false),
  2855. (30, 30, false),
  2856. (50, 50, false),
  2857. ] {
  2858. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  2859. }
  2860. assert!(!touches(&[], 0, usize::MAX));
  2861. }
  2862. }
  2863. /// Whether a title buffer copy that continues the one recorded before it
  2864. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  2865. /// default).
  2866. ///
  2867. /// Each copy is done at submission through the kernel, which reports a
  2868. /// page that is not there instead of faulting (`copy_mapped`), tells the
  2869. /// write watch and the guards, and ends the refreshes gathered so far: a
  2870. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  2871. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  2872. /// continue the one before is counted either way and said on its own line
  2873. /// with the frame rate; the switch is worth that many kernel calls.
  2874. ///
  2875. /// Joined, the same bytes move: [`continues`] joins only copies whose
  2876. /// ranges, taken together, do not overlap, and nothing is recorded between
  2877. /// two steps that follow each other. What differs: a page that is not
  2878. /// mapped now fails the joined copy as a whole (it then goes page by page,
  2879. /// zeros for what cannot be read, as a single copy does), where before
  2880. /// only the copy that held it did.
  2881. fn join_copies() -> bool {
  2882. static ON: OnceLock<bool> = OnceLock::new();
  2883. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  2884. }
  2885. /// Since the last frame-rate line: title buffer copies recorded, and those
  2886. /// that continue the one before ([`join_copies`]).
  2887. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  2888. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  2889. /// where `last` ended, source and destination both, and the two as one do
  2890. /// not overlap (source over destination): then one copy of both moves the
  2891. /// bytes the two would move in turn.
  2892. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  2893. let ((d, s, n), (dst, src, len)) = (last, next);
  2894. let Some(all) = n.checked_add(len) else {
  2895. return false;
  2896. };
  2897. d.checked_add(n) == Some(dst)
  2898. && s.checked_add(n) == Some(src)
  2899. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  2900. }
  2901. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  2902. /// One list's lock at a time: a submission may name a list twice.
  2903. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  2904. let mut back: Vec<Declared> = Vec::new();
  2905. // Where each copy is in it, and the ranges seen: dispatches declare the
  2906. // same ranges thousands of times a frame.
  2907. let mut places: ByCopy<usize> = ByCopy::default();
  2908. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  2909. for list in runs {
  2910. for step in &list.deferred().copies {
  2911. if let Step::GpuWrite(shadow, address, len) = step {
  2912. let key = std::sync::Arc::as_ptr(shadow) as usize;
  2913. if !seen.insert((key, *address, *len)) {
  2914. continue;
  2915. }
  2916. let i = *places.entry(key).or_insert_with(|| {
  2917. back.push((shadow.clone(), Vec::new()));
  2918. back.len() - 1
  2919. });
  2920. back[i].1.push((*address, *address + *len));
  2921. }
  2922. }
  2923. }
  2924. back
  2925. }
  2926. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  2927. /// lines that say what the title's CPU was given while it decided whether
  2928. /// the camera is in a room. The values of the small read-backs
  2929. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  2930. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  2931. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  2932. /// copies found stale after their refresh (`shadow.rs`), and, in the
  2933. /// runtime, the read requests that fail (with 2: every request).
  2934. pub(crate) fn walls_trace() -> bool {
  2935. static ON: OnceLock<bool> = OnceLock::new();
  2936. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  2937. }
  2938. /// After `list` has run: the texels its read-backs copied into host
  2939. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  2940. ///
  2941. /// A submission that is waited for did this itself. One sent ahead
  2942. /// ([`late`]) did not, at any stage: the flights' lists were settled
  2943. /// without it, so the title read a buffer nobody wrote, as before read-backs
  2944. /// were made (the exposure metering's two small float targets, every frame).
  2945. fn read_backs(list: &HostList) {
  2946. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  2947. let mut data = std::ptr::null_mut();
  2948. // SAFETY: a read-back buffer of ours, written by the list that has
  2949. // run; the title's destination holds every row (checked when the
  2950. // copy was recorded).
  2951. unsafe {
  2952. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  2953. let from = data.cast::<u8>().cast_const();
  2954. for line in 0..*rows {
  2955. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  2956. }
  2957. // The walls trace: what the title is handed (one row of at
  2958. // most 24 values: its 5x1 and 1x1 float targets).
  2959. if walls_trace() && *rows == 1 && *row <= 96 {
  2960. let mut values = [0f32; 24];
  2961. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  2962. tracing::info!(
  2963. frame = crate::frame::current(),
  2964. to = format_args!("{:#x}", *at),
  2965. bytes = *row,
  2966. values = ?&values[..*row / 4],
  2967. "walls trace: a read-back lands in title memory"
  2968. );
  2969. }
  2970. buffer.Unmap(0, None);
  2971. }
  2972. }
  2973. }
  2974. }
  2975. /// After the card ran what declared `back`: what shaders wrote there goes
  2976. /// into title memory, and the ranges are done with.
  2977. fn hand_back(back: &[Declared]) {
  2978. if crate::shadow::wide_back() {
  2979. // Every range first (the pieces that differ, found on several
  2980. // threads), then the merges, in order, as below.
  2981. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2982. for (shadow, declared) in back {
  2983. if shadow.carded() {
  2984. continue;
  2985. }
  2986. let mut sorted = declared.clone();
  2987. sorted.sort_unstable();
  2988. let mut spans: Vec<(usize, usize)> = Vec::new();
  2989. for (from, to) in sorted {
  2990. match spans.last_mut() {
  2991. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2992. _ => spans.push((from, to)),
  2993. }
  2994. }
  2995. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2996. }
  2997. #[cfg(feature = "diagnostics")]
  2998. let scanning = std::time::Instant::now();
  2999. let found = crate::shadow::find_all(&work);
  3000. #[cfg(feature = "diagnostics")]
  3001. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3002. for ((shadow, from, to), found) in work.iter().zip(found) {
  3003. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3004. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3005. #[cfg(feature = "diagnostics")]
  3006. crate::copystat::compared(*from, to - from, written);
  3007. }
  3008. for (shadow, declared) in back {
  3009. shadow.copy_back_done(declared);
  3010. }
  3011. return;
  3012. }
  3013. for (shadow, declared) in back {
  3014. if shadow.carded() {
  3015. // Done before (`Host::card_back`).
  3016. shadow.copy_back_done(declared);
  3017. continue;
  3018. }
  3019. // Each byte compared once: the world declares dozens of views
  3020. // of its 174 MB heap that overlap almost entirely, and comparing
  3021. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3022. // MB shaders wrote. Only ranges that overlap or touch are
  3023. // joined: what lies between two was not given to shaders (the
  3024. // snapshot does not hold it).
  3025. let mut sorted = declared.clone();
  3026. sorted.sort_unstable();
  3027. let mut spans: Vec<(usize, usize)> = Vec::new();
  3028. for (from, to) in sorted {
  3029. match spans.last_mut() {
  3030. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3031. _ => spans.push((from, to)),
  3032. }
  3033. }
  3034. for (from, to) in spans {
  3035. let written = shadow.copy_back(from, to - from);
  3036. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3037. #[cfg(feature = "diagnostics")]
  3038. crate::copystat::compared(from, to - from, written);
  3039. }
  3040. shadow.copy_back_done(declared);
  3041. }
  3042. }
  3043. impl Host {
  3044. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3045. /// mesh shaders need both); logged once.
  3046. pub(crate) fn mesh_shaders(&self) -> bool {
  3047. static MESH: OnceLock<bool> = OnceLock::new();
  3048. *MESH.get_or_init(|| {
  3049. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3050. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3051. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3052. };
  3053. // SAFETY: each query writes its own structure of the given size.
  3054. let ok = unsafe {
  3055. self.device
  3056. .CheckFeatureSupport(
  3057. D3D12_FEATURE_D3D12_OPTIONS7,
  3058. (&raw mut options).cast(),
  3059. size_of_val(&options) as u32,
  3060. )
  3061. .is_ok()
  3062. && self
  3063. .device
  3064. .CheckFeatureSupport(
  3065. D3D12_FEATURE_SHADER_MODEL,
  3066. (&raw mut model).cast(),
  3067. size_of_val(&model) as u32,
  3068. )
  3069. .is_ok()
  3070. };
  3071. let mesh = ok
  3072. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3073. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3074. tracing::info!(mesh, "host mesh shader support");
  3075. mesh
  3076. })
  3077. }
  3078. /// Whether the host GPU supports the depth bounds test; logged once.
  3079. pub(crate) fn depth_bounds(&self) -> bool {
  3080. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3081. *BOUNDS.get_or_init(|| {
  3082. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3083. // SAFETY: writes `options` of the given size.
  3084. let ok = unsafe {
  3085. self.device
  3086. .CheckFeatureSupport(
  3087. D3D12_FEATURE_D3D12_OPTIONS2,
  3088. (&raw mut options).cast(),
  3089. size_of_val(&options) as u32,
  3090. )
  3091. .is_ok()
  3092. };
  3093. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3094. tracing::info!(supported, "host depth bounds support");
  3095. supported
  3096. })
  3097. }
  3098. /// A new list, open for recording.
  3099. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3100. #[cfg(feature = "diagnostics")]
  3101. let started = std::time::Instant::now();
  3102. #[cfg(feature = "diagnostics")]
  3103. let before = private_bytes();
  3104. let list = self.make_list();
  3105. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3106. // (May shrink while a list is made, on another thread's account:
  3107. // added as it is, the sum is what counts.)
  3108. #[cfg(feature = "diagnostics")]
  3109. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3110. #[cfg(feature = "diagnostics")]
  3111. {
  3112. use crate::copystat::{C, add};
  3113. add(C::HostLists, 1);
  3114. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3115. }
  3116. list
  3117. }
  3118. /// An allocator and a closed list for a prelude.
  3119. fn make_prelude(&self) -> Option<Prelude> {
  3120. // SAFETY: plain object creation.
  3121. let made: windows::core::Result<Prelude> = unsafe {
  3122. (|| {
  3123. let allocator: ID3D12CommandAllocator =
  3124. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3125. let list: ID3D12GraphicsCommandList =
  3126. self.device
  3127. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3128. list.Close()?;
  3129. Ok((allocator, list))
  3130. })()
  3131. };
  3132. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3133. match made {
  3134. Ok(prelude) => Some(prelude),
  3135. Err(e) => {
  3136. tracing::warn!(error = %e, "no host list for a prelude");
  3137. None
  3138. }
  3139. }
  3140. }
  3141. fn make_list(&self) -> windows::core::Result<HostList> {
  3142. // SAFETY: plain object creation.
  3143. unsafe {
  3144. let allocator: ID3D12CommandAllocator = self
  3145. .device
  3146. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3147. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3148. 0,
  3149. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3150. &allocator,
  3151. None,
  3152. )?;
  3153. let prelude = OnceLock::new();
  3154. if !lazy_prelude() {
  3155. let _ = prelude.set(self.make_prelude());
  3156. }
  3157. Ok(HostList {
  3158. allocator,
  3159. list,
  3160. deferred: Mutex::default(),
  3161. scratch: Mutex::default(),
  3162. states: Mutex::default(),
  3163. twins: Mutex::default(),
  3164. prelude,
  3165. pipelines: Mutex::default(),
  3166. budget: OnceLock::new(),
  3167. card_budget: OnceLock::new(),
  3168. indirect_args: Mutex::default(),
  3169. batch_args: Mutex::default(),
  3170. _alive: Counted::new(),
  3171. #[cfg(feature = "diagnostics")]
  3172. notes: Mutex::default(),
  3173. #[cfg(feature = "diagnostics")]
  3174. stamps: OnceLock::new(),
  3175. })
  3176. }
  3177. }
  3178. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3179. fn card_clock(&self) -> Option<&'static CardClock> {
  3180. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3181. static WATCH: std::sync::Once = std::sync::Once::new();
  3182. let clock = CLOCK
  3183. .get_or_init(|| {
  3184. // SAFETY: a plain fence on our device.
  3185. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3186. Some(CardClock {
  3187. fence,
  3188. state: Mutex::new((0, None)),
  3189. sent: std::sync::Condvar::new(),
  3190. })
  3191. })
  3192. .as_ref()?;
  3193. WATCH.call_once(|| {
  3194. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3195. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3196. }
  3197. });
  3198. Some(clock)
  3199. }
  3200. /// Lists of ours just went to the queue: the clock's signal goes
  3201. /// behind them, and an idle stretch of the card, if one was under way,
  3202. /// ends here ([`CARD_CLOCK_US`]).
  3203. fn card_sent(&self) {
  3204. let Some(clock) = self.card_clock() else {
  3205. return;
  3206. };
  3207. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3208. state.0 += 1;
  3209. // SAFETY: our queue and the clock's fence.
  3210. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3211. if let Some((since, worked_then)) = state.1.take() {
  3212. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3213. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3214. }
  3215. drop(state);
  3216. clock.sent.notify_one();
  3217. }
  3218. /// Whether the host has what copies in the card's memory need (three
  3219. /// lists and the compare); made at the first ask. A copy goes to the
  3220. /// card's memory only if it has.
  3221. pub(crate) fn card_ready(&self) -> bool {
  3222. static READY: OnceLock<bool> = OnceLock::new();
  3223. *READY.get_or_init(|| match self.make_card_work() {
  3224. Ok(work) => {
  3225. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3226. true
  3227. }
  3228. Err(e) => {
  3229. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3230. false
  3231. }
  3232. })
  3233. }
  3234. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3235. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3236. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3237. let mut code: Option<ID3DBlob> = None;
  3238. // SAFETY: the source and names live through the call; the out
  3239. // pointer is ours.
  3240. unsafe {
  3241. D3DCompile(
  3242. CARD_COMPARE.as_ptr().cast(),
  3243. CARD_COMPARE.len(),
  3244. windows::core::s!("card compare"),
  3245. None,
  3246. None,
  3247. windows::core::s!("main"),
  3248. windows::core::s!("cs_5_1"),
  3249. 0,
  3250. 0,
  3251. &mut code,
  3252. None,
  3253. )?;
  3254. }
  3255. let code = code.ok_or_else(windows::core::Error::empty)?;
  3256. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3257. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3258. // in one submission.
  3259. const RESULTS: u64 = 1 << 20;
  3260. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3261. name(&differs, || "card compare results".into());
  3262. // SAFETY: the blob's own bytes; the root signature is inside the
  3263. // shader.
  3264. unsafe {
  3265. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3266. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3267. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3268. pRootSignature: std::mem::transmute_copy(&root),
  3269. CS: D3D12_SHADER_BYTECODE {
  3270. pShaderBytecode: bytes.as_ptr().cast(),
  3271. BytecodeLength: bytes.len(),
  3272. },
  3273. ..Default::default()
  3274. })?;
  3275. #[cfg(feature = "diagnostics")]
  3276. name(&pso, || crate::replay::play::COMPARE.into());
  3277. Ok(CardWork {
  3278. sync: vec![list()?],
  3279. check: vec![list()?],
  3280. fetch: list()?,
  3281. root,
  3282. pso,
  3283. differs: (differs, data as usize, RESULTS),
  3284. fetched: None,
  3285. taken: 0,
  3286. out: 0,
  3287. })
  3288. }
  3289. }
  3290. /// Before a submission's lists run, for copies in the card's memory
  3291. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3292. /// the last submission goes to their card side (a list of ours, run
  3293. /// now; the submission's lists follow it on the queue), and the ranges
  3294. /// this submission's shaders may write get a compare to run after its
  3295. /// lists. `None` if there is nothing to do.
  3296. ///
  3297. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3298. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3299. /// `relay`).
  3300. /// `picked`: ranges that may be written too, and ranges to look at
  3301. /// (`crate::picked`).
  3302. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3303. use std::sync::Arc;
  3304. if !crate::shadow::cards() {
  3305. return None;
  3306. }
  3307. // The ranges this submission's shaders may write, per copy.
  3308. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3309. for list in runs {
  3310. for step in &list.deferred().copies {
  3311. if let Step::GpuWrite(shadow, address, len) = step
  3312. && shadow.carded()
  3313. {
  3314. let range = (*address, *address + *len);
  3315. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3316. Some((_, ranges)) => {
  3317. if !ranges.contains(&range) {
  3318. ranges.push(range);
  3319. }
  3320. }
  3321. None => declared.push((shadow.clone(), vec![range])),
  3322. }
  3323. }
  3324. }
  3325. }
  3326. let declared = crate::picked::with(declared, &picked.written);
  3327. // (Of a copy with a declared range here, that says it.)
  3328. let looked: Vec<&crate::picked::Range> =
  3329. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3330. // With the relay: the order of the queue is held from here until
  3331. // what is taken is on the queue, and the taking is numbered.
  3332. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3333. let sent_as = match order.as_mut() {
  3334. Some(order) => {
  3335. **order += 1;
  3336. **order
  3337. }
  3338. None => 0,
  3339. };
  3340. let mut dirty = crate::shadow::card_dirty(sent_as);
  3341. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3342. return None;
  3343. }
  3344. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3345. let work = work.as_mut()?;
  3346. // A copy whose shader writes are declared for the first time gets
  3347. // its bytes from before, whole.
  3348. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3349. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3350. if shadow.card_make_before(|size| {
  3351. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3352. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3353. Some(before)
  3354. }) {
  3355. whole.push(shadow.clone());
  3356. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3357. dirty.push((shadow.clone(), Vec::new()));
  3358. }
  3359. }
  3360. }
  3361. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3362. let mut looks = None;
  3363. if !dirty.is_empty() {
  3364. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3365. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3366. };
  3367. let (allocator, list) = &sync;
  3368. // SAFETY: the list's last run finished (it ran ahead of a
  3369. // submission that was waited for, and came back after that);
  3370. // live buffers, and the ranges lie in them.
  3371. let recorded = unsafe {
  3372. (|| -> windows::core::Result<()> {
  3373. allocator.Reset()?;
  3374. list.Reset(allocator, None)?;
  3375. if upcheck::on() {
  3376. looks = upcheck::record(self, list, &dirty);
  3377. }
  3378. // Every copy first, then one barrier call, then every
  3379. // pass: a wait between each copy and its pass had the
  3380. // card do them one after the other.
  3381. let mut sent = Vec::new();
  3382. for (shadow, ranges) in &dirty {
  3383. let Some((staging, before, _)) = shadow.card_sides() else {
  3384. continue;
  3385. };
  3386. for &(a, b) in ranges {
  3387. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3388. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3389. }
  3390. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3391. if before.is_some() && !ranges.is_empty() {
  3392. sent.push(transition(
  3393. &shadow.buffer,
  3394. D3D12_RESOURCE_STATE_COPY_DEST,
  3395. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3396. ));
  3397. }
  3398. }
  3399. if !sent.is_empty() {
  3400. list.ResourceBarrier(&sent);
  3401. }
  3402. list.SetComputeRootSignature(&work.root);
  3403. list.SetPipelineState(&work.pso);
  3404. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3405. for (shadow, ranges) in &dirty {
  3406. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3407. continue;
  3408. };
  3409. // No twin (it cost the card the copy's size again,
  3410. // 399 MB in run 75): `before` holds a 128-bit hash
  3411. // of each 64 KiB piece. The pieces just sent up are
  3412. // hashed again, all of them the first time; the
  3413. // compare after the lists hashes the declared
  3414. // pieces and flags those whose hash is another.
  3415. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3416. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3417. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3418. vec![shadow.card_run(0, usize::MAX)]
  3419. } else {
  3420. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3421. };
  3422. // The same pieces in fewer passes (`rehash_runs`).
  3423. let runs = if rehash_runs() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3424. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3425. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3426. for run in runs {
  3427. card_pass(list, &run, size as u32, 0, 0);
  3428. }
  3429. }
  3430. list.Close()?;
  3431. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3432. Ok(())
  3433. })()
  3434. };
  3435. if let Err(e) = recorded {
  3436. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3437. }
  3438. used.push((false, sync));
  3439. }
  3440. drop(order);
  3441. let mut plan = CardPlan {
  3442. ranges: Vec::new(),
  3443. check: None,
  3444. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3445. lists: used,
  3446. sent_as,
  3447. looks,
  3448. };
  3449. // Each byte once, as the copy-back joins the declared ranges. The
  3450. // results go behind those of plans still in the air.
  3451. let mut at = work.taken;
  3452. for (shadow, ranges) in &declared {
  3453. let mut sorted = ranges.clone();
  3454. sorted.sort_unstable();
  3455. let mut spans: Vec<(usize, usize)> = Vec::new();
  3456. for (from, to) in sorted {
  3457. match spans.last_mut() {
  3458. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3459. _ => spans.push((from, to)),
  3460. }
  3461. }
  3462. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3463. for (from, to) in spans {
  3464. let Some(span) = shadow.card_span(from, to) else {
  3465. continue;
  3466. };
  3467. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3468. plan.ranges.push(CardRange {
  3469. shadow: shadow.clone(),
  3470. declared: (from, to),
  3471. span,
  3472. at,
  3473. compared,
  3474. picked: false,
  3475. });
  3476. if compared {
  3477. at += span.pieces;
  3478. }
  3479. }
  3480. }
  3481. for (shadow, from, len) in looked {
  3482. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3483. if let Some(span) = shadow.card_span(*from, from + len)
  3484. && twin
  3485. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3486. {
  3487. plan.ranges.push(CardRange {
  3488. shadow: shadow.clone(),
  3489. declared: (*from, from + len),
  3490. span,
  3491. at,
  3492. compared: true,
  3493. picked: true,
  3494. });
  3495. at += span.pieces;
  3496. }
  3497. }
  3498. work.taken = at;
  3499. if plan.ranges.iter().any(|r| r.compared) {
  3500. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3501. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3502. };
  3503. let (allocator, list) = &check;
  3504. // SAFETY: the list's last run finished (its submission was
  3505. // waited for, and it came back after that); live buffers; the
  3506. // compare's own root signature.
  3507. let recorded = unsafe {
  3508. (|| -> windows::core::Result<ID3D12CommandList> {
  3509. allocator.Reset()?;
  3510. list.Reset(allocator, None)?;
  3511. // What the submission's shaders wrote, first.
  3512. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3513. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3514. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3515. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3516. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3517. pResource: std::mem::ManuallyDrop::new(None),
  3518. }),
  3519. },
  3520. }]);
  3521. list.SetComputeRootSignature(&work.root);
  3522. list.SetPipelineState(&work.pso);
  3523. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3524. for r in plan.ranges.iter().filter(|r| r.compared) {
  3525. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3526. continue;
  3527. };
  3528. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3529. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3530. // (What is only looked at keeps its hashes: what
  3531. // changed there is the next declared range's to land.)
  3532. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  3533. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3534. }
  3535. list.Close()?;
  3536. list.cast()
  3537. })()
  3538. };
  3539. match recorded {
  3540. Ok(list) => plan.check = Some(list),
  3541. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3542. }
  3543. plan.lists.push((true, check));
  3544. }
  3545. work.out += 1;
  3546. Some(plan)
  3547. }
  3548. /// With [`relay`]: whether the compare's result area is half taken by
  3549. /// plans in the air. It starts from the beginning only when no plan is
  3550. /// out, so the caller lets the flights land first.
  3551. fn card_results_low(&self) -> bool {
  3552. CARD_WORK
  3553. .lock()
  3554. .unwrap_or_else(|e| e.into_inner())
  3555. .as_ref()
  3556. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3557. }
  3558. /// The plan's submission has run and its results were read
  3559. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3560. /// when nothing of ours is on the card, so the compare's results start
  3561. /// from the beginning again.
  3562. fn card_done(&self, plan: CardPlan) {
  3563. if let Some(looks) = plan.looks {
  3564. looks.read();
  3565. }
  3566. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3567. let Some(work) = work.as_mut() else {
  3568. return;
  3569. };
  3570. for (check, list) in plan.lists {
  3571. if check { work.check.push(list) } else { work.sync.push(list) }
  3572. }
  3573. work.out = work.out.saturating_sub(1);
  3574. // With the relay other plans may be on the card, their results
  3575. // not read yet: the area starts again only when none is out.
  3576. if !relay() || work.out == 0 {
  3577. work.taken = 0;
  3578. }
  3579. }
  3580. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3581. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3582. // SAFETY: plain object creation.
  3583. let copying = relay_copy().then(|| unsafe {
  3584. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3585. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3586. let list: ID3D12GraphicsCommandList =
  3587. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3588. list.Close()?;
  3589. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3590. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3591. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3592. ..Default::default()
  3593. })?;
  3594. Ok(((allocator, list), queue))
  3595. })()
  3596. });
  3597. let (list, queue) = match copying {
  3598. Some(Ok((list, queue))) => (list, Some(queue)),
  3599. Some(Err(e)) => {
  3600. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3601. (self.make_prelude()?, None)
  3602. }
  3603. None => (self.make_prelude()?, None),
  3604. };
  3605. // SAFETY: plain objects of our own.
  3606. unsafe {
  3607. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3608. let event = CreateEventW(None, false, false, None).ok()?;
  3609. Some(RelayFetch {
  3610. list,
  3611. queue,
  3612. fence,
  3613. event,
  3614. sent: 0,
  3615. buffer: None,
  3616. suspects: torn::Suspects::default(),
  3617. had: crate::land::Had::default(),
  3618. })
  3619. }
  3620. }
  3621. /// [`relay`], on the thread that lands flights: for the plans of the
  3622. /// flights being landed (the card has run them), the pieces their
  3623. /// compares flagged are fetched, once each, with a list and a wait of
  3624. /// this thread's own, and what shaders wrote in them goes into title
  3625. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3626. /// no submission lock; a piece flagged under one range of a plan is
  3627. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3628. /// whatever was sent meanwhile, so it may bring a later flight's
  3629. /// bytes, which that flight's landing then finds merged already; and
  3630. /// nothing is sent back up. `plans` come with the value signalled behind
  3631. /// their flight. `meanwhile` is called while the fetch is on its way, if
  3632. /// there is one.
  3633. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  3634. use crate::land;
  3635. let gathering = std::time::Instant::now();
  3636. let differs = {
  3637. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3638. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3639. };
  3640. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3641. let mut total = 0u64;
  3642. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  3643. fetch.had.landing(first);
  3644. }
  3645. // SAFETY: the mapping of the results. The compares of these plans
  3646. // have run, and their dwords are given to no other plan before these
  3647. // are done with (`card_done`).
  3648. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  3649. if let Some(differs) = differs {
  3650. // Pieces caught while a later flight was at them (`torn`).
  3651. let suspects = fetch.as_ref().map(|f| &f.suspects);
  3652. let mut seen = std::collections::HashSet::new();
  3653. for &(plan, behind) in plans {
  3654. plan.picked_found(differs);
  3655. let flags: Vec<(usize, u32, bool)> = plan
  3656. .ranges
  3657. .iter()
  3658. .filter(|r| !r.picked)
  3659. .flat_map(|r| {
  3660. (0..r.span.pieces).map(move |p| {
  3661. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  3662. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  3663. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  3664. })
  3665. })
  3666. .collect();
  3667. let fetched = flagged_pieces(&flags);
  3668. for r in plan.ranges.iter().filter(|r| !r.picked) {
  3669. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3670. if upcheck::on() {
  3671. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  3672. }
  3673. for p in 0..r.span.pieces {
  3674. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  3675. continue;
  3676. }
  3677. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3678. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  3679. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  3680. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  3681. land::count(land::stat::HAD, 1);
  3682. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  3683. if land::skip_on() {
  3684. continue;
  3685. }
  3686. }
  3687. if upcheck::on() {
  3688. upcheck::fetched(r.shadow.id(), lo);
  3689. }
  3690. seen.insert((copy, lo, hi));
  3691. pieces.push((r.shadow.clone(), lo, hi, total));
  3692. total += (hi - lo) as u64;
  3693. }
  3694. }
  3695. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3696. }
  3697. }
  3698. }
  3699. if land::on() {
  3700. // In the order they are landed, each byte of a copy once.
  3701. let keys: Vec<land::Piece> =
  3702. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  3703. total = 0;
  3704. pieces = land::ordered(&keys)
  3705. .into_iter()
  3706. .map(|(i, title, len)| {
  3707. let shadow = &pieces[i].0;
  3708. let lo = title - shadow.span().0 as usize;
  3709. let at = total;
  3710. total += len as u64;
  3711. (shadow.clone(), lo, lo + len, at)
  3712. })
  3713. .collect();
  3714. }
  3715. land::spent(land::stat::GATHER, gathering);
  3716. if fetch.is_none() {
  3717. *fetch = self.make_relay_fetch();
  3718. }
  3719. // On the copy queue a later flight may be at a piece while it is
  3720. // fetched: the pieces come down whole, to be hashed.
  3721. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  3722. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  3723. if let Some(check) = &check {
  3724. total = check.total;
  3725. }
  3726. // The sends these flights ran behind, all a fetch on the copy queue
  3727. // is known to have run behind.
  3728. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  3729. if pieces.is_empty() {
  3730. // Nothing to fetch: every send so far is older than the next
  3731. // fetch, if that goes to the queue the sends went to.
  3732. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  3733. true => behind,
  3734. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  3735. };
  3736. crate::shadow::relay_fetched(after);
  3737. return;
  3738. }
  3739. let Some(f) = fetch.as_mut() else {
  3740. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  3741. };
  3742. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  3743. let size = total.next_multiple_of(16 << 20);
  3744. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3745. }
  3746. let Some((buffer, data, _)) = f.buffer.clone() else {
  3747. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  3748. };
  3749. f.sent += 1;
  3750. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  3751. let copy_queue = f.queue.clone();
  3752. let waiting = std::time::Instant::now();
  3753. // The flights the fetch runs behind: those in the line by now have
  3754. // been given to the queue. On the copy queue, those landed here.
  3755. let ahead = match copy_queue {
  3756. Some(_) => 0,
  3757. None => line().target,
  3758. };
  3759. // SAFETY: the list's last run was waited for by this thread; live
  3760. // buffers (the copies are held by the plans); the fence and the
  3761. // event are this thread's.
  3762. let ran = unsafe {
  3763. (|| -> windows::core::Result<u64> {
  3764. allocator.Reset()?;
  3765. list.Reset(&allocator, None)?;
  3766. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  3767. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  3768. }
  3769. list.Close()?;
  3770. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  3771. if let Some(queue) = &copy_queue {
  3772. queue.ExecuteCommandLists(&lists);
  3773. queue.Signal(&fence, sent)?;
  3774. meanwhile();
  3775. fence.SetEventOnCompletion(sent, event)?;
  3776. WaitForSingleObject(event, INFINITE);
  3777. return Ok(behind);
  3778. }
  3779. // In the order of the queue: the sends of title bytes so
  3780. // far are ahead of this fetch, every later one behind it.
  3781. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  3782. self.queue.ExecuteCommandLists(&lists);
  3783. let after = *order;
  3784. drop(order);
  3785. self.card_sent();
  3786. self.queue.Signal(&fence, sent)?;
  3787. meanwhile();
  3788. fence.SetEventOnCompletion(sent, event)?;
  3789. WaitForSingleObject(event, INFINITE);
  3790. Ok(after)
  3791. })()
  3792. };
  3793. let after = match ran {
  3794. Ok(after) => after,
  3795. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  3796. };
  3797. let us = waiting.elapsed().as_micros() as u64;
  3798. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  3799. {
  3800. use crate::shadow::CARD_STATS;
  3801. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  3802. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  3803. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  3804. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  3805. }
  3806. let merging = std::time::Instant::now();
  3807. let mut written = 0;
  3808. if land::on() {
  3809. let titles: Vec<(usize, usize)> =
  3810. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  3811. let jobs = land::jobs(&titles);
  3812. let put = std::sync::atomic::AtomicU64::new(0);
  3813. land::each(jobs.len(), &|j| {
  3814. let working = std::time::Instant::now();
  3815. if let Some(check) = &check {
  3816. for i in jobs[j].clone() {
  3817. // SAFETY: as below.
  3818. unsafe { check.look(i, data) };
  3819. }
  3820. }
  3821. let mut notes = land::Notes::default();
  3822. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  3823. let addressed: Vec<(usize, usize, usize)> =
  3824. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  3825. // SAFETY: the mapping of the fetched bytes, `total` of
  3826. // them; the copy into it has run, and the next waits
  3827. // for this call.
  3828. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  3829. }
  3830. notes.flush();
  3831. land::spent(land::stat::CARD_ALL, working);
  3832. });
  3833. land::count(land::stat::JOBS, jobs.len() as u64);
  3834. written = put.into_inner();
  3835. } else {
  3836. let mut title = Vec::new();
  3837. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  3838. if let Some(check) = &check {
  3839. // SAFETY: as below.
  3840. unsafe { check.look(i, data) };
  3841. }
  3842. // SAFETY: the mapping of the fetched bytes, `total` of them;
  3843. // the copy into it has run.
  3844. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  3845. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  3846. shadow.walls_merged(gpu.len(), merged);
  3847. written += merged as u64;
  3848. }
  3849. }
  3850. land::spent(land::stat::CARD, merging);
  3851. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  3852. if let Some(f) = fetch.as_mut() {
  3853. if let Some(check) = &check {
  3854. check.done(&mut f.suspects);
  3855. }
  3856. f.had.fetched(
  3857. ahead,
  3858. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  3859. );
  3860. }
  3861. // Sends up to `after` are of no use to any later merge.
  3862. crate::shadow::relay_fetched(after);
  3863. }
  3864. /// [`relay`], on the thread that lands flights: `items` are the first
  3865. /// things of the line, flights the card has run and what follows them.
  3866. /// What their shaders wrote goes into title memory (copies in the
  3867. /// card's memory first, then the others, each byte once whichever
  3868. /// flights declared it); then every flight's ranges are done with;
  3869. /// then, in the line's order, each flight's read-backs, its
  3870. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  3871. /// is complete before the title is told anything.
  3872. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  3873. let landing = std::time::Instant::now();
  3874. {
  3875. let flights: Vec<&Flight> = items
  3876. .iter()
  3877. .filter_map(|l| match l {
  3878. Late::Run(flight) => Some(flight),
  3879. _ => None,
  3880. })
  3881. .collect();
  3882. if !flights.is_empty() {
  3883. // SAFETY: a plain query.
  3884. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  3885. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  3886. fail(format_args!(
  3887. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  3888. flights.len(),
  3889. runs.len(),
  3890. self.removal_data(&runs),
  3891. last_notes(&runs)
  3892. ));
  3893. }
  3894. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  3895. // (Each byte once: the ranges are joined.)
  3896. let mut back: Vec<Declared> = Vec::new();
  3897. for flight in &flights {
  3898. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  3899. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  3900. Some((_, all)) => all.extend_from_slice(ranges),
  3901. None => back.push((shadow.clone(), ranges.clone())),
  3902. }
  3903. }
  3904. }
  3905. let mut hand_back = relay_hand_back(&back);
  3906. self.relay_card_back(&plans, fetch, &mut || {
  3907. if crate::land::on() {
  3908. hand_back.look(crate::land::stat::SCAN_BESIDE);
  3909. }
  3910. });
  3911. hand_back.merge();
  3912. let finishing = std::time::Instant::now();
  3913. // Only now, and flight by flight: a range another flight
  3914. // in the air declared too stays closed to refreshes.
  3915. for flight in &flights {
  3916. for (shadow, ranges) in &flight.back {
  3917. shadow.copy_back_done(ranges);
  3918. }
  3919. }
  3920. crate::land::spent(crate::land::stat::DONE, finishing);
  3921. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  3922. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  3923. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  3924. }
  3925. }
  3926. // In the order given: what tells the title the card is done.
  3927. let mut last = 0;
  3928. let mut landed = Vec::new();
  3929. let mut telling = std::time::Instant::now();
  3930. for item in items {
  3931. telling = match item {
  3932. Late::Run(flight) => {
  3933. last = flight.number;
  3934. for &i in &flight.order {
  3935. read_backs(flight.lists[i].host());
  3936. }
  3937. if let Some(card) = flight.card {
  3938. self.card_done(card);
  3939. }
  3940. if let Some(own) = flight.own {
  3941. own.landed();
  3942. }
  3943. landed.push((flight.lists, flight.order));
  3944. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  3945. }
  3946. Late::Write(at, what, bytes) => {
  3947. what.write(at as *mut u8, bytes);
  3948. crate::land::spent(crate::land::stat::TOLD, telling)
  3949. }
  3950. Late::Signal(fence, value) => {
  3951. crate::fence::set(fence as crate::object::This, value);
  3952. crate::land::spent(crate::land::stat::TOLD, telling)
  3953. }
  3954. };
  3955. }
  3956. if last > 0 {
  3957. FINISHED.store(last, Ordering::Release);
  3958. bury(last);
  3959. }
  3960. self.log_messages();
  3961. crate::land::spent(crate::land::stat::REST, telling);
  3962. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  3963. {
  3964. let mut line = line();
  3965. let Line {
  3966. line: items,
  3967. written,
  3968. lists,
  3969. settling,
  3970. poke,
  3971. landed: kept,
  3972. in_hand,
  3973. landing,
  3974. ..
  3975. } = &mut *line;
  3976. kept.extend(landed);
  3977. in_hand.clear();
  3978. landing.clear();
  3979. // What is still in the air, from the flights that are.
  3980. written.clear();
  3981. *lists = 0;
  3982. let mut ranges = Vec::new();
  3983. for item in items.iter() {
  3984. if let Late::Run(flight) = item {
  3985. *lists += flight.order.len().max(1);
  3986. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  3987. }
  3988. }
  3989. join_ranges(written, ranges);
  3990. *settling = false;
  3991. // The landed lists are reset, and what queues hold looked at,
  3992. // by the helper thread (they take locks a waiter may hold).
  3993. *poke = true;
  3994. }
  3995. LINE_MOVED.notify_all();
  3996. LINE_LANDED.notify_all();
  3997. }
  3998. /// After a submission ran, for copies in the card's memory: the pieces
  3999. /// of the declared ranges that the compare found differing (all of a
  4000. /// range it did not compare) are fetched, with one more wait for the
  4001. /// card, and what shaders wrote in them goes into title memory.
  4002. /// `submitted` is the last value signalled on the fence. `seen` holds
  4003. /// the pieces fetched already since the card was last waited for
  4004. /// (several submissions settled together name the same ones).
  4005. fn card_back(
  4006. &self,
  4007. plan: &CardPlan,
  4008. submitted: &mut u64,
  4009. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4010. ) {
  4011. if plan.ranges.is_empty() {
  4012. return;
  4013. }
  4014. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4015. let Some(work) = work.as_mut() else {
  4016. return;
  4017. };
  4018. // SAFETY: the mapping of the results, which the compare (it has
  4019. // run) wrote.
  4020. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4021. // The pieces to fetch: the range, the offsets in its copy, and
  4022. // where the bytes come down.
  4023. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4024. let mut total = 0u64;
  4025. plan.picked_found(differs);
  4026. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4027. for p in 0..r.span.pieces {
  4028. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4029. continue;
  4030. }
  4031. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4032. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4033. pieces.push((i, lo, hi, total));
  4034. total += (hi - lo) as u64;
  4035. }
  4036. }
  4037. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4038. }
  4039. let mut written = vec![0usize; plan.ranges.len()];
  4040. if !pieces.is_empty() {
  4041. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4042. let size = total.next_multiple_of(16 << 20);
  4043. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4044. }
  4045. let Some((fetched, data, _)) = &work.fetched else {
  4046. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4047. };
  4048. let waiting = std::time::Instant::now();
  4049. let (allocator, list) = &work.fetch;
  4050. // SAFETY: the list's last run was waited for; live buffers; the
  4051. // fence and event are ours, under the submission lock.
  4052. let ran = unsafe {
  4053. (|| -> windows::core::Result<()> {
  4054. allocator.Reset()?;
  4055. list.Reset(allocator, None)?;
  4056. for &(i, lo, hi, at) in &pieces {
  4057. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4058. }
  4059. list.Close()?;
  4060. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4061. self.card_sent();
  4062. *submitted += 1;
  4063. self.queue.Signal(&self.fence, *submitted)?;
  4064. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4065. let was_working = working(false);
  4066. WaitForSingleObject(self.event, INFINITE);
  4067. stood(waiting);
  4068. working(was_working);
  4069. Ok(())
  4070. })()
  4071. };
  4072. if let Err(e) = ran {
  4073. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4074. }
  4075. {
  4076. use crate::shadow::CARD_STATS;
  4077. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4078. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4079. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4080. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4081. }
  4082. if wide_merge() && pieces.len() >= 8 {
  4083. // The pieces are apart from one another (each its own bytes
  4084. // of its copy and of title memory): several at a time.
  4085. let fetched = *data;
  4086. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4087. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4088. let each = pieces.len().div_ceil(8);
  4089. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4090. .chunks(each)
  4091. .map(|chunk| {
  4092. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4093. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4094. let counts = counts.clone();
  4095. Box::new(move || {
  4096. let mut title = Vec::new();
  4097. for (shadow, i, lo, hi, at) in chunk {
  4098. // SAFETY: the mapping of the fetched bytes;
  4099. // the copy into it has run, and the caller
  4100. // waits for this job.
  4101. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4102. let merged = shadow.card_merge(lo, gpu, &mut title);
  4103. shadow.walls_merged(gpu.len(), merged);
  4104. counts[i].fetch_add(merged, Ordering::Relaxed);
  4105. }
  4106. }) as Box<dyn FnOnce() + Send>
  4107. })
  4108. .collect();
  4109. crate::shadow::wide_run(jobs);
  4110. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4111. *written += count.load(Ordering::Relaxed);
  4112. }
  4113. } else {
  4114. let mut title = Vec::new();
  4115. for &(i, lo, hi, at) in &pieces {
  4116. // SAFETY: the mapping of the fetched bytes, `total` of
  4117. // them; the copy into it has run.
  4118. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4119. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4120. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4121. written[i] += merged;
  4122. }
  4123. }
  4124. }
  4125. for (r, written) in plan.ranges.iter().zip(written) {
  4126. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4127. let (from, to) = r.declared;
  4128. #[cfg(feature = "diagnostics")]
  4129. crate::copystat::compared(from, to - from, written);
  4130. let _ = (from, to);
  4131. }
  4132. }
  4133. /// Runs closed lists and waits for them, and with [`late`] for
  4134. /// everything sent to the card before them, which is settled first.
  4135. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4136. let _ = self.submit(runs, false);
  4137. }
  4138. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4139. /// from the title's, go to the card in `order` and are not waited for.
  4140. /// They join the line of flights and are settled, with the others in
  4141. /// the air, at the next point where what they do can be observed
  4142. /// ([`late`] lists those points); their host lists are reset and kept
  4143. /// for reuse then, as a queue does for the lists it ran.
  4144. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4145. if order.is_empty() {
  4146. crate::list::recycle(lists, &order);
  4147. return;
  4148. }
  4149. late_threads();
  4150. let sent = {
  4151. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4152. self.submit(&runs, true)
  4153. };
  4154. let Some((mut submitted, sent)) = sent else {
  4155. // (Not reached: a submission sent ahead always comes back.)
  4156. crate::list::recycle(lists, &order);
  4157. return;
  4158. };
  4159. let told = !sent.writes.is_empty();
  4160. let most = {
  4161. let mut line = line();
  4162. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4163. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4164. *flying += order.len();
  4165. *target = *submitted;
  4166. items.push(Late::Run(Flight {
  4167. number: sent.number,
  4168. fence: *target,
  4169. lists,
  4170. order,
  4171. card: sent.card,
  4172. back: sent.back,
  4173. own: sent.own,
  4174. }));
  4175. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4176. *flying >= late_most()
  4177. };
  4178. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4179. RELAY_MOVED.notify_one();
  4180. if told && !late_writes() {
  4181. self.settle(&mut submitted, WHY_WRITES);
  4182. } else if most && relay_exact() {
  4183. // Until there are fewer, not until there are none.
  4184. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4185. } else if most {
  4186. self.settle(&mut submitted, WHY_MOST);
  4187. } else {
  4188. LINE_MOVED.notify_one();
  4189. }
  4190. drop(submitted);
  4191. land();
  4192. }
  4193. /// Sends `list`, a closed list of ours (the present's copy), as a
  4194. /// flight ([`late_free_present`]): not waited for, settled with the
  4195. /// others. The caller keeps the list and does not reset it before the
  4196. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4197. /// it ran and was waited for after all.
  4198. fn execute_own(&self, list: &HostList) -> u64 {
  4199. late_threads();
  4200. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4201. return 0;
  4202. };
  4203. let number = sent.number;
  4204. {
  4205. let mut line = line();
  4206. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4207. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4208. *flying += 1;
  4209. *target = *submitted;
  4210. items.push(Late::Run(Flight {
  4211. number,
  4212. fence: *target,
  4213. lists: Vec::new(),
  4214. order: Vec::new(),
  4215. card: sent.card,
  4216. back: sent.back,
  4217. own: sent.own,
  4218. }));
  4219. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4220. }
  4221. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4222. LINE_MOVED.notify_one();
  4223. RELAY_MOVED.notify_one();
  4224. drop(submitted);
  4225. number
  4226. }
  4227. /// Waits for the card to run every flight in the air ([`late`]) and
  4228. /// does what they left to do, as [`Host::execute`] does for one
  4229. /// submission after its wait: the pieces their shaders wrote in copies
  4230. /// in the card's memory are fetched and merged (each once), the ranges
  4231. /// they declared in the other copies are compared and copied back
  4232. /// (each byte once, whichever flights declared it), and then, in the
  4233. /// order they were given: their bottom-of-pipe writes and the fence
  4234. /// signals behind them. `submitted` is the submission lock's value;
  4235. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4236. ///
  4237. /// Everything in the air is settled, never the first flights alone:
  4238. /// the merge writes the copies' CPU side, which a flight still on the
  4239. /// card may be writing too.
  4240. fn settle(&self, submitted: &mut u64, why: usize) {
  4241. if !late() {
  4242. return;
  4243. }
  4244. if relay() {
  4245. // Nothing is settled here: the thread that lands flights does
  4246. // it, in order, and this waits until nothing is in the air and
  4247. // nothing is being landed. Every point that settled before
  4248. // comes here, so each still sees title memory, fences and
  4249. // bottom-of-pipe values as after a settle.
  4250. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4251. return;
  4252. }
  4253. let was_working = working(true);
  4254. let mut counted = false;
  4255. loop {
  4256. let items = {
  4257. let mut line = line();
  4258. if line.line.is_empty() {
  4259. line.settling = false;
  4260. break;
  4261. }
  4262. line.settling = true;
  4263. line.written.clear();
  4264. line.lists = 0;
  4265. std::mem::take(&mut line.line)
  4266. };
  4267. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4268. if !counted {
  4269. counted = true;
  4270. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4271. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4272. }
  4273. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4274. if flights > 0 {
  4275. submitting(2, flights);
  4276. let waiting = std::time::Instant::now();
  4277. // SAFETY: the fence and event are ours, under the
  4278. // submission lock; `submitted` is the last value signalled.
  4279. unsafe {
  4280. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4281. Ok(()) => {
  4282. working(false);
  4283. WaitForSingleObject(self.event, INFINITE);
  4284. stood(waiting);
  4285. working(true);
  4286. }
  4287. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4288. }
  4289. }
  4290. let gpu = waiting.elapsed();
  4291. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4292. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4293. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4294. #[cfg(feature = "diagnostics")]
  4295. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4296. format!("{flights} submissions sent ahead, settled together")
  4297. });
  4298. // SAFETY: a plain query.
  4299. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4300. let runs: Vec<&HostList> = items
  4301. .iter()
  4302. .filter_map(|i| match i {
  4303. Late::Run(f) => Some(f),
  4304. _ => None,
  4305. })
  4306. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4307. .collect();
  4308. fail(format_args!(
  4309. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4310. runs.len(),
  4311. self.removal_data(&runs),
  4312. last_notes(&runs)
  4313. ));
  4314. }
  4315. submitting(3, flights);
  4316. let copying = std::time::Instant::now();
  4317. let mut seen = std::collections::HashSet::new();
  4318. let mut back: Vec<Declared> = Vec::new();
  4319. for item in &items {
  4320. let Late::Run(flight) = item else {
  4321. continue;
  4322. };
  4323. if let Some(card) = &flight.card {
  4324. self.card_back(card, submitted, &mut seen);
  4325. }
  4326. for (shadow, ranges) in &flight.back {
  4327. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4328. Some((_, all)) => {
  4329. for range in ranges {
  4330. if !all.contains(range) {
  4331. all.push(*range);
  4332. }
  4333. }
  4334. }
  4335. None => back.push((shadow.clone(), ranges.clone())),
  4336. }
  4337. }
  4338. }
  4339. hand_back(&back);
  4340. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4341. }
  4342. // In the order given: what tells the title the card is done.
  4343. let mut last = 0;
  4344. let mut landed = Vec::new();
  4345. for item in items {
  4346. match item {
  4347. Late::Run(flight) => {
  4348. last = flight.number;
  4349. for &i in &flight.order {
  4350. read_backs(flight.lists[i].host());
  4351. }
  4352. if let Some(card) = flight.card {
  4353. self.card_done(card);
  4354. }
  4355. landed.push((flight.lists, flight.order));
  4356. }
  4357. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4358. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4359. }
  4360. }
  4361. if last > 0 {
  4362. FINISHED.store(last, Ordering::Release);
  4363. bury(last);
  4364. }
  4365. line().landed.extend(landed);
  4366. }
  4367. if counted {
  4368. self.log_messages();
  4369. submitting(0, 0);
  4370. // What was settled may be what a queue stands at, and the
  4371. // caller may not be one that looks (a read-back, a present).
  4372. if why != WHY_CARD_DONE {
  4373. line().poke = true;
  4374. LINE_MOVED.notify_one();
  4375. }
  4376. }
  4377. working(was_working);
  4378. }
  4379. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4380. /// copies, which flights may be writing and the title wrote too
  4381. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4382. /// those of the submission's one asking, which is made again.
  4383. ///
  4384. /// With [`card_steps`] only the flights that declared them: a range of
  4385. /// a copy nobody declared any more is refreshed like any other. What
  4386. /// they landed is title memory written, so everything is asked and
  4387. /// looked at again; what is left after three times waits as before.
  4388. fn settle_stale(
  4389. &self,
  4390. submitted: &mut u64,
  4391. runs: &[&HostList],
  4392. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4393. ranges: &[(usize, usize)],
  4394. ) {
  4395. if relay_exact() && card_steps::stage() > 0 {
  4396. for _ in 0..3 {
  4397. #[cfg(feature = "diagnostics")]
  4398. blame_stale(&stale);
  4399. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4400. crate::watch::ask_once(ranges);
  4401. stale = stale_under_flights(runs);
  4402. if stale.is_empty() {
  4403. return;
  4404. }
  4405. }
  4406. }
  4407. #[cfg(feature = "diagnostics")]
  4408. blame_stale(&stale);
  4409. self.settle(submitted, WHY_STALE);
  4410. crate::watch::ask_once(ranges);
  4411. }
  4412. /// [`Host::execute`], or with `late` the first half of
  4413. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4414. /// to be done once they have run comes back with the submission lock
  4415. /// still held.
  4416. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4417. #[cfg(feature = "diagnostics")]
  4418. let called = std::time::Instant::now();
  4419. #[cfg(feature = "diagnostics")]
  4420. crate::copystat::submission_begins();
  4421. // One submission at a time from preparation to copy-back: snapshots
  4422. // and the ranges shaders write are per host copy, not per submission.
  4423. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4424. let was_working = working(true);
  4425. submitting(1, runs.len());
  4426. // Flights in the air ([`late`]): a submission that is waited for
  4427. // settles them first, one sent ahead only if preparing it reads
  4428. // what they write.
  4429. // Or the reads are done on the card, behind the flights.
  4430. let own = if late { self.card_steps(runs) } else { None };
  4431. if !late {
  4432. self.settle(&mut submitted, WHY_SYNC);
  4433. } else if own.is_none()
  4434. && let Some(why) = late_blocked(runs)
  4435. {
  4436. if relay_exact() && why == WHY_READ {
  4437. // Only until the flights that may write what is read have
  4438. // landed: their copy-back's end, not the card's other work.
  4439. relay_wait(why, |line| {
  4440. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4441. });
  4442. } else {
  4443. self.settle(&mut submitted, why);
  4444. }
  4445. }
  4446. // That list runs first, and is one of the submission's from here on.
  4447. let with: Vec<&HostList>;
  4448. let runs = match &own {
  4449. Some(own) => {
  4450. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4451. &with[..]
  4452. }
  4453. None => runs,
  4454. };
  4455. let behind = late && flying();
  4456. // Before this submission counts as started: what the sweep lets go
  4457. // of is named by no list, and nothing runs now (behind flights the
  4458. // sweep waits for a submission that finds none in the air: there is
  4459. // one at every present).
  4460. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4461. if !behind {
  4462. if upcheck::on() {
  4463. upcheck::at_rest(self);
  4464. }
  4465. sweep();
  4466. SWEPT.store(now_ms(), Ordering::Relaxed);
  4467. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4468. // With the present sent ahead nothing else brings a moment
  4469. // with nothing in the air: one is made for the sweep.
  4470. self.settle(&mut submitted, WHY_SYNC);
  4471. if upcheck::on() {
  4472. upcheck::at_rest(self);
  4473. }
  4474. sweep();
  4475. SWEPT.store(now_ms(), Ordering::Relaxed);
  4476. }
  4477. let behind = late && flying();
  4478. // The slots that waited for a texture's host copy, before the
  4479. // lists that may read them run.
  4480. crate::descriptor::make_waiting();
  4481. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4482. // The ranges shaders write are counted for it (with the relay).
  4483. crate::shadow::preparing(this_submission);
  4484. let started = std::time::Instant::now();
  4485. #[cfg(feature = "diagnostics")]
  4486. let lock = (started - called).as_micros() as u64;
  4487. #[cfg(feature = "diagnostics")]
  4488. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4489. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4490. // Where each run's lists start in `lists`.
  4491. let mut firsts = Vec::with_capacity(runs.len());
  4492. let mut batch = Batch::default();
  4493. #[cfg(feature = "diagnostics")]
  4494. let split = Split::begin();
  4495. // The time a settle of flights takes inside this preparing: the
  4496. // wait for the card and the copy-back have their own places on the
  4497. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4498. let mut settled = std::time::Duration::ZERO;
  4499. // One write-watch asking for everything the submission refreshes
  4500. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4501. if crate::watch::once() {
  4502. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  4503. for list in runs {
  4504. for step in &list.deferred().copies {
  4505. if let Step::Refresh(shadow, address, len) = step
  4506. && shadow.asked_ahead()
  4507. {
  4508. let span = spans
  4509. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4510. .or_insert((*address, *address + *len));
  4511. *span = (span.0.min(*address), span.1.max(*address + *len));
  4512. }
  4513. }
  4514. }
  4515. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4516. #[cfg(feature = "diagnostics")]
  4517. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  4518. crate::watch::ask_once(&ranges);
  4519. #[cfg(feature = "diagnostics")]
  4520. split.part(0);
  4521. // Behind flights: the title wrote memory that a flight's shaders
  4522. // may write too, and this submission refreshes it. The flights
  4523. // are settled, and the asking made again: the copy-back wrote
  4524. // title memory, which other copies of it must see.
  4525. if behind && upcheck::on() {
  4526. upcheck::reads(runs);
  4527. }
  4528. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  4529. if !stale.is_empty() {
  4530. let settling = std::time::Instant::now();
  4531. self.settle_stale(&mut submitted, runs, stale, &ranges);
  4532. settled += settling.elapsed();
  4533. }
  4534. } else if behind && !stale_under_flights(runs).is_empty() {
  4535. let settling = std::time::Instant::now();
  4536. self.settle(&mut submitted, WHY_STALE);
  4537. settled += settling.elapsed();
  4538. }
  4539. #[cfg(feature = "diagnostics")]
  4540. split.part(1);
  4541. for list in runs {
  4542. list.run_deferred(&mut batch, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4543. firsts.push(lists.len());
  4544. if let Some(prelude) = list.prelude() {
  4545. lists.push(Some(prelude));
  4546. }
  4547. lists.push(list.list.cast().ok());
  4548. }
  4549. batch.flush();
  4550. crate::watch::ask_once_end();
  4551. #[cfg(feature = "diagnostics")]
  4552. split.part(2);
  4553. // The snapshots of the ranges shaders may write, if they were left
  4554. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4555. // lists have not gone to the card.
  4556. {
  4557. #[cfg(feature = "diagnostics")]
  4558. let snapshots = std::time::Instant::now();
  4559. crate::shadow::take_snapshots();
  4560. #[cfg(feature = "diagnostics")]
  4561. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4562. }
  4563. #[cfg(feature = "diagnostics")]
  4564. split.part(3);
  4565. // Copies in the card's memory: what changed on their CPU side goes
  4566. // up ahead of the lists, and a compare of what the shaders may
  4567. // write follows them in the same submission.
  4568. let flown = late && relay();
  4569. if flown && self.card_results_low() {
  4570. let settling = std::time::Instant::now();
  4571. self.settle(&mut submitted, WHY_MOST);
  4572. settled += settling.elapsed();
  4573. }
  4574. // What shaders may write through views they pick: last, so that no
  4575. // refresh of this submission leaves it alone.
  4576. let picked = crate::picked::declare(runs);
  4577. for (shadow, at, len) in &picked.written {
  4578. shadow.writing(*at, *len);
  4579. }
  4580. let card = self.card_before(runs, &picked, flown);
  4581. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4582. lists.push(Some(check));
  4583. }
  4584. #[cfg(feature = "diagnostics")]
  4585. split.part(4);
  4586. let prepared = std::time::Instant::now();
  4587. if late {
  4588. *submitted += 1;
  4589. // SAFETY: closed lists; the fence is ours.
  4590. let signalled = unsafe {
  4591. self.queue.ExecuteCommandLists(&lists);
  4592. self.queue.Signal(&self.fence, *submitted)
  4593. };
  4594. self.card_sent();
  4595. if let Err(e) = signalled {
  4596. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4597. }
  4598. #[cfg(feature = "diagnostics")]
  4599. split.part(5);
  4600. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4601. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4602. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4603. submitting(0, 0);
  4604. #[cfg(feature = "diagnostics")]
  4605. crate::copystat::submission_ends(lock);
  4606. let sent = Sent {
  4607. number: this_submission,
  4608. card,
  4609. back,
  4610. own,
  4611. writes,
  4612. };
  4613. working(was_working);
  4614. return Some((submitted, sent));
  4615. }
  4616. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4617. #[cfg(feature = "diagnostics")]
  4618. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4619. firsts
  4620. .iter()
  4621. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4622. .map(|(&a, &b)| &lists[a..b])
  4623. .collect()
  4624. } else {
  4625. vec![&lists[..]]
  4626. };
  4627. #[cfg(not(feature = "diagnostics"))]
  4628. let groups = [&lists[..]];
  4629. submitting(2, runs.len());
  4630. for (i, group) in groups.iter().enumerate() {
  4631. *submitted += 1;
  4632. let started = std::time::Instant::now();
  4633. // SAFETY: closed lists; the fence and event are ours.
  4634. unsafe {
  4635. self.queue.ExecuteCommandLists(group);
  4636. self.card_sent();
  4637. let waited = self
  4638. .queue
  4639. .Signal(&self.fence, *submitted)
  4640. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4641. match waited {
  4642. Ok(()) => {
  4643. working(false);
  4644. WaitForSingleObject(self.event, INFINITE);
  4645. stood(started);
  4646. working(true);
  4647. }
  4648. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4649. }
  4650. }
  4651. // With timing on each group is one of `runs` (and the compare
  4652. // of copies in the card's memory, with the last): every
  4653. // command's time on the card goes to the sums by pipeline.
  4654. #[cfg(feature = "diagnostics")]
  4655. if timing() {
  4656. // SAFETY: a plain query.
  4657. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4658. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4659. crate::copystat::command_took(&op, ms);
  4660. }
  4661. }
  4662. // A submission of one list was never named here (`groups.len()
  4663. // > 1` was the test): the two 50 ms lists of the gameplay
  4664. // frame, each a submission of its own, printed nothing.
  4665. #[cfg(feature = "diagnostics")]
  4666. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4667. // SAFETY: a plain query.
  4668. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4669. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4670. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4671. for (ms, op) in runs[i].slowest(frequency, 6) {
  4672. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4673. }
  4674. }
  4675. let _ = (i, started);
  4676. }
  4677. let _ = &firsts;
  4678. FINISHED.store(this_submission, Ordering::Release);
  4679. bury(this_submission);
  4680. let gpu = prepared.elapsed();
  4681. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4682. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4683. #[cfg(feature = "diagnostics")]
  4684. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4685. let pipelines: std::collections::BTreeSet<String> = runs
  4686. .iter()
  4687. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4688. .collect();
  4689. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  4690. text.chars().take(1200).collect()
  4691. });
  4692. // The host resets a device whose submission runs for about 2 s.
  4693. if gpu > std::time::Duration::from_millis(250) {
  4694. let pipelines: std::collections::BTreeSet<String> = runs
  4695. .iter()
  4696. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4697. .collect();
  4698. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  4699. }
  4700. // SAFETY: a plain query.
  4701. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4702. fail(format_args!(
  4703. "host GPU device removed after a submission of {} lists{}{}",
  4704. runs.len(),
  4705. self.removal_data(runs),
  4706. last_notes(runs)
  4707. ));
  4708. }
  4709. submitting(3, runs.len());
  4710. // What shaders wrote goes back before the bottom-of-pipe writes,
  4711. // which tell the title the GPU is done; each range once per
  4712. // submission, however many dispatches declared it (the world's
  4713. // passes declare the same big ranges dozens of times).
  4714. let copying = std::time::Instant::now();
  4715. // For copies in the card's memory the compare has run there: the
  4716. // pieces that differ are fetched and merged.
  4717. if let Some(card) = &card {
  4718. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  4719. }
  4720. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4721. hand_back(&back);
  4722. if let Some(card) = card {
  4723. self.card_done(card);
  4724. }
  4725. #[cfg(feature = "diagnostics")]
  4726. if !back.is_empty() {
  4727. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  4728. }
  4729. // Nothing of this submission goes back to the title: no range of
  4730. // shader writes, no value written when it is done. The wait for
  4731. // such a one is only for order and for what the card still holds.
  4732. #[cfg(feature = "diagnostics")]
  4733. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  4734. use crate::copystat::{C, add};
  4735. add(C::NothingBack, 1);
  4736. add(C::NothingBackUs, gpu.as_micros() as u64);
  4737. }
  4738. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4739. for list in runs {
  4740. // Read backs first: a value written at the bottom of the pipe
  4741. // may be what tells the title that they are there.
  4742. read_backs(list);
  4743. for &(at, what, bytes) in &list.deferred().writes {
  4744. what.write(at as *mut u8, bytes);
  4745. }
  4746. }
  4747. self.log_messages();
  4748. submitting(0, 0);
  4749. #[cfg(feature = "diagnostics")]
  4750. crate::copystat::submission_ends(lock);
  4751. // With the relay: nothing is in the air now, so no fetch still to
  4752. // be merged is older than the sends to card copies so far, and
  4753. // their notes can go.
  4754. if relay() {
  4755. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  4756. }
  4757. working(was_working);
  4758. None
  4759. }
  4760. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  4761. /// it lies in (by the names we give them) or the title memory copy just
  4762. /// below it; for each list that did not finish, the command it stopped
  4763. /// at and what the draws and dispatches in flight there run (or, in
  4764. /// lists that never started, the pipelines they bind).
  4765. fn removal_data(&self, runs: &[&HostList]) -> String {
  4766. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  4767. return String::new();
  4768. };
  4769. let mut text = String::new();
  4770. let mut fault_va = None;
  4771. // SAFETY: the outputs are the runtime's, valid while the device
  4772. // lives; nodes are walked as linked, histories have their counts.
  4773. unsafe {
  4774. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  4775. && fault.PageFaultVA != 0
  4776. {
  4777. let va = fault.PageFaultVA;
  4778. fault_va = Some(va);
  4779. text.push_str(&format!("; page fault at {va:#x}"));
  4780. for (what, head) in [
  4781. ("inside", fault.pHeadExistingAllocationNode),
  4782. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  4783. ] {
  4784. let mut names = Vec::new();
  4785. let mut node = head;
  4786. while let Some(n) = node.as_ref()
  4787. && names.len() < 8
  4788. {
  4789. let name = if n.ObjectNameW.is_null() {
  4790. "unnamed".to_owned()
  4791. } else {
  4792. n.ObjectNameW.to_string().unwrap_or_default()
  4793. };
  4794. names.push(format!("{name} (type {})", n.AllocationType.0));
  4795. node = n.pNext;
  4796. }
  4797. if !names.is_empty() {
  4798. text.push_str(&format!("; {what} {names:?}"));
  4799. }
  4800. }
  4801. text.push_str(&crate::shadow::near(va));
  4802. text.push_str(&crate::descriptor::host::near_heaps(va));
  4803. }
  4804. // The plain output: the extended one (with marker texts) came
  4805. // back without stopped lists on this host.
  4806. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  4807. Ok(crumbs) => crumbs,
  4808. Err(e) => {
  4809. text.push_str(&format!("; no breadcrumbs ({e})"));
  4810. return text;
  4811. }
  4812. };
  4813. // Every list's progress (done/count), in the runtime's order.
  4814. let mut progress = Vec::new();
  4815. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  4816. while let Some(p) = node.as_ref() {
  4817. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4818. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  4819. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  4820. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  4821. node = p.pNext;
  4822. }
  4823. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  4824. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  4825. while let Some(p) = plain.as_ref() {
  4826. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4827. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  4828. let history =
  4829. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  4830. text.push_str(&format!(
  4831. "; a list stopped at command {done} of {} (op {})",
  4832. p.BreadcrumbCount, history[done as usize].0
  4833. ));
  4834. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  4835. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  4836. // The k-th marker command is the k-th note.
  4837. #[cfg(feature = "diagnostics")]
  4838. let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| {
  4839. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  4840. history
  4841. .iter()
  4842. .enumerate()
  4843. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  4844. .zip(notes.iter())
  4845. .map(|((at, _), (note, range))| {
  4846. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  4847. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  4848. })
  4849. .collect()
  4850. });
  4851. #[cfg(not(feature = "diagnostics"))]
  4852. let markers: Vec<(u32, String)> = Vec::new();
  4853. #[cfg(not(feature = "diagnostics"))]
  4854. let _ = fault_va;
  4855. if done > 0 {
  4856. text.push_str(&in_flight(history, &markers, done as usize));
  4857. } else if let Some(r) = run {
  4858. let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  4859. text.push_str(&format!(", its pipelines {pipelines:?}"));
  4860. }
  4861. }
  4862. plain = p.pNext;
  4863. }
  4864. }
  4865. text
  4866. }
  4867. /// Moves the debug layer's messages into our log; returns the first
  4868. /// error among them.
  4869. pub(crate) fn log_messages(&self) -> Option<String> {
  4870. let Some(queue) = &self.messages else {
  4871. return None;
  4872. };
  4873. let mut first_error = None;
  4874. // SAFETY: each message is read into a buffer of the size the queue
  4875. // reports, then the queue is emptied.
  4876. unsafe {
  4877. for i in 0..queue.GetNumStoredMessages() {
  4878. let mut size = 0;
  4879. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  4880. continue;
  4881. }
  4882. let mut buffer = vec![0u64; size.div_ceil(8)];
  4883. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  4884. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  4885. let m = &*message;
  4886. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  4887. let text = String::from_utf8_lossy(text);
  4888. let text = text.trim_end_matches('\0');
  4889. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  4890. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  4891. first_error = Some(text.to_owned());
  4892. }
  4893. }
  4894. }
  4895. queue.ClearStoredMessages();
  4896. }
  4897. first_error
  4898. }
  4899. /// A host render target view of `resource`, valid until it is recorded.
  4900. pub(crate) fn rtv(
  4901. &self,
  4902. resource: Option<&ID3D12Resource>,
  4903. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  4904. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4905. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4906. // SAFETY: a slot of our heap and a live resource, or none with a
  4907. // description (a typed null view).
  4908. unsafe {
  4909. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  4910. handle.ptr += (slot * self.rtv_size) as usize;
  4911. self.device
  4912. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  4913. handle
  4914. }
  4915. }
  4916. /// A host depth view of `resource`, valid until it is recorded.
  4917. pub(crate) fn dsv(
  4918. &self,
  4919. resource: &ID3D12Resource,
  4920. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  4921. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4922. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4923. // SAFETY: a slot of our heap and a live resource.
  4924. unsafe {
  4925. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  4926. handle.ptr += (slot * self.dsv_size) as usize;
  4927. self.device
  4928. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  4929. handle
  4930. }
  4931. }
  4932. }
  4933. impl HostList {
  4934. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  4935. #[cfg(feature = "diagnostics")]
  4936. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  4937. if !timing() {
  4938. return None;
  4939. }
  4940. self.stamps
  4941. .get_or_init(|| {
  4942. let device = &host()?.device;
  4943. let mut heap: Option<ID3D12QueryHeap> = None;
  4944. let mut back: Option<ID3D12Resource> = None;
  4945. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  4946. let desc = D3D12_RESOURCE_DESC {
  4947. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  4948. Width: u64::from(STAMPS) * 8,
  4949. Height: 1,
  4950. DepthOrArraySize: 1,
  4951. MipLevels: 1,
  4952. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  4953. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  4954. ..Default::default()
  4955. };
  4956. // SAFETY: plain object creation.
  4957. unsafe {
  4958. device
  4959. .CreateQueryHeap(
  4960. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  4961. &mut heap,
  4962. )
  4963. .ok()?;
  4964. device
  4965. .CreateCommittedResource(
  4966. &readback,
  4967. D3D12_HEAP_FLAG_NONE,
  4968. &desc,
  4969. D3D12_RESOURCE_STATE_COPY_DEST,
  4970. None,
  4971. &mut back,
  4972. )
  4973. .ok()?;
  4974. }
  4975. Some((heap?, back?))
  4976. })
  4977. .as_ref()
  4978. }
  4979. /// The noted commands that took longest on the GPU, longest first, as
  4980. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  4981. #[cfg(feature = "diagnostics")]
  4982. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  4983. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  4984. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  4985. return Vec::new();
  4986. };
  4987. let mut data = std::ptr::null_mut();
  4988. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  4989. // SAFETY: a read-back buffer the finished list resolved into.
  4990. let stamps: Vec<u64> = unsafe {
  4991. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  4992. return Vec::new();
  4993. }
  4994. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  4995. back.Unmap(0, None);
  4996. s
  4997. };
  4998. let mut times: Vec<(f64, String)> = (0..count)
  4999. .map(|i| {
  5000. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5001. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5002. })
  5003. .collect();
  5004. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5005. times.truncate(n);
  5006. times
  5007. }
  5008. pub(crate) fn close(&self) {
  5009. self.twins_to_depth();
  5010. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5011. if let Some((scratch, _)) = scratch {
  5012. self.indirect_common(&scratch);
  5013. }
  5014. self.batches_common();
  5015. self.card_budget_out();
  5016. #[cfg(feature = "diagnostics")]
  5017. if let Some((heap, back)) = self.stamps() {
  5018. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5019. // SAFETY: an open list, our heap and read-back buffer.
  5020. unsafe {
  5021. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5022. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5023. }
  5024. }
  5025. // SAFETY: our list.
  5026. if let Err(e) = unsafe { self.list.Close() } {
  5027. fail(format_args!(
  5028. "a host command list did not close ({e}): a command recorded into it was invalid"
  5029. ));
  5030. }
  5031. }
  5032. /// Only after the list's last submission finished (every one is waited
  5033. /// for).
  5034. pub(crate) fn reset(&self) {
  5035. #[cfg(feature = "diagnostics")]
  5036. let started = std::time::Instant::now();
  5037. self._alive.used();
  5038. *self.deferred() = Deferred::default();
  5039. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5040. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5041. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5042. #[cfg(feature = "diagnostics")]
  5043. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5044. {
  5045. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5046. (scratch.current, scratch.used) = (0, 0);
  5047. // Every submission of the list has run: nothing reads its
  5048. // scratch memory any more, and the next list to ask takes it.
  5049. if scratch_pool() {
  5050. give_chunks(std::mem::take(&mut scratch.chunks));
  5051. }
  5052. }
  5053. // SAFETY: the list is not executing.
  5054. let reset = unsafe {
  5055. self.allocator
  5056. .Reset()
  5057. .and_then(|()| self.list.Reset(&self.allocator, None))
  5058. };
  5059. if let Err(e) = reset {
  5060. fail(format_args!("a host command list did not reset ({e})"));
  5061. }
  5062. #[cfg(feature = "diagnostics")]
  5063. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5064. }
  5065. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5066. /// list: the host texture and the state it leaves, if that is a change.
  5067. /// The list's first use of a texture records nothing: its prelude brings
  5068. /// the texture there at submission.
  5069. pub(crate) fn transition(
  5070. &self,
  5071. resource: crate::object::This,
  5072. wanted: u32,
  5073. ) -> Option<(&'static ID3D12Resource, u32)> {
  5074. let texture = crate::resource::host_resource(resource)?;
  5075. let copy = crate::resource::host_copy(resource)?;
  5076. let wanted = legal_state(texture, wanted);
  5077. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5078. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5079. std::collections::hash_map::Entry::Vacant(v) => {
  5080. v.insert((wanted, wanted, copy));
  5081. None
  5082. }
  5083. std::collections::hash_map::Entry::Occupied(mut o) => {
  5084. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5085. (before != wanted).then_some((texture, before))
  5086. }
  5087. }
  5088. }
  5089. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5090. /// as [`HostList::transition`] does a title resource's host copy, and
  5091. /// records the barrier: for textures that are not a title resource's
  5092. /// host copy (colour twins) and for the copies between the two.
  5093. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5094. let wanted = legal_state(&copy.texture, wanted);
  5095. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5096. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5097. std::collections::hash_map::Entry::Vacant(v) => {
  5098. v.insert((wanted, wanted, copy.clone()));
  5099. None
  5100. }
  5101. std::collections::hash_map::Entry::Occupied(mut o) => {
  5102. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5103. (before != wanted).then_some(before)
  5104. }
  5105. };
  5106. drop(states);
  5107. if let Some(before) = before {
  5108. let barrier = transition(
  5109. &copy.texture,
  5110. D3D12_RESOURCE_STATES(before as i32),
  5111. D3D12_RESOURCE_STATES(wanted as i32),
  5112. );
  5113. // SAFETY: an open list and a live texture.
  5114. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5115. }
  5116. }
  5117. /// A use of title texture `resource` about to be recorded, if it is a
  5118. /// depth texture with a colour twin (false if it is not): of the twin
  5119. /// (`colour`: unordered access) or of the depth texture (depth target,
  5120. /// clear, shader read, copy, resolve), writing it or only reading. The
  5121. /// side used is first brought up to date: by a copy recorded here if
  5122. /// this list wrote the other side since, by the list's prelude if the
  5123. /// list uses the side as it finds it. The twin is left in the
  5124. /// unordered access state; the caller moves the depth texture to the
  5125. /// state its use needs, as for any texture. A twin still ahead when the
  5126. /// list closes is copied then (`twins_to_depth`).
  5127. /// shortcut: every depth target bound for a draw counts as written
  5128. /// (also when the draw only tests), and every unordered access view a
  5129. /// shader names as written; views a shader picks from the heap by a
  5130. /// computed index are not seen here at all.
  5131. pub(crate) fn twin_use(
  5132. &self,
  5133. resource: crate::object::This,
  5134. colour: bool,
  5135. write: bool,
  5136. ) -> bool {
  5137. const UNORDERED_ACCESS: u32 = 0x8;
  5138. // Asked for every texture a draw reads: most have no twin.
  5139. let Some(twin) = crate::resource::twin(resource) else {
  5140. return false;
  5141. };
  5142. let Some(depth) = crate::resource::host_copy(resource) else {
  5143. return false;
  5144. };
  5145. let side = usize::from(colour);
  5146. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5147. let u = twins
  5148. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5149. .or_insert_with(|| TwinUse {
  5150. depth: depth.clone(),
  5151. twin: twin.clone(),
  5152. needs: [false; 2],
  5153. behind: [None; 2],
  5154. writing: false,
  5155. late: false,
  5156. });
  5157. let copy = match u.behind[side] {
  5158. Some(behind) => behind,
  5159. None => {
  5160. u.needs[side] = true;
  5161. false
  5162. }
  5163. };
  5164. u.behind[side] = Some(false);
  5165. match (write, colour) {
  5166. // Shaders write the twin when the draw or dispatch runs: what
  5167. // the same one reads of the depth texture is prepared before
  5168. // (`twins_written`).
  5169. (true, true) => u.writing = true,
  5170. (true, false) => u.behind[1] = Some(true),
  5171. (false, _) => {}
  5172. }
  5173. // shortcut: the depth plane's twin is not drawn into the plane
  5174. // here: the pass sets a pipeline and a target of ours, which a list
  5175. // still recording the title's commands cannot take. This use sees
  5176. // the plane as it was; the pass runs when the list closes
  5177. // (`twins_to_depth`). Counted.
  5178. if copy && !colour && twin.plane.is_some() {
  5179. u.late = true;
  5180. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5181. }
  5182. drop(twins);
  5183. if copy {
  5184. self.twin_copy(&depth, &twin, colour);
  5185. } else if colour {
  5186. self.settle(&twin.colour, UNORDERED_ACCESS);
  5187. }
  5188. // The depth plane's twin is written through unordered access too.
  5189. if colour && let Some(plane) = &twin.plane {
  5190. self.settle(plane, UNORDERED_ACCESS);
  5191. }
  5192. true
  5193. }
  5194. /// Records the pass that draws the twin of the depth plane of `depth`
  5195. /// into the plane, if `twin` has one, with the moves to the states the
  5196. /// pass needs; the twin is left in the unordered access state. Only
  5197. /// for a list that records nothing of the title's afterwards
  5198. /// (`record_plane_pass`).
  5199. fn pass_plane(
  5200. &self,
  5201. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5202. twin: &crate::resource::Twin,
  5203. ) {
  5204. const UNORDERED_ACCESS: u32 = 0x8;
  5205. const DEPTH_WRITE: u32 = 0x10;
  5206. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5207. let Some(plane) = &twin.plane else { return };
  5208. self.settle(depth, DEPTH_WRITE);
  5209. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5210. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5211. self.settle(plane, UNORDERED_ACCESS);
  5212. }
  5213. /// Records the copy of a depth texture into its colour twin (`colour`)
  5214. /// or of the twin into the depth texture, with the moves to the copy
  5215. /// states. The twin is left in the unordered access state.
  5216. fn twin_copy(
  5217. &self,
  5218. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5219. twin: &crate::resource::Twin,
  5220. colour: bool,
  5221. ) {
  5222. const UNORDERED_ACCESS: u32 = 0x8;
  5223. const COPY_DEST: u32 = 0x400;
  5224. const COPY_SOURCE: u32 = 0x800;
  5225. let (from, to) = if colour {
  5226. (depth, &twin.colour)
  5227. } else {
  5228. (&twin.colour, depth)
  5229. };
  5230. self.settle(from, COPY_SOURCE);
  5231. self.settle(to, COPY_DEST);
  5232. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5233. self.settle(&twin.colour, UNORDERED_ACCESS);
  5234. }
  5235. /// Before the list closes: the depth textures whose twins it wrote last
  5236. /// are given what was written, and left readable by shaders. Shaders
  5237. /// that pick a view from the heap by a computed index are not seen by
  5238. /// `twin_use` and read the depth texture in lists that never name it
  5239. /// (in a captured frame of the title no table names a shadow
  5240. /// map for reading but the pass that fills the next one).
  5241. fn twins_to_depth(&self) {
  5242. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5243. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5244. let written: Vec<_> = twins
  5245. .values_mut()
  5246. .filter(|u| u.behind[0] == Some(true) || u.late)
  5247. .map(|u| {
  5248. // Not copied again if the list copied since the last write
  5249. // and only the depth plane's pass is left.
  5250. let copy = u.behind[0] == Some(true);
  5251. u.behind[0] = Some(false);
  5252. u.late = false;
  5253. (u.depth.clone(), u.twin.clone(), copy)
  5254. })
  5255. .collect();
  5256. drop(twins);
  5257. for (depth, twin, copy) in &written {
  5258. if *copy {
  5259. self.twin_copy(depth, twin, false);
  5260. }
  5261. // Nothing of the title's is recorded after this: the pass may
  5262. // leave its own pipeline and target set.
  5263. self.pass_plane(depth, twin);
  5264. self.settle(depth, SHADER_RESOURCE);
  5265. }
  5266. }
  5267. /// The draw or dispatch just prepared is recorded: the twins it writes
  5268. /// now hold what their depth textures lack.
  5269. pub(crate) fn twins_written(&self) {
  5270. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5271. for u in twins.values_mut().filter(|u| u.writing) {
  5272. u.writing = false;
  5273. u.behind[0] = Some(true);
  5274. }
  5275. }
  5276. /// At submission: the list that moves each texture this list uses from
  5277. /// its real state to the one the list starts with; the textures' real
  5278. /// states become those the list ends with. For depth textures with a
  5279. /// colour twin it first copies the side the list uses as it finds it
  5280. /// from the other, if a list submitted earlier left it behind.
  5281. fn prelude(&self) -> Option<ID3D12CommandList> {
  5282. const COPY_DEST: u32 = 0x400;
  5283. const COPY_SOURCE: u32 = 0x800;
  5284. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5285. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5286. // The copies (depth texture, twin, whether into the twin); the
  5287. // sides are then as this list leaves them.
  5288. let mut syncs = Vec::new();
  5289. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5290. for u in twins.values() {
  5291. let real = u.twin.behind.load(Ordering::Relaxed);
  5292. let mut behind = [real & 1 != 0, real & 2 != 0];
  5293. for side in [0, 1] {
  5294. if u.needs[side] && behind[side] {
  5295. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5296. behind = [false; 2];
  5297. }
  5298. }
  5299. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5300. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5301. u.twin.behind.store(left, Ordering::Relaxed);
  5302. }
  5303. drop(twins);
  5304. // A copy runs with its textures in the copy states: each moves
  5305. // there from its real state, and from there to the state the list
  5306. // starts with (back to its real state if the list does not use it).
  5307. let mut to_copy = Vec::new();
  5308. let mut barriers = Vec::new();
  5309. let mut copying = std::collections::HashMap::new();
  5310. for (depth, twin, colour) in &syncs {
  5311. let (from, to) = if *colour {
  5312. (depth, &twin.colour)
  5313. } else {
  5314. (&twin.colour, depth)
  5315. };
  5316. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  5317. let key = std::sync::Arc::as_ptr(texture) as usize;
  5318. let real = texture.state.load(Ordering::Relaxed);
  5319. copying.insert(key, state);
  5320. if real != state {
  5321. to_copy.push(transition(
  5322. &texture.texture,
  5323. host_state(real),
  5324. host_state(state),
  5325. ));
  5326. if !states.contains_key(&key) {
  5327. barriers.push(transition(
  5328. &texture.texture,
  5329. host_state(state),
  5330. host_state(real),
  5331. ));
  5332. }
  5333. }
  5334. }
  5335. }
  5336. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5337. let real = copy.state.swap(*last, Ordering::Relaxed);
  5338. let real = copying.get(key).copied().unwrap_or(real);
  5339. (real != *first)
  5340. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5341. }));
  5342. if barriers.is_empty() && syncs.is_empty() {
  5343. return None;
  5344. }
  5345. let Some((allocator, list)) = self
  5346. .prelude
  5347. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5348. .as_ref()
  5349. else {
  5350. fail(format_args!("no host list for a state prelude"));
  5351. };
  5352. // SAFETY: the prelude is not executing (every submission is waited
  5353. // for); the textures are live.
  5354. let recorded = unsafe {
  5355. allocator.Reset().and_then(|()| {
  5356. list.Reset(allocator, None)?;
  5357. if !to_copy.is_empty() {
  5358. list.ResourceBarrier(&to_copy);
  5359. }
  5360. for (depth, twin, colour) in &syncs {
  5361. record_twin_copy(list, &depth.texture, twin, *colour);
  5362. }
  5363. if !barriers.is_empty() {
  5364. list.ResourceBarrier(&barriers);
  5365. }
  5366. list.Close()
  5367. })
  5368. };
  5369. if let Err(e) = recorded {
  5370. fail(format_args!("a host state prelude did not record ({e})"));
  5371. }
  5372. list.cast().ok()
  5373. }
  5374. /// Notes what the command about to be recorded does, as a marker
  5375. /// command whose text the list keeps (diagnostics, with device-removed
  5376. /// data on): the report pairs the breadcrumbs' marker commands with the
  5377. /// texts in order and names the commands a fault stopped among.
  5378. #[cfg(feature = "diagnostics")]
  5379. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5380. self.note(what, None);
  5381. }
  5382. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5383. /// `(address, bytes)`: the report places the faulting address in it.
  5384. #[cfg(feature = "diagnostics")]
  5385. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5386. self.note(what, Some(range));
  5387. }
  5388. #[cfg(feature = "diagnostics")]
  5389. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5390. if !dred_on() {
  5391. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5392. return;
  5393. }
  5394. {
  5395. let started = std::time::Instant::now();
  5396. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5397. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5398. // SAFETY: an open list and our query heap.
  5399. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5400. }
  5401. let what = what();
  5402. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5403. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5404. const UNICODE: u32 = 0;
  5405. // SAFETY: an open list; the marker is copied when recorded.
  5406. unsafe {
  5407. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5408. };
  5409. self.notes
  5410. .lock()
  5411. .unwrap_or_else(|e| e.into_inner())
  5412. .push((what, range));
  5413. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5414. }
  5415. }
  5416. /// Whether nothing recorded since the list was opened does any work:
  5417. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5418. /// upload or resolve (they defer a step or move a texture's state), no
  5419. /// bottom-of-pipe write. State set on the list does not count.
  5420. pub(crate) fn untouched(&self) -> bool {
  5421. {
  5422. let deferred = self.deferred();
  5423. if !(deferred.copies.is_empty()
  5424. && deferred.uploads.is_empty()
  5425. && deferred.kept.is_empty()
  5426. && deferred.textures.is_empty()
  5427. && deferred.writes.is_empty()
  5428. && deferred.backs.is_empty())
  5429. {
  5430. return false;
  5431. }
  5432. }
  5433. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5434. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5435. }
  5436. /// Notes a pipeline the list binds.
  5437. pub(crate) fn used_pipeline(&self, name: &str) {
  5438. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5439. if !pipelines.contains(name) {
  5440. pipelines.insert(name.to_owned());
  5441. }
  5442. }
  5443. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5444. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5445. }
  5446. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5447. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5448. let mut deferred = self.deferred();
  5449. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5450. // A copy that goes on where the one recorded just before it ended,
  5451. // source and destination both: with `join_copies` the two are one
  5452. // step.
  5453. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5454. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5455. {
  5456. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5457. if join_copies() {
  5458. *n += len;
  5459. return;
  5460. }
  5461. }
  5462. deferred
  5463. .copies
  5464. .push(Step::Copy(dst as usize, src as usize, len));
  5465. deferred.refreshed.clear();
  5466. }
  5467. /// Copies `len` bytes of title memory at `src` into the list's upload
  5468. /// memory at `dst` when the list is submitted.
  5469. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5470. self.deferred()
  5471. .copies
  5472. .push(Step::Fill(dst as usize, src as usize, len, None));
  5473. }
  5474. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5475. /// title heap's address, and the slot) shows.
  5476. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5477. self.deferred()
  5478. .copies
  5479. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  5480. }
  5481. /// As [`HostList::defer_fill`], for the beginning of a buffer
  5482. /// [`HostList::upload`] made.
  5483. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  5484. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  5485. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  5486. }
  5487. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5488. /// when the list is submitted (once per range until a title copy
  5489. /// intervenes), keeping the copy alive until the list is reset.
  5490. pub(crate) fn defer_refresh(
  5491. &self,
  5492. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5493. address: usize,
  5494. len: usize,
  5495. ) {
  5496. let mut deferred = self.deferred();
  5497. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5498. if deferred.refreshed.insert(key) {
  5499. deferred
  5500. .copies
  5501. .push(Step::Refresh(shadow.clone(), address, len));
  5502. }
  5503. }
  5504. /// Shaders of the list write `[address, address + len)` of a buffer's
  5505. /// host copy: copied back into title memory once the list has run.
  5506. pub(crate) fn defer_gpu_write(
  5507. &self,
  5508. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5509. address: usize,
  5510. len: usize,
  5511. ) {
  5512. self.deferred()
  5513. .copies
  5514. .push(Step::GpuWrite(shadow.clone(), address, len));
  5515. }
  5516. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5517. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5518. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5519. /// the list is reset.
  5520. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5521. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5522. }
  5523. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5524. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5525. self.deferred().writes.push((dst as usize, what, bytes));
  5526. }
  5527. /// A mapped upload buffer of `size` bytes, alive until the list is
  5528. /// reset.
  5529. ///
  5530. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5531. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5532. // With [`card_steps`] the card may be the one that fills it.
  5533. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  5534. name(&buffer, || format!("list upload {size:#x}"));
  5535. self.deferred().hold_upload(buffer.clone(), size);
  5536. Some((buffer, data))
  5537. }
  5538. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5539. /// reset: the host GPU address and the CPU pointer.
  5540. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5541. let host = host()?;
  5542. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5543. let len = len.max(1).next_multiple_of(256);
  5544. if len > SCRATCH_CHUNK {
  5545. let (buffer, data) = host.upload_buffer(len)?;
  5546. name(&buffer, || format!("list scratch {len:#x}"));
  5547. // SAFETY: a live buffer.
  5548. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  5549. self.deferred().hold_upload(buffer, len);
  5550. return Some((gpu, data));
  5551. }
  5552. // The chunk in use while `len` fits in what is left of it, else the
  5553. // next one (a list's first chunk may be a small one).
  5554. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5555. (s.current, s.used) = (s.current + 1, 0);
  5556. }
  5557. if s.current == s.chunks.len() {
  5558. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  5559. SCRATCH_FIRST
  5560. } else {
  5561. SCRATCH_CHUNK
  5562. };
  5563. let chunk = take_chunk(host, size)?;
  5564. s.chunks.push((chunk, size));
  5565. s.used = 0;
  5566. }
  5567. let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu);
  5568. let at = s.used;
  5569. s.used += len;
  5570. Some((gpu + at, (data + at as usize) as *mut u8))
  5571. }
  5572. /// The bytes of scratch chunks the list holds now (after a reset:
  5573. /// none while lists share their chunks).
  5574. pub(crate) fn scratch_kept(&self) -> u64 {
  5575. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5576. scratch.chunks.iter().map(|c| c.1).sum()
  5577. }
  5578. /// The host address of the list's indirect-work budget, zeroed at each
  5579. /// submission of the list from the first use after a reset on.
  5580. pub(crate) fn budget(&self) -> Option<u64> {
  5581. let (buffer, data) = self
  5582. .budget
  5583. .get_or_init(|| {
  5584. let (b, d) = host()?.shared_buffer(256)?;
  5585. Some((b, d as usize))
  5586. })
  5587. .as_ref()?;
  5588. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5589. let mut deferred = self.deferred();
  5590. if !deferred.budget_zeroed {
  5591. deferred.budget_zeroed = true;
  5592. let at = *data;
  5593. // SAFETY: the list's own mapped words, written before it runs.
  5594. // The words after the budget hold what the clamp noted about the
  5595. // list's last run (mesh dispatches: the largest group count
  5596. // asked for, the groups asked in all; with the card's copy, as
  5597. // the list's end copied them here): taken, then zeroed.
  5598. let notes = Box::new(move || unsafe {
  5599. let words = at as *mut u32;
  5600. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  5601. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  5602. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  5603. for k in 0..3 {
  5604. words.add(k).write_volatile(0);
  5605. }
  5606. });
  5607. deferred.copies.push(Step::Host(notes, (0, 0)));
  5608. drop(deferred);
  5609. if let Some(card) = card {
  5610. self.zero_card_budget(card);
  5611. }
  5612. }
  5613. // SAFETY: a live buffer.
  5614. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  5615. }
  5616. /// The budget's words in the card's own memory ([`card_budget`]), if
  5617. /// the list can zero them itself (`WriteBufferImmediate`).
  5618. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  5619. if !card_budget() {
  5620. return None;
  5621. }
  5622. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  5623. let buffer = host()?.uav_buffer(256)?;
  5624. name(&buffer, || "indirect budget".to_owned());
  5625. Some(buffer)
  5626. }
  5627. /// Records, before the list's first clamp, the zeroing of the card's
  5628. /// copy of the budget: common, written as a copy, then left for
  5629. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  5630. fn zero_card_budget(&self, card: &ID3D12Resource) {
  5631. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  5632. return;
  5633. };
  5634. // SAFETY: a live buffer.
  5635. let at = unsafe { card.GetGPUVirtualAddress() };
  5636. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  5637. Dest: at + offset,
  5638. Value: 0,
  5639. });
  5640. // SAFETY: an open list; the buffer is the list's own and in the
  5641. // common state at the start of every recording.
  5642. unsafe {
  5643. self.list.ResourceBarrier(&[transition(
  5644. card,
  5645. D3D12_RESOURCE_STATE_COMMON,
  5646. D3D12_RESOURCE_STATE_COPY_DEST,
  5647. )]);
  5648. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  5649. self.list.ResourceBarrier(&[transition(
  5650. card,
  5651. D3D12_RESOURCE_STATE_COPY_DEST,
  5652. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5653. )]);
  5654. }
  5655. }
  5656. /// Before the list closes, if this recording charged the card's copy
  5657. /// of the budget: its notes on mesh records go to the mapped words
  5658. /// (read at the next submission), and it goes back to common.
  5659. fn card_budget_out(&self) {
  5660. if !self.deferred().budget_zeroed {
  5661. return;
  5662. }
  5663. let (Some(Some(card)), Some(Some((mapped, _)))) =
  5664. (self.card_budget.get(), self.budget.get())
  5665. else {
  5666. return;
  5667. };
  5668. // SAFETY: an open list; both buffers are the list's own. The
  5669. // mapped one is promoted from common to the copy destination.
  5670. unsafe {
  5671. self.list.ResourceBarrier(&[transition(
  5672. card,
  5673. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5674. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5675. )]);
  5676. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  5677. self.list.ResourceBarrier(&[transition(
  5678. card,
  5679. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5680. D3D12_RESOURCE_STATE_COMMON,
  5681. )]);
  5682. }
  5683. }
  5684. /// A device-local unordered-access buffer of at least `size` bytes for
  5685. /// clamped indirect arguments, reused across executions and resets of the
  5686. /// list. Smaller buffers replaced mid-list stay alive until
  5687. /// [`HostList::reset`].
  5688. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  5689. let needed = size.max(64 << 10);
  5690. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  5691. if let Some((buffer, cap)) = &*slot
  5692. && *cap >= needed
  5693. {
  5694. return Some(buffer.clone());
  5695. }
  5696. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  5697. let alloc = prev
  5698. .saturating_mul(2)
  5699. .max(needed)
  5700. .next_multiple_of(64 << 10);
  5701. let buffer = host()?.uav_buffer(alloc)?;
  5702. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  5703. let old = slot.replace((buffer.clone(), alloc));
  5704. drop(slot);
  5705. if let Some((old_buf, _)) = old {
  5706. // It ends the list common, as every scratch buffer does.
  5707. self.indirect_common(&old_buf);
  5708. self.keep(&old_buf);
  5709. }
  5710. Some(buffer)
  5711. }
  5712. /// Where the next batch of clamped records goes: a device-local buffer
  5713. /// the list keeps from recording to recording, the batch's place in it
  5714. /// and the state the buffer is in. Every batch of a recording has a place
  5715. /// of its own: the executions before it may still read theirs.
  5716. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  5717. use crate::indirect::batch::{JOBS, SLOT};
  5718. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5719. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  5720. if buffer == args.0.len() {
  5721. let size = u64::from(BATCHES * JOBS * SLOT);
  5722. let made = host()?.uav_buffer(size)?;
  5723. name(&made, || format!("indirect batches {size:#x}"));
  5724. args.0.push(made);
  5725. }
  5726. args.1 += 1;
  5727. // (Its first batch finds it as the recording before left it:
  5728. // `batches_common`.)
  5729. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  5730. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  5731. }
  5732. /// Before the list closes: the scratch buffers of the batched clamps go
  5733. /// back to the common state, where the next recording expects them.
  5734. fn batches_common(&self) {
  5735. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5736. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  5737. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  5738. .iter()
  5739. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  5740. .collect();
  5741. if !barriers.is_empty() {
  5742. // SAFETY: an open list and live buffers this recording left in
  5743. // `INDIRECT_ARGUMENT`.
  5744. unsafe { self.list.ResourceBarrier(&barriers) };
  5745. }
  5746. }
  5747. /// Moves `scratch` back to the common state if a clamp left it readable
  5748. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  5749. /// list's first clamp expects it. Done before the list closes and before
  5750. /// a bigger scratch buffer replaces it: one barrier per list (where
  5751. /// there was one per indirect execution), and the list ends as it
  5752. /// begins however it is submitted.
  5753. fn indirect_common(&self, scratch: &ID3D12Resource) {
  5754. {
  5755. let mut deferred = self.deferred();
  5756. if deferred.indirect_readable != scratch.as_raw() as usize {
  5757. return;
  5758. }
  5759. deferred.indirect_readable = 0;
  5760. }
  5761. let barrier = transition(
  5762. scratch,
  5763. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  5764. D3D12_RESOURCE_STATE_COMMON,
  5765. );
  5766. // SAFETY: an open list and a live buffer this recording left in
  5767. // `INDIRECT_ARGUMENT`.
  5768. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5769. }
  5770. /// The state the list's indirect scratch buffer `scratch` is in at this
  5771. /// point of the recording: indirect arguments if a clamp in this
  5772. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  5773. /// common: the state a buffer is made in, and the one a recording
  5774. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  5775. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  5776. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  5777. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  5778. } else {
  5779. D3D12_RESOURCE_STATE_COMMON
  5780. }
  5781. }
  5782. /// A clamp recorded in this list left `scratch` readable as indirect
  5783. /// arguments. It stays so for every execution that reads it, until the
  5784. /// next clamp moves it back to unordered access.
  5785. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  5786. self.deferred().indirect_readable = scratch.as_raw() as usize;
  5787. }
  5788. /// Keeps `object` alive until the list is reset.
  5789. pub(crate) fn keep(&self, object: &impl Interface) {
  5790. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  5791. self.deferred().kept.push(object);
  5792. }
  5793. }
  5794. /// Whether this is the first time since the reset that the list asks
  5795. /// about `key` (a texture to bring up to date).
  5796. pub(crate) fn first_use(&self, key: usize) -> bool {
  5797. self.deferred().textures.insert(key)
  5798. }
  5799. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  5800. /// reset.
  5801. pub(crate) fn used(&self, key: usize) -> bool {
  5802. self.deferred().textures.contains(&key)
  5803. }
  5804. /// Runs `work` when the list is submitted, in order with its copies.
  5805. /// `work` may write title memory (refreshes after it copy again).
  5806. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  5807. self.deferred().copies.push(Step::Run(Box::new(work)));
  5808. self.deferred().refreshed.clear();
  5809. }
  5810. /// As [`HostList::defer`], for work that writes only host memory.
  5811. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  5812. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  5813. }
  5814. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  5815. /// memory at `from`.
  5816. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  5817. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  5818. }
  5819. /// Brings a texture's staging buffer up to date when the list is
  5820. /// submitted, keeping it alive until the list is reset.
  5821. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  5822. self.deferred().copies.push(Step::Texture(staging));
  5823. }
  5824. /// Runs the list's submission-time steps; refreshes go into `batch`
  5825. /// (the title's big buffers, a 174 MB one among them, are read by most
  5826. /// lists of a submission, through many ranges). Copies and fills that
  5827. /// `taken` names (by their place) are left out: they are done on the
  5828. /// card ([`card_steps`]).
  5829. fn run_deferred(&self, batch: &mut Batch, taken: impl Fn(usize) -> bool) {
  5830. #[cfg(feature = "diagnostics")]
  5831. use crate::copystat::{C, add};
  5832. // The time and the bytes of the copies and fills, some 13,000 a
  5833. // frame between 20,000 refreshes: summed here and added once.
  5834. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  5835. #[cfg(feature = "diagnostics")]
  5836. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  5837. for (i, step) in self.deferred().copies.iter().enumerate() {
  5838. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  5839. continue;
  5840. }
  5841. let (started, copied) = match step {
  5842. &Step::Copy(dst, src, len) => {
  5843. let started = std::time::Instant::now();
  5844. #[cfg(feature = "diagnostics")]
  5845. {
  5846. copies += 1;
  5847. }
  5848. batch.title_written();
  5849. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  5850. // With the submission's one asking: the journal learns it.
  5851. crate::watch::wrote(dst, len);
  5852. (started, len)
  5853. }
  5854. &Step::Fill(dst, src, len, _) => {
  5855. let started = std::time::Instant::now();
  5856. #[cfg(feature = "diagnostics")]
  5857. {
  5858. copies += 1;
  5859. }
  5860. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  5861. (started, len)
  5862. }
  5863. Step::Refresh(shadow, address, len) => {
  5864. #[cfg(feature = "diagnostics")]
  5865. {
  5866. refreshes += 1;
  5867. refreshed += *len as u64;
  5868. }
  5869. batch.add(shadow, *address, *len);
  5870. continue;
  5871. }
  5872. Step::Run(work) | Step::Host(work, _) => {
  5873. #[cfg(feature = "diagnostics")]
  5874. let started = std::time::Instant::now();
  5875. if matches!(step, Step::Run(_)) {
  5876. batch.title_written();
  5877. }
  5878. work();
  5879. // It wrote title memory, where is not known here: the
  5880. // submission's one asking ends, later refreshes ask anew.
  5881. if matches!(step, Step::Run(_)) {
  5882. crate::watch::ask_once_end();
  5883. }
  5884. #[cfg(feature = "diagnostics")]
  5885. {
  5886. add(C::Runs, 1);
  5887. add(C::RunUs, started.elapsed().as_micros() as u64);
  5888. }
  5889. continue;
  5890. }
  5891. Step::GpuWrite(shadow, address, len) => {
  5892. // The shaders start from the title's data: this copy's
  5893. // pending refresh first. The other copies' wait for
  5894. // the next flush of all (flushing all of them at every
  5895. // range a dispatch writes made thousands of write-watch
  5896. // askings a frame).
  5897. batch.flush_one(shadow);
  5898. #[cfg(feature = "diagnostics")]
  5899. let snapshot = std::time::Instant::now();
  5900. shadow.writing(*address, *len);
  5901. #[cfg(feature = "diagnostics")]
  5902. {
  5903. add(C::GpuWrites, 1);
  5904. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  5905. }
  5906. continue;
  5907. }
  5908. Step::Texture(staging) => {
  5909. if batch.texture_due(staging) {
  5910. batch.due.push(staging.clone());
  5911. if !wide_textures() {
  5912. batch.refresh_textures();
  5913. }
  5914. }
  5915. continue;
  5916. }
  5917. };
  5918. us += started.elapsed();
  5919. bytes += copied as u64;
  5920. }
  5921. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  5922. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  5923. #[cfg(feature = "diagnostics")]
  5924. {
  5925. add(C::Copies, copies);
  5926. add(C::CopyBytes, bytes);
  5927. add(C::Refreshes, refreshes);
  5928. add(C::RefreshBytes, refreshed);
  5929. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  5930. }
  5931. }
  5932. }
  5933. /// A table by a copy's address.
  5934. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  5935. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  5936. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  5937. /// but our own.
  5938. #[derive(Default)]
  5939. pub(crate) struct AddressHash(u64);
  5940. impl std::hash::Hasher for AddressHash {
  5941. fn finish(&self) -> u64 {
  5942. self.0
  5943. }
  5944. fn write(&mut self, bytes: &[u8]) {
  5945. for &b in bytes {
  5946. self.write_usize(usize::from(b));
  5947. }
  5948. }
  5949. fn write_usize(&mut self, n: usize) {
  5950. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  5951. self.0 = h ^ (h >> 32);
  5952. }
  5953. }
  5954. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  5955. /// preparing: the write-watch asking for a submission; the title's bytes put
  5956. /// in under flights' writes; the lists' steps, the refreshes among them; the
  5957. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  5958. /// of the steps: the refreshes, and the copies and fills (those with the
  5959. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  5960. /// is of. Of the refreshes, those before ranges are given to shaders, one
  5961. /// copy at a time: nanoseconds, and how many.
  5962. #[cfg(feature = "diagnostics")]
  5963. static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  5964. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  5965. /// those known to copy nothing, and those done on several threads.
  5966. #[cfg(feature = "diagnostics")]
  5967. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  5968. /// Counts into [`SPLIT`].
  5969. #[cfg(feature = "diagnostics")]
  5970. struct Split(std::cell::Cell<std::time::Instant>);
  5971. #[cfg(feature = "diagnostics")]
  5972. impl Split {
  5973. fn begin() -> Split {
  5974. Split(std::cell::Cell::new(std::time::Instant::now()))
  5975. }
  5976. /// Nanoseconds since the last part.
  5977. fn so_far(&self) -> u64 {
  5978. self.0.get().elapsed().as_nanos() as u64
  5979. }
  5980. /// What came since the last part was part `i`.
  5981. fn part(&self, i: usize) {
  5982. let now = std::time::Instant::now();
  5983. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  5984. }
  5985. }
  5986. /// The split of the preparing, per frame, for the frame-rate line.
  5987. #[cfg(feature = "diagnostics")]
  5988. fn split_line(frames: f64) {
  5989. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  5990. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  5991. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  5992. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  5993. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect();
  5994. tracing::info!(
  5995. "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' \
  5996. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  5997. 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 \
  5998. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
  5999. ms[0],
  6000. ms[8],
  6001. ms[1],
  6002. ms[2],
  6003. ms[6],
  6004. f[0],
  6005. f[1],
  6006. f[2],
  6007. f[3],
  6008. ms[9],
  6009. ms[10] * 1e6,
  6010. ms[7],
  6011. ms[3],
  6012. ms[4],
  6013. ms[5],
  6014. if crate::watch::light() { "on" } else { "off" },
  6015. );
  6016. tracing::info!(
  6017. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6018. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6019. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6020. waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \
  6021. as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)",
  6022. a[0],
  6023. a[1] / 1024.0,
  6024. a[11] / 1e6,
  6025. a[12],
  6026. a[10],
  6027. a[9],
  6028. a[2],
  6029. a[3],
  6030. a[4],
  6031. a[5],
  6032. a[6],
  6033. a[7] / 1e6,
  6034. a[8] / 1e6,
  6035. s[0],
  6036. s[1],
  6037. s[2],
  6038. );
  6039. tracing::info!(
  6040. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures",
  6041. h[0],
  6042. h[1],
  6043. h[2],
  6044. );
  6045. }
  6046. /// Whether a submission's refreshes of host copies run on several threads,
  6047. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6048. ///
  6049. /// A submission brings some sixty copies up to date, one after the other
  6050. /// on the submitting thread: for each, the pages the title wrote are asked
  6051. /// for and read through the kernel into the copy. That is the frame line's
  6052. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6053. /// another: each refresh writes its own copy and its own notes, and reads
  6054. /// title memory. With the switch the copies of a flush (four or more) are
  6055. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6056. /// The write-watch journal and the guards are behind their own locks, as
  6057. /// they are for the title's threads.
  6058. fn wide_refresh() -> bool {
  6059. static ON: OnceLock<bool> = OnceLock::new();
  6060. *ON.get_or_init(|| {
  6061. wide_refresh_enabled(
  6062. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6063. std::thread::available_parallelism().ok().map(|n| n.get()),
  6064. )
  6065. })
  6066. }
  6067. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6068. match setting {
  6069. Some("1") => true,
  6070. Some("0") => false,
  6071. _ => logical_cpus.is_some_and(|n| n >= 4),
  6072. }
  6073. }
  6074. #[cfg(test)]
  6075. mod wide_refresh_tests {
  6076. use super::wide_refresh_enabled;
  6077. #[test]
  6078. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6079. assert!(wide_refresh_enabled(None, Some(4)));
  6080. assert!(wide_refresh_enabled(None, Some(16)));
  6081. assert!(!wide_refresh_enabled(None, Some(2)));
  6082. assert!(!wide_refresh_enabled(None, None));
  6083. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6084. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6085. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6086. }
  6087. }
  6088. /// A submission's refreshes not done yet, merged per buffer copy into the
  6089. /// range that covers them: done before a step that writes title memory or
  6090. /// gives a range to shaders, and before the lists run.
  6091. ///
  6092. /// Also the textures brought up to date in the submission so far: most
  6093. /// lists of a world submission sample the same textures, and a texture in
  6094. /// physical-page memory is hashed whole each time it is checked. Checked
  6095. /// once, it is checked again only after a step that writes title memory.
  6096. #[derive(Default)]
  6097. struct Batch {
  6098. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6099. /// Where each copy (by address) is in `refreshes`: the list that makes
  6100. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6101. /// for every refresh of a submission was tens of millions of
  6102. /// comparisons a frame.
  6103. index: ByCopy<usize>,
  6104. /// Staging buffers (by address) refreshed since the last title write,
  6105. /// or due to be.
  6106. textures: std::collections::HashSet<usize>,
  6107. /// Those due ([`Batch::refresh_textures`]).
  6108. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6109. }
  6110. /// Whether a submission's textures are brought up to date on several
  6111. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6112. /// name them, as before).
  6113. ///
  6114. /// They are read, hashed and, if they changed, detiled into their staging
  6115. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6116. /// its own buffer, notes and lock, and is refreshed by the title's own
  6117. /// threads as it is. They are done before the next step that writes title
  6118. /// memory, as the copies' refreshes are, and before the lists go to the
  6119. /// card. What is new: the note of a list that its upload takes what the
  6120. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6121. /// an earlier list of the submission asked for, not behind it. The texture
  6122. /// is then uploaded by a later list too, once more than needed.
  6123. fn wide_textures() -> bool {
  6124. static ON: OnceLock<bool> = OnceLock::new();
  6125. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6126. }
  6127. impl Batch {
  6128. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6129. let end = address + len;
  6130. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6131. match self.index.get(&key) {
  6132. Some(&at) => {
  6133. let r = &mut self.refreshes[at];
  6134. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6135. }
  6136. None => {
  6137. self.index.insert(key, self.refreshes.len());
  6138. self.refreshes.push((shadow.clone(), address, end));
  6139. }
  6140. }
  6141. }
  6142. /// Before shaders are given a range of `shadow`'s copy: its pending
  6143. /// refresh is done, the others stay pending.
  6144. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  6145. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  6146. return;
  6147. };
  6148. let (shadow, from, to) = self.refreshes.swap_remove(at);
  6149. // The last entry took its place.
  6150. if let Some(moved) = self.refreshes.get(at) {
  6151. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  6152. }
  6153. #[cfg(feature = "diagnostics")]
  6154. let started = std::time::Instant::now();
  6155. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  6156. Self::update(&shadow, from, to);
  6157. }
  6158. #[cfg(feature = "diagnostics")]
  6159. {
  6160. let ns = started.elapsed().as_nanos() as u64;
  6161. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6162. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6163. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  6164. }
  6165. }
  6166. /// Brings `[from, to)` of a copy up to date, timed.
  6167. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  6168. let started = std::time::Instant::now();
  6169. let copied = shadow.update(from, to - from);
  6170. let us = started.elapsed().as_micros() as u64;
  6171. #[cfg(feature = "diagnostics")]
  6172. crate::copystat::range(from, to - from, us, 0);
  6173. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  6174. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  6175. }
  6176. /// Whether `staging` is still to be refreshed in this submission (and
  6177. /// notes it refreshed).
  6178. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  6179. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  6180. }
  6181. /// Before a step that writes title memory: pending refreshes are done
  6182. /// first, and textures are checked again after it.
  6183. fn title_written(&mut self) {
  6184. self.flush();
  6185. self.textures.clear();
  6186. }
  6187. /// The textures due are brought up to date.
  6188. fn refresh_textures(&mut self) {
  6189. if self.due.len() < 2 || !wide_textures() {
  6190. self.due.drain(..).for_each(|staging| staging.refresh());
  6191. return;
  6192. }
  6193. // The time counted is the time it took, not the threads' sum.
  6194. let started = std::time::Instant::now();
  6195. let before = PREPARING[2].load(Ordering::Relaxed);
  6196. let due = std::mem::take(&mut self.due);
  6197. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  6198. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  6199. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6200. }
  6201. fn flush(&mut self) {
  6202. self.refresh_textures();
  6203. self.index.clear();
  6204. if self.refreshes.is_empty() {
  6205. return;
  6206. }
  6207. #[cfg(feature = "diagnostics")]
  6208. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  6209. self.flush_all();
  6210. #[cfg(feature = "diagnostics")]
  6211. {
  6212. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6213. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  6214. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  6215. }
  6216. }
  6217. fn flush_all(&mut self) {
  6218. // Most of a flush's copies are as they were: they are told so here,
  6219. // from what the submission's asking found, before anything is asked
  6220. // and any thread woken. (Thousands of them, the heap's buffer views
  6221. // once a frame: on the threads, below.)
  6222. const FEW: usize = 256;
  6223. let light = crate::watch::light();
  6224. if light && self.refreshes.len() <= FEW {
  6225. let started = std::time::Instant::now();
  6226. #[cfg(feature = "diagnostics")]
  6227. let all = self.refreshes.len();
  6228. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  6229. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6230. #[cfg(feature = "diagnostics")]
  6231. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  6232. }
  6233. // One write-watch asking for the copies that lie close together,
  6234. // not one per copy.
  6235. let ahead = self.refreshes.len() > 1;
  6236. if ahead {
  6237. let started = std::time::Instant::now();
  6238. let ranges: Vec<(usize, usize)> = self
  6239. .refreshes
  6240. .iter()
  6241. .filter(|r| r.0.asked_ahead())
  6242. .map(|r| (r.1, r.2))
  6243. .collect();
  6244. crate::watch::ask_ahead(&ranges);
  6245. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6246. }
  6247. if wide_refresh() && self.refreshes.len() >= 4 {
  6248. // Each copy on its own, several at a time: a copy's refresh
  6249. // writes that copy and reads title memory, nothing of another's.
  6250. // The time counted is the time it took, not the threads' sum.
  6251. let started = std::time::Instant::now();
  6252. let before = PREPARING[0].load(Ordering::Relaxed);
  6253. #[cfg(feature = "diagnostics")]
  6254. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  6255. if light {
  6256. // A number to a free thread, not a job to each copy.
  6257. let refreshes = std::mem::take(&mut self.refreshes);
  6258. crate::shadow::wide_each(refreshes.len(), move |i| {
  6259. let (shadow, from, to) = &refreshes[i];
  6260. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  6261. #[cfg(feature = "diagnostics")]
  6262. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  6263. return;
  6264. }
  6265. Self::update(shadow, *from, *to);
  6266. });
  6267. } else {
  6268. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  6269. .refreshes
  6270. .drain(..)
  6271. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  6272. .collect();
  6273. crate::shadow::wide_run(jobs);
  6274. }
  6275. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6276. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6277. } else {
  6278. for (shadow, from, to) in self.refreshes.drain(..) {
  6279. Self::update(&shadow, from, to);
  6280. }
  6281. }
  6282. if ahead {
  6283. crate::watch::ask_ahead_done();
  6284. }
  6285. }
  6286. }
  6287. /// Copies title memory at submission. The ranges were checked against their
  6288. /// resources when recorded, but the title may since have unmapped pages of
  6289. /// them (tiled memory, page mappings), which read as zeros here; a title
  6290. /// destination (`title_dst`) that is not all mapped is left alone.
  6291. ///
  6292. /// The source is read through the kernel (`ReadProcessMemory`), which
  6293. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  6294. /// cost about 2 ms per copy in the title's big pools (it walks the page
  6295. /// tables to the region's end), which made copies run at 100-200 MB/s.
  6296. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  6297. #[cfg(feature = "diagnostics")]
  6298. match crate::copystat::mode() {
  6299. 1 => {
  6300. // SAFETY: timing only: the caller vouches for the source.
  6301. unsafe { std::ptr::copy(src, dst, len) };
  6302. return;
  6303. }
  6304. 2 => return,
  6305. _ => {}
  6306. }
  6307. if len == 0 {
  6308. return;
  6309. }
  6310. // A title destination that is not all mapped is left alone. Asking
  6311. // Windows first (`VirtualQuery`) walks the page tables to the end of
  6312. // the destination's region: in the title's big blocks that is
  6313. // milliseconds a copy, and it was a seventh of the submitting thread's
  6314. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  6315. // says the same when it fails, so the question is only asked then.
  6316. // `VICTORY_COPY_ASK=1` asks first, as before.
  6317. static ASK: OnceLock<bool> = OnceLock::new();
  6318. let ask_first = title_dst
  6319. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  6320. if ask_first && !crate::texture::committed(dst, len) {
  6321. return;
  6322. }
  6323. if title_dst {
  6324. // The kernel writes the destination: it must not be guarded.
  6325. crate::watch::writing(dst as usize, len);
  6326. }
  6327. #[cfg(feature = "diagnostics")]
  6328. let moved = std::time::Instant::now();
  6329. let whole = read(src, dst, len);
  6330. #[cfg(feature = "diagnostics")]
  6331. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  6332. if whole {
  6333. return;
  6334. }
  6335. // The copy failed: a source page is not there, or the destination is
  6336. // not all mapped. Then the destination stays as it is (the kernel may
  6337. // have written its first pages).
  6338. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  6339. return;
  6340. }
  6341. #[cfg(feature = "diagnostics")]
  6342. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  6343. #[cfg(feature = "diagnostics")]
  6344. let sparse = std::time::Instant::now();
  6345. if !title_dst && len >= 64 << 10 {
  6346. read_sparse(src, dst, len);
  6347. } else {
  6348. read_pieces(src, dst, len);
  6349. }
  6350. #[cfg(feature = "diagnostics")]
  6351. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  6352. }
  6353. /// After a failed bulk read into host memory, skip contiguous holes. Never
  6354. /// cache the query across copies: the title may remap the same address.
  6355. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  6356. use windows_sys::Win32::System::Memory::{
  6357. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  6358. };
  6359. let mut offset = 0;
  6360. while offset < len {
  6361. let at = src.wrapping_add(offset);
  6362. let to = dst.wrapping_add(offset);
  6363. let remaining = len - offset;
  6364. // SAFETY: the query inspects an address and fills a local structure.
  6365. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  6366. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  6367. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  6368. .saturating_sub(at as usize).min(remaining);
  6369. if size != size_of_val(&info) || n == 0 {
  6370. read_pieces(at, to, remaining);
  6371. break;
  6372. }
  6373. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  6374. #[cfg(feature = "diagnostics")]
  6375. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6376. // SAFETY: this path is only used with a writable host destination.
  6377. unsafe { to.write_bytes(0, n) };
  6378. } else if !read(at, to, n) {
  6379. // A mapping may change between query and read.
  6380. read_pieces(at, to, n);
  6381. }
  6382. offset += n;
  6383. }
  6384. }
  6385. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  6386. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  6387. // that fails), zeros for what cannot be read.
  6388. for_pieces(src as usize, len, 64 << 10, |at, n| {
  6389. let to = dst.wrapping_add(at - src as usize);
  6390. if !read(at as *const u8, to, n) {
  6391. for_pieces(at, n, 4 << 10, |at, n| {
  6392. let to = dst.wrapping_add(at - src as usize);
  6393. if !read(at as *const u8, to, n) {
  6394. #[cfg(feature = "diagnostics")]
  6395. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6396. // SAFETY: inside the destination, which is mapped.
  6397. unsafe { to.write_bytes(0, n) };
  6398. }
  6399. });
  6400. }
  6401. });
  6402. }
  6403. /// Reads title memory at `src` into `dst`; false if a page of it is not
  6404. /// readable.
  6405. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  6406. read(src, dst.as_mut_ptr(), dst.len())
  6407. }
  6408. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  6409. /// readable.
  6410. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  6411. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  6412. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6413. if crate::safecopy::on() {
  6414. // SAFETY: the destination is mapped writable memory of `len` bytes;
  6415. // a source page that is not there fails the copy.
  6416. return unsafe { crate::safecopy::copy(dst, src, len) };
  6417. }
  6418. let mut done = 0;
  6419. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  6420. // kernel checks the source.
  6421. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  6422. }
  6423. #[link(name = "ntdll", kind = "raw-dylib")]
  6424. unsafe extern "system" {
  6425. /// The kernel's write into a process's memory, `(process, address,
  6426. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  6427. /// the range is not there or not writable. It changes no protection.
  6428. fn NtWriteVirtualMemory(
  6429. process: *mut std::ffi::c_void,
  6430. base: *mut std::ffi::c_void,
  6431. buffer: *const std::ffi::c_void,
  6432. size: usize,
  6433. written: *mut usize,
  6434. ) -> i32;
  6435. }
  6436. /// Whether title memory is written with the kernel's own call
  6437. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  6438. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  6439. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  6440. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  6441. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  6442. fn direct_writes() -> bool {
  6443. static ON: OnceLock<bool> = OnceLock::new();
  6444. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  6445. }
  6446. /// Copies host memory into title memory after a submission (what shaders
  6447. /// wrote), leaving pages that are not mapped alone.
  6448. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  6449. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  6450. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6451. let direct = direct_writes();
  6452. let write = |at: usize, n: usize| {
  6453. let from = src.wrapping_add(at - dst as usize);
  6454. if crate::safecopy::on() {
  6455. // SAFETY: the source is ours; a destination page that is not
  6456. // there, or not writable, fails the copy.
  6457. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  6458. }
  6459. let mut done = 0;
  6460. if direct {
  6461. // SAFETY: as below; the kernel checks the destination and
  6462. // writes nothing it cannot (the caller opened its guards:
  6463. // `crate::watch::writing`).
  6464. return unsafe {
  6465. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  6466. };
  6467. }
  6468. // SAFETY: the source is our mapped host copy; the kernel checks the
  6469. // destination.
  6470. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  6471. };
  6472. if len == 0 || write(dst as usize, len) {
  6473. return;
  6474. }
  6475. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  6476. if !write(at, n) {
  6477. for_pieces(at, n, 4 << 10, |at, n| {
  6478. write(at, n);
  6479. });
  6480. }
  6481. });
  6482. }
  6483. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  6484. /// `step`.
  6485. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  6486. let end = start + len;
  6487. let mut at = start;
  6488. while at < end {
  6489. let next = ((at / step + 1) * step).min(end);
  6490. f(at, next - at);
  6491. at = next;
  6492. }
  6493. }
  6494. impl Host {
  6495. /// A buffer in the upload heap, mapped for writing.
  6496. /// A buffer of `size` bytes the card writes and we read (a read back),
  6497. /// in the state copies into it need.
  6498. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  6499. let heap = D3D12_HEAP_PROPERTIES {
  6500. Type: D3D12_HEAP_TYPE_READBACK,
  6501. ..Default::default()
  6502. };
  6503. let desc = D3D12_RESOURCE_DESC {
  6504. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6505. Width: size.max(1),
  6506. Height: 1,
  6507. DepthOrArraySize: 1,
  6508. MipLevels: 1,
  6509. SampleDesc: DXGI_SAMPLE_DESC {
  6510. Count: 1,
  6511. Quality: 0,
  6512. },
  6513. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6514. ..Default::default()
  6515. };
  6516. let mut buffer: Option<ID3D12Resource> = None;
  6517. // SAFETY: plain creation of a read-back buffer.
  6518. let made = unsafe {
  6519. self.device.CreateCommittedResource(
  6520. &heap,
  6521. D3D12_HEAP_FLAG_NONE,
  6522. &desc,
  6523. D3D12_RESOURCE_STATE_COPY_DEST,
  6524. None,
  6525. &mut buffer,
  6526. )
  6527. };
  6528. match made {
  6529. Ok(()) => buffer,
  6530. Err(e) => {
  6531. tracing::warn!(error = %e, size, "no read-back buffer");
  6532. None
  6533. }
  6534. }
  6535. }
  6536. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6537. MADE[0].fetch_add(1, Ordering::Relaxed);
  6538. MADE[1].fetch_add(size, Ordering::Relaxed);
  6539. let heap = D3D12_HEAP_PROPERTIES {
  6540. Type: D3D12_HEAP_TYPE_UPLOAD,
  6541. ..Default::default()
  6542. };
  6543. let desc = D3D12_RESOURCE_DESC {
  6544. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6545. Width: size.max(1),
  6546. Height: 1,
  6547. DepthOrArraySize: 1,
  6548. MipLevels: 1,
  6549. SampleDesc: DXGI_SAMPLE_DESC {
  6550. Count: 1,
  6551. Quality: 0,
  6552. },
  6553. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6554. ..Default::default()
  6555. };
  6556. let mut buffer: Option<ID3D12Resource> = None;
  6557. let mut data = std::ptr::null_mut();
  6558. // SAFETY: plain creation and mapping of an upload buffer.
  6559. let made = unsafe {
  6560. self.device
  6561. .CreateCommittedResource(
  6562. &heap,
  6563. D3D12_HEAP_FLAG_NONE,
  6564. &desc,
  6565. D3D12_RESOURCE_STATE_GENERIC_READ,
  6566. None,
  6567. &mut buffer,
  6568. )
  6569. .and_then(|()| {
  6570. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  6571. b.Map(0, None, Some(&mut data))
  6572. })
  6573. };
  6574. match made {
  6575. Ok(()) => Some((buffer?, data.cast())),
  6576. Err(e) => {
  6577. tracing::warn!(error = %e, size, "no upload buffer");
  6578. None
  6579. }
  6580. }
  6581. }
  6582. }
  6583. /// The swap chain formats a presented texture can be copied into: its own
  6584. /// family's.
  6585. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  6586. Some(match format.0 {
  6587. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  6588. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  6589. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  6590. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  6591. _ => return None,
  6592. })
  6593. }
  6594. const BUFFERS: u32 = 2;
  6595. struct Presenter {
  6596. swap_chain: IDXGISwapChain3,
  6597. width: u32,
  6598. height: u32,
  6599. format: DXGI_FORMAT,
  6600. copy: HostList,
  6601. /// With presents sent ahead ([`late_free_present`]): a list for each
  6602. /// present in the air, and the submission it last flew as (it is used
  6603. /// again once that one has finished).
  6604. ahead: Vec<(HostList, u64)>,
  6605. hwnd: HWND,
  6606. meter: Meter,
  6607. }
  6608. /// The frame rate, shown in the window's caption every second and logged
  6609. /// every few seconds.
  6610. struct Meter {
  6611. since: std::time::Instant,
  6612. frames: u32,
  6613. #[cfg(feature = "diagnostics")]
  6614. copy_stats_frames: u64,
  6615. drawn: u64,
  6616. logged: std::time::Instant,
  6617. /// The caption the window had, once read.
  6618. caption: Option<Vec<u16>>,
  6619. }
  6620. impl Meter {
  6621. fn new() -> Self {
  6622. let now = std::time::Instant::now();
  6623. Meter {
  6624. since: now,
  6625. frames: 0,
  6626. #[cfg(feature = "diagnostics")]
  6627. copy_stats_frames: 0,
  6628. drawn: crate::draw::drawn(),
  6629. logged: now,
  6630. caption: None,
  6631. }
  6632. }
  6633. /// Counts a presented frame.
  6634. fn frame(&mut self, hwnd: HWND) {
  6635. #[cfg(feature = "diagnostics")]
  6636. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  6637. #[cfg(feature = "diagnostics")]
  6638. crate::copystat::presented();
  6639. self.frames += 1;
  6640. #[cfg(feature = "diagnostics")]
  6641. {
  6642. self.copy_stats_frames += 1;
  6643. }
  6644. let elapsed = self.since.elapsed();
  6645. if elapsed < std::time::Duration::from_secs(1) {
  6646. return;
  6647. }
  6648. let drawn = crate::draw::drawn();
  6649. let frames = f64::from(self.frames);
  6650. let fps = frames / elapsed.as_secs_f64();
  6651. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  6652. let draws = (drawn - self.drawn) as f64 / frames;
  6653. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  6654. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  6655. let [cpu, gpu] = [0, 1].map(|i| {
  6656. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  6657. });
  6658. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  6659. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  6660. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  6661. });
  6662. let [back_ms, back_mb] = [0, 1].map(|i| {
  6663. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  6664. });
  6665. let dropped = crate::draw::take_dropped() as f64 / frames;
  6666. let indirect = crate::list::take_indirect() as f64 / frames;
  6667. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  6668. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  6669. tracing::info!(
  6670. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  6671. );
  6672. late_line(frames);
  6673. card_clock_line(frames, ms);
  6674. crate::shadow::back_line(frames);
  6675. #[cfg(feature = "diagnostics")]
  6676. split_line(frames);
  6677. {
  6678. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6679. if passes + compares > 0.0 {
  6680. tracing::info!(
  6681. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  6682. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  6683. if rehash_runs() { "on" } else { "off" }
  6684. );
  6685. }
  6686. }
  6687. {
  6688. let [own, asking, still, all] =
  6689. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  6690. if all >= 1.0 {
  6691. tracing::info!(
  6692. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  6693. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  6694. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  6695. );
  6696. }
  6697. let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6698. if through + left > 0.0 {
  6699. tracing::info!(
  6700. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  6701. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there)"
  6702. );
  6703. }
  6704. }
  6705. {
  6706. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6707. if copies > 0.0 {
  6708. tracing::info!(
  6709. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  6710. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  6711. if join_copies() { "on" } else { "off" }
  6712. );
  6713. }
  6714. }
  6715. // Passes over the heap's buffer views for shaders that pick them by index.
  6716. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  6717. let picked_ms =
  6718. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  6719. // Copies between depth textures and their colour twins, each way.
  6720. let [twin_to_depth, twin_to_colour] =
  6721. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6722. // Depth planes drawn from their twins.
  6723. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  6724. // Copies in the card's memory (`crate::shadow::cards`).
  6725. let card = crate::shadow::card_stats();
  6726. #[cfg(feature = "diagnostics")]
  6727. let slow = crate::watch::slow_asks();
  6728. // Over the same frames as the counts above.
  6729. #[cfg(feature = "diagnostics")]
  6730. let drops = crate::pipeline::take_drops();
  6731. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  6732. self.logged = std::time::Instant::now();
  6733. tracing::info!(
  6734. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  6735. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  6736. );
  6737. {
  6738. let [queued, due, away, partly, oldest] =
  6739. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  6740. let [same, parts, tails] =
  6741. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  6742. tracing::info!(
  6743. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  6744. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  6745. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  6746. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  6747. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  6748. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  6749. {} made slots found unmapped and made null",
  6750. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  6751. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  6752. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  6753. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  6754. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  6755. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  6756. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  6757. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  6758. );
  6759. }
  6760. #[cfg(feature = "diagnostics")]
  6761. tracing::info!(
  6762. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  6763. slow[0] as f64 / frames,
  6764. slow[1] as f64 / 1e3 / frames,
  6765. slow[2] as f64 / 1e3
  6766. );
  6767. if crate::shadow::cards() {
  6768. let per_frame = |i: usize| card[i] as f64 / frames;
  6769. tracing::info!(
  6770. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  6771. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  6772. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  6773. card[7],
  6774. card[8] >> 20,
  6775. card[9] >> 20,
  6776. per_frame(0) / 1e6,
  6777. per_frame(1),
  6778. per_frame(2),
  6779. per_frame(3),
  6780. per_frame(4) / 1e6,
  6781. per_frame(5),
  6782. per_frame(6) / 1e3
  6783. );
  6784. }
  6785. tracing::info!(
  6786. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  6787. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  6788. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  6789. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  6790. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  6791. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  6792. {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}",
  6793. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  6794. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  6795. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  6796. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  6797. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  6798. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  6799. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  6800. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  6801. refused = format!(
  6802. "{}; 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",
  6803. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  6804. crate::resource::TWINS[0].load(Ordering::Relaxed),
  6805. crate::resource::TWINS[1].load(Ordering::Relaxed),
  6806. crate::resource::PLANES[1].load(Ordering::Relaxed),
  6807. crate::resource::PLANES[2].load(Ordering::Relaxed)
  6808. ),
  6809. making = crate::pipeline::making(),
  6810. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  6811. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  6812. );
  6813. #[cfg(feature = "diagnostics")]
  6814. {
  6815. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6816. tracing::info!(
  6817. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  6818. put[0],
  6819. put[1],
  6820. put[2] / 1e6,
  6821. put[3]
  6822. );
  6823. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  6824. for (why, n) in drops.iter().take(40) {
  6825. tracing::info!(
  6826. "dropped {:.1}/frame without a host pipeline: {why}",
  6827. *n as f64 / frames
  6828. );
  6829. }
  6830. }
  6831. }
  6832. if self.caption.is_none() {
  6833. // The window's own text, read without a message.
  6834. let mut buffer = vec![0u16; 512];
  6835. // SAFETY: a window handle and a buffer of that length.
  6836. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  6837. buffer.truncate(n.max(0) as usize);
  6838. self.caption = Some(buffer);
  6839. }
  6840. let Some(caption) = &self.caption else { return };
  6841. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  6842. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  6843. text.push(0);
  6844. // Setting the text waits for the window's thread (a title thread,
  6845. // which may not pump for a while), so a thread of ours does it and
  6846. // presenting never waits; it takes the newest text when free.
  6847. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  6848. static SETTER: std::sync::Once = std::sync::Once::new();
  6849. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  6850. SETTER.call_once(|| {
  6851. let _ = std::thread::Builder::new()
  6852. .name("victory-caption".into())
  6853. .spawn(|| {
  6854. loop {
  6855. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  6856. match next {
  6857. // SAFETY: a window handle and a NUL-terminated text.
  6858. Some((hwnd, text)) => unsafe {
  6859. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  6860. },
  6861. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  6862. }
  6863. }
  6864. });
  6865. });
  6866. }
  6867. }
  6868. impl Host {
  6869. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  6870. /// as frame `frame` (saved if captures are on). `None` if nothing was
  6871. /// shown; else, in diagnostics builds, whether the frame was black.
  6872. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  6873. // SAFETY: a live resource.
  6874. let desc = unsafe { texture.GetDesc() };
  6875. let Some(format) = swap_format(desc.Format) else {
  6876. tracing::warn!(format = desc.Format.0, "cannot present this format");
  6877. return None;
  6878. };
  6879. let (width, height) = (desc.Width as u32, desc.Height);
  6880. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  6881. if presenter.is_none() {
  6882. *presenter = match self.presenter(width, height, format) {
  6883. Ok(p) => Some(p),
  6884. Err(e) => {
  6885. tracing::warn!(error = %e, "no swap chain");
  6886. return None;
  6887. }
  6888. };
  6889. }
  6890. let p = presenter.as_mut()?;
  6891. if (p.width, p.height, p.format) != (width, height, format) {
  6892. // Presents sent ahead hold back buffers until they have run.
  6893. settle_now(WHY_SYNC);
  6894. // SAFETY: no back buffer is held; every submission was waited for.
  6895. let resized = unsafe {
  6896. p.swap_chain
  6897. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  6898. };
  6899. match resized {
  6900. Ok(()) => {
  6901. (p.width, p.height, p.format) = (width, height, format);
  6902. tracing::info!(
  6903. width,
  6904. height,
  6905. format = format.0,
  6906. frame,
  6907. "the swap chain's buffers were made again for another size or format"
  6908. );
  6909. self.log_video_memory("right after the swap chain's buffers were made again");
  6910. }
  6911. Err(e) => {
  6912. tracing::warn!(error = %e, width, height, "swap chain not resized");
  6913. return None;
  6914. }
  6915. }
  6916. }
  6917. let state = D3D12_RESOURCE_STATES(state as i32);
  6918. // SAFETY: our swap chain, list and a live source texture.
  6919. unsafe {
  6920. let index = p.swap_chain.GetCurrentBackBufferIndex();
  6921. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  6922. return None;
  6923. };
  6924. // Sent ahead ([`late_free_present`]) unless the frame is to be
  6925. // read back at once (a saved or listed frame): then a list of
  6926. // its own, one whose last flight has finished or a new one.
  6927. #[cfg(feature = "diagnostics")]
  6928. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  6929. #[cfg(not(feature = "diagnostics"))]
  6930. let read_now = false;
  6931. let slot = if late_free_present() && !read_now {
  6932. let finished = FINISHED.load(Ordering::Acquire);
  6933. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  6934. let list = self.new_list().ok()?;
  6935. list.close();
  6936. p.ahead.push((list, 0));
  6937. Some(p.ahead.len() - 1)
  6938. })
  6939. } else {
  6940. None
  6941. };
  6942. let copy = match slot {
  6943. Some(i) => &p.ahead[i].0,
  6944. None => &p.copy,
  6945. };
  6946. copy.reset();
  6947. let list = &copy.list;
  6948. list.ResourceBarrier(&[
  6949. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  6950. transition(
  6951. &back,
  6952. D3D12_RESOURCE_STATE_PRESENT,
  6953. D3D12_RESOURCE_STATE_COPY_DEST,
  6954. ),
  6955. ]);
  6956. list.CopyResource(&back, texture);
  6957. #[cfg(feature = "diagnostics")]
  6958. let capture = crate::capture::wanted(frame)
  6959. .then(|| crate::capture::read_back(&self.device, list, texture))
  6960. .flatten();
  6961. #[cfg(feature = "diagnostics")]
  6962. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  6963. #[cfg(not(feature = "diagnostics"))]
  6964. let _ = frame;
  6965. list.ResourceBarrier(&[
  6966. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  6967. transition(
  6968. &back,
  6969. D3D12_RESOURCE_STATE_COPY_DEST,
  6970. D3D12_RESOURCE_STATE_PRESENT,
  6971. ),
  6972. ]);
  6973. copy.close();
  6974. match slot {
  6975. Some(i) => {
  6976. let flown = self.execute_own(copy);
  6977. p.ahead[i].1 = flown;
  6978. }
  6979. None => self.execute(&[copy]),
  6980. }
  6981. #[cfg(feature = "diagnostics")]
  6982. if let Some((buffer, footprint)) = capture {
  6983. crate::capture::save_read_back(frame, &buffer, &footprint);
  6984. }
  6985. #[cfg(feature = "diagnostics")]
  6986. crate::replay::record::present(texture, state);
  6987. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  6988. p.meter.frame(p.hwnd);
  6989. #[cfg(feature = "diagnostics")]
  6990. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  6991. #[cfg(not(feature = "diagnostics"))]
  6992. Some(false)
  6993. }
  6994. }
  6995. fn presenter(
  6996. &self,
  6997. width: u32,
  6998. height: u32,
  6999. format: DXGI_FORMAT,
  7000. ) -> windows::core::Result<Presenter> {
  7001. let hwnd = match title_window() {
  7002. Some(hwnd) => hwnd,
  7003. None => window(width, height)?,
  7004. };
  7005. self.log_video_memory("right before the swap chain is made");
  7006. // SAFETY: plain object creation for our window.
  7007. unsafe {
  7008. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  7009. let desc = DXGI_SWAP_CHAIN_DESC1 {
  7010. Width: width,
  7011. Height: height,
  7012. Format: format,
  7013. SampleDesc: DXGI_SAMPLE_DESC {
  7014. Count: 1,
  7015. Quality: 0,
  7016. },
  7017. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  7018. BufferCount: BUFFERS,
  7019. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  7020. ..Default::default()
  7021. };
  7022. let swap_chain = factory
  7023. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  7024. .cast::<IDXGISwapChain3>()?;
  7025. let copy = self.new_list()?;
  7026. copy.close();
  7027. tracing::info!(width, height, format = format.0, "presenting to a window");
  7028. self.log_video_memory("right after the swap chain is made");
  7029. Ok(Presenter {
  7030. swap_chain,
  7031. width,
  7032. height,
  7033. format,
  7034. copy,
  7035. ahead: Vec::new(),
  7036. hwnd,
  7037. meter: Meter::new(),
  7038. })
  7039. }
  7040. }
  7041. }
  7042. /// A visible top-level window of this process: the one the title made, if
  7043. /// it made one.
  7044. fn title_window() -> Option<HWND> {
  7045. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  7046. let mut process = 0;
  7047. // SAFETY: a window handle from the enumeration; `found` is ours.
  7048. unsafe {
  7049. GetWindowThreadProcessId(hwnd, Some(&mut process));
  7050. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  7051. && IsWindowVisible(hwnd).as_bool()
  7052. {
  7053. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  7054. return false.into();
  7055. }
  7056. }
  7057. true.into()
  7058. }
  7059. let mut found: Option<HWND> = None;
  7060. // SAFETY: the callback only writes `found`, which outlives the call.
  7061. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  7062. found
  7063. }
  7064. /// `state` without the bits the host texture's flags forbid: the console
  7065. /// lets the title name states its own resources allow (unordered access on
  7066. /// a depth target, whose host copy cannot have both).
  7067. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  7068. // SAFETY: a plain query.
  7069. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  7070. }
  7071. /// [`legal_state`] for a texture with resource flags `flags`.
  7072. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  7073. // (flag, set or clear forbids, state bits): render target, unordered
  7074. // access, depth, denied shader resource.
  7075. const FORBIDDEN: [(u32, bool, u32); 4] = [
  7076. (0x1, false, 0x4),
  7077. (0x4, false, 0x8),
  7078. (0x2, false, 0x10 | 0x20),
  7079. (0x8, true, 0x40 | 0x80),
  7080. ];
  7081. FORBIDDEN
  7082. .iter()
  7083. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  7084. .fold(state, |s, &(_, _, bits)| s & !bits)
  7085. }
  7086. impl Host {
  7087. /// The card's memory as the system accounts it to this process, in
  7088. /// bytes: the budget and the use of the card's own memory, then of the
  7089. /// PC's memory shared with the card (where the system moves what does
  7090. /// not fit on the card).
  7091. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  7092. let adapter = self.adapter.as_ref()?;
  7093. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7094. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7095. // SAFETY: plain queries that fill our structures.
  7096. unsafe {
  7097. adapter
  7098. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7099. .ok()?;
  7100. adapter
  7101. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7102. .ok()?;
  7103. }
  7104. // The card's budget moved by 256 MB or more since the last look:
  7105. // said at once, with what was in use at the last look, so the log
  7106. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  7107. // the first world frame in runs 179 to 185, and the memory line,
  7108. // seconds later, was the first to show it. We reserve nothing
  7109. // and make the swap chain once, at the start.)
  7110. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  7111. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  7112. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  7113. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  7114. tracing::info!(
  7115. "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",
  7116. last[0] >> 20,
  7117. own.Budget >> 20,
  7118. crate::frame::current(),
  7119. last[1] >> 20,
  7120. last[2] >> 20
  7121. );
  7122. self.log_video_memory("right after that change");
  7123. }
  7124. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  7125. }
  7126. /// Both of the system's memory groups for this process, in bytes: for
  7127. /// the card's own memory and then for the PC's memory shared with the
  7128. /// card, the budget, the use, what could still be reserved and what
  7129. /// is reserved (the layer reserves none).
  7130. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  7131. let adapter = self.adapter.as_ref()?;
  7132. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7133. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7134. // SAFETY: plain queries that fill our structures.
  7135. unsafe {
  7136. adapter
  7137. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7138. .ok()?;
  7139. adapter
  7140. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7141. .ok()?;
  7142. }
  7143. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  7144. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  7145. };
  7146. Some([all(&own), all(&shared)])
  7147. }
  7148. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  7149. pub(crate) fn log_video_memory(&self, when: &str) {
  7150. let Some([own, shared]) = self.video_memory_groups() else {
  7151. return;
  7152. };
  7153. tracing::info!(
  7154. "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)",
  7155. when,
  7156. own[0] >> 20,
  7157. own[1] >> 20,
  7158. own[2] >> 20,
  7159. own[3] >> 20,
  7160. shared[0] >> 20,
  7161. shared[1] >> 20,
  7162. shared[2] >> 20,
  7163. shared[3] >> 20
  7164. );
  7165. }
  7166. /// A buffer in system memory that the CPU maps (write-back, so reading
  7167. /// it is fast too) and shaders read and write: for host copies of title
  7168. /// memory that shaders write, which upload memory cannot be. Starts in
  7169. /// the common state (buffers move out of it implicitly).
  7170. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7171. MADE[2].fetch_add(1, Ordering::Relaxed);
  7172. MADE[3].fetch_add(size, Ordering::Relaxed);
  7173. let heap = D3D12_HEAP_PROPERTIES {
  7174. Type: D3D12_HEAP_TYPE_CUSTOM,
  7175. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  7176. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  7177. ..Default::default()
  7178. };
  7179. let desc = D3D12_RESOURCE_DESC {
  7180. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7181. Width: size.max(1),
  7182. Height: 1,
  7183. DepthOrArraySize: 1,
  7184. MipLevels: 1,
  7185. SampleDesc: DXGI_SAMPLE_DESC {
  7186. Count: 1,
  7187. Quality: 0,
  7188. },
  7189. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7190. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7191. ..Default::default()
  7192. };
  7193. let mut buffer: Option<ID3D12Resource> = None;
  7194. let mut data = std::ptr::null_mut();
  7195. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7196. let made = unsafe {
  7197. self.device
  7198. .CreateCommittedResource(
  7199. &heap,
  7200. D3D12_HEAP_FLAG_NONE,
  7201. &desc,
  7202. D3D12_RESOURCE_STATE_COMMON,
  7203. None,
  7204. &mut buffer,
  7205. )
  7206. .and_then(|()| {
  7207. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7208. b.Map(0, None, Some(&mut data))
  7209. })
  7210. };
  7211. match made {
  7212. Ok(()) => Some((buffer?, data.cast())),
  7213. Err(e) => {
  7214. tracing::warn!(error = %e, size, "no shared buffer");
  7215. None
  7216. }
  7217. }
  7218. }
  7219. /// A device-local buffer shaders may write (unordered access) and indirect
  7220. /// execution may read, starting in the common state.
  7221. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7222. MADE[4].fetch_add(1, Ordering::Relaxed);
  7223. MADE[5].fetch_add(size, Ordering::Relaxed);
  7224. let heap = D3D12_HEAP_PROPERTIES {
  7225. Type: D3D12_HEAP_TYPE_DEFAULT,
  7226. ..Default::default()
  7227. };
  7228. let desc = D3D12_RESOURCE_DESC {
  7229. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7230. Width: size.max(1),
  7231. Height: 1,
  7232. DepthOrArraySize: 1,
  7233. MipLevels: 1,
  7234. SampleDesc: DXGI_SAMPLE_DESC {
  7235. Count: 1,
  7236. Quality: 0,
  7237. },
  7238. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7239. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7240. ..Default::default()
  7241. };
  7242. let mut buffer: Option<ID3D12Resource> = None;
  7243. // SAFETY: plain creation of a device-local buffer.
  7244. let made = unsafe {
  7245. self.device.CreateCommittedResource(
  7246. &heap,
  7247. D3D12_HEAP_FLAG_NONE,
  7248. &desc,
  7249. D3D12_RESOURCE_STATE_COMMON,
  7250. None,
  7251. &mut buffer,
  7252. )
  7253. };
  7254. match made {
  7255. Ok(()) => buffer,
  7256. Err(e) => {
  7257. tracing::warn!(error = %e, size, "no unordered-access buffer");
  7258. None
  7259. }
  7260. }
  7261. }
  7262. }
  7263. /// For adapters without device-removed data (the software one): the last
  7264. /// commands each list of the failed submission noted (diagnostics, with
  7265. /// `VICTORY_D3D12_DRED`).
  7266. fn last_notes(runs: &[&HostList]) -> String {
  7267. #[cfg(feature = "diagnostics")]
  7268. {
  7269. let mut text = String::new();
  7270. for (i, r) in runs.iter().enumerate() {
  7271. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  7272. for (n, _) in notes.iter().rev().take(6).rev() {
  7273. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  7274. }
  7275. }
  7276. text
  7277. }
  7278. #[cfg(not(feature = "diagnostics"))]
  7279. {
  7280. let _ = runs;
  7281. String::new()
  7282. }
  7283. }
  7284. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  7285. /// command reads (diagnostics).
  7286. #[cfg(feature = "diagnostics")]
  7287. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  7288. let end = start + bytes;
  7289. if va < start {
  7290. format!(" (fault {:#x} below its source)", start - va)
  7291. } else if va < end {
  7292. format!(" (fault at source +{:#x})", va - start)
  7293. } else {
  7294. format!(" (fault {:#x} past its source's end)", va - end)
  7295. }
  7296. }
  7297. /// The commands that may have been running where a list stopped at
  7298. /// command `done`: those between the barriers around it (work between
  7299. /// barriers overlaps on the GPU), by kind, and what the markers just
  7300. /// before them say (`HostList::note_op`: diagnostics builds with
  7301. /// device-removed data on).
  7302. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  7303. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  7304. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  7305. let to = history[done..]
  7306. .iter()
  7307. .position(barrier)
  7308. .map_or(history.len(), |b| (done + b).max(done + 1));
  7309. let mut text = format!(", commands {from}..{to} between its barriers:");
  7310. let mut shown = 0;
  7311. // From just before the command the GPU had not finished: the first
  7312. // twelve after the barrier named draws long done when a list of 79
  7313. // mesh draws stopped at its 45th (run 41).
  7314. for i in from.max(done.saturating_sub(4))..to {
  7315. let op = history[i];
  7316. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  7317. continue;
  7318. }
  7319. shown += 1;
  7320. let marker = i
  7321. .checked_sub(1)
  7322. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  7323. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  7324. .map_or("no marker", |(_, s)| s.as_str());
  7325. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  7326. }
  7327. text
  7328. }
  7329. pub(crate) fn transition(
  7330. resource: &ID3D12Resource,
  7331. before: D3D12_RESOURCE_STATES,
  7332. after: D3D12_RESOURCE_STATES,
  7333. ) -> D3D12_RESOURCE_BARRIER {
  7334. D3D12_RESOURCE_BARRIER {
  7335. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  7336. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  7337. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  7338. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  7339. // SAFETY: a borrowed pointer; the barrier never releases it.
  7340. pResource: unsafe { std::mem::transmute_copy(resource) },
  7341. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  7342. StateBefore: before,
  7343. StateAfter: after,
  7344. }),
  7345. },
  7346. }
  7347. }
  7348. /// A window of the given client size, owned by its own message thread.
  7349. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7350. let (sender, receiver) = std::sync::mpsc::channel();
  7351. std::thread::Builder::new()
  7352. .name("victory-window".into())
  7353. .spawn(move || {
  7354. let made = make_window(width, height);
  7355. let ok = made.is_ok();
  7356. let _ = sender.send(made.map(|h| h.0 as usize));
  7357. if ok {
  7358. pump();
  7359. }
  7360. })
  7361. .map_err(|_| windows::core::Error::empty())?;
  7362. let hwnd = receiver
  7363. .recv()
  7364. .map_err(|_| windows::core::Error::empty())??;
  7365. Ok(HWND(hwnd as *mut _))
  7366. }
  7367. extern "system" fn window_proc(
  7368. hwnd: HWND,
  7369. message: u32,
  7370. wparam: WPARAM,
  7371. lparam: LPARAM,
  7372. ) -> LRESULT {
  7373. // SAFETY: the default handling for our window.
  7374. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  7375. }
  7376. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7377. const CLASS: PCWSTR = w!("VIctory");
  7378. // SAFETY: registers our class once and creates a window of it.
  7379. unsafe {
  7380. let instance = GetModuleHandleW(None)?;
  7381. let class = WNDCLASSEXW {
  7382. cbSize: size_of::<WNDCLASSEXW>() as u32,
  7383. lpfnWndProc: Some(window_proc),
  7384. hInstance: instance.into(),
  7385. lpszClassName: CLASS,
  7386. hCursor: LoadCursorW(None, IDC_ARROW)?,
  7387. ..Default::default()
  7388. };
  7389. RegisterClassExW(&class);
  7390. let mut rect = RECT {
  7391. left: 0,
  7392. top: 0,
  7393. right: width as i32,
  7394. bottom: height as i32,
  7395. };
  7396. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  7397. CreateWindowExW(
  7398. WINDOW_EX_STYLE(0),
  7399. CLASS,
  7400. w!("VIctory"),
  7401. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  7402. CW_USEDEFAULT,
  7403. CW_USEDEFAULT,
  7404. rect.right - rect.left,
  7405. rect.bottom - rect.top,
  7406. None,
  7407. None,
  7408. Some(instance.into()),
  7409. None,
  7410. )
  7411. }
  7412. }
  7413. fn pump() {
  7414. let mut message = MSG::default();
  7415. // SAFETY: the standard message loop of this thread's window.
  7416. unsafe {
  7417. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  7418. let _ = TranslateMessage(&message);
  7419. DispatchMessageW(&message);
  7420. }
  7421. }
  7422. }
  7423. #[cfg(test)]
  7424. mod trail {
  7425. /// The trail keeps the newest things, and the report made when the
  7426. /// host device is removed says them and the pipeline library's state
  7427. /// (no card is asked for any of it).
  7428. #[test]
  7429. fn the_removal_report_says_the_newest_things_done() {
  7430. for n in 0..super::TRAIL_MOST + 5 {
  7431. super::trail(|| format!("thing {n} done"));
  7432. }
  7433. let text = super::removal_context();
  7434. assert!(text.contains("the submitting thread was"));
  7435. assert!(text.contains("pipeline library: no call running"));
  7436. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  7437. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  7438. }
  7439. }
  7440. #[cfg(test)]
  7441. mod spare {
  7442. use super::Spare;
  7443. /// Kept things come back by size, the last given first, and nothing is
  7444. /// kept past the limit.
  7445. #[test]
  7446. fn kept_things_come_back_by_size_within_the_limit() {
  7447. let mut spare: Spare<u32> = Spare::new();
  7448. assert_eq!(spare.take(4), None);
  7449. assert_eq!(spare.give(1, 4, 10), None);
  7450. assert_eq!(spare.give(2, 1, 10), None);
  7451. assert_eq!(spare.give(3, 4, 10), None);
  7452. assert_eq!(spare.bytes, 9);
  7453. // Past the limit: handed back, nothing changes.
  7454. assert_eq!(spare.give(4, 4, 10), Some(4));
  7455. assert_eq!(spare.bytes, 9);
  7456. assert_eq!(spare.take(2), None, "no thing of that size");
  7457. assert_eq!(spare.take(4), Some(3));
  7458. assert_eq!(spare.take(4), Some(1));
  7459. assert_eq!(spare.take(4), None);
  7460. assert_eq!(spare.take(1), Some(2));
  7461. assert_eq!(spare.bytes, 0);
  7462. assert!(spare.kept.is_empty());
  7463. }
  7464. }
  7465. #[cfg(test)]
  7466. mod refresh_tests {
  7467. use super::Batch;
  7468. use crate::shadow::Shadow;
  7469. use std::sync::Arc;
  7470. use windows_sys::Win32::System::Memory::{
  7471. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  7472. VirtualAlloc,
  7473. };
  7474. const PAGE: usize = 64 << 10;
  7475. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  7476. /// Title memory for the tests (never given back: copies of it stay in
  7477. /// the guards): write-watched, or a view of a section.
  7478. fn title(len: usize, view: bool) -> usize {
  7479. // SAFETY: plain allocations.
  7480. let at = unsafe {
  7481. if view {
  7482. let section =
  7483. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  7484. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  7485. // As the runtime tells of it.
  7486. crate::title_memory_section(section as usize, len as u64, true);
  7487. crate::title_memory_remapped(at, len);
  7488. crate::title_memory_view(at, len, section as usize, 0);
  7489. at
  7490. } else {
  7491. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  7492. }
  7493. };
  7494. assert_ne!(at, 0);
  7495. at
  7496. }
  7497. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  7498. /// and every fourth page not there: as a title that streams has it.
  7499. fn with_holes(blocks: usize) -> usize {
  7500. use windows_sys::Win32::System::Memory::{
  7501. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  7502. VirtualAlloc2, VirtualFree,
  7503. };
  7504. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7505. // SAFETY: a placeholder and a section of our own.
  7506. unsafe {
  7507. let at = VirtualAlloc2(
  7508. GetCurrentProcess(),
  7509. std::ptr::null(),
  7510. blocks * PAGE,
  7511. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  7512. PAGE_NOACCESS,
  7513. std::ptr::null_mut(),
  7514. 0,
  7515. ) as usize;
  7516. assert_ne!(at, 0);
  7517. let len = blocks * PAGE;
  7518. let section =
  7519. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  7520. for block in (0..blocks).filter(|b| b % 4 != 3) {
  7521. let to = at + block * PAGE;
  7522. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  7523. let view = MapViewOfFile3(
  7524. section,
  7525. GetCurrentProcess(),
  7526. to as *const _,
  7527. (block * PAGE) as u64,
  7528. PAGE,
  7529. MEM_REPLACE_PLACEHOLDER,
  7530. PAGE_READWRITE,
  7531. std::ptr::null_mut(),
  7532. 0,
  7533. );
  7534. assert_eq!(view.Value as usize, to);
  7535. crate::title_memory_remapped(to, PAGE);
  7536. }
  7537. at
  7538. }
  7539. }
  7540. fn memory(len: usize) -> *mut u8 {
  7541. // SAFETY: a plain allocation.
  7542. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  7543. }
  7544. struct Random(u64);
  7545. impl Random {
  7546. fn below(&mut self, n: usize) -> usize {
  7547. self.0 ^= self.0 << 13;
  7548. self.0 ^= self.0 >> 7;
  7549. self.0 ^= self.0 << 17;
  7550. (self.0 >> 11) as usize % n
  7551. }
  7552. }
  7553. /// Prepares as a submission does: one asking for all the ranges, the
  7554. /// refreshes in several flushes, the asking's end.
  7555. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  7556. // One at a time, as submissions are.
  7557. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  7558. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  7559. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  7560. crate::watch::ask_once(&asked);
  7561. let mut batch = Batch::default();
  7562. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  7563. for (shadow, at, len) in part {
  7564. batch.add(shadow, *at, *len);
  7565. }
  7566. batch.flush();
  7567. }
  7568. crate::watch::ask_once_end();
  7569. }
  7570. /// Whatever is written where, by the title or by us, and whichever
  7571. /// copies (of both kinds of memory, over one another, none on a page
  7572. /// line) are refreshed in which ranges: a refreshed range holds what
  7573. /// title memory holds.
  7574. #[test]
  7575. fn refreshed_ranges_hold_title_memory() {
  7576. // SAFETY (all blocks): title memory and copies of the test's own,
  7577. // written by this thread and, in `Batch::flush`, by the threads that
  7578. // refresh, which are done when it returns.
  7579. let mut random = Random(0x1234_5678_9ABC_DEF1);
  7580. const LEN: usize = 24 * PAGE;
  7581. let regions = [title(LEN, false), title(LEN, true)];
  7582. let mut copies = Vec::new();
  7583. for &region in &regions {
  7584. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  7585. let data = memory(to - from);
  7586. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  7587. }
  7588. }
  7589. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  7590. for round in 0..600 {
  7591. for _ in 0..random.below(4) {
  7592. let at = regions[random.below(2)] + random.below(LEN - 64);
  7593. let n = 1 + random.below(60);
  7594. if random.below(3) == 0 {
  7595. // What shaders wrote.
  7596. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  7597. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  7598. Shadow::put(at, &was, &now);
  7599. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  7600. continue;
  7601. }
  7602. for i in 0..n {
  7603. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  7604. }
  7605. }
  7606. let mut ranges = Vec::new();
  7607. for (shadow, _) in &copies {
  7608. if random.below(3) == 0 {
  7609. continue;
  7610. }
  7611. let (start, len) = shadow.span();
  7612. let (start, len) = (start as usize, len as usize);
  7613. // Often the range of the time before, as a list's is.
  7614. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  7615. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  7616. ranges.push((shadow.clone(), start + from, n));
  7617. }
  7618. if ranges.is_empty() {
  7619. continue;
  7620. }
  7621. let flushes = 1 + random.below(3);
  7622. submission(&ranges, flushes);
  7623. for (shadow, at, n) in &ranges {
  7624. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  7625. let start = shadow.span().0 as usize;
  7626. let same = unsafe {
  7627. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  7628. };
  7629. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  7630. }
  7631. }
  7632. }
  7633. /// A copy in the card's memory, with the card's side and the sends to it
  7634. /// played by the test.
  7635. struct Carded {
  7636. shadow: Arc<Shadow>,
  7637. data: usize,
  7638. start: usize,
  7639. len: usize,
  7640. /// The last send, the last send every fetch to come is behind, and
  7641. /// the card's bytes: the queue's order is the order it is locked in.
  7642. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  7643. /// Whether a flight that writes it has not landed.
  7644. flying: std::sync::atomic::AtomicBool,
  7645. /// The dword of each eight its shaders write.
  7646. class: usize,
  7647. }
  7648. impl Carded {
  7649. fn new(start: usize, len: usize, class: usize) -> Carded {
  7650. let data = memory(len);
  7651. Carded {
  7652. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  7653. data: data as usize,
  7654. start,
  7655. len,
  7656. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  7657. flying: std::sync::atomic::AtomicBool::new(false),
  7658. class,
  7659. }
  7660. }
  7661. /// What changed on the CPU's side goes up.
  7662. fn send(&self) {
  7663. let mut card = self.card.lock().unwrap();
  7664. card.0 += 1;
  7665. let (number, merged) = (card.0, card.1);
  7666. for (a, b) in self.shadow.send_up(number, merged) {
  7667. // SAFETY: the copy's bytes; nothing writes those that are to
  7668. // go up.
  7669. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  7670. }
  7671. }
  7672. }
  7673. /// Everything at once: the title writes its memory on two threads, the
  7674. /// submitting thread puts its bytes in under shader writes
  7675. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  7676. /// the card's memory, one not), sends up what changed and declares what
  7677. /// the next flight's shaders write, and what flights wrote is landed
  7678. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  7679. /// still and the copies are refreshed once more, each of them, and the
  7680. /// card's side of those that have one, hold what title memory holds, and
  7681. /// title memory what was written last.
  7682. ///
  7683. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  7684. /// only takes the block out of the guards' clean ones and leaves its bit,
  7685. /// or if a fault leaves the bit; in some thousand rounds,
  7686. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  7687. #[test]
  7688. fn landings_title_writes_and_light_refreshes_at_once() {
  7689. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  7690. assert!(crate::safecopy::on());
  7691. const LEN: usize = 24 * PAGE;
  7692. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  7693. let region = title(LEN, true);
  7694. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  7695. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  7696. let plain = {
  7697. let (start, len) = (region + 700, LEN - 9000);
  7698. let data = memory(len);
  7699. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  7700. };
  7701. let stop = AtomicBool::new(false);
  7702. // Also when an assertion fails on one of the threads.
  7703. struct Stop<'a>(&'a AtomicBool);
  7704. impl Drop for Stop<'_> {
  7705. fn drop(&mut self) {
  7706. self.0.store(true, Ordering::Relaxed);
  7707. }
  7708. }
  7709. // Held shared by who writes title memory, alone while it is looked at.
  7710. let still = std::sync::RwLock::new(());
  7711. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  7712. std::thread::scope(|s| {
  7713. for t in 0..2usize {
  7714. let (stop, still) = (&stop, &still);
  7715. s.spawn(move || {
  7716. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  7717. let mut value = 0u32;
  7718. while !stop.load(Ordering::Relaxed) {
  7719. {
  7720. let _moving = still.read().unwrap();
  7721. for _ in 0..3 {
  7722. value += 1;
  7723. // Of each eight dwords, one a thread.
  7724. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  7725. dword(at).store(value, Ordering::Relaxed);
  7726. }
  7727. }
  7728. std::thread::sleep(std::time::Duration::from_micros(20));
  7729. }
  7730. });
  7731. }
  7732. // Lands flights.
  7733. {
  7734. let (carded, stop) = (&carded, &stop);
  7735. s.spawn(move || {
  7736. let _stop = Stop(stop);
  7737. while let Ok((which, ranges, value)) = flights.recv() {
  7738. let c = &carded[which];
  7739. // Fetched: the card's bytes, behind every send so far.
  7740. let (after, now) = {
  7741. let card = c.card.lock().unwrap();
  7742. (card.0, card.2.clone())
  7743. };
  7744. // By piece: 64 KiB of title memory.
  7745. let mut pieces = Vec::new();
  7746. for &(from, to) in &ranges {
  7747. let mut at = from;
  7748. while at < to {
  7749. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  7750. pieces.push((at, next, now.as_ptr() as usize + at));
  7751. at = next;
  7752. }
  7753. }
  7754. let parts: Vec<_> = pieces.chunks(3).collect();
  7755. crate::land::each(parts.len(), &|i| {
  7756. let mut notes = crate::land::Notes::default();
  7757. // SAFETY: the bytes of `now`; each piece once.
  7758. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  7759. notes.flush();
  7760. });
  7761. for &(from, to) in &ranges {
  7762. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  7763. // (The next fetch may have brought more.)
  7764. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  7765. }
  7766. }
  7767. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  7768. c.shadow.copy_back_done(&done);
  7769. c.card.lock().unwrap().1 = after;
  7770. c.flying.store(false, Ordering::Release);
  7771. }
  7772. });
  7773. }
  7774. let _stop = Stop(&stop);
  7775. let mut random = Random(0xABCD_EF01_2345_6789);
  7776. let check = |round: usize, random: &mut Random, quiet: bool| {
  7777. for c in &carded {
  7778. if c.shadow.writes_pending() {
  7779. let mut runs = usize::MAX;
  7780. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  7781. }
  7782. }
  7783. let mut ranges = Vec::new();
  7784. for (shadow, start, len) in
  7785. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  7786. {
  7787. // All of it, or a part; often the same part.
  7788. let (from, n) = match random.below(3) {
  7789. _ if quiet => (0, len),
  7790. 0 => (0, len),
  7791. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  7792. _ => {
  7793. let from = random.below(len / 4) * 4;
  7794. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  7795. }
  7796. };
  7797. ranges.push((shadow.clone(), start + from, n));
  7798. }
  7799. submission(&ranges, 1 + random.below(3));
  7800. carded.iter().for_each(Carded::send);
  7801. };
  7802. let mut value = 1u32;
  7803. for round in 0..rounds {
  7804. check(round, &mut random, false);
  7805. // The flight of this submission: its shaders' writes.
  7806. for (which, c) in carded.iter().enumerate() {
  7807. if c.flying.swap(true, Ordering::Acquire) {
  7808. continue;
  7809. }
  7810. value += 1;
  7811. let mut ranges: Vec<(usize, usize)> = Vec::new();
  7812. let first = random.below(6) * PAGE / 2;
  7813. for k in 0..2 {
  7814. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  7815. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  7816. if from < to {
  7817. ranges.push((from, to));
  7818. }
  7819. }
  7820. for &(from, to) in &ranges {
  7821. c.shadow.writing(c.start + from, to - from);
  7822. }
  7823. {
  7824. let mut card = c.card.lock().unwrap();
  7825. for &(from, to) in &ranges {
  7826. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  7827. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  7828. }
  7829. }
  7830. }
  7831. fly.send((which, ranges, value)).unwrap();
  7832. }
  7833. if round % 20 != 19 {
  7834. continue;
  7835. }
  7836. // Still: no flight in the air, no title write.
  7837. let _still = still.write().unwrap();
  7838. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  7839. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  7840. std::thread::yield_now();
  7841. }
  7842. check(round, &mut random, true);
  7843. // SAFETY: the test's own memory, written by nobody now.
  7844. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  7845. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  7846. for c in &carded {
  7847. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  7848. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  7849. let card = c.card.lock().unwrap();
  7850. assert_eq!(first(&card.2, there), None, "round {round}: a card copy's card side (class {})", c.class);
  7851. }
  7852. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  7853. }
  7854. drop(fly);
  7855. });
  7856. }
  7857. /// The title's bytes put in under shader writes, for a copy of 174 MB
  7858. /// whose shader writes were declared as 40 ranges that overlap, with 12
  7859. /// pages written since. Run with `--ignored --nocapture`, and with
  7860. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  7861. #[test]
  7862. #[ignore]
  7863. fn bytes_under_overlapping_ranges() {
  7864. const BIG: usize = 174 << 20;
  7865. let big = title(BIG, true);
  7866. // SAFETY (both): the test's own memory.
  7867. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  7868. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  7869. copy.update(big, BIG);
  7870. copy.take_dirty();
  7871. for i in 0..40 {
  7872. copy.writing(big + i * 5920, BIG - i * 5920);
  7873. }
  7874. let mut best = f64::MAX;
  7875. for round in 0..30 {
  7876. for i in 0..12 {
  7877. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  7878. }
  7879. let started = std::time::Instant::now();
  7880. let mut runs = usize::MAX;
  7881. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  7882. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  7883. copy.take_dirty();
  7884. }
  7885. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  7886. }
  7887. /// A range nothing wrote is known to be as it was, at its ends too, and
  7888. /// is so no more once something wrote it.
  7889. #[test]
  7890. fn unchanged_ranges_are_known() {
  7891. for view in [false, true] {
  7892. let region = title(8 * PAGE, view);
  7893. // (A page read for the first time counts as written.)
  7894. // SAFETY: the test's own memory.
  7895. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  7896. let data = memory(8 * PAGE);
  7897. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  7898. // Ends in the middle of pages.
  7899. let (at, len) = (region + 500, 5 * PAGE);
  7900. let look = |expected: bool, what: &str| {
  7901. // The submission's one asking, which takes two ranges. (Again
  7902. // if a submission of another test ended it.)
  7903. let mut known = false;
  7904. for _ in 0..100 {
  7905. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  7906. known = copy.nothing_new(at, len);
  7907. if known || !expected {
  7908. break;
  7909. }
  7910. }
  7911. assert_eq!(known, expected, "view {view}: {what}");
  7912. let copied = copy.update(at, len);
  7913. crate::watch::ask_once_end();
  7914. copied
  7915. };
  7916. assert_eq!(look(false, "never taken"), len);
  7917. assert_eq!(look(true, "taken"), 0);
  7918. assert_eq!(look(true, "taken"), 0);
  7919. // SAFETY: the test's own memory.
  7920. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  7921. assert_eq!(look(false, "written at its end"), PAGE - 500);
  7922. assert_eq!(look(true, "taken again"), 0);
  7923. // Outside the range, on its last page.
  7924. // SAFETY: as above.
  7925. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  7926. assert_eq!(look(false, "written on its last page"), 500);
  7927. // A longer range was never taken whole.
  7928. assert!(!copy.nothing_new(region, 6 * PAGE));
  7929. }
  7930. }
  7931. /// A part of a copy in the card's memory taken again goes up only if it
  7932. /// differs (with `VICTORY_SEND_CHANGED=1`), whole when never taken.
  7933. #[test]
  7934. fn only_what_differs_goes_up() {
  7935. let region = title(4 * PAGE, true);
  7936. let data = memory(4 * PAGE);
  7937. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  7938. copy.update(region, 4 * PAGE);
  7939. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  7940. // What the relay does: shader writes into title memory, and into the
  7941. // CPU's side.
  7942. crate::watch::landing(region + PAGE + 640, 64);
  7943. // SAFETY: the test's own memory.
  7944. unsafe {
  7945. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  7946. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  7947. }
  7948. copy.update(region, 4 * PAGE);
  7949. let again = copy.take_dirty();
  7950. // SAFETY: as above.
  7951. unsafe { ((region + 2 * PAGE + 128) as *mut u8).write_volatile(9) };
  7952. copy.update(region, 4 * PAGE);
  7953. let written = copy.take_dirty();
  7954. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") {
  7955. assert_eq!(again, []);
  7956. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 192)]);
  7957. } else {
  7958. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  7959. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  7960. }
  7961. // SAFETY: as above.
  7962. assert_eq!(unsafe { data.add(2 * PAGE + 128).read() }, 9);
  7963. }
  7964. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  7965. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  7966. /// big copy that 55 landed pieces and 9 title writes opened, while a
  7967. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  7968. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  7969. #[test]
  7970. #[ignore]
  7971. fn frame_of_refreshes() {
  7972. let mut random = Random(0x9876_5432_1234_5671);
  7973. const EACH: usize = 224 << 10;
  7974. const BIG: usize = 174 << 20;
  7975. let watched = title(3000 * EACH, false);
  7976. // `VICTORY_BENCH_HOLES=0`: views without holes.
  7977. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  7978. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  7979. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  7980. let big = title(BIG, true);
  7981. // SAFETY: the test's own memory.
  7982. unsafe {
  7983. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  7984. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  7985. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  7986. }
  7987. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  7988. }
  7989. let mut small = Vec::new();
  7990. for i in 0..4400 {
  7991. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  7992. let data = memory(EACH);
  7993. // The range views read, not all of the copy.
  7994. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  7995. }
  7996. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  7997. // The same memory, as another copy: what is landed is landed through
  7998. // it, and the refreshes are of the first.
  7999. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8000. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  8001. let (mut sum, mut landing) = (0.0, 0.0);
  8002. const FRAMES: usize = 12;
  8003. for frame in 0..FRAMES {
  8004. let mut took = [0f64; 2];
  8005. for i in 0..30 {
  8006. // The title's writes, and the relay's beside the submission.
  8007. for _ in 0..9 {
  8008. let at = views + random.below(1400 * EACH / 8) * 8;
  8009. if there(at) {
  8010. // SAFETY: the test's own memory.
  8011. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8012. }
  8013. }
  8014. for _ in 0..60 {
  8015. let at = watched + random.below(3000 * EACH / 8) * 8;
  8016. // SAFETY: the test's own memory.
  8017. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8018. }
  8019. let first = random.below(BIG / PAGE - 60);
  8020. let lands = lands.clone();
  8021. let land = std::thread::spawn(move || {
  8022. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  8023. let started = std::time::Instant::now();
  8024. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  8025. let pieces: Vec<_> =
  8026. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  8027. let mut notes = crate::land::Notes::default();
  8028. // SAFETY: the bytes of `now`; nothing else lands here.
  8029. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  8030. notes.flush();
  8031. }
  8032. started.elapsed().as_secs_f64() * 1e3
  8033. });
  8034. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  8035. small.iter().cloned().chain([heap.clone()]).collect()
  8036. } else {
  8037. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  8038. };
  8039. let started = std::time::Instant::now();
  8040. submission(&ranges, 3);
  8041. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  8042. let put = land.join().unwrap();
  8043. if frame >= 2 {
  8044. landing += put;
  8045. }
  8046. heap.0.take_dirty();
  8047. }
  8048. if frame >= 2 {
  8049. sum += took[0] + took[1];
  8050. for k in 0..2 {
  8051. best[k] = best[k].min(took[k]);
  8052. asking[k] += took[k];
  8053. }
  8054. }
  8055. }
  8056. println!(
  8057. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  8058. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  8059. crate::watch::light(),
  8060. sum / (FRAMES - 2) as f64,
  8061. asking[0] / (FRAMES - 2) as f64,
  8062. best[0],
  8063. asking[1] / (FRAMES - 2) as f64,
  8064. best[1],
  8065. landing / (FRAMES - 2) as f64,
  8066. );
  8067. #[cfg(feature = "diagnostics")]
  8068. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  8069. }
  8070. }
  8071. #[cfg(test)]
  8072. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  8073. use super::Batch;
  8074. use std::sync::Arc;
  8075. #[test]
  8076. fn a_texture_is_checked_once_per_submission() {
  8077. let mut batch = Batch::default();
  8078. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  8079. // The first list sampling each texture checks it ...
  8080. assert!(batch.texture_due(&a));
  8081. assert!(batch.texture_due(&b));
  8082. // ... later lists of the same submission do not.
  8083. assert!(!batch.texture_due(&a));
  8084. assert!(!batch.texture_due(&a.clone()));
  8085. assert!(!batch.texture_due(&b));
  8086. }
  8087. #[test]
  8088. fn title_writes_make_textures_due_again() {
  8089. let mut batch = Batch::default();
  8090. let a = Arc::new(1u32);
  8091. assert!(batch.texture_due(&a));
  8092. assert!(!batch.texture_due(&a));
  8093. // A copy into title memory or work that may write it may have
  8094. // changed the texture's memory.
  8095. batch.title_written();
  8096. assert!(batch.texture_due(&a));
  8097. assert!(!batch.texture_due(&a));
  8098. // A fresh submission starts over.
  8099. let mut next = Batch::default();
  8100. assert!(next.texture_due(&a));
  8101. }
  8102. /// The hashing a submission does for textures in physical-page memory,
  8103. /// with every list checking the textures it samples (before) and with
  8104. /// each checked once (after). Run with
  8105. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  8106. #[test]
  8107. #[ignore = "benchmark"]
  8108. fn texture_checks_per_submission() {
  8109. const TEXTURES: usize = 48;
  8110. const SIZE: usize = 4 << 20;
  8111. const LISTS: usize = 12;
  8112. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  8113. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  8114. .collect();
  8115. let submit = |dedupe: bool| {
  8116. let mut batch = Batch::default();
  8117. let mut hashed = 0usize;
  8118. let started = std::time::Instant::now();
  8119. for _ in 0..LISTS {
  8120. for t in &textures {
  8121. if !dedupe || batch.texture_due(t) {
  8122. std::hint::black_box(blake3::hash(t));
  8123. hashed += 1;
  8124. }
  8125. }
  8126. }
  8127. (started.elapsed(), hashed)
  8128. };
  8129. submit(false); // warm up
  8130. let (before, n_before) = submit(false);
  8131. let (after, n_after) = submit(true);
  8132. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  8133. println!(
  8134. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  8135. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  8136. SIZE >> 20,
  8137. before.as_secs_f64() / after.as_secs_f64()
  8138. );
  8139. }
  8140. #[test]
  8141. fn vram_idle_ms_scales_with_pressure() {
  8142. use super::vram_idle_ms;
  8143. let gib = 1024 * 1024 * 1024;
  8144. // Normal (< 75%)
  8145. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  8146. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  8147. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  8148. // Moderate (75%..85%)
  8149. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  8150. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  8151. // High (>= 85%, including over-budget)
  8152. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  8153. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  8154. // Missing or zero budget falls back to normal
  8155. assert_eq!(vram_idle_ms(None), 5_000);
  8156. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  8157. }
  8158. #[test]
  8159. fn ram_idle_ms_scales_with_pressure() {
  8160. use super::ram_idle_ms;
  8161. let gib = 1024 * 1024 * 1024;
  8162. // Normal (>= 4 GiB)
  8163. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  8164. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  8165. // Moderate (2 GiB..4 GiB)
  8166. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  8167. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  8168. // High (< 2 GiB)
  8169. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  8170. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  8171. // Missing falls back to normal
  8172. assert_eq!(ram_idle_ms(None), 10_000);
  8173. }
  8174. }