host.rs 431 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807
  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<std::collections::VecDeque<(u64, Retired)>> = Mutex::new(std::collections::VecDeque::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. #[allow(dead_code)]
  72. enum Retired {
  73. Any(Box<dyn std::any::Any>),
  74. /// What a descriptor slot showed: 20,000 a frame, without a box each.
  75. Resource(ID3D12Resource),
  76. }
  77. // SAFETY: what is retired is D3D12 objects (free-threaded) and the
  78. // reference-counted wrappers holding them, dropped once.
  79. unsafe impl Send for Retired {}
  80. /// Milliseconds since the first call.
  81. pub(crate) fn now_ms() -> u64 {
  82. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  83. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  84. }
  85. /// [`now_ms`] to the system's tick (16 ms): a few nanoseconds, where the
  86. /// performance counter's are 25. For what is noted tens of thousands of
  87. /// times a frame and read in tenths of a second.
  88. pub(crate) fn coarse_ms() -> u64 {
  89. use windows_sys::Win32::System::SystemInformation::GetTickCount64;
  90. // The same beginning as `now_ms`.
  91. static BEGAN: OnceLock<u64> = OnceLock::new();
  92. // SAFETY: a plain query.
  93. let now = unsafe { GetTickCount64() };
  94. now.saturating_sub(*BEGAN.get_or_init(|| now.saturating_sub(now_ms())))
  95. }
  96. /// This moment, for telling later how long ago it was ([`long_ago`]): the
  97. /// frames begun so far (high half, `crate::frame::current`) and tenths of a
  98. /// second since the start. Host copies of title memory, staging buffers and
  99. /// host textures note when they were last used with it.
  100. pub(crate) fn moment() -> u64 {
  101. (crate::frame::current() << 32) | ((coarse_ms() / 100) & 0xffff_ffff)
  102. }
  103. /// Whether `moment` lies at least `ms` milliseconds and `frames` frames
  104. /// back. Both: at seconds per frame, what every frame uses is not touched
  105. /// for seconds, and at many frames per second not for many frames. (A title
  106. /// that never waits for frames has no frame count: nothing is then idle.)
  107. pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
  108. let now = self::moment();
  109. let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
  110. (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
  111. }
  112. /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
  113. pub(crate) fn available_physical_ram() -> Option<u64> {
  114. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  115. // SAFETY: plain data the call fills in.
  116. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  117. m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
  118. // SAFETY: a sized structure.
  119. let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
  120. ok.then_some(m.ullAvailPhys)
  121. }
  122. /// How long host copies of textures the title fills must have been idle to
  123. /// be let go, in milliseconds, and how many bytes of them go at most (the
  124. /// longest idle first): none but those of ten minutes while what is in use
  125. /// of the card (`used`: without what our own blocks have free, with what is
  126. /// kept free for others) is under 88 % of its budget, else enough to come
  127. /// down to 85 %. `VICTORY_TEXTURE_KEEP=0`: [`vram_idle_ms`]' older rule,
  128. /// all that are idle; `=1`: that rule with its two longer times.
  129. ///
  130. /// (By those times everything idle for 2.5 s went from 75 % of the budget
  131. /// on: 61,000 of them in the first 300 s of session play-1125-0203, at 78 to
  132. /// 80 %, of which 13,000 were made and uploaded again.)
  133. pub(crate) fn vram_keep(budget: u64, used: u64) -> (u64, u64) {
  134. const KEPT_MS: u64 = 600_000;
  135. const IDLE_MS: u64 = 5_000;
  136. const SHORT_MS: u64 = 1_500;
  137. if budget == 0 {
  138. return (IDLE_MS, u64::MAX);
  139. }
  140. let share = |percent: u64| budget / 100 * percent;
  141. if used < share(88) {
  142. (KEPT_MS, u64::MAX)
  143. } else if used < share(95) {
  144. (IDLE_MS, used - share(85))
  145. } else {
  146. (SHORT_MS, used - share(85))
  147. }
  148. }
  149. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  150. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  151. /// handles not yet recorded into a list or slot remain protected.
  152. ///
  153. /// With room on the card nothing has to go: in session play-1125-0127 88,000
  154. /// of them (31 GB) went after 5 s with 7 GB of the card free, and 24,700
  155. /// (12 GB) had to be made and uploaded again.
  156. /// `VICTORY_TEXTURE_KEEP=0`: 5 s there too, as before.
  157. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  158. static KEEP: OnceLock<bool> = OnceLock::new();
  159. let keep = *KEEP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_KEEP").is_none_or(|v| v != "0"));
  160. vram_idle_for(video_memory, keep)
  161. }
  162. fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 {
  163. const KEPT_MS: u64 = 600_000;
  164. const LONG_MS: u64 = 30_000;
  165. const NORMAL_MS: u64 = 5_000;
  166. const MODERATE_MS: u64 = 2_500;
  167. const HIGH_MS: u64 = 1_000;
  168. let Some([budget, used, ..]) = video_memory else {
  169. return NORMAL_MS;
  170. };
  171. if budget == 0 {
  172. return NORMAL_MS;
  173. }
  174. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  175. if used_pct >= 85 {
  176. HIGH_MS
  177. } else if used_pct >= 75 {
  178. MODERATE_MS
  179. } else if !keep {
  180. NORMAL_MS
  181. } else if used_pct >= 68 {
  182. LONG_MS
  183. } else {
  184. KEPT_MS
  185. }
  186. }
  187. /// Whether new memory is made resident, and waited for, before anything can
  188. /// name it (on by default; `VICTORY_WAIT_RESIDENT=0`: as before). A heap or
  189. /// resource of the default kind is resident once it is made, but its
  190. /// mapping into the card's address space is work of the system's that runs
  191. /// later: only lists sent after it wait for it. Lists sent before run on,
  192. /// and read our descriptor heaps as they are: a slot that shows a texture
  193. /// in a new block is a page fault for them until the block is mapped. The
  194. /// device losses of the night of 2026-11-25 were that (run n08: the fault
  195. /// lay in a texture made in the same tenth of a second, in a new block).
  196. fn wait_resident() -> bool {
  197. static ON: OnceLock<bool> = OnceLock::new();
  198. *ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_RESIDENT").is_none_or(|v| v != "0"))
  199. }
  200. /// The flag memory is made with that [`resident`] waits for.
  201. pub(crate) fn not_resident() -> D3D12_HEAP_FLAGS {
  202. if wait_resident() { D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT } else { D3D12_HEAP_FLAG_NONE }
  203. }
  204. /// A queue of its own that new memory is waited for with ([`mapped`]).
  205. struct Aside {
  206. queue: ID3D12CommandQueue,
  207. list: ID3D12CommandList,
  208. fence: ID3D12Fence,
  209. event: windows::Win32::Foundation::HANDLE,
  210. value: u64,
  211. _keep: (ID3D12CommandAllocator, [ID3D12Resource; 2]),
  212. }
  213. // SAFETY: D3D12 objects are free-threaded, the event is waited on by one
  214. // thread at a time (the lock).
  215. unsafe impl Send for Aside {}
  216. /// New memory of the card is mapped into its address space when this
  217. /// returns: a copy of a few bytes is sent to a queue of ours after the
  218. /// memory was made, which the system starts only when all mappings asked
  219. /// for so far are done, and waited for. (`MakeResident` came back before
  220. /// that: run n11 was lost as n08 was with it alone.) Best done off a hot
  221. /// path: a tenth of a millisecond to some.
  222. pub(crate) fn mapped(device: &ID3D12Device) -> windows::core::Result<()> {
  223. static ASIDE: Mutex<Option<Aside>> = Mutex::new(None);
  224. if !wait_resident() {
  225. return Ok(());
  226. }
  227. let started = std::time::Instant::now();
  228. let mut aside = ASIDE.lock().unwrap_or_else(|e| e.into_inner());
  229. // SAFETY: plain object creation; the objects the list names are kept.
  230. unsafe {
  231. if aside.is_none() {
  232. let buffer = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| -> windows::core::Result<ID3D12Resource> {
  233. let mut made: Option<ID3D12Resource> = None;
  234. device.CreateCommittedResource(
  235. &D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() },
  236. D3D12_HEAP_FLAG_NONE,
  237. &D3D12_RESOURCE_DESC {
  238. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  239. Width: 256,
  240. Height: 1,
  241. DepthOrArraySize: 1,
  242. MipLevels: 1,
  243. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  244. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  245. ..Default::default()
  246. },
  247. state,
  248. None,
  249. &mut made,
  250. )?;
  251. made.ok_or_else(windows::core::Error::empty)
  252. };
  253. let from = buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ)?;
  254. let to = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST)?;
  255. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  256. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  257. ..Default::default()
  258. })?;
  259. let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  260. let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  261. list.CopyBufferRegion(&to, 0, &from, 0, 16);
  262. list.Close()?;
  263. *aside = Some(Aside {
  264. queue,
  265. list: list.cast()?,
  266. fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?,
  267. event: CreateEventW(None, false, false, None)?,
  268. value: 0,
  269. _keep: (allocator, [from, to]),
  270. });
  271. }
  272. let Some(a) = aside.as_mut() else { return Ok(()) };
  273. a.queue.ExecuteCommandLists(&[Some(a.list.clone())]);
  274. a.value += 1;
  275. a.queue.Signal(&a.fence, a.value)?;
  276. if a.fence.GetCompletedValue() < a.value {
  277. a.fence.SetEventOnCompletion(a.value, a.event)?;
  278. WaitForSingleObject(a.event, INFINITE);
  279. }
  280. }
  281. let us = started.elapsed().as_micros() as u64;
  282. MAPPED[0].fetch_add(1, Ordering::Relaxed);
  283. MAPPED[1].fetch_add(us, Ordering::Relaxed);
  284. MAPPED[2].fetch_max(us, Ordering::Relaxed);
  285. let n = MAPPED[0].load(Ordering::Relaxed);
  286. if n == 1 || n.is_multiple_of(200) {
  287. tracing::info!(
  288. "new card memory waited for until it is mapped (VICTORY_WAIT_RESIDENT=0: not), since the start: {n} times, {:.1} ms, the longest {:.1} ms",
  289. MAPPED[1].load(Ordering::Relaxed) as f64 / 1000.0,
  290. MAPPED[2].load(Ordering::Relaxed) as f64 / 1000.0
  291. );
  292. }
  293. Ok(())
  294. }
  295. /// Times, microseconds and the longest of [`mapped`].
  296. static MAPPED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  297. /// New memory (made with [`not_resident`]) is resident when this returns.
  298. pub(crate) fn resident(device: &ID3D12Device, object: &impl Interface) -> windows::core::Result<()> {
  299. if !wait_resident() {
  300. return Ok(());
  301. }
  302. let started = std::time::Instant::now();
  303. let object: ID3D12Pageable = object.cast()?;
  304. // SAFETY: a live heap or resource of the device's.
  305. let made = unsafe { device.MakeResident(&[Some(object)]) };
  306. let us = started.elapsed().as_micros() as u64;
  307. RESIDENT[0].fetch_add(1, Ordering::Relaxed);
  308. RESIDENT[1].fetch_add(us, Ordering::Relaxed);
  309. RESIDENT[2].fetch_max(us, Ordering::Relaxed);
  310. static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  311. let n = RESIDENT[0].load(Ordering::Relaxed);
  312. if n >= 1000 * (SAID.load(Ordering::Relaxed) + 1) {
  313. SAID.store(n / 1000, Ordering::Relaxed);
  314. tracing::info!(
  315. "new memory waited for (VICTORY_WAIT_RESIDENT=0: not), since the start: {n} times, {:.1} ms, the longest {:.1} ms",
  316. RESIDENT[1].load(Ordering::Relaxed) as f64 / 1000.0,
  317. RESIDENT[2].load(Ordering::Relaxed) as f64 / 1000.0
  318. );
  319. }
  320. made
  321. }
  322. /// Times, microseconds and the longest of [`resident`].
  323. static RESIDENT: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  324. /// Whether memory the card was given stays with it while there is room (on
  325. /// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader
  326. /// that reads past a view (a raw load through a typed, structured or
  327. /// constant buffer view has no end on AMD: `indirect::tests::raw_loads_past_views`)
  328. /// or through a slot that shows wrong data reads whatever lies there, and
  329. /// nothing happens; where memory was given back it is a page fault, and the
  330. /// device is lost. Both losses of 2026-11-25 were reads in memory given back
  331. /// seconds before (a block of textures; a list's scratch and a window of
  332. /// title memory). Kept are: empty blocks of textures ([`crate::pool`]) below
  333. /// 85 % of the card's budget, windows of title memory and staging buffers
  334. /// for five minutes with 12 GiB of the PC's memory free, and 1 GiB of
  335. /// scratch chunks.
  336. pub(crate) fn keep_freed() -> bool {
  337. static ON: OnceLock<bool> = OnceLock::new();
  338. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_FREED").is_none_or(|v| v != "0"))
  339. }
  340. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  341. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  342. /// when free physical RAM is low. Never returns less than 2,000 ms.
  343. /// With plenty of it five minutes ([`keep_freed`]).
  344. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  345. ram_idle_for(avail_phys, keep_freed())
  346. }
  347. fn ram_idle_for(avail_phys: Option<u64>, keep: bool) -> u64 {
  348. const GIB: u64 = 1024 * 1024 * 1024;
  349. const KEPT_MS: u64 = 300_000;
  350. if keep && avail_phys.is_some_and(|avail| avail >= 12 * GIB) {
  351. return KEPT_MS;
  352. }
  353. const NORMAL_MS: u64 = 10_000;
  354. const MODERATE_MS: u64 = 5_000;
  355. const HIGH_MS: u64 = 2_000;
  356. let Some(avail) = avail_phys else {
  357. return NORMAL_MS;
  358. };
  359. if avail < 2 * GIB {
  360. HIGH_MS
  361. } else if avail < 4 * GIB {
  362. MODERATE_MS
  363. } else {
  364. NORMAL_MS
  365. }
  366. }
  367. /// How many references are held on a host object (its COM count): ours
  368. /// all, since the host's views and commands hold none. A buffer or texture
  369. /// with one is held by its owner alone: no descriptor slot keeps it
  370. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  371. pub(crate) fn references(object: &impl Interface) -> u32 {
  372. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  373. let raw = object.as_raw();
  374. // SAFETY: a live COM object, whose first three methods are those of
  375. // `IUnknown` (query, add a reference, release one); the pair leaves the
  376. // count as it was, and the release returns it. The first is not called.
  377. unsafe {
  378. let methods = *raw.cast::<*const [Method; 3]>();
  379. ((*methods)[1])(raw);
  380. ((*methods)[2])(raw)
  381. }
  382. }
  383. /// Once a second, before a submission starts: lets go of what nothing
  384. /// names any more (copies of windows of title memory, staging buffers,
  385. /// host copies of textures the title fills).
  386. /// `VICTORY_SWEEP=0` keeps everything, as before.
  387. fn sweep() {
  388. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  389. crate::inplace::tick();
  390. static ON: OnceLock<bool> = OnceLock::new();
  391. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  392. return;
  393. }
  394. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  395. let now = now_ms();
  396. let last = LAST.load(Ordering::Relaxed);
  397. if now < last + 1000
  398. || LAST
  399. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  400. .is_err()
  401. {
  402. return;
  403. }
  404. #[cfg(feature = "diagnostics")]
  405. crate::book::check();
  406. crate::pool::room(host().and_then(|h| h.video_memory()));
  407. crate::pipeline::trim_library();
  408. crate::shadow::let_go_idle();
  409. crate::texture::let_go_idle();
  410. crate::resource::let_go_idle();
  411. }
  412. /// The number of the newest submission begun, and of the newest of which all
  413. /// before it have finished too.
  414. pub(crate) fn submissions() -> (u64, u64) {
  415. (STARTED.load(Ordering::Acquire), FINISHED.load(Ordering::Acquire))
  416. }
  417. /// Drops `object` once every submission running now has finished: at once
  418. /// if none is.
  419. pub(crate) fn retire<T: 'static>(object: T) {
  420. // (Those the title made and the host has not begun get the next numbers.)
  421. let queued = crate::queue::queued();
  422. let started = STARTED.load(Ordering::Acquire) + queued;
  423. if bury_lag() == 0 && started <= FINISHED.load(Ordering::Acquire) {
  424. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  425. drop(object);
  426. return;
  427. }
  428. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  429. RETIRED
  430. .lock()
  431. .unwrap_or_else(|e| e.into_inner())
  432. .push_back((started, Retired::Any(Box::new(object))));
  433. }
  434. /// [`retire`] for a resource.
  435. pub(crate) fn retire_resource(object: ID3D12Resource) {
  436. let queued = crate::queue::queued();
  437. let started = STARTED.load(Ordering::Acquire) + queued;
  438. if bury_lag() == 0 && started <= FINISHED.load(Ordering::Acquire) {
  439. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  440. drop(object);
  441. return;
  442. }
  443. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  444. RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object)));
  445. }
  446. /// How many submissions later than it could (the last one that may use it
  447. /// has finished) an object let go is dropped, and a host list that has run
  448. /// is reset, about two frames: the device losses of the night of 2026-11-25
  449. /// were page faults in memory nothing of ours named any more, at no command
  450. /// in particular. Objects let go while nothing runs wait as well: lists
  451. /// recorded and not yet sent may name them. `VICTORY_BURY_LAG=0`: not.
  452. fn bury_lag() -> u64 {
  453. static LAG: OnceLock<u64> = OnceLock::new();
  454. *LAG.get_or_init(|| std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(64))
  455. }
  456. /// Drops what waited for submissions up to `finished` ([`bury_lag`]). The
  457. /// numbers come in order, but for threads that overtake each other: one of
  458. /// those is dropped a little later than it could be.
  459. fn bury(finished: u64) {
  460. let finished = finished.saturating_sub(bury_lag());
  461. let done: Vec<(u64, Retired)> = {
  462. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  463. let n = retired.iter().take_while(|(at, _)| *at <= finished).count();
  464. if n == 0 {
  465. return;
  466. }
  467. retired.drain(..n).collect()
  468. };
  469. drop(done);
  470. }
  471. /// Objects [`retire`] dropped at once (no submission was running) and
  472. /// kept until a running submission finished, since the start.
  473. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  474. /// What the layer did to the host's objects lately, newest last (sweeps
  475. /// that let host copies go, pipeline library calls, saves and trims): said
  476. /// once when the host device is removed ([`log_removal_context`]), with
  477. /// what the submitting thread and the pipeline workers were doing at that
  478. /// moment. A device the driver removes "internally" names no command, and
  479. /// the pass that happens to notice first names only the view it was at:
  480. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  481. /// pipeline library call that no line of the log tied to them.
  482. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  483. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  484. /// The entries kept.
  485. const TRAIL_MOST: usize = 96;
  486. fn trail_on() -> bool {
  487. static ON: OnceLock<bool> = OnceLock::new();
  488. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  489. }
  490. /// Microseconds since the first call.
  491. pub(crate) fn now_us() -> u64 {
  492. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  493. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  494. }
  495. /// The calling thread, as the log's other lines name threads.
  496. pub(crate) fn thread_id() -> u32 {
  497. // SAFETY: a plain query.
  498. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  499. }
  500. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  501. /// run when the trail is kept.
  502. pub(crate) fn trail(what: impl FnOnce() -> String) {
  503. if !trail_on() {
  504. return;
  505. }
  506. let entry = (now_us(), thread_id(), what());
  507. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  508. if trail.len() >= TRAIL_MOST {
  509. trail.pop_front();
  510. }
  511. trail.push_back(entry);
  512. }
  513. /// What the submitting thread is doing (0 nothing: between submissions,
  514. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  515. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  516. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  517. fn submitting(phase: u64, lists: usize) {
  518. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  519. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  520. SUBMITTING[0].store(phase, Ordering::Relaxed);
  521. }
  522. /// What was going on when the host device went: whether a submission was
  523. /// on the card, the pipeline library's state and the calls running in it,
  524. /// and the trail.
  525. pub(crate) fn removal_context() -> String {
  526. use std::fmt::Write;
  527. let now = now_us();
  528. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  529. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  530. 0 => "between submissions (nothing of ours was running on the card)",
  531. 1 => "preparing a submission (nothing of ours was running on the card)",
  532. 2 => "waiting for the card to run a submission",
  533. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  534. };
  535. let mut text = format!(
  536. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  537. SUBMITTING[1].load(Ordering::Relaxed),
  538. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  539. crate::pipeline::library_removal_note(),
  540. RETIREMENTS[0].load(Ordering::Relaxed),
  541. RETIREMENTS[1].load(Ordering::Relaxed),
  542. STARTED.load(Ordering::Relaxed),
  543. FINISHED.load(Ordering::Relaxed),
  544. );
  545. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  546. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  547. for (at, thread, what) in trail.iter() {
  548. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  549. }
  550. text
  551. }
  552. /// Says [`removal_context`] in the log, once: called by whoever finds the
  553. /// host device removed.
  554. pub(crate) fn log_removal_context() {
  555. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  556. if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) {
  557. return;
  558. }
  559. tracing::error!("when the host device went: {}", removal_context());
  560. if dred_any() {
  561. let data = host().map(|h| h.removal_data(&[])).unwrap_or_default();
  562. tracing::error!("device-removed data{}", if data.is_empty() { "; none" } else { &data });
  563. }
  564. }
  565. /// Time spent in submissions since the last frame-rate line, in
  566. /// microseconds: preparing them on the CPU (title memory copies, texture
  567. /// detiling), then waiting for the GPU.
  568. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  569. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  570. /// After submissions: shader-written ranges compared and copied back into
  571. /// title memory (microseconds, bytes that differed), since the last
  572. /// frame-rate line.
  573. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  574. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  575. /// The card's clock, for the frame line of every run, in microseconds since
  576. /// the last one: how long the card had nothing of ours queued; how much of
  577. /// that while the thread that holds the submission lock was working (the
  578. /// card idle behind us: preparing and copying back are done with the card
  579. /// standing); and how long that thread stood waiting for the card.
  580. ///
  581. /// Every send of lists to the queue is followed by a signal on a fence of
  582. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  583. /// the newest signal and notes the moment the card reached it with nothing
  584. /// newer sent; the next send ends that idle stretch.
  585. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  586. /// Of the thread that holds the submission lock: the microseconds it has
  587. /// worked so far (preparing, copying back; not its waits for the card), and
  588. /// since when it works now ([`now_us`] plus one; 0: it does not).
  589. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  590. /// The thread that holds the submission lock starts (`on`) or stops
  591. /// working; whether it worked until now.
  592. fn working(on: bool) -> bool {
  593. let now = now_us() + 1;
  594. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  595. if since != 0 {
  596. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  597. }
  598. since != 0
  599. }
  600. /// [`WORKING`] as of now: microseconds worked so far.
  601. fn worked() -> u64 {
  602. let since = WORKING[1].load(Ordering::Relaxed);
  603. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  604. WORKING[0].load(Ordering::Relaxed) + now
  605. }
  606. /// The thread that holds the submission lock stood waiting for the card
  607. /// from `since` until now ([`CARD_CLOCK_US`]).
  608. fn stood(since: std::time::Instant) {
  609. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  610. }
  611. /// What [`CARD_CLOCK_US`] is measured with.
  612. struct CardClock {
  613. fence: ID3D12Fence,
  614. /// Signals sent so far; and, while the card has reached the last of
  615. /// them, since when and what [`worked`] said then.
  616. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  617. sent: std::sync::Condvar,
  618. }
  619. // SAFETY: a fence (free-threaded) behind a lock.
  620. unsafe impl Send for CardClock {}
  621. // SAFETY: as above.
  622. unsafe impl Sync for CardClock {}
  623. /// The clock's thread: waits for the newest signal sent and notes when the
  624. /// card got there with nothing newer behind it.
  625. fn card_clock_watch(clock: &'static CardClock) {
  626. // SAFETY: a plain event of our own.
  627. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  628. return;
  629. };
  630. let mut seen = 0;
  631. loop {
  632. let target = {
  633. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  634. while state.0 == seen {
  635. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  636. }
  637. state.0
  638. };
  639. // SAFETY: the clock's fence and this thread's event.
  640. unsafe {
  641. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  642. WaitForSingleObject(event, INFINITE);
  643. }
  644. }
  645. seen = target;
  646. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  647. if state.0 == target && state.1.is_none() {
  648. state.1 = Some((std::time::Instant::now(), worked()));
  649. }
  650. }
  651. }
  652. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  653. /// frame's time.
  654. fn card_clock_line(frames: f64, ms: f64) {
  655. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  656. tracing::info!(
  657. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  658. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  659. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  660. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  661. );
  662. }
  663. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  664. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  665. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  666. std::sync::atomic::AtomicU64::new(0),
  667. std::sync::atomic::AtomicU64::new(0),
  668. std::sync::atomic::AtomicU64::new(0),
  669. std::sync::atomic::AtomicU64::new(0),
  670. ];
  671. /// Host buffers made since the start, as (count, bytes): in the upload heap
  672. /// (staging, list scratch), shared with the processor (host copies of title
  673. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  674. /// For the memory line: against what is alive, they show what was let go.
  675. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  676. /// What of that is alive now, for the memory line (`MADE` counts what was
  677. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  678. /// and nothing said how many were alive): host lists; the lists' scratch
  679. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  680. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  681. /// instead of made, since the start; and the lists' other upload buffers
  682. /// (texture data copied from buffers, scratch too big for a chunk) and
  683. /// their bytes.
  684. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  685. /// About host lists, for the memory line: lists made by the host since the
  686. /// start; preludes made (a list's second allocator and list, made when it
  687. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  688. /// bytes the process's private memory grew by while lists were being made
  689. /// (what a list costs: host objects with the driver's command memory; 631
  690. /// lists were alive in run 65, each with a prelude it may never use).
  691. /// Then the lists alive that were never reset since they were made: the
  692. /// host sides of title lists the title made and has not used (a host list
  693. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  694. /// makes at its start).
  695. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  696. /// The process's private bytes (diagnostics: around the making of lists).
  697. #[cfg(feature = "diagnostics")]
  698. fn private_bytes() -> u64 {
  699. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  700. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  701. let mut c = PROCESS_MEMORY_COUNTERS {
  702. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  703. ..Default::default()
  704. };
  705. // SAFETY: our own process and a sized structure.
  706. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  707. c.PagefileUsage as u64
  708. }
  709. /// What the runtime does when the host GPU fails for good: report it like a
  710. /// crash and end the run. The console has no such state, and carrying on
  711. /// draws nothing at seconds per frame.
  712. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  713. /// Sets what a host GPU failure does (the runtime's crash report).
  714. pub fn on_failure(report: fn(&str) -> !) {
  715. let _ = ON_FAILURE.set(report);
  716. }
  717. /// Ends the run on a host GPU failure: what failed, the removal reason and
  718. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  719. /// diagnostics build names the command).
  720. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  721. let mut text = what.to_string();
  722. if let Some(host) = host() {
  723. // SAFETY: a plain query.
  724. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  725. text.push_str(&format!("; device removed: {e}"));
  726. log_removal_context();
  727. }
  728. match host.log_messages() {
  729. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  730. None if host.messages.is_none() => text.push_str(
  731. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  732. ),
  733. None => {}
  734. }
  735. }
  736. tracing::error!("{text}");
  737. // Tests have no log: the reason goes to their output.
  738. #[cfg(test)]
  739. eprintln!("host GPU failure: {text}");
  740. match ON_FAILURE.get() {
  741. Some(report) => report(&text),
  742. None => std::process::abort(),
  743. }
  744. }
  745. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  746. /// The host GPU if it is made already.
  747. #[cfg(feature = "diagnostics")]
  748. pub(crate) fn made_host() -> Option<&'static Host> {
  749. HOST.get()?.as_ref()
  750. }
  751. /// The host GPU, created on first use; `None` without one (a run then
  752. /// behaves as before: nothing executes).
  753. pub(crate) fn host() -> Option<&'static Host> {
  754. HOST.get_or_init(|| match create() {
  755. Ok(host) => Some(host),
  756. Err(e) => {
  757. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  758. None
  759. }
  760. })
  761. .as_ref()
  762. }
  763. fn create() -> windows::core::Result<Host> {
  764. // SAFETY: plain D3D12 object creation with valid descriptions.
  765. unsafe {
  766. // The debug layer only in builds with diagnostics.
  767. let debug = cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DEBUG");
  768. if debug {
  769. let mut layer: Option<ID3D12Debug> = None;
  770. match D3D12GetDebugInterface(&mut layer) {
  771. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  772. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  773. }
  774. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  775. // descriptor heap indices and the like become messages naming
  776. // the command instead of page faults. Without state tracking
  777. // (directly indexed textures are not transitioned).
  778. if crate::switch::on("VICTORY_D3D12_GBV")
  779. && let Some(l) = &layer
  780. {
  781. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  782. d1.SetEnableGPUBasedValidation(true);
  783. }
  784. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  785. d2.SetGPUBasedValidationFlags(
  786. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  787. );
  788. }
  789. tracing::info!("GPU-based validation on");
  790. }
  791. }
  792. // Diagnostics: device-removed data (the command that faulted, the
  793. // faulting address), read when the device is removed.
  794. if dred_any() {
  795. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  796. if D3D12GetDebugInterface(&mut dred).is_ok()
  797. && let Some(dred) = dred
  798. {
  799. if dred_on() || dred_light() {
  800. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  801. }
  802. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  803. tracing::info!(
  804. breadcrumbs = dred_on() || dred_light(),
  805. markers = dred_on(),
  806. "crash tracing on (device-removed data)"
  807. );
  808. } else {
  809. tracing::warn!("crash tracing asked for and not there: no device-removed data settings");
  810. }
  811. }
  812. let mut device: Option<ID3D12Device> = None;
  813. // Diagnostics: the software adapter, on which a shader's wild access
  814. // is an access violation in this process (a crash report with the
  815. // address and instruction) instead of a GPU fault and driver reset.
  816. if cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_WARP") {
  817. let adapter = warp_adapter()?;
  818. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  819. tracing::info!("host device on the software adapter (WARP)");
  820. } else {
  821. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  822. // Whether a GPU hang ends the run or freezes the PC (#1054).
  823. crate::tdr::log();
  824. }
  825. let device = device.ok_or_else(windows::core::Error::empty)?;
  826. // Before anything is made with it (`VICTORY_RECORD`).
  827. #[cfg(feature = "diagnostics")]
  828. crate::replay::record::from_env(&device);
  829. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  830. // driver compiling shaders again on the "D3D Background Thread"s,
  831. // for minutes after pipelines were made or loaded) is switched off.
  832. // An experiment: while those threads ran, the same shot took
  833. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  834. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  835. // whether the card is slower with the shaders it then keeps is not
  836. // known.
  837. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  838. && let Ok(device6) = device.cast::<ID3D12Device6>()
  839. {
  840. let set = device6.SetBackgroundProcessingMode(
  841. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  842. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  843. None,
  844. None,
  845. );
  846. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  847. }
  848. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  849. // cross-lane code stays in 32-lane halves translated for waves of 32
  850. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  851. if device
  852. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  853. .is_ok()
  854. {
  855. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  856. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  857. }
  858. let messages = debug
  859. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  860. .flatten();
  861. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  862. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  863. ..Default::default()
  864. })?;
  865. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  866. let event = CreateEventW(None, false, false, None)?;
  867. let rtvs: ID3D12DescriptorHeap =
  868. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  869. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  870. NumDescriptors: RTV_RING,
  871. ..Default::default()
  872. })?;
  873. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  874. let dsvs: ID3D12DescriptorHeap =
  875. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  876. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  877. NumDescriptors: RTV_RING,
  878. ..Default::default()
  879. })?;
  880. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  881. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  882. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  883. .ok();
  884. tracing::info!("host D3D12 device ready");
  885. Ok(Host {
  886. device,
  887. queue,
  888. fence,
  889. submitted: Mutex::new(0),
  890. event,
  891. rtvs,
  892. rtv_size,
  893. dsvs,
  894. dsv_size,
  895. next_dsv: AtomicU32::new(0),
  896. messages,
  897. next_rtv: AtomicU32::new(0),
  898. presenter: Mutex::new(None),
  899. adapter,
  900. })
  901. }
  902. }
  903. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  904. /// Reject it before creating a device in diagnostics' software-only mode.
  905. pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  906. // SAFETY: plain DXGI adapter queries.
  907. unsafe {
  908. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  909. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  910. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  911. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  912. tracing::warn!(
  913. vendor = format_args!("{:#x}", desc.VendorId),
  914. flags = format_args!("{:#x}", desc.Flags),
  915. "DXGI did not identify the WARP adapter as software; refusing device"
  916. );
  917. return Err(windows::core::Error::from_hresult(
  918. windows::Win32::Foundation::E_FAIL,
  919. ));
  920. }
  921. Ok(adapter)
  922. }
  923. }
  924. #[cfg(test)]
  925. mod tests {
  926. /// A list of ours is found by its name, with the debug layer's note or not.
  927. #[cfg(feature = "diagnostics")]
  928. #[test]
  929. fn a_list_is_found_by_the_number_in_its_name() {
  930. assert_eq!(super::list_number("victory host list 7"), Some(7));
  931. assert_eq!(super::list_number("victory host list 158 (debug layer indirect)"), Some(158));
  932. assert_eq!(super::list_number("victory host list 7x"), None);
  933. assert_eq!(super::list_number("victory host list 7 x"), None);
  934. assert_eq!(super::list_number("another list 7"), None);
  935. assert_eq!(super::list_number(""), None);
  936. }
  937. /// What is there of a range some of whose pages are not: those bytes,
  938. /// counted, and zeros for the rest, whatever the buffer held.
  939. #[test]
  940. fn what_is_there_is_read_and_the_rest_is_zeros() {
  941. use windows_sys::Win32::System::Memory::*;
  942. const SIZE: usize = 0x8_0000;
  943. // SAFETY: a reservation of ours; only committed pages are written.
  944. unsafe {
  945. let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  946. assert!(!at.is_null());
  947. // 0-0x1_1000 and 0x3_0000-0x4_0000 are there.
  948. for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] {
  949. assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null());
  950. at.add(from).write_bytes(0x5a, len);
  951. }
  952. // From an address inside a page, as textures are packed.
  953. let mut out = vec![0x77u8; SIZE - 0x300];
  954. assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000);
  955. for (i, &b) in out.iter().enumerate() {
  956. let from = i + 0x300;
  957. let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from);
  958. assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}");
  959. }
  960. // All there: one read.
  961. let mut out = vec![0x77u8; 0x1_0000];
  962. assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000);
  963. assert!(out.iter().all(|&b| b == 0x5a));
  964. // Nothing there.
  965. let mut out = vec![0x77u8; 0x1_0000];
  966. assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0);
  967. assert!(out.iter().all(|&b| b == 0));
  968. assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0);
  969. }
  970. }
  971. /// Zeros for a title destination that went meanwhile are no fault.
  972. #[test]
  973. fn zeros_where_nothing_is_are_lost() {
  974. use windows_sys::Win32::System::Memory::*;
  975. // SAFETY: a reservation of ours, its first page committed.
  976. unsafe {
  977. let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  978. assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
  979. at.write_bytes(7, 4096);
  980. super::zero(at, 4096);
  981. assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
  982. super::zero(at.add(4096), 4096);
  983. VirtualFree(at.cast(), 0, MEM_RELEASE);
  984. }
  985. }
  986. #[test]
  987. fn sparse_copies_preserve_islands_and_observe_remaps() {
  988. use windows_sys::Win32::System::Memory::*;
  989. const N: usize = 5 << 16;
  990. // SAFETY: we reserve a private region, commit selected pages inside it,
  991. // and only directly access the pages while they are writable.
  992. unsafe {
  993. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  994. assert!(!base.is_null());
  995. let mut expected = vec![0; N];
  996. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  997. let at = base.add(offset);
  998. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  999. at.write_bytes(value, 4096);
  1000. expected[offset..offset + 4096].fill(value);
  1001. }
  1002. for remap in [false, true] {
  1003. if remap {
  1004. let mut old = 0;
  1005. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  1006. expected[..4096].fill(0);
  1007. let at = base.add(1 << 16);
  1008. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  1009. at.write_bytes(0xc7, 4096);
  1010. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  1011. }
  1012. let mut out = vec![0xee; N];
  1013. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  1014. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  1015. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  1016. }
  1017. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  1018. }
  1019. }
  1020. use super::*;
  1021. #[test]
  1022. fn warp_adapter_accepts_only_software() {
  1023. // This probes DXGI without creating a D3D12 device or running a title.
  1024. // SAFETY: plain DXGI adapter queries.
  1025. let raw = unsafe {
  1026. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  1027. else {
  1028. return;
  1029. };
  1030. factory.EnumWarpAdapter::<IDXGIAdapter>()
  1031. };
  1032. let Ok(raw) = raw else { return };
  1033. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  1034. // IDXGIAdapter1; `raw` owns that interface.
  1035. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  1036. eprintln!(
  1037. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  1038. desc.VendorId, desc.Flags
  1039. );
  1040. assert_eq!(
  1041. warp_adapter().is_ok(),
  1042. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  1043. );
  1044. }
  1045. }
  1046. /// The batches of clamped records in one scratch buffer
  1047. /// ([`HostList::batch_place`]).
  1048. const BATCHES: u32 = 8;
  1049. /// A host command list and its allocator, always used together.
  1050. pub(crate) struct HostList {
  1051. allocator: ID3D12CommandAllocator,
  1052. pub(crate) list: ID3D12GraphicsCommandList,
  1053. /// Work for submission time, in recorded order.
  1054. deferred: Mutex<Deferred>,
  1055. /// Upload memory for data the list's draws make (expanded vertices),
  1056. /// reused after a reset.
  1057. scratch: Mutex<Scratch>,
  1058. /// Host texture states the list assumes, by host copy: at its start and
  1059. /// at its end. Lists are recorded on many threads and run in submission
  1060. /// order, so the transitions from a texture's real state are made at
  1061. /// submission, in `prelude`. Holding the copies keeps every texture the
  1062. /// list names alive until it is reset, even if the title releases the
  1063. /// resource first.
  1064. states: Mutex<States>,
  1065. /// What the list does with depth textures that have a colour twin, by
  1066. /// twin ([`TwinUse`]).
  1067. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  1068. /// The list that runs those transitions just before this one, made
  1069. /// when the list first has such transitions ([`lazy_prelude`]).
  1070. prelude: OnceLock<Option<Prelude>>,
  1071. /// The pipelines the list binds, for reports of slow submissions.
  1072. pipelines: std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>,
  1073. /// What its indirect executions ran, for the report of a removed device.
  1074. #[cfg(feature = "diagnostics")]
  1075. indirects: indirects::Shared,
  1076. /// The work its indirect executions may still do (`indirect`): a
  1077. /// shader-writable word, zeroed when the list is submitted, and after
  1078. /// it what the clamp notes about mesh records. In memory the CPU maps.
  1079. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  1080. /// The same words in the card's own memory ([`card_budget`]), which the
  1081. /// clamp uses instead when there is one: zeroed in the list before its
  1082. /// first clamp, its notes copied to `budget` when the list closes.
  1083. card_budget: OnceLock<Option<ID3D12Resource>>,
  1084. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  1085. /// grown to the largest indirect execution recorded on the list.
  1086. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  1087. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  1088. /// how many batches of this recording have a place in them.
  1089. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  1090. /// Refreshes of host copies that a thread of ours is still finding, and
  1091. /// where among the list's steps they belong ([`aside`]).
  1092. coming: Mutex<Option<(usize, std::sync::Arc<aside::Coming>)>>,
  1093. /// Another number each time something changes that what a draw reads
  1094. /// depends on ([`HostList::changed_something`]); no two lists have the
  1095. /// same.
  1096. epoch: std::sync::atomic::AtomicU64,
  1097. /// Counts the list in [`ALIVE`] while it lives.
  1098. _alive: Counted,
  1099. /// The texts of the markers `note_op` set, in order (for device-removed
  1100. /// data without marker texts), with the host GPU range a copy reads.
  1101. #[cfg(feature = "diagnostics")]
  1102. notes: std::sync::Arc<Mutex<Vec<Note>>>,
  1103. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  1104. /// and at the end, and where they are read back.
  1105. #[cfg(feature = "diagnostics")]
  1106. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  1107. }
  1108. /// A list's prelude: an allocator and a closed list.
  1109. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  1110. /// Whether a host list's prelude is made when the list first needs one. A
  1111. /// prelude runs the texture transitions and twin copies a list needs before
  1112. /// it; lists that name no texture never have one, and every host list was
  1113. /// made with one all the same: twice the host objects per list, for the
  1114. /// title's 630 lists and for every list made anew.
  1115. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  1116. fn lazy_prelude() -> bool {
  1117. static ON: OnceLock<bool> = OnceLock::new();
  1118. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  1119. }
  1120. /// Timestamps per list (diagnostics); commands past them are not timed.
  1121. #[cfg(feature = "diagnostics")]
  1122. const STAMPS: u32 = 4096;
  1123. /// A marker's text and the host range its command reads (diagnostics).
  1124. #[cfg(feature = "diagnostics")]
  1125. type Note = (String, Option<(u64, u64)>);
  1126. type States = std::collections::HashMap<
  1127. usize,
  1128. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  1129. >;
  1130. /// What a list does with a depth texture that has a colour twin
  1131. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  1132. /// in submission order, so a list cannot know which side an earlier list
  1133. /// leaves behind: it notes which sides it uses as it finds them, and its
  1134. /// prelude copies one side into the other at submission if that side is
  1135. /// behind then. From its first use of a side on, the list knows.
  1136. struct TwinUse {
  1137. /// The depth texture (the title resource's host copy) and its twin.
  1138. depth: std::sync::Arc<crate::resource::HostTexture>,
  1139. twin: std::sync::Arc<crate::resource::Twin>,
  1140. /// The sides (depth texture, twin) the list uses as it finds them.
  1141. needs: [bool; 2],
  1142. /// Whether each side lacks what the other was written last, where the
  1143. /// list is now; `None`: as the list found it.
  1144. behind: [Option<bool>; 2],
  1145. /// The draw or dispatch being prepared writes the twin.
  1146. writing: bool,
  1147. /// The depth plane's twin holds what the plane lacks although the list
  1148. /// copied the twins since: the plane's pass waits for the list's close.
  1149. late: bool,
  1150. }
  1151. /// The pass that draws the twin of a depth plane into the plane: one
  1152. /// triangle over each mip of each slice, its pixel shader writing the
  1153. /// twin's texel as the depth, with the depth test "always" and no stencil
  1154. /// (the stencil plane is copied through a buffer and not touched here).
  1155. ///
  1156. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  1157. /// the step times the float nearest 1/65535 (0x37800080). That is how
  1158. /// The title's tiled lighting computes the depth of the
  1159. /// rectangles it then draws with the test "equal", one class of materials
  1160. /// a draw (all six of its vertex shaders multiply the class number by that
  1161. /// constant), so the pass and the draw give the host the same float, and
  1162. /// the host turns the same float into the same 24 bits. The step divided
  1163. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  1164. /// and lands in another 24-bit step for 127 of them (none under 385).
  1165. const PLANE_CORNERS: &str = r#"
  1166. float4 corner(uint i : SV_VertexID) : SV_Position {
  1167. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  1168. }
  1169. "#;
  1170. const PLANE_STEPS: &str = r#"
  1171. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  1172. Texture2DArray<uint> twin : register(t0);
  1173. [RootSignature(RS)]
  1174. float plane(float4 p : SV_Position) : SV_Depth {
  1175. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  1176. }
  1177. "#;
  1178. const PLANE_FLOATS: &str = r#"
  1179. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  1180. Texture2DArray<float> twin : register(t0);
  1181. [RootSignature(RS)]
  1182. float plane(float4 p : SV_Position) : SV_Depth {
  1183. return twin.Load(int4(int2(p.xy), 0, 0));
  1184. }
  1185. "#;
  1186. /// Views of twins the pass reads, in a heap of ours used as a ring.
  1187. /// shortcut: a view must last until its list has run; with one or two
  1188. /// passes a frame the ring is far from coming round.
  1189. const PLANE_VIEWS: u32 = 256;
  1190. /// What the pass draws with: the heap of its views of twins, and per kind
  1191. /// of twin (16-bit steps or floats) and depth format the root signature
  1192. /// and pipeline, made when first needed (`None`: the host refused).
  1193. struct PlanePass {
  1194. views: ID3D12DescriptorHeap,
  1195. cpu: usize,
  1196. gpu: u64,
  1197. step: u32,
  1198. next: AtomicU32,
  1199. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  1200. }
  1201. /// The pass's root signature and pipeline for one kind of twin and one
  1202. /// depth format.
  1203. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  1204. // SAFETY: D3D12 objects are free-threaded.
  1205. unsafe impl Send for PlanePass {}
  1206. // SAFETY: as above.
  1207. unsafe impl Sync for PlanePass {}
  1208. fn plane_pass() -> Option<&'static PlanePass> {
  1209. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  1210. PASS.get_or_init(|| {
  1211. let host = host()?;
  1212. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1213. // SAFETY: plain heap creation and queries.
  1214. unsafe {
  1215. let views: ID3D12DescriptorHeap = host
  1216. .device
  1217. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  1218. Type: kind,
  1219. NumDescriptors: PLANE_VIEWS,
  1220. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  1221. NodeMask: 0,
  1222. })
  1223. .ok()?;
  1224. Some(PlanePass {
  1225. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  1226. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  1227. step: host.device.GetDescriptorHandleIncrementSize(kind),
  1228. views,
  1229. next: AtomicU32::new(0),
  1230. made: Mutex::default(),
  1231. })
  1232. }
  1233. })
  1234. .as_ref()
  1235. }
  1236. /// Compiles function `entry` of `source` for `target` with the system's
  1237. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  1238. pub(crate) fn compile(
  1239. source: &str,
  1240. entry: windows::core::PCSTR,
  1241. target: windows::core::PCSTR,
  1242. ) -> windows::core::Result<Vec<u8>> {
  1243. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  1244. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  1245. let mut code: Option<ID3DBlob> = None;
  1246. let mut errors: Option<ID3DBlob> = None;
  1247. // SAFETY: the source and names live through the call; out pointers ours.
  1248. let compiled = unsafe {
  1249. D3DCompile(
  1250. source.as_ptr().cast(),
  1251. source.len(),
  1252. windows::core::s!("victory"),
  1253. None,
  1254. None,
  1255. entry,
  1256. target,
  1257. 0,
  1258. 0,
  1259. &mut code,
  1260. Some(&mut errors),
  1261. )
  1262. };
  1263. if let Err(e) = compiled {
  1264. if let Some(errors) = errors {
  1265. // SAFETY: the blob's own bytes.
  1266. let text = unsafe {
  1267. std::slice::from_raw_parts(
  1268. errors.GetBufferPointer().cast::<u8>(),
  1269. errors.GetBufferSize(),
  1270. )
  1271. };
  1272. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  1273. }
  1274. return Err(e);
  1275. }
  1276. let code = code.ok_or_else(windows::core::Error::empty)?;
  1277. // SAFETY: the blob's own bytes.
  1278. let bytes = unsafe {
  1279. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  1280. };
  1281. Ok(bytes.to_vec())
  1282. }
  1283. impl PlanePass {
  1284. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  1285. /// or of floats and the depth format `format`.
  1286. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  1287. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1288. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  1289. return pipeline.clone();
  1290. }
  1291. let pipeline = match Self::make(steps, format) {
  1292. Ok(pipeline) => Some(pipeline),
  1293. Err(e) => {
  1294. tracing::warn!(
  1295. error = %e,
  1296. steps,
  1297. format = format.0,
  1298. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  1299. );
  1300. None
  1301. }
  1302. };
  1303. made.push((steps, format.0, pipeline.clone()));
  1304. pipeline
  1305. }
  1306. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  1307. use windows::core::s;
  1308. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  1309. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  1310. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  1311. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  1312. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  1313. pShaderBytecode: bytes.as_ptr().cast(),
  1314. BytecodeLength: bytes.len(),
  1315. };
  1316. // SAFETY: the root signature is inside the pixel shader; the
  1317. // description points at live data and never releases its pointer.
  1318. unsafe {
  1319. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  1320. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1321. pRootSignature: std::mem::transmute_copy(&root),
  1322. VS: code(&vs[..]),
  1323. PS: code(&ps[..]),
  1324. SampleMask: u32::MAX,
  1325. RasterizerState: D3D12_RASTERIZER_DESC {
  1326. FillMode: D3D12_FILL_MODE_SOLID,
  1327. CullMode: D3D12_CULL_MODE_NONE,
  1328. DepthClipEnable: true.into(),
  1329. ..Default::default()
  1330. },
  1331. // Every texel is written; stencil stays off.
  1332. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1333. DepthEnable: true.into(),
  1334. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  1335. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1336. ..Default::default()
  1337. },
  1338. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1339. DSVFormat: format,
  1340. SampleDesc: DXGI_SAMPLE_DESC {
  1341. Count: 1,
  1342. Quality: 0,
  1343. },
  1344. ..Default::default()
  1345. };
  1346. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1347. Ok((root, pipeline))
  1348. }
  1349. }
  1350. }
  1351. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1352. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1353. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1354. /// heap, graphics root signature, pipeline, depth target, viewport,
  1355. /// scissor and topology and puts none of them back: it is for a list that
  1356. /// records nothing of the title's after it.
  1357. fn record_plane_pass(
  1358. list: &ID3D12GraphicsCommandList,
  1359. depth: &ID3D12Resource,
  1360. plane: &ID3D12Resource,
  1361. ) {
  1362. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1363. return;
  1364. };
  1365. // SAFETY: live resources.
  1366. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1367. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1368. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1369. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1370. let steps = twin.Format.0 == 53;
  1371. let format = DXGI_FORMAT(match of.Format.0 {
  1372. 44 => 45,
  1373. 19 => 20,
  1374. typed => typed,
  1375. });
  1376. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1377. return;
  1378. };
  1379. for slice in 0..u32::from(of.DepthOrArraySize) {
  1380. for mip in 0..u32::from(of.MipLevels) {
  1381. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1382. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1383. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1384. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1385. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1386. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1387. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1388. MostDetailedMip: mip,
  1389. MipLevels: 1,
  1390. FirstArraySlice: slice,
  1391. ArraySize: 1,
  1392. ..Default::default()
  1393. },
  1394. },
  1395. };
  1396. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1397. Format: format,
  1398. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1399. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1400. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1401. MipSlice: mip,
  1402. FirstArraySlice: slice,
  1403. ArraySize: 1,
  1404. },
  1405. },
  1406. ..Default::default()
  1407. };
  1408. let target = host.dsv(depth, Some(&target));
  1409. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1410. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1411. ptr: pass.cpu + (slot * pass.step) as usize,
  1412. };
  1413. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1414. ptr: pass.gpu + u64::from(slot * pass.step),
  1415. };
  1416. // SAFETY: an open list; a slot of our heap; live resources and
  1417. // objects (the pass's own live as long as the process).
  1418. unsafe {
  1419. host.device
  1420. .CreateShaderResourceView(plane, Some(&view), cpu);
  1421. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1422. list.SetGraphicsRootSignature(&root);
  1423. list.SetPipelineState(&pipeline);
  1424. list.SetGraphicsRootDescriptorTable(0, gpu);
  1425. list.OMSetRenderTargets(0, None, false, Some(&target));
  1426. list.RSSetViewports(&[D3D12_VIEWPORT {
  1427. TopLeftX: 0.0,
  1428. TopLeftY: 0.0,
  1429. Width: width as f32,
  1430. Height: height as f32,
  1431. MinDepth: 0.0,
  1432. MaxDepth: 1.0,
  1433. }]);
  1434. list.RSSetScissorRects(&[RECT {
  1435. left: 0,
  1436. top: 0,
  1437. right: width as i32,
  1438. bottom: height as i32,
  1439. }]);
  1440. list.IASetPrimitiveTopology(
  1441. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1442. );
  1443. list.DrawInstanced(3, 1, 0, 0);
  1444. }
  1445. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1446. }
  1447. }
  1448. }
  1449. /// Records into `list` the copy of a depth texture into its colour twin
  1450. /// (`colour`) or of the twin into the depth texture, both already in their
  1451. /// copy states: whole textures of one size in one format family, which the
  1452. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1453. /// alone, through the twin's buffer.
  1454. fn record_twin_copy(
  1455. list: &ID3D12GraphicsCommandList,
  1456. depth: &ID3D12Resource,
  1457. twin: &crate::resource::Twin,
  1458. colour: bool,
  1459. ) {
  1460. let (from, to) = if colour {
  1461. (depth, &twin.colour.texture)
  1462. } else {
  1463. (&twin.colour.texture, depth)
  1464. };
  1465. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1466. // shortcut: the depth plane's twin is not given the plane (that is a
  1467. // pass the other way: the plane read by a shader, the twin as its
  1468. // target). The twin then lacks what draws and clears wrote to the
  1469. // plane since shaders last wrote the twin. In the title
  1470. // nothing writes that plane but the twin's pass (its 192 draws against
  1471. // it only test, run 29), so the twin lacks nothing. Counted.
  1472. if colour && twin.plane.is_some() {
  1473. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1474. }
  1475. let Some(through) = &twin.through else {
  1476. // SAFETY: an open list and two live textures.
  1477. unsafe { list.CopyResource(to, from) };
  1478. return;
  1479. };
  1480. // A stencil plane and its twin: each mip and slice of the plane goes
  1481. // into the buffer, laid out as the host lays the plane out for copies,
  1482. // and from the buffer into the other texture, whole subresources both
  1483. // times. In the depth texture the stencil plane's subresources follow
  1484. // the depth plane's; the twin has the one plane.
  1485. let Some(host) = host() else { return };
  1486. // SAFETY: a live texture.
  1487. let of = unsafe { depth.GetDesc() };
  1488. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1489. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1490. // SAFETY: a plain query writing `planes` footprints.
  1491. unsafe {
  1492. host.device.GetCopyableFootprints(
  1493. &of,
  1494. planes,
  1495. planes,
  1496. 0,
  1497. Some(rows.as_mut_ptr()),
  1498. None,
  1499. None,
  1500. None,
  1501. );
  1502. }
  1503. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1504. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1505. // SAFETY: a borrowed pointer the location never releases.
  1506. pResource: unsafe { std::mem::transmute_copy(texture) },
  1507. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1508. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1509. SubresourceIndex: index,
  1510. },
  1511. };
  1512. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1513. // SAFETY: as above.
  1514. pResource: unsafe { std::mem::transmute_copy(through) },
  1515. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1516. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1517. PlacedFootprint: *row,
  1518. },
  1519. };
  1520. let (common, source, dest) = (
  1521. D3D12_RESOURCE_STATE_COMMON,
  1522. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1523. D3D12_RESOURCE_STATE_COPY_DEST,
  1524. );
  1525. // SAFETY: an open list and live resources; the buffer was made as big
  1526. // as these footprints, and rests in the common state between copies.
  1527. unsafe {
  1528. list.ResourceBarrier(&[transition(through, common, dest)]);
  1529. for (i, row) in rows.iter().enumerate() {
  1530. let index = first_from + i as u32;
  1531. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1532. }
  1533. list.ResourceBarrier(&[transition(through, dest, source)]);
  1534. for (i, row) in rows.iter().enumerate() {
  1535. let index = first_to + i as u32;
  1536. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1537. }
  1538. list.ResourceBarrier(&[transition(through, source, common)]);
  1539. }
  1540. }
  1541. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1542. /// builds).
  1543. pub(crate) fn dred_on() -> bool {
  1544. static ON: OnceLock<bool> = OnceLock::new();
  1545. *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED") && !dred_faults() && !dred_light())
  1546. }
  1547. /// Breadcrumbs and the faulting address, but no markers and no texts
  1548. /// (`VICTORY_D3D12_DRED=light`): which list a removed device stopped in, at
  1549. /// which of its commands, and the pipelines the list binds; formatting a text
  1550. /// for every command is what makes the whole of it slow.
  1551. pub(crate) fn dred_light() -> bool {
  1552. static ON: OnceLock<bool> = OnceLock::new();
  1553. *ON.get_or_init(|| {
  1554. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "light")
  1555. })
  1556. }
  1557. /// Any of the three.
  1558. pub(crate) fn dred_any() -> bool {
  1559. dred_on() || dred_light() || dred_faults()
  1560. }
  1561. /// Whether only the faulting address of a removed device is kept
  1562. /// (`VICTORY_D3D12_DRED=faults`): no breadcrumbs, no markers and no texts, so
  1563. /// it costs next to nothing and can stay on while the title is played.
  1564. pub(crate) fn dred_faults() -> bool {
  1565. static ON: OnceLock<bool> = OnceLock::new();
  1566. *ON.get_or_init(|| {
  1567. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "faults")
  1568. })
  1569. }
  1570. /// The lists alive while device-removed data is on, by the number their name
  1571. /// ends in, with their marker texts and the pipelines they bind: a report made
  1572. /// on another thread than the one that submits has no lists of its own.
  1573. #[cfg(feature = "diagnostics")]
  1574. #[allow(clippy::type_complexity)]
  1575. static LIST_NOTES: Mutex<
  1576. std::collections::BTreeMap<
  1577. u32,
  1578. (
  1579. std::sync::Weak<Mutex<Vec<Note>>>,
  1580. std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>,
  1581. std::sync::Weak<Mutex<indirects::Indirects>>,
  1582. ),
  1583. >,
  1584. > = Mutex::new(std::collections::BTreeMap::new());
  1585. /// The number in the name of a list of ours ("victory host list 7", which the
  1586. /// debug layer ends with a note of its own in brackets).
  1587. #[cfg(feature = "diagnostics")]
  1588. fn list_number(name: &str) -> Option<u32> {
  1589. let rest = name.strip_prefix("victory host list ")?;
  1590. let digits = rest.split(' ').next()?;
  1591. (rest.len() == digits.len() || rest[digits.len()..].starts_with(" (")).then(|| digits.parse().ok()).flatten()
  1592. }
  1593. /// Indirect mesh dispatches since the last frame line: the largest group
  1594. /// count a record asked for, and the groups asked in all (from the lists'
  1595. /// budget buffers, a run late).
  1596. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1597. /// Whether a list's indirect-work budget lives in the card's own memory
  1598. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1599. /// before). The clamp charges it with atomics, at least two in a row for
  1600. /// every clamp; in mapped memory on a card of its own each of them
  1601. /// crosses the bus.
  1602. fn card_budget() -> bool {
  1603. static ON: OnceLock<bool> = OnceLock::new();
  1604. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1605. }
  1606. /// Whether each list of a submission runs and is timed on its own, slow
  1607. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1608. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1609. #[cfg(feature = "diagnostics")]
  1610. fn timing() -> bool {
  1611. static ON: OnceLock<bool> = OnceLock::new();
  1612. *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING"))
  1613. }
  1614. /// Names a host object for the device-removed report, which names the
  1615. /// allocations a page fault hit (only with device-removed data on), or for
  1616. /// the frame recorder (`VICTORY_RECORD`).
  1617. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1618. #[cfg(feature = "diagnostics")]
  1619. if crate::book::on()
  1620. && let Ok(resource) = object.cast::<ID3D12Resource>()
  1621. {
  1622. let text = text();
  1623. crate::book::made(&resource, || text.clone());
  1624. return name_it(object, || text);
  1625. }
  1626. name_it(object, text);
  1627. }
  1628. fn name_it(object: &impl Interface, text: impl FnOnce() -> String) {
  1629. #[cfg(feature = "diagnostics")]
  1630. if crate::replay::record::on() {
  1631. let text = text();
  1632. crate::replay::record::name(object, &text);
  1633. if dred_any()
  1634. && let Ok(object) = object.cast::<ID3D12Object>()
  1635. {
  1636. // SAFETY: a plain call on a live object.
  1637. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1638. }
  1639. return;
  1640. }
  1641. if dred_any()
  1642. && let Ok(object) = object.cast::<ID3D12Object>()
  1643. {
  1644. // SAFETY: a plain call on a live object.
  1645. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1646. }
  1647. }
  1648. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1649. /// [`LISTS`]`[3]` until it is first reset.
  1650. struct Counted {
  1651. /// Not reset since it was made.
  1652. fresh: std::sync::atomic::AtomicBool,
  1653. }
  1654. impl Counted {
  1655. fn new() -> Counted {
  1656. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1657. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1658. Counted {
  1659. fresh: std::sync::atomic::AtomicBool::new(true),
  1660. }
  1661. }
  1662. /// The list is reset: it is in use.
  1663. fn used(&self) {
  1664. if self.fresh.swap(false, Ordering::Relaxed) {
  1665. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1666. }
  1667. }
  1668. }
  1669. impl Drop for Counted {
  1670. fn drop(&mut self) {
  1671. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1672. self.used();
  1673. }
  1674. }
  1675. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1676. /// mapping.
  1677. struct Chunk {
  1678. buffer: ID3D12Resource,
  1679. data: usize,
  1680. }
  1681. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1682. // written only by the list that holds the chunk.
  1683. unsafe impl Send for Chunk {}
  1684. /// Upload chunks handed out front to back: the chunks (each with its
  1685. /// bytes), the one in use and the bytes used in it.
  1686. #[derive(Default)]
  1687. struct Scratch {
  1688. chunks: Vec<(Chunk, u64)>,
  1689. current: usize,
  1690. used: u64,
  1691. }
  1692. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1693. unsafe impl Send for Scratch {}
  1694. impl Drop for Scratch {
  1695. fn drop(&mut self) {
  1696. give_chunks(std::mem::take(&mut self.chunks));
  1697. }
  1698. }
  1699. const SCRATCH_CHUNK: u64 = 4 << 20;
  1700. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1701. /// lists put a few constants or a rectangle's corners there, and every
  1702. /// list that did took 4 MiB of the PC's memory for it.
  1703. const SCRATCH_FIRST: u64 = 256 << 10;
  1704. /// The most bytes of chunks kept while no list holds them.
  1705. const SPARE_MOST: u64 = 128 << 20;
  1706. /// The same with [`keep_freed`].
  1707. const SPARE_KEPT: u64 = 1 << 30;
  1708. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1709. /// first needs one, a small one first, and gives all of them back when it
  1710. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1711. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1712. /// host lists of held submissions, which live for one submission, each
  1713. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1714. /// freed per frame of gameplay (run 60).
  1715. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1716. fn scratch_pool() -> bool {
  1717. static ON: OnceLock<bool> = OnceLock::new();
  1718. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1719. }
  1720. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1721. /// for one of the same size.
  1722. struct Spare<T> {
  1723. kept: Vec<(T, u64)>,
  1724. bytes: u64,
  1725. }
  1726. impl<T> Spare<T> {
  1727. const fn new() -> Self {
  1728. Spare { kept: Vec::new(), bytes: 0 }
  1729. }
  1730. /// A kept thing of `size` bytes, the one given last.
  1731. fn take(&mut self, size: u64) -> Option<T> {
  1732. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1733. self.bytes -= size;
  1734. Some(self.kept.remove(at).0)
  1735. }
  1736. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1737. /// `most`: then it comes back.
  1738. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1739. if self.bytes + size > most {
  1740. return Some(thing);
  1741. }
  1742. self.bytes += size;
  1743. self.kept.push((thing, size));
  1744. None
  1745. }
  1746. }
  1747. /// Scratch chunks no list holds.
  1748. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1749. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1750. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1751. if scratch_pool()
  1752. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1753. {
  1754. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1755. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1756. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1757. return Some(chunk);
  1758. }
  1759. let (buffer, data) = host.upload_buffer(size)?;
  1760. name(&buffer, || "list scratch".into());
  1761. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1762. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1763. Some(Chunk {
  1764. buffer,
  1765. data: data as usize,
  1766. })
  1767. }
  1768. /// A list is done with `chunks` (it was reset after its submissions ran,
  1769. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1770. /// without the pool.
  1771. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1772. if chunks.is_empty() {
  1773. return;
  1774. }
  1775. let mut freed = Vec::new();
  1776. {
  1777. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1778. for (chunk, size) in chunks {
  1779. let back = if scratch_pool() {
  1780. spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST })
  1781. } else {
  1782. Some(chunk)
  1783. };
  1784. match back {
  1785. None => {
  1786. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1787. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1788. }
  1789. Some(chunk) => {
  1790. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1791. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1792. freed.push(chunk);
  1793. }
  1794. }
  1795. }
  1796. }
  1797. // Freed outside the lock.
  1798. drop(freed);
  1799. }
  1800. /// What the host keeps for copies in the card's own memory
  1801. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1802. struct CardWork {
  1803. /// Before a submission's lists: what changed on the copies' CPU side
  1804. /// goes to their card side. Those not in use: a plan takes one and
  1805. /// gives it back when its submission has run (`Host::card_done`), so
  1806. /// that submissions sent ahead ([`late`]) each have their own.
  1807. sync: Vec<Prelude>,
  1808. /// After them, in the same submission: the compare of the declared
  1809. /// ranges with their bytes from before. As `sync`.
  1810. check: Vec<Prelude>,
  1811. /// After it ran: the pieces that differ come down.
  1812. fetch: Prelude,
  1813. root: ID3D12RootSignature,
  1814. pso: ID3D12PipelineState,
  1815. /// One dword per piece compared, odd where the piece differs: PC
  1816. /// memory, mapped (buffer, mapping, bytes).
  1817. differs: (ID3D12Resource, usize, u64),
  1818. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1819. fetched: Option<(ID3D12Resource, usize, u64)>,
  1820. /// The dwords of `differs` taken by plans whose results were not read
  1821. /// yet.
  1822. taken: u32,
  1823. /// Plans made and not done with (`Host::card_done`).
  1824. out: u32,
  1825. }
  1826. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1827. // under the submission lock.
  1828. unsafe impl Send for CardWork {}
  1829. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1830. /// The compare of a declared range of a copy in the card's memory with
  1831. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1832. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1833. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1834. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1835. /// byte just outside the range costs a fetch that finds nothing.
  1836. ///
  1837. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1838. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1839. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1840. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1841. /// those steps.
  1842. pub(crate) const CARD_COMPARE: &str = r#"
  1843. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1844. cbuffer Span : register(b0) {
  1845. uint first; // the first piece
  1846. uint skew; // where the copy starts in its piece 0
  1847. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1848. uint pieces;
  1849. uint out_at; // the first piece's dword in `differs`, in bytes
  1850. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1851. };
  1852. ByteAddressBuffer now : register(t0);
  1853. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1854. // last sent up (or hashed whole, the first time).
  1855. RWByteAddressBuffer hashes : register(u0);
  1856. RWByteAddressBuffer differs : register(u1);
  1857. groupshared uint4 parts[64];
  1858. [RootSignature(RS)]
  1859. [numthreads(64, 1, 1)]
  1860. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1861. uint piece = first + id.x;
  1862. uint lo = piece * 65536u;
  1863. lo = lo > skew ? lo - skew : 0u;
  1864. uint hi = min((piece + 1u) * 65536u - skew, size);
  1865. lo = lo & ~15u;
  1866. hi = (hi + 15u) & ~15u;
  1867. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1868. [loop]
  1869. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1870. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1871. h = h.yzwx ^ (h >> 15);
  1872. }
  1873. parts[thread] = h;
  1874. GroupMemoryBarrierWithGroupSync();
  1875. if (thread != 0u) return;
  1876. h = parts[0];
  1877. [loop]
  1878. for (uint i = 1u; i < 64u; ++i) {
  1879. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1880. h = h.yzwx ^ (h >> 15);
  1881. }
  1882. if (compare != 0u) {
  1883. // The flag, and above it 31 bits of the hash (`torn`).
  1884. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1885. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1886. // With the copy-back on its own thread: the next compare of the
  1887. // piece finds what is written from here on.
  1888. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1889. } else {
  1890. hashes.Store4(piece * 16u, h);
  1891. }
  1892. }
  1893. "#;
  1894. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1895. #[cfg(test)]
  1896. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1897. torn::hash(bytes)
  1898. }
  1899. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1900. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1901. /// parts a dispatch can hold.
  1902. ///
  1903. /// # Safety
  1904. /// The list is open with the compare's root signature, pipeline and buffers
  1905. /// set, and the pieces lie in the buffer.
  1906. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1907. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1908. let mut done = 0;
  1909. while done < span.pieces {
  1910. let n = (span.pieces - done).min(MOST);
  1911. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1912. // SAFETY: the caller's.
  1913. unsafe {
  1914. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1915. list.Dispatch(n, 1, 1);
  1916. }
  1917. done += n;
  1918. }
  1919. }
  1920. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1921. /// the card's memory are hashed in runs of pieces that touch, each piece
  1922. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1923. /// per range sent up.
  1924. ///
  1925. /// These passes are ours, they run on the card before every submission's
  1926. /// lists: a pass takes the time of one piece however few its pieces are.
  1927. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1928. /// a piece hashed when it need not be, or not hashed when it should, costs
  1929. /// a fetch that finds nothing and loses no shader write.
  1930. fn rehash_runs() -> bool {
  1931. static ON: OnceLock<bool> = OnceLock::new();
  1932. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1933. }
  1934. /// Since the last frame-rate line, of our own passes over copies in the
  1935. /// card's memory: hash passes after ranges were sent up, the pieces they
  1936. /// hashed, and compare passes after the lists.
  1937. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1938. /// Whether what shaders wrote to copies in the card's memory is merged
  1939. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1940. /// default). The pieces the card's compare found differing come down in
  1941. /// one fetch and were then merged one after the other on the thread that
  1942. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1943. /// with the copy's CPU side byte by byte and put into title memory through
  1944. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1945. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1946. /// landings do not come here: `crate::land` has threads of its own.)
  1947. fn wide_merge() -> bool {
  1948. static ON: OnceLock<bool> = OnceLock::new();
  1949. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1950. }
  1951. /// One declared range of a copy in the card's memory, in a submission.
  1952. struct CardRange {
  1953. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1954. /// As declared (title addresses), for the statistics.
  1955. declared: (usize, usize),
  1956. span: crate::shadow::CardSpan,
  1957. /// Its first piece's dword in the compare's results.
  1958. at: u32,
  1959. /// Whether the card compares it; else every piece is fetched.
  1960. compared: bool,
  1961. /// Looked at by `crate::picked`, and not declared: what is found changed
  1962. /// there was written through a view nobody declared. Not landed.
  1963. picked: bool,
  1964. }
  1965. impl CardPlan {
  1966. /// `crate::picked` is told where what it looked at changed, by the
  1967. /// compare's results.
  1968. fn picked_found(&self, differs: &[u32]) {
  1969. for r in self.ranges.iter().filter(|r| r.picked) {
  1970. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1971. if let Some(p) = changed {
  1972. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1973. }
  1974. }
  1975. }
  1976. }
  1977. /// What a submission does for copies in the card's memory.
  1978. struct CardPlan {
  1979. ranges: Vec<CardRange>,
  1980. /// The compare, run after the submission's lists.
  1981. check: Option<ID3D12CommandList>,
  1982. /// The copies whose card side was brought up to date, alive until the
  1983. /// submission has run.
  1984. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1985. /// The lists of ours the plan recorded (whether the compare, the
  1986. /// list), given back by `Host::card_done`.
  1987. lists: Vec<(bool, Prelude)>,
  1988. /// With [`relay`]: the number of the send to copies in the card's memory
  1989. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1990. sent_as: u64,
  1991. /// With [`upcheck`]: the look at what it sent up.
  1992. looks: Option<upcheck::Looks>,
  1993. /// With [`send`]: the memory its sends come from.
  1994. sends: Option<send::Memory>,
  1995. }
  1996. /// One piece of submission-time work, in recorded order.
  1997. enum Step {
  1998. /// A copy into title memory (destination, source, bytes): the title's
  1999. /// buffer copies, which later refreshes must see.
  2000. Copy(usize, usize, usize),
  2001. /// A copy of title memory into the list's own upload memory, and how
  2002. /// the card could bring the bytes instead.
  2003. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  2004. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  2005. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  2006. /// intervenes.
  2007. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  2008. /// Work that may write title memory.
  2009. Run(Box<dyn Fn() + Send>),
  2010. /// Work that writes host memory only, and the title memory it reads
  2011. /// (from, to; empty for none).
  2012. Host(Box<dyn Fn() + Send>, (usize, usize)),
  2013. /// Shaders write a range (address, bytes) of a buffer's host copy.
  2014. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  2015. /// Brings a texture's staging buffer up to date: once per submission,
  2016. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  2017. Texture(std::sync::Arc<crate::texture::Staging>),
  2018. /// A title buffer copy that the list does on the card ([`place`]): what
  2019. /// is done on the CPU for it.
  2020. Placed(place::Placed),
  2021. }
  2022. /// What a list does on the CPU when it is submitted: copies between host
  2023. /// memory regions (title buffers, upload buffers and buffer copies), and
  2024. /// the upload buffers its GPU commands read, kept until the list is reset.
  2025. #[derive(Default)]
  2026. struct Deferred {
  2027. /// Destination, source, bytes.
  2028. copies: Vec<Step>,
  2029. uploads: Vec<ID3D12Resource>,
  2030. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  2031. upload_bytes: u64,
  2032. /// Host objects the list's commands name (pipelines, root signatures,
  2033. /// descriptor heaps): the title may release its objects before it
  2034. /// submits the list.
  2035. kept: Vec<windows::core::IUnknown>,
  2036. /// Buffer ranges refreshed since the last title copy (host copy,
  2037. /// address, bytes): refreshing them again would find the same bytes.
  2038. refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>,
  2039. /// Textures whose contents the list brings up to date.
  2040. textures: std::collections::HashSet<usize>,
  2041. /// Bottom-of-pipe writes, done once the list has run: address, what,
  2042. /// bytes.
  2043. writes: Vec<(usize, crate::queue::Written, usize)>,
  2044. /// Textures read back (texture to buffer copies), done once the list
  2045. /// has run: the host buffer the list copies the texels into, the title
  2046. /// memory they go to, the bytes of a row, the rows, the title's row
  2047. /// pitch.
  2048. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  2049. /// Whether the indirect-work budget is zeroed for this recording (a
  2050. /// step on the CPU, or in the list for the card's copy).
  2051. budget_zeroed: bool,
  2052. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  2053. /// interface pointer) that a clamp in this recording left readable as
  2054. /// indirect arguments; 0 if none. It stays readable until the next
  2055. /// clamp into it ([`HostList::indirect_state`]).
  2056. indirect_readable: usize,
  2057. }
  2058. impl Deferred {
  2059. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  2060. /// reset.
  2061. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  2062. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  2063. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  2064. self.upload_bytes += size;
  2065. self.uploads.push(buffer);
  2066. }
  2067. }
  2068. impl Drop for Deferred {
  2069. fn drop(&mut self) {
  2070. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  2071. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  2072. }
  2073. }
  2074. /// Whether a queue's submissions go to the card without a wait for each
  2075. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  2076. /// waits for every list on its own).
  2077. ///
  2078. /// Every submission was prepared, sent, waited for and copied back before
  2079. /// the next one was looked at, so the card stood idle while we prepared
  2080. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  2081. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  2082. /// other, on the one thread that submits.
  2083. ///
  2084. /// With the switch a queue's submission is sent and joins a line of
  2085. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  2086. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  2087. /// for the card, what their shaders wrote copied back once per byte, then
  2088. /// their bottom-of-pipe writes and the fence signals behind them, in
  2089. /// order) at the next point where the title, or our own preparing, can
  2090. /// observe what they do. Those points, exactly:
  2091. ///
  2092. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  2093. /// read-back or map of a texture, a clear or upload run at once;
  2094. /// 2. the next submission reads title memory that a flight's shaders may
  2095. /// write: a title buffer copy, a fill of upload memory, a texture's
  2096. /// memory, any step that runs code of ours on title memory
  2097. /// ([`late_blocked`]);
  2098. /// 3. the next submission refreshes a range of a host copy that a flight's
  2099. /// shaders may write, and the title wrote a page of it since it was last
  2100. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  2101. /// alone until the flight's writes are back, as it always did within a
  2102. /// submission;
  2103. /// 4. a queue stands at a wait for a memory value that no flight's
  2104. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  2105. /// write ([`late_met`]);
  2106. /// 5. the title blocks on a fence without an event;
  2107. /// 6. the card has run every flight (a thread of ours waits for that:
  2108. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  2109. ///
  2110. /// What the title is told (bottom-of-pipe writes, fence values) is told
  2111. /// when the card has really run the work, later than before and never
  2112. /// earlier; a fence signalled on a queue while flights are in the air is
  2113. /// set behind them. A wait for a memory value that a flight's
  2114. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  2115. /// the card behind that flight, which is the order the wait asks for.
  2116. ///
  2117. /// What it assumes beyond today: memory the title rewrites between two of
  2118. /// its submissions, without waiting for the first, may be seen by the
  2119. /// first's shaders (as on the console, where the card reads title memory
  2120. /// when it runs, not when the list is submitted).
  2121. pub(crate) fn late() -> bool {
  2122. late_stage() > 0
  2123. }
  2124. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  2125. fn late_stage() -> u8 {
  2126. static STAGE: OnceLock<u8> = OnceLock::new();
  2127. *STAGE.get_or_init(|| {
  2128. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  2129. return 0;
  2130. }
  2131. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  2132. Ok("1") => 1,
  2133. Ok("2") => 2,
  2134. Ok("3") => 3,
  2135. // The relay alone: on top of stage 3.
  2136. Err(_) if crate::shadow::relay() => 3,
  2137. _ => 0,
  2138. }
  2139. })
  2140. }
  2141. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  2142. /// longer a point. Where the title wrote a page that lies in a range a
  2143. /// flight's shaders may write, the bytes the title changed are found (the
  2144. /// page as it is now against what the copy held when the flight was
  2145. /// prepared) and put into the copy, and only those: what the flight's
  2146. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  2147. /// flights are settled for it only where that cannot be done: memory that
  2148. /// is not write-watched, or a copy in the card's memory with more changed
  2149. /// runs than a submission should send up one by one.
  2150. ///
  2151. /// In run 92 (stage 1) this point settled the flights five times a frame
  2152. /// of twelve, each time with the card's work still to wait for: 172 ms a
  2153. /// frame of waiting were left of 200.
  2154. ///
  2155. /// What differs from settling first: a byte both the title and a flight's
  2156. /// shader wrote is the title's if the shader wrote it first, the shader's
  2157. /// if it wrote it afterwards; settled first it was always the shader's.
  2158. /// The title writing a byte a shader of its own is writing is a race on
  2159. /// the console too.
  2160. fn late_exact() -> bool {
  2161. late_stage() > 1
  2162. }
  2163. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  2164. /// no longer a point where flights are settled). The copy to the back
  2165. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  2166. /// its own for each present in the air) and the swap chain is told to
  2167. /// present behind it; the queue's call returns, and the card finishes the
  2168. /// frame while the title records the next one. What the title is told
  2169. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  2170. /// has run it, by the settling thread.
  2171. ///
  2172. /// What is left out with it: the look whether the presented frame is black
  2173. /// (diagnostics; it reads the frame back at once). A frame that is saved
  2174. /// or listed is presented the old way. Once every second and a half a
  2175. /// submission settles the flights all the same, for the sweep that lets
  2176. /// idle host objects go (it needs nothing in the air).
  2177. pub(crate) fn late_free_present() -> bool {
  2178. late_stage() > 2
  2179. }
  2180. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  2181. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  2182. /// and is off with it, in the timing run and with kept snapshots).
  2183. ///
  2184. /// With [`late`] alone every settle does three things on the thread that
  2185. /// holds the submission lock: it waits for everything in the air, copies
  2186. /// back with the card standing, and only then goes on preparing. The frame
  2187. /// stays a relay: the card works about 242 ms of it and one thread
  2188. /// prepares, waits and copies back for about 220.
  2189. ///
  2190. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  2191. /// soon as the card has run them, in the order they were sent and without
  2192. /// the submission lock: it fetches and merges what their shaders wrote to
  2193. /// copies in the card's memory, compares and merges the other copies,
  2194. /// frees the flights' ranges, and then does their read-backs, their
  2195. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  2196. /// order. The submitting thread meanwhile prepares and sends the next
  2197. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  2198. /// that thread has landed everything in the air, at the same points as
  2199. /// before (the list in [`late`]), so whoever can observe title memory, a
  2200. /// fence or a present still does so only after the flights before it are
  2201. /// merged.
  2202. ///
  2203. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  2204. /// flight; a merge that never stores into memory the card may be writing;
  2205. /// sends to card copies numbered) and here: flights land in the order of
  2206. /// [`LINE`] by one thread, so a later flight's results never reach title
  2207. /// memory before an earlier flight's; the compare on the card stores the
  2208. /// hash it made, so each flight's compare flags exactly what changed since
  2209. /// the compare before it, however late the pieces are fetched; the fetch
  2210. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  2211. /// title bytes the card had received when it ran.
  2212. pub(crate) fn relay() -> bool {
  2213. static ON: OnceLock<bool> = OnceLock::new();
  2214. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  2215. }
  2216. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  2217. /// title memory a flight's shaders may write (a title buffer copy, a fill
  2218. /// of upload memory, a texture) waits only until the flights that declared
  2219. /// that memory have landed, not for everything in the air; and at
  2220. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  2221. /// both wait for everything.
  2222. fn relay_exact() -> bool {
  2223. static ON: OnceLock<bool> = OnceLock::new();
  2224. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  2225. // since the walls of the first room were found drawn in every run with
  2226. // this set and in fewer than half without it).
  2227. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  2228. }
  2229. /// Whether the pieces the relay fetches from the card's memory come over the
  2230. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  2231. /// draws.
  2232. ///
  2233. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  2234. /// and with the relay that is most of a frame: the thread that lands flights
  2235. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  2236. /// a few milliseconds of copying, and everything that waits for a landing
  2237. /// (the title's fences, reads of memory flights may write) waited with it.
  2238. ///
  2239. /// What changes: the fetch runs when its flights are done and beside later
  2240. /// submissions, so of the sends of title bytes it is only known to have run
  2241. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  2242. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  2243. /// the title's, newer than what the flights wrote. A later flight's bytes
  2244. /// may be in what is fetched, as before.
  2245. fn relay_copy() -> bool {
  2246. static ON: OnceLock<bool> = OnceLock::new();
  2247. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  2248. }
  2249. /// Told when something joins [`LINE`], for the thread that lands flights
  2250. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  2251. /// what queues hold.
  2252. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2253. /// Told when flights have landed ([`relay`]): who waits for that looks
  2254. /// again.
  2255. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  2256. /// With [`relay`], the order of what we put on the queue: the number of
  2257. /// sends of changed ranges to copies in the card's memory so far
  2258. /// (`Host::card_before`). Held from the taking of the ranges until their
  2259. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  2260. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  2261. /// later one.
  2262. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  2263. /// Since the last frame-rate line, of the thread that lands flights
  2264. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  2265. /// card with nothing to land, microseconds it waited for fetches of card
  2266. /// copies' pieces, microseconds of landing in all.
  2267. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  2268. /// Of the line's things in order (a flight: the value signalled on the
  2269. /// host's fence behind it; a write or a signal behind a flight: `None`):
  2270. /// how many, from the front, can be landed when the card has reached
  2271. /// `completed`: everything ahead of the first flight it has not run. A
  2272. /// later flight never lands before an earlier one, and what follows a
  2273. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  2274. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  2275. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  2276. }
  2277. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  2278. /// holds, for every piece of every range of the plan, the copy, the
  2279. /// piece's number in the copy and whether the compare flagged it there (or
  2280. /// did not run). The pieces to fetch, under whichever range, in order: all
  2281. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  2282. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  2283. /// the hash, so the second of them may find it stored already and not
  2284. /// flag it.
  2285. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  2286. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  2287. pieces.sort_unstable();
  2288. pieces.dedup();
  2289. pieces
  2290. }
  2291. #[cfg(test)]
  2292. mod relay_tests {
  2293. use super::{flagged_pieces, landable};
  2294. /// Two flights and what follows each: nothing of the second lands
  2295. /// before the card has run it, and nothing behind a flight lands
  2296. /// before the flight.
  2297. #[test]
  2298. fn flights_land_in_the_order_they_were_sent() {
  2299. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  2300. let line = [Some(5), None, None, Some(6), None];
  2301. assert_eq!(landable(&line, 4), 0);
  2302. assert_eq!(landable(&line, 5), 3);
  2303. assert_eq!(landable(&line, 6), 5);
  2304. assert_eq!(landable(&line, u64::MAX), 5);
  2305. // Signals with no flight ahead land at once; behind one they wait.
  2306. assert_eq!(landable(&[None, None], 0), 2);
  2307. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  2308. assert_eq!(landable(&[], 3), 0);
  2309. // After the first three landed, the rest when its turn comes.
  2310. assert_eq!(landable(&line[3..], 5), 0);
  2311. assert_eq!(landable(&line[3..], 6), 2);
  2312. }
  2313. /// A piece flagged under one range of a plan is fetched under every
  2314. /// range that holds a part of it; pieces of other copies are not.
  2315. #[test]
  2316. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  2317. let (a, b) = (0x1000usize, 0x2000usize);
  2318. // Copy a: piece 3 under two ranges, flagged under the first only;
  2319. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  2320. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  2321. let fetch = flagged_pieces(&flags);
  2322. assert!(fetch.contains(&(a, 3)));
  2323. assert!(!fetch.contains(&(a, 4)));
  2324. assert!(!fetch.contains(&(b, 3)));
  2325. assert!(fetch.contains(&(b, 9)));
  2326. assert_eq!(fetch.len(), 2);
  2327. }
  2328. }
  2329. /// The most host lists in the air before the flights are settled
  2330. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  2331. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  2332. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  2333. /// 32 settled the flights three times a
  2334. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  2335. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  2336. /// descriptor slots, upload
  2337. /// memory and scratch chunks are held until then, and a frame's lists held
  2338. /// all at once ran the slots out before (run 45).
  2339. fn late_most() -> usize {
  2340. static MOST: OnceLock<usize> = OnceLock::new();
  2341. *MOST.get_or_init(|| {
  2342. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  2343. })
  2344. }
  2345. /// Whether a submission with bottom-of-pipe writes may fly
  2346. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  2347. /// the title is told at once, as before; for telling a title that polls
  2348. /// such a value from one that does not).
  2349. fn late_writes() -> bool {
  2350. static ON: OnceLock<bool> = OnceLock::new();
  2351. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  2352. }
  2353. /// Per host copy, the ranges a submission's shaders may write, as declared
  2354. /// (address, end).
  2355. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  2356. /// What [`Host::submit`] hands back for a submission it sent and did not
  2357. /// wait for.
  2358. struct Sent {
  2359. /// Its number among the submissions started.
  2360. number: u64,
  2361. card: Option<CardPlan>,
  2362. back: Vec<Declared>,
  2363. /// What was taken off it to be done on the card.
  2364. own: Option<card_steps::Taken>,
  2365. /// Its bottom-of-pipe writes.
  2366. writes: Vec<(usize, crate::queue::Written, usize)>,
  2367. }
  2368. /// A submission on the card that has not been waited for ([`late`]): its
  2369. /// host lists, taken from the title's (which it may reset meanwhile), and
  2370. /// what is to be done once it has run.
  2371. struct Flight {
  2372. number: u64,
  2373. /// The value signalled on the host's fence behind it.
  2374. fence: u64,
  2375. lists: Vec<crate::list::Detached>,
  2376. order: Vec<usize>,
  2377. card: Option<CardPlan>,
  2378. back: Vec<Declared>,
  2379. /// The list of ours that ran ahead of them ([`card_steps`]).
  2380. own: Option<card_steps::Taken>,
  2381. }
  2382. /// One thing in the line of what waits for the card, in order.
  2383. enum Late {
  2384. Run(Flight),
  2385. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  2386. Write(usize, crate::queue::Written, usize),
  2387. /// A fence (its address) signalled behind the flights before it.
  2388. Signal(usize, u64),
  2389. }
  2390. struct Line {
  2391. line: Vec<Late>,
  2392. /// The title memory the flights' shaders may write (address, end), in
  2393. /// order and joined.
  2394. written: Vec<(usize, usize)>,
  2395. /// Host lists in the flights.
  2396. lists: usize,
  2397. /// The value signalled on the host's fence behind the last flight.
  2398. target: u64,
  2399. /// A settle has taken the line and is not done: a signal still goes
  2400. /// behind it.
  2401. settling: bool,
  2402. /// Something was settled away from a queue's own calls: the helper
  2403. /// thread looks at what queues hold.
  2404. poke: bool,
  2405. /// Host lists of settled flights, reset and given back outside the
  2406. /// submission lock ([`land`]: a settle may run under a caller's own
  2407. /// locks).
  2408. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2409. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2410. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2411. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2412. /// With [`card_steps`]: what the flights being landed write.
  2413. landing: Vec<card_steps::Writer>,
  2414. }
  2415. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2416. // into; touched under the lock.
  2417. unsafe impl Send for Line {}
  2418. static LINE: Mutex<Line> = Mutex::new(Line {
  2419. line: Vec::new(),
  2420. written: Vec::new(),
  2421. lists: 0,
  2422. target: 0,
  2423. settling: false,
  2424. poke: false,
  2425. landed: Vec::new(),
  2426. in_hand: Vec::new(),
  2427. landing: Vec::new(),
  2428. });
  2429. /// Told when a flight joins [`LINE`] or it is poked.
  2430. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2431. fn line() -> std::sync::MutexGuard<'static, Line> {
  2432. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2433. }
  2434. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2435. const WHY_SYNC: usize = 2;
  2436. const WHY_CARD_DONE: usize = 3;
  2437. const WHY_VALUE: usize = 4;
  2438. const WHY_STALE: usize = 5;
  2439. const WHY_READ: usize = 6;
  2440. const WHY_RUN: usize = 7;
  2441. const WHY_MOST: usize = 8;
  2442. const WHY_WRITES: usize = 9;
  2443. const WHY_FENCE: usize = 10;
  2444. /// Since the last frame-rate line: submissions sent without a wait;
  2445. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2446. /// microseconds settles waited for the card; value waits met by a flight's
  2447. /// bottom-of-pipe write; fence signals set behind flights.
  2448. /// Then: the settles for title memory read, by what read it (a buffer
  2449. /// copy, a fill of upload memory, a texture).
  2450. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2451. /// Since the last frame-rate line: the microseconds settles waited for the
  2452. /// card, by why they settled (the `WHY_` places).
  2453. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2454. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2455. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2456. if from >= to {
  2457. return false;
  2458. }
  2459. let at = ranges.partition_point(|r| r.1 <= from);
  2460. ranges.get(at).is_some_and(|r| r.0 < to)
  2461. }
  2462. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2463. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2464. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2465. ranges.sort_unstable();
  2466. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2467. for &(from, to) in ranges.iter() {
  2468. match out.last_mut() {
  2469. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2470. _ => out.push((from, to)),
  2471. }
  2472. }
  2473. *ranges = out;
  2474. }
  2475. /// Whether anything is in the air.
  2476. fn flying() -> bool {
  2477. if !late() {
  2478. return false;
  2479. }
  2480. let line = line();
  2481. // (With the relay: also while flights are being landed.)
  2482. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2483. }
  2484. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2485. /// before they are settled, if so. Preparing reads title memory on the
  2486. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2487. /// runs steps of ours that may read or write it anywhere; what the
  2488. /// flights' shaders write is not there yet.
  2489. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2490. let (written, copies) = {
  2491. let line = line();
  2492. if line.written.is_empty() {
  2493. return None;
  2494. }
  2495. (line.written.clone(), card_steps::copies(&line))
  2496. };
  2497. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2498. }
  2499. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2500. /// flights when the title itself wrote the memory since they were given it
  2501. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2502. ///
  2503. /// The title's 174 MB heap is declared written as a whole (a root view has
  2504. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2505. /// bytes a frame, at a new place each time, waited for every flight's
  2506. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2507. /// named). The title writes those bytes just before the draw that reads
  2508. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2509. ///
  2510. /// Or no shader's write went into that page in the last 600 frames
  2511. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2512. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2513. /// before the page was taken.
  2514. ///
  2515. /// What can go wrong: a constant a flight's shader really writes, in a
  2516. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2517. /// for the first time, is read as it was before that flight.
  2518. fn fill_is_titles(src: usize, len: usize) -> bool {
  2519. const SMALL: usize = 64 << 10;
  2520. static ON: OnceLock<bool> = OnceLock::new();
  2521. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2522. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2523. }
  2524. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2525. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2526. /// in (start, bytes).
  2527. #[cfg(feature = "diagnostics")]
  2528. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2529. /// How often and how long, and the address the last one read.
  2530. #[cfg(feature = "diagnostics")]
  2531. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2532. /// What the wait that comes next is for, and why not on the card.
  2533. #[cfg(feature = "diagnostics")]
  2534. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2535. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2536. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2537. /// shaders.
  2538. #[cfg(feature = "diagnostics")]
  2539. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2540. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2541. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2542. /// raw address (1).
  2543. #[cfg(feature = "diagnostics")]
  2544. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2545. if len < 1 << 20 {
  2546. return;
  2547. }
  2548. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2549. let e = all
  2550. .get_or_insert_with(Default::default)
  2551. .entry((address as usize, (address + len) as usize, pipeline))
  2552. .or_insert_with(|| {
  2553. let shaders = match pipeline {
  2554. 0 => "a view in a table".into(),
  2555. 1 => "a raw address".into(),
  2556. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2557. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2558. }),
  2559. };
  2560. (0, shaders)
  2561. });
  2562. e.0 += 1;
  2563. }
  2564. #[cfg(feature = "diagnostics")]
  2565. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2566. let i = written.partition_point(|r| r.1 <= at);
  2567. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2568. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2569. let why = blamed.1;
  2570. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2571. }
  2572. /// Why [`card_steps`] left the submission to the wait that comes next.
  2573. #[cfg(feature = "diagnostics")]
  2574. fn refused(why: &'static str) {
  2575. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2576. }
  2577. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2578. #[cfg(feature = "diagnostics")]
  2579. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2580. if let Some((shadow, from, _)) = stale.first() {
  2581. let (start, len) = shadow.span();
  2582. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2583. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2584. }
  2585. }
  2586. /// The wait for what [`blame`] last named, or a wait of another reason than
  2587. /// title memory read, took `us`.
  2588. #[cfg(feature = "diagnostics")]
  2589. fn blamed(why: usize, us: u64) {
  2590. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2591. let (key, at) = match (why, named) {
  2592. (WHY_READ | WHY_STALE, Some(named)) => named,
  2593. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2594. _ => {
  2595. let kind = match why {
  2596. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2597. WHY_VALUE => "a memory value",
  2598. WHY_STALE => "title memory changed under shader writes",
  2599. WHY_RUN => "a step of ours",
  2600. WHY_MOST => "lists in the air",
  2601. WHY_FENCE => "a blocking fence wait",
  2602. _ => "another reason",
  2603. };
  2604. ((kind, "", 0, 0, 0), 0)
  2605. }
  2606. };
  2607. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2608. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2609. *e = (e.0 + 1, e.1 + us, at);
  2610. }
  2611. /// For the frame-rate line: the five that waited longest.
  2612. #[cfg(feature = "diagnostics")]
  2613. fn log_blame(frames: f64) {
  2614. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2615. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2616. let mut all: Vec<_> = all.into_iter().collect();
  2617. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2618. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2619. // The passes that declare it written, the ones that do so most.
  2620. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2621. for ((a, b, _), (n, shaders)) in &wide {
  2622. if *a < at + len && at < *b {
  2623. *passes.entry(shaders).or_default() += n;
  2624. }
  2625. }
  2626. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2627. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2628. let passes: Vec<String> =
  2629. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2630. tracing::info!(
  2631. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2632. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2633. us as f64 / 1e3 / frames,
  2634. n as f64 / frames,
  2635. passes.join(", "),
  2636. match (why.is_empty(), kind) {
  2637. (true, _) => "",
  2638. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2639. _ => "; not done on the card: ",
  2640. },
  2641. );
  2642. }
  2643. }
  2644. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2645. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2646. touches(written, src, src + len) && !fill_is_titles(src, len)
  2647. }
  2648. /// Whether they stop a title buffer copy, and if so whether by its source.
  2649. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2650. let read = read_blocked(written, src, len);
  2651. (read || touches(written, dst, dst + len)).then_some(read)
  2652. }
  2653. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2654. /// may write (in order, joined); `count` whether the kind of read is
  2655. /// counted for the frame line.
  2656. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2657. if written.is_empty() {
  2658. return None;
  2659. }
  2660. // Destinations of copies at their place, if a step reads them.
  2661. let mut placed: Vec<(usize, usize)> = Vec::new();
  2662. for list in runs {
  2663. for step in &list.deferred().copies {
  2664. match step {
  2665. &Step::Copy(dst, src, len) => {
  2666. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2667. if count {
  2668. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2669. #[cfg(feature = "diagnostics")]
  2670. if _read {
  2671. blame("a buffer copy's source", written, src, len);
  2672. } else {
  2673. blame("a buffer copy's destination", written, dst, len);
  2674. }
  2675. }
  2676. return Some(WHY_READ);
  2677. }
  2678. }
  2679. &Step::Fill(_, src, len, _) => {
  2680. if read_blocked(written, src, len) {
  2681. if count {
  2682. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2683. #[cfg(feature = "diagnostics")]
  2684. blame("a fill of upload memory", written, src, len);
  2685. }
  2686. return Some(WHY_READ);
  2687. }
  2688. }
  2689. Step::Texture(staging) => {
  2690. let (at, len) = staging.memory();
  2691. if touches(written, at, at + len) {
  2692. if count {
  2693. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2694. #[cfg(feature = "diagnostics")]
  2695. blame("a texture", written, at, len);
  2696. }
  2697. return Some(WHY_READ);
  2698. }
  2699. }
  2700. Step::Run(_) => return Some(WHY_RUN),
  2701. Step::Placed(p) => match p.waits(written) {
  2702. place::Waits::No => {}
  2703. place::Waits::ForReaders => placed.push((p.dst, p.dst + p.len)),
  2704. place::Waits::Yes => {
  2705. if count {
  2706. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2707. #[cfg(feature = "diagnostics")]
  2708. blame("a buffer copy at its place", written, p.src, p.len);
  2709. }
  2710. return Some(WHY_READ);
  2711. }
  2712. },
  2713. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2714. }
  2715. }
  2716. }
  2717. (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ)
  2718. }
  2719. /// With flights in the air, after the submission's write-watch asking:
  2720. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2721. /// may write and that the title wrote since it was last copied. The
  2722. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2723. /// the title's bytes there would reach the card a submission late.
  2724. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2725. use std::sync::Arc;
  2726. // Per copy, the span of what is refreshed (a flush brings that much
  2727. // up to date at most).
  2728. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2729. // Where each copy is in it, if shaders may be writing it (none begins to
  2730. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2731. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2732. for list in runs {
  2733. for step in &list.deferred().copies {
  2734. if let Step::Refresh(shadow, address, len) = step {
  2735. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2736. shadow.writes_pending().then(|| {
  2737. spans.push((shadow.clone(), *address, *address + *len));
  2738. spans.len() - 1
  2739. })
  2740. });
  2741. if let Some(i) = *place {
  2742. let s = &mut spans[i];
  2743. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2744. }
  2745. }
  2746. }
  2747. }
  2748. if late_exact() {
  2749. // The title's bytes are put in beside the flights' writes; a
  2750. // settle is still due where that could not be done. At most this
  2751. // many changed runs go up to copies in the card's memory, each a
  2752. // copy of its own there. With [`card_steps`] the pages of the
  2753. // title's ring of constants come here too, which were waited for
  2754. // before: hundreds of short runs each, at about 1.5 us a run.
  2755. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2756. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2757. return spans;
  2758. }
  2759. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2760. spans
  2761. }
  2762. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2763. /// air, if there are any, and is set when they are settled. Whether it
  2764. /// did; if not the caller sets the fence now.
  2765. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2766. if !late() {
  2767. return false;
  2768. }
  2769. let mut line = line();
  2770. if line.line.is_empty() && !line.settling {
  2771. return false;
  2772. }
  2773. line.line.push(Late::Signal(fence, value));
  2774. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2775. drop(line);
  2776. // A signal alone (behind a settle under way) has no flight to wake
  2777. // the helper thread for it.
  2778. LINE_MOVED.notify_one();
  2779. RELAY_MOVED.notify_one();
  2780. true
  2781. }
  2782. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2783. /// whether it is met once the flights in the air have run. A flight's
  2784. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2785. /// for the card: the part behind the wait goes to the card behind that
  2786. /// flight, which is the order the wait asks for. If the flights may write
  2787. /// the value in a way not known here (shaders, a timestamp, another
  2788. /// width), they are settled and memory is asked again.
  2789. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2790. let (address, bytes) = wait.place();
  2791. {
  2792. let line = line();
  2793. if line.line.is_empty() && line.in_hand.is_empty() {
  2794. return false;
  2795. }
  2796. let mut unsure = touches(&line.written, address, address + bytes);
  2797. // (With the relay: first the writes of flights being landed.)
  2798. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2799. Late::Write(at, what, n) => Some((at, what, n)),
  2800. _ => None,
  2801. }));
  2802. for (at, what, n) in writes {
  2803. if *at >= address + bytes || address >= *at + *n {
  2804. continue;
  2805. }
  2806. match what {
  2807. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2808. if wait.holds_for(*v) {
  2809. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2810. return true;
  2811. }
  2812. }
  2813. _ => unsure = true,
  2814. }
  2815. }
  2816. if !unsure {
  2817. return false;
  2818. }
  2819. }
  2820. settle_now(WHY_VALUE);
  2821. wait.met()
  2822. }
  2823. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2824. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2825. pub(crate) fn settle_now(why: usize) {
  2826. if !late() {
  2827. return;
  2828. }
  2829. let Some(host) = host() else {
  2830. return;
  2831. };
  2832. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2833. host.settle(&mut submitted, why);
  2834. }
  2835. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2836. pub(crate) fn settle_for_present() {
  2837. settle_now(WHY_SYNC);
  2838. }
  2839. pub(crate) fn settle_for_fence() {
  2840. settle_now(WHY_FENCE);
  2841. }
  2842. /// Resets the host lists of settled flights and keeps them for reuse, as
  2843. /// a queue does for the lists it ran (`crate::list::recycle`).
  2844. fn land() {
  2845. let landed: Vec<_> = {
  2846. let mut line = line();
  2847. let n = line.landed.len().saturating_sub(bury_lag() as usize);
  2848. line.landed.drain(..n).collect()
  2849. };
  2850. for (lists, order) in landed {
  2851. crate::list::recycle(lists, &order);
  2852. }
  2853. }
  2854. /// The thread that settles the flights once the card has run them all
  2855. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2856. /// at the next call that settles, and a title thread that polls such a
  2857. /// value while the submitting thread waits for that thread would never
  2858. /// see it.
  2859. fn late_helper() {
  2860. crate::cores::keep_on_fast_cores("victory-late-wait");
  2861. let Some(host) = host() else {
  2862. return;
  2863. };
  2864. // SAFETY: a plain event of our own.
  2865. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2866. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2867. return;
  2868. };
  2869. loop {
  2870. let target = {
  2871. let mut line = line();
  2872. loop {
  2873. if line.poke {
  2874. line.poke = false;
  2875. break None;
  2876. }
  2877. // (With the relay the flights are another thread's.)
  2878. if !relay() && !line.line.is_empty() && !line.settling {
  2879. break Some(line.target);
  2880. }
  2881. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2882. }
  2883. };
  2884. let Some(target) = target else {
  2885. let mut helping = crate::timeline::span("helper: landed lists reset and given back");
  2886. land();
  2887. helping.next("helper: looking at what queues hold");
  2888. crate::queue::release_held(false);
  2889. continue;
  2890. };
  2891. // The card first, without the submission lock: the submitting
  2892. // thread prepares and sends meanwhile.
  2893. // SAFETY: our fence and event.
  2894. unsafe {
  2895. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2896. #[cfg(feature = "diagnostics")]
  2897. let _card = crate::timeline::card_wait(Some(target));
  2898. WaitForSingleObject(event, INFINITE);
  2899. }
  2900. }
  2901. {
  2902. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2903. // Something newer went up meanwhile: the card is waited for
  2904. // again, the submitting thread is not held up for it.
  2905. if line().target != target {
  2906. continue;
  2907. }
  2908. host.settle(&mut submitted, WHY_CARD_DONE);
  2909. }
  2910. land();
  2911. crate::queue::release_held(false);
  2912. }
  2913. }
  2914. /// Starts the threads of [`late`], once: the one that settles flights when
  2915. /// the card has run them and looks at what queues hold, and with [`relay`]
  2916. /// the one that lands flights.
  2917. fn late_threads() {
  2918. static HELPER: std::sync::Once = std::sync::Once::new();
  2919. HELPER.call_once(|| {
  2920. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2921. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2922. }
  2923. tracing::info!(
  2924. most = late_most(),
  2925. writes = late_writes(),
  2926. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2927. );
  2928. if relay() {
  2929. // Without it nothing would ever land.
  2930. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2931. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2932. }
  2933. tracing::info!(
  2934. exact = relay_exact(),
  2935. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2936. );
  2937. }
  2938. });
  2939. }
  2940. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2941. /// time flights have landed. Counted as a settle for `why`, and its time
  2942. /// as waiting for the card. The caller may hold the submission lock: the
  2943. /// thread that lands flights never takes it.
  2944. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2945. let mut line = line();
  2946. if done(&line) {
  2947. return;
  2948. }
  2949. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2950. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2951. let was_working = working(false);
  2952. let waiting = std::time::Instant::now();
  2953. let _waiting = crate::timeline::span(match why {
  2954. WHY_SYNC => "waiting for landings: everything (a present, the sweep)",
  2955. WHY_VALUE => "waiting for landings: a memory value",
  2956. WHY_STALE => "waiting for landings: title memory changed under shader writes",
  2957. WHY_READ => "waiting for landings: title memory read",
  2958. WHY_MOST => "waiting for landings: lists in the air",
  2959. WHY_FENCE => "waiting for landings: a blocking fence wait",
  2960. _ => "waiting for landings: another reason",
  2961. });
  2962. while !done(&line) {
  2963. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2964. }
  2965. drop(line);
  2966. stood(waiting);
  2967. working(was_working);
  2968. let us = waiting.elapsed().as_micros() as u64;
  2969. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2970. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2971. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2972. #[cfg(feature = "diagnostics")]
  2973. blamed(why, us);
  2974. }
  2975. /// What the thread that lands flights fetches card copies' pieces with
  2976. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2977. /// behind the submission lock), and the memory the pieces come down to.
  2978. struct RelayFetch {
  2979. list: Prelude,
  2980. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2981. queue: Option<ID3D12CommandQueue>,
  2982. fence: ID3D12Fence,
  2983. event: HANDLE,
  2984. /// The last value signalled on `fence`.
  2985. sent: u64,
  2986. /// Buffer, mapping, bytes.
  2987. buffer: Option<(ID3D12Resource, usize, u64)>,
  2988. /// Pieces caught while a later flight was writing them.
  2989. suspects: torn::Suspects,
  2990. /// What earlier fetches brought of flights not landed yet.
  2991. had: crate::land::Had,
  2992. }
  2993. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2994. /// the first flights of the line it takes them, with what follows them,
  2995. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2996. /// the card, or for a flight. It takes neither the submission lock nor
  2997. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2998. /// lists and looking at what queues hold are left to [`late_helper`].
  2999. fn relay_worker() {
  3000. crate::cores::keep_on_fast_cores("victory-relay");
  3001. let Some(host) = host() else {
  3002. return;
  3003. };
  3004. // SAFETY: a plain event of our own.
  3005. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  3006. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  3007. };
  3008. let mut fetch: Option<RelayFetch> = None;
  3009. loop {
  3010. let next = {
  3011. let mut line = line();
  3012. loop {
  3013. if line.line.is_empty() {
  3014. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  3015. continue;
  3016. }
  3017. let fences: Vec<Option<u64>> = line
  3018. .line
  3019. .iter()
  3020. .map(|l| match l {
  3021. Late::Run(flight) => Some(flight.fence),
  3022. _ => None,
  3023. })
  3024. .collect();
  3025. // SAFETY: a plain query.
  3026. let completed = unsafe { host.fence.GetCompletedValue() };
  3027. let n = landable(&fences, completed);
  3028. if n == 0 {
  3029. // The first thing is a flight the card has not run.
  3030. break Err(fences[0].unwrap_or(0));
  3031. }
  3032. line.settling = true;
  3033. let items: Vec<Late> = line.line.drain(..n).collect();
  3034. line.in_hand = items
  3035. .iter()
  3036. .filter_map(|l| match l {
  3037. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  3038. _ => None,
  3039. })
  3040. .collect();
  3041. if card_steps::stage() > 0 {
  3042. line.landing = card_steps::writers(&items);
  3043. }
  3044. break Ok(items);
  3045. }
  3046. };
  3047. match next {
  3048. Ok(items) => host.relay_land(items, &mut fetch),
  3049. Err(target) => {
  3050. let waiting = std::time::Instant::now();
  3051. #[cfg(feature = "diagnostics")]
  3052. let _card = crate::timeline::card_wait(Some(target));
  3053. // SAFETY: the host's fence and this thread's event.
  3054. let waited = unsafe {
  3055. host.fence.SetEventOnCompletion(target, event).map(|()| {
  3056. WaitForSingleObject(event, INFINITE);
  3057. })
  3058. };
  3059. if waited.is_err() {
  3060. std::thread::sleep(std::time::Duration::from_millis(1));
  3061. }
  3062. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  3063. }
  3064. }
  3065. }
  3066. }
  3067. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  3068. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  3069. /// once, the pieces that differ found on several threads; but the merge is
  3070. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  3071. /// are not done with here (each flight's are, afterwards). In two steps:
  3072. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  3073. /// which needs nothing that the fetch from the card's memory brings), and
  3074. /// the merge.
  3075. struct RelayBack {
  3076. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  3077. found: Option<Vec<Vec<(usize, usize)>>>,
  3078. }
  3079. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  3080. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3081. for (shadow, declared) in back {
  3082. if shadow.carded() {
  3083. continue;
  3084. }
  3085. let mut spans: Vec<(usize, usize)> = Vec::new();
  3086. join_ranges(&mut spans, declared.iter().copied());
  3087. for &(from, to) in &spans {
  3088. shadow.relay_compared(from, to - from);
  3089. }
  3090. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3091. }
  3092. RelayBack { work, found: None }
  3093. }
  3094. impl RelayBack {
  3095. /// Looks the ranges through, once; its time counts as `stat`.
  3096. fn look(&mut self, stat: usize) {
  3097. if self.work.is_empty() || self.found.is_some() {
  3098. return;
  3099. }
  3100. let scanning = std::time::Instant::now();
  3101. // Looked through without a lock: a piece that changes meanwhile (a
  3102. // later flight writing, the title's bytes going in) is found now or
  3103. // by that flight's landing, and the merge looks again under the
  3104. // lock.
  3105. self.found = Some(crate::shadow::find_all(&self.work));
  3106. crate::land::spent(stat, scanning);
  3107. #[cfg(feature = "diagnostics")]
  3108. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3109. }
  3110. /// What differs goes into title memory.
  3111. fn merge(mut self) {
  3112. use crate::land;
  3113. self.look(land::stat::SCAN);
  3114. let Some(found) = self.found else {
  3115. return;
  3116. };
  3117. let merging = std::time::Instant::now();
  3118. let mut written: Vec<u64> = Vec::new();
  3119. if land::on() {
  3120. // Pieces in the same block of title memory in one job, in order.
  3121. let pieces: Vec<(usize, usize, usize)> =
  3122. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  3123. let start = |i: usize| self.work[i].0.span().0 as usize;
  3124. let mut order: Vec<usize> = (0..pieces.len()).collect();
  3125. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  3126. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  3127. let jobs = land::jobs(&cut);
  3128. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  3129. land::each(jobs.len(), &|j| {
  3130. let working = std::time::Instant::now();
  3131. let mut notes = land::Notes::default();
  3132. for &p in &order[jobs[j].clone()] {
  3133. let (i, at, n) = pieces[p];
  3134. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  3135. }
  3136. notes.flush();
  3137. land::spent(land::stat::BACK_ALL, working);
  3138. });
  3139. land::count(land::stat::JOBS, jobs.len() as u64);
  3140. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  3141. } else {
  3142. let (mut now, mut title) = (Vec::new(), Vec::new());
  3143. for ((shadow, ..), found) in self.work.iter().zip(found) {
  3144. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  3145. written.push(found.into_iter().map(merge).sum());
  3146. }
  3147. }
  3148. land::spent(land::stat::BACK, merging);
  3149. for ((_, from, to), written) in self.work.iter().zip(written) {
  3150. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  3151. #[cfg(feature = "diagnostics")]
  3152. crate::copystat::compared(*from, to - from, written as usize);
  3153. let _ = (from, to);
  3154. }
  3155. }
  3156. }
  3157. /// For the frame-rate line, with [`late`]: what the line of flights did
  3158. /// per frame since the last one.
  3159. fn late_line(frames: f64) {
  3160. if !late() {
  3161. return;
  3162. }
  3163. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3164. tracing::info!(
  3165. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  3166. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  3167. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  3168. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  3169. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  3170. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  3171. s[0],
  3172. s[1],
  3173. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  3174. s[12] / 1000.0,
  3175. s[WHY_SYNC],
  3176. s[WHY_CARD_DONE],
  3177. s[WHY_VALUE],
  3178. s[WHY_STALE],
  3179. s[WHY_READ],
  3180. s[15],
  3181. s[16],
  3182. s[17],
  3183. s[WHY_RUN],
  3184. late_most(),
  3185. s[WHY_MOST],
  3186. s[WHY_WRITES],
  3187. s[WHY_FENCE],
  3188. s[13],
  3189. s[14],
  3190. );
  3191. {
  3192. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  3193. tracing::info!(
  3194. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  3195. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  3196. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  3197. w[WHY_SYNC],
  3198. w[WHY_CARD_DONE],
  3199. w[WHY_VALUE],
  3200. w[WHY_STALE],
  3201. w[WHY_READ],
  3202. w[WHY_RUN],
  3203. w[WHY_MOST],
  3204. w[WHY_WRITES],
  3205. w[WHY_FENCE],
  3206. );
  3207. }
  3208. if relay() {
  3209. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3210. tracing::info!(
  3211. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  3212. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  3213. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  3214. \"settles\" above are waits of other threads for it)",
  3215. r[1],
  3216. r[0],
  3217. r[2] / 1000.0,
  3218. r[3] / 1000.0,
  3219. r[4] / 1000.0,
  3220. );
  3221. if send::own() {
  3222. let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3223. tracing::info!(
  3224. "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
  3225. taking them out of the CPU sides",
  3226. t[0] / (1 << 20) as f64,
  3227. t[1],
  3228. t[2],
  3229. t[3] / 1000.0,
  3230. );
  3231. }
  3232. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3233. if t[0] > 0.0 {
  3234. tracing::info!(
  3235. "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",
  3236. t[0],
  3237. t[1],
  3238. t[2],
  3239. );
  3240. }
  3241. }
  3242. crate::land::log(frames);
  3243. if place::on() {
  3244. let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3245. tracing::info!(
  3246. "title buffer copies at their place in the lists, per frame (VICTORY_COPIES_IN_PLACE): {:.1} of {:.1} KB, {:.1} of them out of what shaders wrote; {:.2} copies into textures out of what shaders wrote",
  3247. t[0],
  3248. t[1] / 1024.0,
  3249. t[2],
  3250. t[3],
  3251. );
  3252. }
  3253. card_steps::log(frames);
  3254. crate::picked::log(frames);
  3255. #[cfg(feature = "diagnostics")]
  3256. log_blame(frames);
  3257. if late_exact() {
  3258. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  3259. tracing::info!(
  3260. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  3261. {runs:.0} changed runs, {:.2} MB",
  3262. bytes / (1 << 20) as f64
  3263. );
  3264. }
  3265. }
  3266. pub(crate) mod aside;
  3267. pub(crate) mod awake;
  3268. mod card_steps;
  3269. pub(crate) mod indirects;
  3270. mod place;
  3271. mod send;
  3272. pub(crate) use send::{goes_as_words, words_under};
  3273. #[cfg(feature = "diagnostics")]
  3274. pub(crate) mod spans;
  3275. mod torn;
  3276. pub(crate) mod upcheck;
  3277. #[cfg(feature = "diagnostics")]
  3278. mod stamps;
  3279. #[cfg(feature = "diagnostics")]
  3280. pub(crate) use stamps::{timeline_ready, timeline_restart, timeline_stamps};
  3281. #[cfg(test)]
  3282. mod late_tests {
  3283. use super::{continues, join_ranges, touches};
  3284. /// Copies join only when both ends continue and the whole does not
  3285. /// overlap itself.
  3286. #[test]
  3287. fn copies_join_only_end_to_end_and_apart() {
  3288. // (destination, source, bytes)
  3289. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  3290. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  3291. // A gap, or only one side continues.
  3292. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  3293. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  3294. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  3295. // Together they would overlap: the second reads what the first wrote.
  3296. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  3297. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  3298. // They touch without overlapping.
  3299. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  3300. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  3301. }
  3302. /// Ranges are found by what they hold, not by where they start, and a
  3303. /// range that only touches another's end does not touch it.
  3304. #[test]
  3305. fn ranges_touch_where_they_overlap() {
  3306. let mut ranges = Vec::new();
  3307. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  3308. assert_eq!(ranges, [(10, 25), (40, 60)]);
  3309. join_ranges(&mut ranges, [(25, 40)]);
  3310. assert_eq!(ranges, [(10, 60)]);
  3311. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  3312. for (from, to, hit) in [
  3313. (0, 10, false),
  3314. (0, 11, true),
  3315. (24, 25, true),
  3316. (25, 40, false),
  3317. (25, 41, true),
  3318. (59, 200, true),
  3319. (60, 100, false),
  3320. (100, 101, true),
  3321. (101, 500, false),
  3322. (30, 30, false),
  3323. (50, 50, false),
  3324. ] {
  3325. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  3326. }
  3327. assert!(!touches(&[], 0, usize::MAX));
  3328. }
  3329. }
  3330. /// Whether a title buffer copy that continues the one recorded before it
  3331. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  3332. /// default).
  3333. ///
  3334. /// Each copy is done at submission through the kernel, which reports a
  3335. /// page that is not there instead of faulting (`copy_mapped`), tells the
  3336. /// write watch and the guards, and ends the refreshes gathered so far: a
  3337. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  3338. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  3339. /// continue the one before is counted either way and said on its own line
  3340. /// with the frame rate; the switch is worth that many kernel calls.
  3341. ///
  3342. /// Joined, the same bytes move: [`continues`] joins only copies whose
  3343. /// ranges, taken together, do not overlap, and nothing is recorded between
  3344. /// two steps that follow each other. What differs: a page that is not
  3345. /// mapped now fails the joined copy as a whole (it then goes page by page,
  3346. /// zeros for what cannot be read, as a single copy does), where before
  3347. /// only the copy that held it did.
  3348. fn join_copies() -> bool {
  3349. static ON: OnceLock<bool> = OnceLock::new();
  3350. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  3351. }
  3352. /// Since the last frame-rate line: title buffer copies recorded, and those
  3353. /// that continue the one before ([`join_copies`]).
  3354. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  3355. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  3356. /// where `last` ended, source and destination both, and the two as one do
  3357. /// not overlap (source over destination): then one copy of both moves the
  3358. /// bytes the two would move in turn.
  3359. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  3360. let ((d, s, n), (dst, src, len)) = (last, next);
  3361. let Some(all) = n.checked_add(len) else {
  3362. return false;
  3363. };
  3364. d.checked_add(n) == Some(dst)
  3365. && s.checked_add(n) == Some(src)
  3366. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  3367. }
  3368. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  3369. /// One list's lock at a time: a submission may name a list twice.
  3370. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  3371. let mut back: Vec<Declared> = Vec::new();
  3372. // Where each copy is in it, and the ranges seen: dispatches declare the
  3373. // same ranges thousands of times a frame.
  3374. let mut places: ByCopy<usize> = ByCopy::default();
  3375. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  3376. for list in runs {
  3377. for step in &list.deferred().copies {
  3378. if let Step::GpuWrite(shadow, address, len) = step {
  3379. let key = std::sync::Arc::as_ptr(shadow) as usize;
  3380. if !seen.insert((key, *address, *len)) {
  3381. continue;
  3382. }
  3383. let i = *places.entry(key).or_insert_with(|| {
  3384. back.push((shadow.clone(), Vec::new()));
  3385. back.len() - 1
  3386. });
  3387. back[i].1.push((*address, *address + *len));
  3388. }
  3389. }
  3390. }
  3391. back
  3392. }
  3393. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  3394. /// lines that say what the title's CPU was given while it decided whether
  3395. /// the camera is in a room. The values of the small read-backs
  3396. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  3397. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  3398. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  3399. /// copies found stale after their refresh (`shadow.rs`; only with
  3400. /// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
  3401. /// runtime, the read requests that fail (with 2: every request).
  3402. pub(crate) fn walls_trace() -> bool {
  3403. static ON: OnceLock<bool> = OnceLock::new();
  3404. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  3405. }
  3406. /// After `list` has run: the texels its read-backs copied into host
  3407. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  3408. ///
  3409. /// A submission that is waited for did this itself. One sent ahead
  3410. /// ([`late`]) did not, at any stage: the flights' lists were settled
  3411. /// without it, so the title read a buffer nobody wrote, as before read-backs
  3412. /// were made (the exposure metering's two small float targets, every frame).
  3413. fn read_backs(list: &HostList) {
  3414. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  3415. let mut data = std::ptr::null_mut();
  3416. // SAFETY: a read-back buffer of ours, written by the list that has
  3417. // run; the title's destination holds every row (checked when the
  3418. // copy was recorded).
  3419. unsafe {
  3420. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  3421. let from = data.cast::<u8>().cast_const();
  3422. for line in 0..*rows {
  3423. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  3424. }
  3425. // The walls trace: what the title is handed (one row of at
  3426. // most 24 values: its 5x1 and 1x1 float targets).
  3427. if walls_trace() && *rows == 1 && *row <= 96 {
  3428. let mut values = [0f32; 24];
  3429. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  3430. tracing::info!(
  3431. frame = crate::frame::current(),
  3432. to = format_args!("{:#x}", *at),
  3433. bytes = *row,
  3434. values = ?&values[..*row / 4],
  3435. "walls trace: a read-back lands in title memory"
  3436. );
  3437. }
  3438. buffer.Unmap(0, None);
  3439. }
  3440. }
  3441. }
  3442. }
  3443. /// After the card ran what declared `back`: what shaders wrote there goes
  3444. /// into title memory, and the ranges are done with.
  3445. fn hand_back(back: &[Declared]) {
  3446. if crate::shadow::wide_back() {
  3447. // Every range first (the pieces that differ, found on several
  3448. // threads), then the merges, in order, as below.
  3449. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3450. for (shadow, declared) in back {
  3451. if shadow.carded() {
  3452. continue;
  3453. }
  3454. let mut sorted = declared.clone();
  3455. sorted.sort_unstable();
  3456. let mut spans: Vec<(usize, usize)> = Vec::new();
  3457. for (from, to) in sorted {
  3458. match spans.last_mut() {
  3459. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3460. _ => spans.push((from, to)),
  3461. }
  3462. }
  3463. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3464. }
  3465. #[cfg(feature = "diagnostics")]
  3466. let scanning = std::time::Instant::now();
  3467. let found = crate::shadow::find_all(&work);
  3468. #[cfg(feature = "diagnostics")]
  3469. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3470. for ((shadow, from, to), found) in work.iter().zip(found) {
  3471. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3472. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3473. #[cfg(feature = "diagnostics")]
  3474. crate::copystat::compared(*from, to - from, written);
  3475. }
  3476. for (shadow, declared) in back {
  3477. shadow.copy_back_done(declared);
  3478. }
  3479. return;
  3480. }
  3481. for (shadow, declared) in back {
  3482. if shadow.carded() {
  3483. // Done before (`Host::card_back`).
  3484. shadow.copy_back_done(declared);
  3485. continue;
  3486. }
  3487. // Each byte compared once: the world declares dozens of views
  3488. // of its 174 MB heap that overlap almost entirely, and comparing
  3489. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3490. // MB shaders wrote. Only ranges that overlap or touch are
  3491. // joined: what lies between two was not given to shaders (the
  3492. // snapshot does not hold it).
  3493. let mut sorted = declared.clone();
  3494. sorted.sort_unstable();
  3495. let mut spans: Vec<(usize, usize)> = Vec::new();
  3496. for (from, to) in sorted {
  3497. match spans.last_mut() {
  3498. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3499. _ => spans.push((from, to)),
  3500. }
  3501. }
  3502. for (from, to) in spans {
  3503. let written = shadow.copy_back(from, to - from);
  3504. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3505. #[cfg(feature = "diagnostics")]
  3506. crate::copystat::compared(from, to - from, written);
  3507. }
  3508. shadow.copy_back_done(declared);
  3509. }
  3510. }
  3511. impl Host {
  3512. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3513. /// mesh shaders need both); logged once.
  3514. pub(crate) fn mesh_shaders(&self) -> bool {
  3515. static MESH: OnceLock<bool> = OnceLock::new();
  3516. *MESH.get_or_init(|| {
  3517. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3518. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3519. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3520. };
  3521. // SAFETY: each query writes its own structure of the given size.
  3522. let ok = unsafe {
  3523. self.device
  3524. .CheckFeatureSupport(
  3525. D3D12_FEATURE_D3D12_OPTIONS7,
  3526. (&raw mut options).cast(),
  3527. size_of_val(&options) as u32,
  3528. )
  3529. .is_ok()
  3530. && self
  3531. .device
  3532. .CheckFeatureSupport(
  3533. D3D12_FEATURE_SHADER_MODEL,
  3534. (&raw mut model).cast(),
  3535. size_of_val(&model) as u32,
  3536. )
  3537. .is_ok()
  3538. };
  3539. let mesh = ok
  3540. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3541. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3542. tracing::info!(mesh, "host mesh shader support");
  3543. mesh
  3544. })
  3545. }
  3546. /// Whether the host GPU supports the depth bounds test; logged once.
  3547. pub(crate) fn depth_bounds(&self) -> bool {
  3548. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3549. *BOUNDS.get_or_init(|| {
  3550. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3551. // SAFETY: writes `options` of the given size.
  3552. let ok = unsafe {
  3553. self.device
  3554. .CheckFeatureSupport(
  3555. D3D12_FEATURE_D3D12_OPTIONS2,
  3556. (&raw mut options).cast(),
  3557. size_of_val(&options) as u32,
  3558. )
  3559. .is_ok()
  3560. };
  3561. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3562. tracing::info!(supported, "host depth bounds support");
  3563. supported
  3564. })
  3565. }
  3566. /// A new list, open for recording.
  3567. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3568. #[cfg(feature = "diagnostics")]
  3569. let started = std::time::Instant::now();
  3570. #[cfg(feature = "diagnostics")]
  3571. let before = private_bytes();
  3572. let list = self.make_list();
  3573. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3574. // (May shrink while a list is made, on another thread's account:
  3575. // added as it is, the sum is what counts.)
  3576. #[cfg(feature = "diagnostics")]
  3577. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3578. #[cfg(feature = "diagnostics")]
  3579. {
  3580. use crate::copystat::{C, add};
  3581. add(C::HostLists, 1);
  3582. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3583. }
  3584. list
  3585. }
  3586. /// An allocator and a closed list for a prelude.
  3587. fn make_prelude(&self) -> Option<Prelude> {
  3588. // SAFETY: plain object creation.
  3589. let made: windows::core::Result<Prelude> = unsafe {
  3590. (|| {
  3591. let allocator: ID3D12CommandAllocator =
  3592. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3593. let list: ID3D12GraphicsCommandList =
  3594. self.device
  3595. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3596. list.Close()?;
  3597. Ok((allocator, list))
  3598. })()
  3599. };
  3600. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3601. match made {
  3602. Ok(prelude) => Some(prelude),
  3603. Err(e) => {
  3604. tracing::warn!(error = %e, "no host list for a prelude");
  3605. None
  3606. }
  3607. }
  3608. }
  3609. fn make_list(&self) -> windows::core::Result<HostList> {
  3610. // SAFETY: plain object creation.
  3611. unsafe {
  3612. let allocator: ID3D12CommandAllocator = self
  3613. .device
  3614. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3615. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3616. 0,
  3617. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3618. &allocator,
  3619. None,
  3620. )?;
  3621. let prelude = OnceLock::new();
  3622. if !lazy_prelude() {
  3623. let _ = prelude.set(self.make_prelude());
  3624. }
  3625. #[cfg(feature = "diagnostics")]
  3626. let notes = std::sync::Arc::<Mutex<Vec<Note>>>::default();
  3627. let pipelines = std::sync::Arc::<Mutex<std::collections::BTreeSet<String>>>::default();
  3628. #[cfg(feature = "diagnostics")]
  3629. let indirects = indirects::Shared::default();
  3630. #[cfg(feature = "diagnostics")]
  3631. if dred_on() || dred_light() {
  3632. static NUMBER: AtomicU32 = AtomicU32::new(0);
  3633. let number = NUMBER.fetch_add(1, Ordering::Relaxed);
  3634. name(&list, || format!("victory host list {number}"));
  3635. let mut all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  3636. if number.is_multiple_of(256) {
  3637. all.retain(|_, l| l.0.strong_count() > 0);
  3638. }
  3639. all.insert(
  3640. number,
  3641. (
  3642. std::sync::Arc::downgrade(&notes),
  3643. std::sync::Arc::downgrade(&pipelines),
  3644. std::sync::Arc::downgrade(&indirects),
  3645. ),
  3646. );
  3647. }
  3648. Ok(HostList {
  3649. allocator,
  3650. list,
  3651. deferred: Mutex::default(),
  3652. scratch: Mutex::default(),
  3653. states: Mutex::default(),
  3654. twins: Mutex::default(),
  3655. prelude,
  3656. pipelines,
  3657. #[cfg(feature = "diagnostics")]
  3658. indirects,
  3659. budget: OnceLock::new(),
  3660. card_budget: OnceLock::new(),
  3661. indirect_args: Mutex::default(),
  3662. batch_args: Mutex::default(),
  3663. coming: Mutex::default(),
  3664. epoch: std::sync::atomic::AtomicU64::new(next_epoch()),
  3665. _alive: Counted::new(),
  3666. #[cfg(feature = "diagnostics")]
  3667. notes,
  3668. #[cfg(feature = "diagnostics")]
  3669. stamps: OnceLock::new(),
  3670. })
  3671. }
  3672. }
  3673. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3674. fn card_clock(&self) -> Option<&'static CardClock> {
  3675. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3676. static WATCH: std::sync::Once = std::sync::Once::new();
  3677. let clock = CLOCK
  3678. .get_or_init(|| {
  3679. // SAFETY: a plain fence on our device.
  3680. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3681. Some(CardClock {
  3682. fence,
  3683. state: Mutex::new((0, None)),
  3684. sent: std::sync::Condvar::new(),
  3685. })
  3686. })
  3687. .as_ref()?;
  3688. WATCH.call_once(|| {
  3689. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3690. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3691. }
  3692. });
  3693. Some(clock)
  3694. }
  3695. /// Lists of ours just went to the queue: the clock's signal goes
  3696. /// behind them, and an idle stretch of the card, if one was under way,
  3697. /// ends here ([`CARD_CLOCK_US`]).
  3698. fn card_sent(&self) {
  3699. let Some(clock) = self.card_clock() else {
  3700. return;
  3701. };
  3702. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3703. state.0 += 1;
  3704. // SAFETY: our queue and the clock's fence.
  3705. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3706. if let Some((since, worked_then)) = state.1.take() {
  3707. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3708. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3709. }
  3710. drop(state);
  3711. clock.sent.notify_one();
  3712. }
  3713. /// Whether the host has what copies in the card's memory need (three
  3714. /// lists and the compare); made at the first ask. A copy goes to the
  3715. /// card's memory only if it has.
  3716. pub(crate) fn card_ready(&self) -> bool {
  3717. static READY: OnceLock<bool> = OnceLock::new();
  3718. *READY.get_or_init(|| match self.make_card_work() {
  3719. Ok(work) => {
  3720. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3721. true
  3722. }
  3723. Err(e) => {
  3724. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3725. false
  3726. }
  3727. })
  3728. }
  3729. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3730. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3731. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3732. let mut code: Option<ID3DBlob> = None;
  3733. // SAFETY: the source and names live through the call; the out
  3734. // pointer is ours.
  3735. unsafe {
  3736. D3DCompile(
  3737. CARD_COMPARE.as_ptr().cast(),
  3738. CARD_COMPARE.len(),
  3739. windows::core::s!("card compare"),
  3740. None,
  3741. None,
  3742. windows::core::s!("main"),
  3743. windows::core::s!("cs_5_1"),
  3744. 0,
  3745. 0,
  3746. &mut code,
  3747. None,
  3748. )?;
  3749. }
  3750. let code = code.ok_or_else(windows::core::Error::empty)?;
  3751. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3752. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3753. // in one submission.
  3754. const RESULTS: u64 = 1 << 20;
  3755. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3756. name(&differs, || "card compare results".into());
  3757. // SAFETY: the blob's own bytes; the root signature is inside the
  3758. // shader.
  3759. unsafe {
  3760. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3761. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3762. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3763. pRootSignature: std::mem::transmute_copy(&root),
  3764. CS: D3D12_SHADER_BYTECODE {
  3765. pShaderBytecode: bytes.as_ptr().cast(),
  3766. BytecodeLength: bytes.len(),
  3767. },
  3768. ..Default::default()
  3769. })?;
  3770. #[cfg(feature = "diagnostics")]
  3771. name(&pso, || crate::replay::play::COMPARE.into());
  3772. Ok(CardWork {
  3773. sync: vec![list()?],
  3774. check: vec![list()?],
  3775. fetch: list()?,
  3776. root,
  3777. pso,
  3778. differs: (differs, data as usize, RESULTS),
  3779. fetched: None,
  3780. taken: 0,
  3781. out: 0,
  3782. })
  3783. }
  3784. }
  3785. /// Before a submission's lists run, for copies in the card's memory
  3786. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3787. /// the last submission goes to their card side (a list of ours, run
  3788. /// now; the submission's lists follow it on the queue), and the ranges
  3789. /// this submission's shaders may write get a compare to run after its
  3790. /// lists. `None` if there is nothing to do.
  3791. ///
  3792. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3793. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3794. /// `relay`).
  3795. /// `picked`: ranges that may be written too, and ranges to look at
  3796. /// (`crate::picked`).
  3797. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3798. use std::sync::Arc;
  3799. if !crate::shadow::cards() {
  3800. return None;
  3801. }
  3802. // The ranges this submission's shaders may write, per copy.
  3803. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3804. for list in runs {
  3805. for step in &list.deferred().copies {
  3806. if let Step::GpuWrite(shadow, address, len) = step
  3807. && shadow.carded()
  3808. {
  3809. let range = (*address, *address + *len);
  3810. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3811. Some((_, ranges)) => {
  3812. if !ranges.contains(&range) {
  3813. ranges.push(range);
  3814. }
  3815. }
  3816. None => declared.push((shadow.clone(), vec![range])),
  3817. }
  3818. }
  3819. }
  3820. }
  3821. let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
  3822. // (Of a copy with a declared range here, that says it.)
  3823. let looked: Vec<&crate::picked::Range> =
  3824. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3825. // With the relay: the order of the queue is held from here until
  3826. // what is taken is on the queue, and the taking is numbered.
  3827. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3828. let sent_as = match order.as_mut() {
  3829. Some(order) => {
  3830. **order += 1;
  3831. **order
  3832. }
  3833. None => 0,
  3834. };
  3835. let mut dirty = crate::shadow::card_dirty(sent_as);
  3836. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3837. return None;
  3838. }
  3839. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3840. let work = work.as_mut()?;
  3841. // A copy whose shader writes are declared for the first time gets
  3842. // its bytes from before, whole.
  3843. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3844. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3845. if shadow.card_make_before(|size| {
  3846. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3847. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3848. Some(before)
  3849. }) {
  3850. whole.push(shadow.clone());
  3851. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3852. dirty.push((shadow.clone(), Vec::new()));
  3853. }
  3854. }
  3855. }
  3856. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3857. let mut looks = None;
  3858. // The bytes as they are now, whatever later submissions put there.
  3859. let own = if send::own() { send::take(self, &dirty) } else { None };
  3860. if !dirty.is_empty() {
  3861. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3862. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3863. };
  3864. let (allocator, list) = &sync;
  3865. // SAFETY: the list's last run finished (it ran ahead of a
  3866. // submission that was waited for, and came back after that);
  3867. // live buffers, and the ranges lie in them.
  3868. let recorded = unsafe {
  3869. (|| -> windows::core::Result<()> {
  3870. allocator.Reset()?;
  3871. list.Reset(allocator, None)?;
  3872. if upcheck::on() {
  3873. looks = upcheck::record(self, list, &dirty);
  3874. }
  3875. // Every copy first, then one barrier call, then every
  3876. // pass: a wait between each copy and its pass had the
  3877. // card do them one after the other.
  3878. let mut sent = Vec::new();
  3879. if let Some(own) = &own {
  3880. own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
  3881. }
  3882. for (shadow, ranges) in &dirty {
  3883. let Some((staging, before, _)) = shadow.card_sides() else {
  3884. continue;
  3885. };
  3886. for &(a, b) in ranges {
  3887. if own.is_none() {
  3888. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3889. }
  3890. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3891. }
  3892. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3893. if own.is_none() && before.is_some() && !ranges.is_empty() {
  3894. sent.push(transition(
  3895. &shadow.buffer,
  3896. D3D12_RESOURCE_STATE_COPY_DEST,
  3897. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3898. ));
  3899. }
  3900. }
  3901. if !sent.is_empty() {
  3902. list.ResourceBarrier(&sent);
  3903. }
  3904. list.SetComputeRootSignature(&work.root);
  3905. list.SetPipelineState(&work.pso);
  3906. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3907. for (shadow, ranges) in &dirty {
  3908. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3909. continue;
  3910. };
  3911. // No twin (it cost the card the copy's size again,
  3912. // 399 MB in run 75): `before` holds a 128-bit hash
  3913. // of each 64 KiB piece. The pieces just sent up are
  3914. // hashed again, all of them the first time; the
  3915. // compare after the lists hashes the declared
  3916. // pieces and flags those whose hash is another.
  3917. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3918. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3919. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3920. vec![shadow.card_run(0, usize::MAX)]
  3921. } else {
  3922. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3923. };
  3924. // The same pieces in fewer passes (`rehash_runs`).
  3925. let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3926. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3927. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3928. for run in runs {
  3929. card_pass(list, &run, size as u32, 0, 0);
  3930. }
  3931. }
  3932. list.Close()?;
  3933. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3934. Ok(())
  3935. })()
  3936. };
  3937. if let Err(e) = recorded {
  3938. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3939. }
  3940. used.push((false, sync));
  3941. }
  3942. drop(order);
  3943. let mut plan = CardPlan {
  3944. ranges: Vec::new(),
  3945. check: None,
  3946. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3947. lists: used,
  3948. sent_as,
  3949. looks,
  3950. sends: own.map(send::Own::memory),
  3951. };
  3952. // Each byte once, as the copy-back joins the declared ranges. The
  3953. // results go behind those of plans still in the air.
  3954. let mut at = work.taken;
  3955. for (shadow, ranges) in &declared {
  3956. let mut sorted = ranges.clone();
  3957. sorted.sort_unstable();
  3958. let mut spans: Vec<(usize, usize)> = Vec::new();
  3959. for (from, to) in sorted {
  3960. match spans.last_mut() {
  3961. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3962. _ => spans.push((from, to)),
  3963. }
  3964. }
  3965. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3966. for (from, to) in spans {
  3967. let Some(span) = shadow.card_span(from, to) else {
  3968. continue;
  3969. };
  3970. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3971. plan.ranges.push(CardRange {
  3972. shadow: shadow.clone(),
  3973. declared: (from, to),
  3974. span,
  3975. at,
  3976. compared,
  3977. picked: false,
  3978. });
  3979. if compared {
  3980. at += span.pieces;
  3981. }
  3982. }
  3983. }
  3984. for (shadow, from, len) in looked {
  3985. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3986. if let Some(span) = shadow.card_span(*from, from + len)
  3987. && twin
  3988. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3989. {
  3990. plan.ranges.push(CardRange {
  3991. shadow: shadow.clone(),
  3992. declared: (*from, from + len),
  3993. span,
  3994. at,
  3995. compared: true,
  3996. picked: true,
  3997. });
  3998. at += span.pieces;
  3999. }
  4000. }
  4001. work.taken = at;
  4002. if plan.ranges.iter().any(|r| r.compared) {
  4003. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  4004. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  4005. };
  4006. let (allocator, list) = &check;
  4007. // SAFETY: the list's last run finished (its submission was
  4008. // waited for, and it came back after that); live buffers; the
  4009. // compare's own root signature.
  4010. let recorded = unsafe {
  4011. (|| -> windows::core::Result<ID3D12CommandList> {
  4012. allocator.Reset()?;
  4013. list.Reset(allocator, None)?;
  4014. // What the submission's shaders wrote, first.
  4015. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  4016. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  4017. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  4018. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  4019. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  4020. pResource: std::mem::ManuallyDrop::new(None),
  4021. }),
  4022. },
  4023. }]);
  4024. list.SetComputeRootSignature(&work.root);
  4025. list.SetPipelineState(&work.pso);
  4026. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  4027. for r in plan.ranges.iter().filter(|r| r.compared) {
  4028. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  4029. continue;
  4030. };
  4031. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  4032. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  4033. // (What is only looked at keeps its hashes: what
  4034. // changed there is the next declared range's to land.)
  4035. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  4036. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  4037. }
  4038. list.Close()?;
  4039. list.cast()
  4040. })()
  4041. };
  4042. match recorded {
  4043. Ok(list) => plan.check = Some(list),
  4044. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  4045. }
  4046. plan.lists.push((true, check));
  4047. }
  4048. work.out += 1;
  4049. Some(plan)
  4050. }
  4051. /// With [`relay`]: whether the compare's result area is half taken by
  4052. /// plans in the air. It starts from the beginning only when no plan is
  4053. /// out, so the caller lets the flights land first.
  4054. fn card_results_low(&self) -> bool {
  4055. CARD_WORK
  4056. .lock()
  4057. .unwrap_or_else(|e| e.into_inner())
  4058. .as_ref()
  4059. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  4060. }
  4061. /// The plan's submission has run and its results were read
  4062. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  4063. /// when nothing of ours is on the card, so the compare's results start
  4064. /// from the beginning again.
  4065. fn card_done(&self, plan: CardPlan) {
  4066. if let Some(looks) = plan.looks {
  4067. looks.read();
  4068. }
  4069. if let Some(memory) = plan.sends {
  4070. send::give_back(memory);
  4071. }
  4072. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4073. let Some(work) = work.as_mut() else {
  4074. return;
  4075. };
  4076. for (check, list) in plan.lists {
  4077. if check { work.check.push(list) } else { work.sync.push(list) }
  4078. }
  4079. work.out = work.out.saturating_sub(1);
  4080. // With the relay other plans may be on the card, their results
  4081. // not read yet: the area starts again only when none is out.
  4082. if !relay() || work.out == 0 {
  4083. work.taken = 0;
  4084. }
  4085. }
  4086. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  4087. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  4088. // SAFETY: plain object creation.
  4089. let copying = relay_copy().then(|| unsafe {
  4090. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  4091. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  4092. let list: ID3D12GraphicsCommandList =
  4093. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  4094. list.Close()?;
  4095. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  4096. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  4097. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  4098. ..Default::default()
  4099. })?;
  4100. Ok(((allocator, list), queue))
  4101. })()
  4102. });
  4103. let (list, queue) = match copying {
  4104. Some(Ok((list, queue))) => (list, Some(queue)),
  4105. Some(Err(e)) => {
  4106. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  4107. (self.make_prelude()?, None)
  4108. }
  4109. None => (self.make_prelude()?, None),
  4110. };
  4111. // SAFETY: plain objects of our own.
  4112. unsafe {
  4113. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  4114. let event = CreateEventW(None, false, false, None).ok()?;
  4115. Some(RelayFetch {
  4116. list,
  4117. queue,
  4118. fence,
  4119. event,
  4120. sent: 0,
  4121. buffer: None,
  4122. suspects: torn::Suspects::default(),
  4123. had: crate::land::Had::default(),
  4124. })
  4125. }
  4126. }
  4127. /// [`relay`], on the thread that lands flights: for the plans of the
  4128. /// flights being landed (the card has run them), the pieces their
  4129. /// compares flagged are fetched, once each, with a list and a wait of
  4130. /// this thread's own, and what shaders wrote in them goes into title
  4131. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  4132. /// no submission lock; a piece flagged under one range of a plan is
  4133. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  4134. /// whatever was sent meanwhile, so it may bring a later flight's
  4135. /// bytes, which that flight's landing then finds merged already; and
  4136. /// nothing is sent back up. `plans` come with the value signalled behind
  4137. /// their flight. `meanwhile` is called while the fetch is on its way, if
  4138. /// there is one.
  4139. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  4140. use crate::land;
  4141. let gathering = std::time::Instant::now();
  4142. let differs = {
  4143. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4144. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  4145. };
  4146. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  4147. let mut total = 0u64;
  4148. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  4149. fetch.had.landing(first);
  4150. }
  4151. // SAFETY: the mapping of the results. The compares of these plans
  4152. // have run, and their dwords are given to no other plan before these
  4153. // are done with (`card_done`).
  4154. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  4155. if let Some(differs) = differs {
  4156. // Pieces caught while a later flight was at them (`torn`).
  4157. let suspects = fetch.as_ref().map(|f| &f.suspects);
  4158. let mut seen = std::collections::HashSet::new();
  4159. for &(plan, behind) in plans {
  4160. plan.picked_found(differs);
  4161. let flags: Vec<(usize, u32, bool)> = plan
  4162. .ranges
  4163. .iter()
  4164. .filter(|r| !r.picked)
  4165. .flat_map(|r| {
  4166. (0..r.span.pieces).map(move |p| {
  4167. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  4168. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  4169. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  4170. })
  4171. })
  4172. .collect();
  4173. let fetched = flagged_pieces(&flags);
  4174. for r in plan.ranges.iter().filter(|r| !r.picked) {
  4175. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  4176. if upcheck::on() {
  4177. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  4178. }
  4179. for p in 0..r.span.pieces {
  4180. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  4181. continue;
  4182. }
  4183. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4184. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  4185. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  4186. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  4187. land::count(land::stat::HAD, 1);
  4188. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  4189. if land::skip_on() {
  4190. continue;
  4191. }
  4192. }
  4193. if upcheck::on() {
  4194. upcheck::fetched(r.shadow.id(), lo);
  4195. }
  4196. seen.insert((copy, lo, hi));
  4197. pieces.push((r.shadow.clone(), lo, hi, total));
  4198. total += (hi - lo) as u64;
  4199. }
  4200. }
  4201. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4202. }
  4203. }
  4204. }
  4205. if land::on() {
  4206. // In the order they are landed, each byte of a copy once.
  4207. let keys: Vec<land::Piece> =
  4208. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  4209. total = 0;
  4210. pieces = land::ordered(&keys)
  4211. .into_iter()
  4212. .map(|(i, title, len)| {
  4213. let shadow = &pieces[i].0;
  4214. let lo = title - shadow.span().0 as usize;
  4215. let at = total;
  4216. total += len as u64;
  4217. (shadow.clone(), lo, lo + len, at)
  4218. })
  4219. .collect();
  4220. }
  4221. land::spent(land::stat::GATHER, gathering);
  4222. if fetch.is_none() {
  4223. *fetch = self.make_relay_fetch();
  4224. }
  4225. // On the copy queue a later flight may be at a piece while it is
  4226. // fetched: the pieces come down whole, to be hashed.
  4227. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  4228. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  4229. if let Some(check) = &check {
  4230. total = check.total;
  4231. }
  4232. // The sends these flights ran behind, all a fetch on the copy queue
  4233. // is known to have run behind.
  4234. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  4235. if pieces.is_empty() {
  4236. // Nothing to fetch: every send so far is older than the next
  4237. // fetch, if that goes to the queue the sends went to.
  4238. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  4239. true => behind,
  4240. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  4241. };
  4242. crate::shadow::relay_fetched(after);
  4243. return;
  4244. }
  4245. let Some(f) = fetch.as_mut() else {
  4246. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  4247. };
  4248. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  4249. let size = total.next_multiple_of(16 << 20);
  4250. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4251. }
  4252. let Some((buffer, data, _)) = f.buffer.clone() else {
  4253. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  4254. };
  4255. f.sent += 1;
  4256. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  4257. let copy_queue = f.queue.clone();
  4258. let waiting = std::time::Instant::now();
  4259. // The flights the fetch runs behind: those in the line by now have
  4260. // been given to the queue. On the copy queue, those landed here.
  4261. let ahead = match copy_queue {
  4262. Some(_) => 0,
  4263. None => line().target,
  4264. };
  4265. // SAFETY: the list's last run was waited for by this thread; live
  4266. // buffers (the copies are held by the plans); the fence and the
  4267. // event are this thread's.
  4268. let ran = unsafe {
  4269. (|| -> windows::core::Result<u64> {
  4270. allocator.Reset()?;
  4271. list.Reset(&allocator, None)?;
  4272. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  4273. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  4274. }
  4275. list.Close()?;
  4276. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  4277. let _fetching = crate::timeline::span("landing: fetching pieces");
  4278. if let Some(queue) = &copy_queue {
  4279. queue.ExecuteCommandLists(&lists);
  4280. queue.Signal(&fence, sent)?;
  4281. meanwhile();
  4282. fence.SetEventOnCompletion(sent, event)?;
  4283. #[cfg(feature = "diagnostics")]
  4284. let _card = crate::timeline::card_wait(None);
  4285. WaitForSingleObject(event, INFINITE);
  4286. return Ok(behind);
  4287. }
  4288. // In the order of the queue: the sends of title bytes so
  4289. // far are ahead of this fetch, every later one behind it.
  4290. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  4291. self.queue.ExecuteCommandLists(&lists);
  4292. let after = *order;
  4293. drop(order);
  4294. self.card_sent();
  4295. self.queue.Signal(&fence, sent)?;
  4296. meanwhile();
  4297. fence.SetEventOnCompletion(sent, event)?;
  4298. #[cfg(feature = "diagnostics")]
  4299. let _card = crate::timeline::card_wait(None);
  4300. WaitForSingleObject(event, INFINITE);
  4301. Ok(after)
  4302. })()
  4303. };
  4304. let after = match ran {
  4305. Ok(after) => after,
  4306. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  4307. };
  4308. let us = waiting.elapsed().as_micros() as u64;
  4309. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  4310. {
  4311. use crate::shadow::CARD_STATS;
  4312. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4313. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4314. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4315. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  4316. }
  4317. let merging = std::time::Instant::now();
  4318. let _merging = crate::timeline::span("landing: merging fetched pieces");
  4319. let mut written = 0;
  4320. if land::on() {
  4321. let titles: Vec<(usize, usize)> =
  4322. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  4323. let jobs = land::jobs(&titles);
  4324. let put = std::sync::atomic::AtomicU64::new(0);
  4325. land::each(jobs.len(), &|j| {
  4326. let working = std::time::Instant::now();
  4327. if let Some(check) = &check {
  4328. for i in jobs[j].clone() {
  4329. // SAFETY: as below.
  4330. unsafe { check.look(i, data) };
  4331. }
  4332. }
  4333. let mut notes = land::Notes::default();
  4334. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  4335. let addressed: Vec<(usize, usize, usize)> =
  4336. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  4337. // SAFETY: the mapping of the fetched bytes, `total` of
  4338. // them; the copy into it has run, and the next waits
  4339. // for this call.
  4340. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  4341. }
  4342. notes.flush();
  4343. land::spent(land::stat::CARD_ALL, working);
  4344. });
  4345. land::count(land::stat::JOBS, jobs.len() as u64);
  4346. written = put.into_inner();
  4347. } else {
  4348. let mut title = Vec::new();
  4349. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  4350. if let Some(check) = &check {
  4351. // SAFETY: as below.
  4352. unsafe { check.look(i, data) };
  4353. }
  4354. // SAFETY: the mapping of the fetched bytes, `total` of them;
  4355. // the copy into it has run.
  4356. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  4357. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  4358. shadow.walls_merged(gpu.len(), merged);
  4359. written += merged as u64;
  4360. }
  4361. }
  4362. land::spent(land::stat::CARD, merging);
  4363. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  4364. if let Some(f) = fetch.as_mut() {
  4365. if let Some(check) = &check {
  4366. check.done(&mut f.suspects);
  4367. }
  4368. f.had.fetched(
  4369. ahead,
  4370. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  4371. );
  4372. }
  4373. // Sends up to `after` are of no use to any later merge.
  4374. crate::shadow::relay_fetched(after);
  4375. }
  4376. /// [`relay`], on the thread that lands flights: `items` are the first
  4377. /// things of the line, flights the card has run and what follows them.
  4378. /// What their shaders wrote goes into title memory (copies in the
  4379. /// card's memory first, then the others, each byte once whichever
  4380. /// flights declared it); then every flight's ranges are done with;
  4381. /// then, in the line's order, each flight's read-backs, its
  4382. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  4383. /// is complete before the title is told anything.
  4384. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  4385. let landing = std::time::Instant::now();
  4386. let mut stage = crate::timeline::span("landing: what is to be looked through");
  4387. {
  4388. let flights: Vec<&Flight> = items
  4389. .iter()
  4390. .filter_map(|l| match l {
  4391. Late::Run(flight) => Some(flight),
  4392. _ => None,
  4393. })
  4394. .collect();
  4395. if !flights.is_empty() {
  4396. // SAFETY: a plain query.
  4397. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4398. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  4399. fail(format_args!(
  4400. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  4401. flights.len(),
  4402. runs.len(),
  4403. self.removal_data(&runs),
  4404. last_notes(&runs)
  4405. ));
  4406. }
  4407. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  4408. // (Each byte once: the ranges are joined.)
  4409. let mut back: Vec<Declared> = Vec::new();
  4410. for flight in &flights {
  4411. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  4412. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4413. Some((_, all)) => all.extend_from_slice(ranges),
  4414. None => back.push((shadow.clone(), ranges.clone())),
  4415. }
  4416. }
  4417. }
  4418. let mut hand_back = relay_hand_back(&back);
  4419. stage.next("landing: copies in the card's memory");
  4420. self.relay_card_back(&plans, fetch, &mut || {
  4421. if crate::land::on() {
  4422. let _looking = crate::timeline::span("landing: looking through copies, beside the fetch");
  4423. hand_back.look(crate::land::stat::SCAN_BESIDE);
  4424. }
  4425. });
  4426. stage.next("landing: copies in the PC's memory");
  4427. hand_back.merge();
  4428. stage.next("landing: ranges done with");
  4429. let finishing = std::time::Instant::now();
  4430. // Only now, and flight by flight: a range another flight
  4431. // in the air declared too stays closed to refreshes.
  4432. for flight in &flights {
  4433. for (shadow, ranges) in &flight.back {
  4434. shadow.copy_back_done(ranges);
  4435. }
  4436. }
  4437. crate::land::spent(crate::land::stat::DONE, finishing);
  4438. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4439. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  4440. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  4441. }
  4442. }
  4443. // In the order given: what tells the title the card is done.
  4444. stage.next("landing: read-backs, telling the title");
  4445. let mut last = 0;
  4446. let mut landed = Vec::new();
  4447. let mut telling = std::time::Instant::now();
  4448. for item in items {
  4449. telling = match item {
  4450. Late::Run(flight) => {
  4451. last = flight.number;
  4452. for &i in &flight.order {
  4453. read_backs(flight.lists[i].host());
  4454. }
  4455. if let Some(card) = flight.card {
  4456. self.card_done(card);
  4457. }
  4458. if let Some(own) = flight.own {
  4459. own.landed();
  4460. }
  4461. landed.push((flight.lists, flight.order));
  4462. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  4463. }
  4464. Late::Write(at, what, bytes) => {
  4465. what.write(at as *mut u8, bytes);
  4466. crate::land::spent(crate::land::stat::TOLD, telling)
  4467. }
  4468. Late::Signal(fence, value) => {
  4469. crate::fence::set(fence as crate::object::This, value);
  4470. crate::land::spent(crate::land::stat::TOLD, telling)
  4471. }
  4472. };
  4473. }
  4474. if last > 0 {
  4475. FINISHED.store(last, Ordering::Release);
  4476. bury(last);
  4477. }
  4478. stage.next("landing: the rest");
  4479. self.log_messages();
  4480. crate::land::spent(crate::land::stat::REST, telling);
  4481. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4482. {
  4483. let mut line = line();
  4484. let Line {
  4485. line: items,
  4486. written,
  4487. lists,
  4488. settling,
  4489. poke,
  4490. landed: kept,
  4491. in_hand,
  4492. landing,
  4493. ..
  4494. } = &mut *line;
  4495. kept.extend(landed);
  4496. in_hand.clear();
  4497. landing.clear();
  4498. // What is still in the air, from the flights that are.
  4499. written.clear();
  4500. *lists = 0;
  4501. let mut ranges = Vec::new();
  4502. for item in items.iter() {
  4503. if let Late::Run(flight) = item {
  4504. *lists += flight.order.len().max(1);
  4505. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  4506. }
  4507. }
  4508. join_ranges(written, ranges);
  4509. *settling = false;
  4510. // The landed lists are reset, and what queues hold looked at,
  4511. // by the helper thread (they take locks a waiter may hold).
  4512. *poke = true;
  4513. }
  4514. LINE_MOVED.notify_all();
  4515. LINE_LANDED.notify_all();
  4516. }
  4517. /// After a submission ran, for copies in the card's memory: the pieces
  4518. /// of the declared ranges that the compare found differing (all of a
  4519. /// range it did not compare) are fetched, with one more wait for the
  4520. /// card, and what shaders wrote in them goes into title memory.
  4521. /// `submitted` is the last value signalled on the fence. `seen` holds
  4522. /// the pieces fetched already since the card was last waited for
  4523. /// (several submissions settled together name the same ones).
  4524. fn card_back(
  4525. &self,
  4526. plan: &CardPlan,
  4527. submitted: &mut u64,
  4528. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4529. ) {
  4530. if plan.ranges.is_empty() {
  4531. return;
  4532. }
  4533. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4534. let Some(work) = work.as_mut() else {
  4535. return;
  4536. };
  4537. // SAFETY: the mapping of the results, which the compare (it has
  4538. // run) wrote.
  4539. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4540. // The pieces to fetch: the range, the offsets in its copy, and
  4541. // where the bytes come down.
  4542. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4543. let mut total = 0u64;
  4544. plan.picked_found(differs);
  4545. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4546. for p in 0..r.span.pieces {
  4547. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4548. continue;
  4549. }
  4550. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4551. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4552. pieces.push((i, lo, hi, total));
  4553. total += (hi - lo) as u64;
  4554. }
  4555. }
  4556. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4557. }
  4558. let mut written = vec![0usize; plan.ranges.len()];
  4559. if !pieces.is_empty() {
  4560. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4561. let size = total.next_multiple_of(16 << 20);
  4562. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4563. }
  4564. let Some((fetched, data, _)) = &work.fetched else {
  4565. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4566. };
  4567. let waiting = std::time::Instant::now();
  4568. let (allocator, list) = &work.fetch;
  4569. // SAFETY: the list's last run was waited for; live buffers; the
  4570. // fence and event are ours, under the submission lock.
  4571. let ran = unsafe {
  4572. (|| -> windows::core::Result<()> {
  4573. allocator.Reset()?;
  4574. list.Reset(allocator, None)?;
  4575. for &(i, lo, hi, at) in &pieces {
  4576. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4577. }
  4578. list.Close()?;
  4579. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4580. self.card_sent();
  4581. *submitted += 1;
  4582. self.queue.Signal(&self.fence, *submitted)?;
  4583. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4584. let was_working = working(false);
  4585. WaitForSingleObject(self.event, INFINITE);
  4586. stood(waiting);
  4587. working(was_working);
  4588. Ok(())
  4589. })()
  4590. };
  4591. if let Err(e) = ran {
  4592. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4593. }
  4594. {
  4595. use crate::shadow::CARD_STATS;
  4596. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4597. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4598. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4599. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4600. }
  4601. if wide_merge() && pieces.len() >= 8 {
  4602. // The pieces are apart from one another (each its own bytes
  4603. // of its copy and of title memory): several at a time.
  4604. let fetched = *data;
  4605. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4606. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4607. let each = pieces.len().div_ceil(8);
  4608. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4609. .chunks(each)
  4610. .map(|chunk| {
  4611. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4612. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4613. let counts = counts.clone();
  4614. Box::new(move || {
  4615. let mut title = Vec::new();
  4616. for (shadow, i, lo, hi, at) in chunk {
  4617. // SAFETY: the mapping of the fetched bytes;
  4618. // the copy into it has run, and the caller
  4619. // waits for this job.
  4620. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4621. let merged = shadow.card_merge(lo, gpu, &mut title);
  4622. shadow.walls_merged(gpu.len(), merged);
  4623. counts[i].fetch_add(merged, Ordering::Relaxed);
  4624. }
  4625. }) as Box<dyn FnOnce() + Send>
  4626. })
  4627. .collect();
  4628. crate::shadow::wide_run(jobs);
  4629. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4630. *written += count.load(Ordering::Relaxed);
  4631. }
  4632. } else {
  4633. let mut title = Vec::new();
  4634. for &(i, lo, hi, at) in &pieces {
  4635. // SAFETY: the mapping of the fetched bytes, `total` of
  4636. // them; the copy into it has run.
  4637. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4638. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4639. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4640. written[i] += merged;
  4641. }
  4642. }
  4643. }
  4644. for (r, written) in plan.ranges.iter().zip(written) {
  4645. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4646. let (from, to) = r.declared;
  4647. #[cfg(feature = "diagnostics")]
  4648. crate::copystat::compared(from, to - from, written);
  4649. let _ = (from, to);
  4650. }
  4651. }
  4652. /// Runs closed lists and waits for them, and with [`late`] for
  4653. /// everything sent to the card before them, which is settled first.
  4654. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4655. // Behind what the title's queues were given before it.
  4656. crate::queue::before_sync();
  4657. let _ = self.submit(runs, false);
  4658. }
  4659. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4660. /// from the title's, go to the card in `order` and are not waited for.
  4661. /// They join the line of flights and are settled, with the others in
  4662. /// the air, at the next point where what they do can be observed
  4663. /// ([`late`] lists those points); their host lists are reset and kept
  4664. /// for reuse then, as a queue does for the lists it ran.
  4665. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4666. if order.is_empty() {
  4667. crate::list::recycle(lists, &order);
  4668. return;
  4669. }
  4670. late_threads();
  4671. let sent = {
  4672. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4673. self.submit(&runs, true)
  4674. };
  4675. let Some((mut submitted, sent)) = sent else {
  4676. // (Not reached: a submission sent ahead always comes back.)
  4677. crate::list::recycle(lists, &order);
  4678. return;
  4679. };
  4680. let told = !sent.writes.is_empty();
  4681. let most = {
  4682. let mut line = line();
  4683. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4684. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4685. *flying += order.len();
  4686. *target = *submitted;
  4687. items.push(Late::Run(Flight {
  4688. number: sent.number,
  4689. fence: *target,
  4690. lists,
  4691. order,
  4692. card: sent.card,
  4693. back: sent.back,
  4694. own: sent.own,
  4695. }));
  4696. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4697. *flying >= late_most()
  4698. };
  4699. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4700. RELAY_MOVED.notify_one();
  4701. if told && !late_writes() {
  4702. self.settle(&mut submitted, WHY_WRITES);
  4703. } else if most && relay_exact() {
  4704. // Until there are fewer, not until there are none.
  4705. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4706. } else if most {
  4707. self.settle(&mut submitted, WHY_MOST);
  4708. } else {
  4709. LINE_MOVED.notify_one();
  4710. }
  4711. drop(submitted);
  4712. let _landing = crate::timeline::span("landed lists reset and given back");
  4713. land();
  4714. }
  4715. /// Sends `list`, a closed list of ours (the present's copy), as a
  4716. /// flight ([`late_free_present`]): not waited for, settled with the
  4717. /// others. The caller keeps the list and does not reset it before the
  4718. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4719. /// it ran and was waited for after all.
  4720. fn execute_own(&self, list: &HostList) -> u64 {
  4721. late_threads();
  4722. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4723. return 0;
  4724. };
  4725. let number = sent.number;
  4726. {
  4727. let mut line = line();
  4728. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4729. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4730. *flying += 1;
  4731. *target = *submitted;
  4732. items.push(Late::Run(Flight {
  4733. number,
  4734. fence: *target,
  4735. lists: Vec::new(),
  4736. order: Vec::new(),
  4737. card: sent.card,
  4738. back: sent.back,
  4739. own: sent.own,
  4740. }));
  4741. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4742. }
  4743. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4744. LINE_MOVED.notify_one();
  4745. RELAY_MOVED.notify_one();
  4746. drop(submitted);
  4747. number
  4748. }
  4749. /// Waits for the card to run every flight in the air ([`late`]) and
  4750. /// does what they left to do, as [`Host::execute`] does for one
  4751. /// submission after its wait: the pieces their shaders wrote in copies
  4752. /// in the card's memory are fetched and merged (each once), the ranges
  4753. /// they declared in the other copies are compared and copied back
  4754. /// (each byte once, whichever flights declared it), and then, in the
  4755. /// order they were given: their bottom-of-pipe writes and the fence
  4756. /// signals behind them. `submitted` is the submission lock's value;
  4757. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4758. ///
  4759. /// Everything in the air is settled, never the first flights alone:
  4760. /// the merge writes the copies' CPU side, which a flight still on the
  4761. /// card may be writing too.
  4762. fn settle(&self, submitted: &mut u64, why: usize) {
  4763. if !late() {
  4764. return;
  4765. }
  4766. if relay() {
  4767. // Nothing is settled here: the thread that lands flights does
  4768. // it, in order, and this waits until nothing is in the air and
  4769. // nothing is being landed. Every point that settled before
  4770. // comes here, so each still sees title memory, fences and
  4771. // bottom-of-pipe values as after a settle.
  4772. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4773. return;
  4774. }
  4775. let was_working = working(true);
  4776. let _settling = crate::timeline::span("settling flights");
  4777. let mut counted = false;
  4778. loop {
  4779. let items = {
  4780. let mut line = line();
  4781. if line.line.is_empty() {
  4782. line.settling = false;
  4783. break;
  4784. }
  4785. line.settling = true;
  4786. line.written.clear();
  4787. line.lists = 0;
  4788. std::mem::take(&mut line.line)
  4789. };
  4790. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4791. if !counted {
  4792. counted = true;
  4793. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4794. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4795. }
  4796. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4797. if flights > 0 {
  4798. submitting(2, flights);
  4799. let waiting = std::time::Instant::now();
  4800. // SAFETY: the fence and event are ours, under the
  4801. // submission lock; `submitted` is the last value signalled.
  4802. unsafe {
  4803. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4804. Ok(()) => {
  4805. working(false);
  4806. #[cfg(feature = "diagnostics")]
  4807. let _card = crate::timeline::card_wait(Some(*submitted));
  4808. WaitForSingleObject(self.event, INFINITE);
  4809. stood(waiting);
  4810. working(true);
  4811. }
  4812. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4813. }
  4814. }
  4815. let gpu = waiting.elapsed();
  4816. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4817. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4818. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4819. #[cfg(feature = "diagnostics")]
  4820. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4821. format!("{flights} submissions sent ahead, settled together")
  4822. });
  4823. // SAFETY: a plain query.
  4824. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4825. let runs: Vec<&HostList> = items
  4826. .iter()
  4827. .filter_map(|i| match i {
  4828. Late::Run(f) => Some(f),
  4829. _ => None,
  4830. })
  4831. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4832. .collect();
  4833. fail(format_args!(
  4834. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4835. runs.len(),
  4836. self.removal_data(&runs),
  4837. last_notes(&runs)
  4838. ));
  4839. }
  4840. submitting(3, flights);
  4841. let copying = std::time::Instant::now();
  4842. let mut seen = std::collections::HashSet::new();
  4843. let mut back: Vec<Declared> = Vec::new();
  4844. for item in &items {
  4845. let Late::Run(flight) = item else {
  4846. continue;
  4847. };
  4848. if let Some(card) = &flight.card {
  4849. self.card_back(card, submitted, &mut seen);
  4850. }
  4851. for (shadow, ranges) in &flight.back {
  4852. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4853. Some((_, all)) => {
  4854. for range in ranges {
  4855. if !all.contains(range) {
  4856. all.push(*range);
  4857. }
  4858. }
  4859. }
  4860. None => back.push((shadow.clone(), ranges.clone())),
  4861. }
  4862. }
  4863. }
  4864. hand_back(&back);
  4865. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4866. }
  4867. // In the order given: what tells the title the card is done.
  4868. let mut last = 0;
  4869. let mut landed = Vec::new();
  4870. for item in items {
  4871. match item {
  4872. Late::Run(flight) => {
  4873. last = flight.number;
  4874. for &i in &flight.order {
  4875. read_backs(flight.lists[i].host());
  4876. }
  4877. if let Some(card) = flight.card {
  4878. self.card_done(card);
  4879. }
  4880. landed.push((flight.lists, flight.order));
  4881. }
  4882. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4883. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4884. }
  4885. }
  4886. if last > 0 {
  4887. FINISHED.store(last, Ordering::Release);
  4888. bury(last);
  4889. }
  4890. line().landed.extend(landed);
  4891. }
  4892. if counted {
  4893. self.log_messages();
  4894. submitting(0, 0);
  4895. // What was settled may be what a queue stands at, and the
  4896. // caller may not be one that looks (a read-back, a present).
  4897. if why != WHY_CARD_DONE {
  4898. line().poke = true;
  4899. LINE_MOVED.notify_one();
  4900. }
  4901. }
  4902. working(was_working);
  4903. }
  4904. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4905. /// copies, which flights may be writing and the title wrote too
  4906. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4907. /// those of the submission's one asking, which is made again.
  4908. ///
  4909. /// With [`card_steps`] only the flights that declared them: a range of
  4910. /// a copy nobody declared any more is refreshed like any other. What
  4911. /// they landed is title memory written, so everything is asked and
  4912. /// looked at again; what is left after three times waits as before.
  4913. fn settle_stale(
  4914. &self,
  4915. submitted: &mut u64,
  4916. runs: &[&HostList],
  4917. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4918. ranges: &[(usize, usize)],
  4919. ) {
  4920. if relay_exact() && card_steps::stage() > 0 {
  4921. for _ in 0..3 {
  4922. #[cfg(feature = "diagnostics")]
  4923. blame_stale(&stale);
  4924. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4925. crate::watch::ask_once(ranges);
  4926. stale = stale_under_flights(runs);
  4927. if stale.is_empty() {
  4928. return;
  4929. }
  4930. }
  4931. }
  4932. #[cfg(feature = "diagnostics")]
  4933. blame_stale(&stale);
  4934. self.settle(submitted, WHY_STALE);
  4935. crate::watch::ask_once(ranges);
  4936. }
  4937. /// [`Host::execute`], or with `late` the first half of
  4938. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4939. /// to be done once they have run comes back with the submission lock
  4940. /// still held.
  4941. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4942. #[cfg(feature = "diagnostics")]
  4943. let called = std::time::Instant::now();
  4944. #[cfg(feature = "diagnostics")]
  4945. crate::copystat::submission_begins();
  4946. // One submission at a time from preparation to copy-back: snapshots
  4947. // and the ranges shaders write are per host copy, not per submission.
  4948. let mut stage = crate::timeline::span("submit: the submission lock");
  4949. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4950. let was_working = working(true);
  4951. submitting(1, runs.len());
  4952. #[cfg(feature = "diagnostics")]
  4953. let ahead = Split::begin();
  4954. #[cfg(feature = "diagnostics")]
  4955. SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed);
  4956. stage.next("submit: steps given to the card");
  4957. // Flights in the air ([`late`]): a submission that is waited for
  4958. // settles them first, one sent ahead only if preparing it reads
  4959. // what they write.
  4960. // Or the reads are done on the card, behind the flights.
  4961. let own = if late { self.card_steps(runs) } else { None };
  4962. #[cfg(feature = "diagnostics")]
  4963. ahead.part(12);
  4964. stage.next("submit: waiting for flights it reads from");
  4965. if !late {
  4966. self.settle(&mut submitted, WHY_SYNC);
  4967. } else if own.is_none()
  4968. && let Some(why) = late_blocked(runs)
  4969. {
  4970. if relay_exact() && why == WHY_READ {
  4971. // Only until the flights that may write what is read have
  4972. // landed: their copy-back's end, not the card's other work.
  4973. relay_wait(why, |line| {
  4974. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4975. });
  4976. } else {
  4977. self.settle(&mut submitted, why);
  4978. }
  4979. }
  4980. #[cfg(feature = "diagnostics")]
  4981. ahead.part(13);
  4982. // Descriptors the title copied into placed heaps directly, before
  4983. // command lists that index those slots are submitted.
  4984. let heaps_synced = crate::descriptor::begin_sync_heaps();
  4985. // That list runs first, and is one of the submission's from here on.
  4986. let with: Vec<&HostList>;
  4987. let runs = match &own {
  4988. Some(own) => {
  4989. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4990. &with[..]
  4991. }
  4992. None => runs,
  4993. };
  4994. stage.next("submit: the sweep");
  4995. let behind = late && flying();
  4996. // Before this submission counts as started: what the sweep lets go
  4997. // of is named by no list, and nothing runs now (behind flights the
  4998. // sweep waits for a submission that finds none in the air: there is
  4999. // one at every present).
  5000. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  5001. if !behind {
  5002. if upcheck::on() {
  5003. upcheck::at_rest(self);
  5004. }
  5005. sweep();
  5006. SWEPT.store(now_ms(), Ordering::Relaxed);
  5007. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  5008. // With the present sent ahead nothing else brings a moment
  5009. // with nothing in the air: one is made for the sweep.
  5010. self.settle(&mut submitted, WHY_SYNC);
  5011. if upcheck::on() {
  5012. upcheck::at_rest(self);
  5013. }
  5014. sweep();
  5015. SWEPT.store(now_ms(), Ordering::Relaxed);
  5016. }
  5017. let behind = late && flying();
  5018. stage.next("submit: gathering what to ask about");
  5019. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  5020. // The ranges shaders write are counted for it (with the relay).
  5021. crate::shadow::preparing(this_submission);
  5022. let started = std::time::Instant::now();
  5023. #[cfg(feature = "diagnostics")]
  5024. ahead.part(14);
  5025. #[cfg(feature = "diagnostics")]
  5026. let lock = (started - called).as_micros() as u64;
  5027. #[cfg(feature = "diagnostics")]
  5028. crate::copystat::add(crate::copystat::C::Submissions, 1);
  5029. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  5030. // Where each run's lists start in `lists`.
  5031. let mut firsts = Vec::with_capacity(runs.len());
  5032. let mut batch = Batch::default();
  5033. #[cfg(feature = "diagnostics")]
  5034. let split = Split::begin();
  5035. // The time a settle of flights takes inside this preparing: the
  5036. // wait for the card and the copy-back have their own places on the
  5037. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  5038. let mut settled = std::time::Duration::ZERO;
  5039. // One write-watch asking for everything the submission refreshes
  5040. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  5041. if crate::watch::once() {
  5042. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  5043. for list in runs {
  5044. for step in &list.deferred().copies {
  5045. if let Step::Refresh(shadow, address, len) = step
  5046. && shadow.asked_ahead()
  5047. {
  5048. let span = spans
  5049. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  5050. .or_insert((*address, *address + *len));
  5051. *span = (span.0.min(*address), span.1.max(*address + *len));
  5052. }
  5053. }
  5054. }
  5055. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  5056. #[cfg(feature = "diagnostics")]
  5057. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  5058. stage.next("submit: asking the write watch");
  5059. crate::watch::ask_once(&ranges);
  5060. #[cfg(feature = "diagnostics")]
  5061. split.part(0);
  5062. stage.next("submit: title bytes under flights' writes");
  5063. // Behind flights: the title wrote memory that a flight's shaders
  5064. // may write too, and this submission refreshes it. The flights
  5065. // are settled, and the asking made again: the copy-back wrote
  5066. // title memory, which other copies of it must see.
  5067. if upcheck::on() {
  5068. upcheck::order(runs);
  5069. if behind {
  5070. upcheck::reads(runs);
  5071. }
  5072. }
  5073. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  5074. if !stale.is_empty() {
  5075. let settling = std::time::Instant::now();
  5076. self.settle_stale(&mut submitted, runs, stale, &ranges);
  5077. settled += settling.elapsed();
  5078. }
  5079. } else if behind && !stale_under_flights(runs).is_empty() {
  5080. let settling = std::time::Instant::now();
  5081. self.settle(&mut submitted, WHY_STALE);
  5082. settled += settling.elapsed();
  5083. }
  5084. #[cfg(feature = "diagnostics")]
  5085. split.part(1);
  5086. // What flights in the air may write.
  5087. let air = line().written.clone();
  5088. stage.next("submit: refreshes ahead of writes");
  5089. if ahead_of_writes() {
  5090. batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  5091. }
  5092. stage.next("submit: the lists' steps");
  5093. for list in runs {
  5094. list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  5095. firsts.push(lists.len());
  5096. if let Some(prelude) = list.prelude() {
  5097. lists.push(Some(prelude));
  5098. }
  5099. lists.push(list.list.cast().ok());
  5100. }
  5101. batch.fill();
  5102. stage.next("submit: the last refreshes");
  5103. batch.flush();
  5104. crate::watch::ask_once_end();
  5105. #[cfg(feature = "diagnostics")]
  5106. split.part(2);
  5107. stage.next("submit: snapshots");
  5108. // The snapshots of the ranges shaders may write, if they were left
  5109. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  5110. // lists have not gone to the card.
  5111. {
  5112. #[cfg(feature = "diagnostics")]
  5113. let snapshots = std::time::Instant::now();
  5114. crate::shadow::take_snapshots();
  5115. #[cfg(feature = "diagnostics")]
  5116. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  5117. }
  5118. #[cfg(feature = "diagnostics")]
  5119. split.part(3);
  5120. stage.next("submit: copies in the card's memory");
  5121. // Copies in the card's memory: what changed on their CPU side goes
  5122. // up ahead of the lists, and a compare of what the shaders may
  5123. // write follows them in the same submission.
  5124. let flown = late && relay();
  5125. if flown && self.card_results_low() {
  5126. let settling = std::time::Instant::now();
  5127. self.settle(&mut submitted, WHY_MOST);
  5128. settled += settling.elapsed();
  5129. }
  5130. // What shaders may write through views they pick: last, so that no
  5131. // refresh of this submission leaves it alone.
  5132. let picked = crate::picked::declare(runs);
  5133. for (shadow, at, len) in &picked.written {
  5134. shadow.writing(*at, *len);
  5135. }
  5136. let card = self.card_before(runs, &picked, flown);
  5137. // The sends are taken: from here on the references hold what the
  5138. // copies in the lists put.
  5139. for (shadow, at, bytes) in batch.placed.drain(..) {
  5140. shadow.placed_copy(at, &bytes);
  5141. }
  5142. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  5143. lists.push(Some(check));
  5144. }
  5145. #[cfg(feature = "diagnostics")]
  5146. split.part(4);
  5147. stage.next("submit: waiting for the heaps' records");
  5148. drop(heaps_synced);
  5149. // The slots that waited for a texture's host copy, before the
  5150. // lists that may read them run.
  5151. crate::descriptor::make_waiting();
  5152. #[cfg(feature = "diagnostics")]
  5153. split.part(15);
  5154. let prepared = std::time::Instant::now();
  5155. stage.next("submit: sending");
  5156. // When it runs on the card, for the timeline.
  5157. #[cfg(feature = "diagnostics")]
  5158. let stamp = stamps::take();
  5159. #[cfg(feature = "diagnostics")]
  5160. if let Some((ahead, behind)) = stamp.and_then(stamps::lists) {
  5161. lists.insert(0, Some(ahead));
  5162. lists.push(Some(behind));
  5163. firsts.iter_mut().for_each(|first| *first += 1);
  5164. }
  5165. #[cfg(feature = "diagnostics")]
  5166. let sending = crate::timeline::ticks();
  5167. if late {
  5168. *submitted += 1;
  5169. #[cfg(feature = "diagnostics")]
  5170. if let Some([front, behind]) = self.span_lists() {
  5171. lists.insert(0, Some(front));
  5172. lists.push(Some(behind));
  5173. }
  5174. // SAFETY: closed lists; the fence is ours.
  5175. let signalled = unsafe {
  5176. self.queue.ExecuteCommandLists(&lists);
  5177. self.queue.Signal(&self.fence, *submitted)
  5178. };
  5179. awake::sent(&self.device);
  5180. #[cfg(feature = "diagnostics")]
  5181. crate::timeline::sent(sending, *submitted, stamp);
  5182. self.card_sent();
  5183. stage.next("submit: noting what is in the air");
  5184. if let Err(e) = signalled {
  5185. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  5186. }
  5187. #[cfg(feature = "diagnostics")]
  5188. split.part(5);
  5189. let back = crate::picked::with(declared_writes(runs), &picked.written);
  5190. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  5191. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  5192. submitting(0, 0);
  5193. #[cfg(feature = "diagnostics")]
  5194. crate::copystat::submission_ends(lock);
  5195. let sent = Sent {
  5196. number: this_submission,
  5197. card,
  5198. back,
  5199. own,
  5200. writes,
  5201. };
  5202. working(was_working);
  5203. return Some((submitted, sent));
  5204. }
  5205. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  5206. #[cfg(feature = "diagnostics")]
  5207. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  5208. firsts
  5209. .iter()
  5210. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  5211. .map(|(&a, &b)| &lists[a..b])
  5212. .collect()
  5213. } else {
  5214. vec![&lists[..]]
  5215. };
  5216. #[cfg(not(feature = "diagnostics"))]
  5217. let groups = [&lists[..]];
  5218. submitting(2, runs.len());
  5219. for (i, group) in groups.iter().enumerate() {
  5220. *submitted += 1;
  5221. let started = std::time::Instant::now();
  5222. // SAFETY: closed lists; the fence and event are ours.
  5223. unsafe {
  5224. self.queue.ExecuteCommandLists(group);
  5225. self.card_sent();
  5226. let waited = self
  5227. .queue
  5228. .Signal(&self.fence, *submitted)
  5229. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  5230. #[cfg(feature = "diagnostics")]
  5231. crate::timeline::sent(sending, *submitted, stamp);
  5232. match waited {
  5233. Ok(()) => {
  5234. working(false);
  5235. #[cfg(feature = "diagnostics")]
  5236. let _card = crate::timeline::card_wait(Some(*submitted));
  5237. WaitForSingleObject(self.event, INFINITE);
  5238. stood(started);
  5239. working(true);
  5240. }
  5241. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  5242. }
  5243. }
  5244. // With timing on each group is one of `runs` (and the compare
  5245. // of copies in the card's memory, with the last): every
  5246. // command's time on the card goes to the sums by pipeline.
  5247. #[cfg(feature = "diagnostics")]
  5248. if timing() {
  5249. // SAFETY: a plain query.
  5250. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  5251. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  5252. crate::copystat::command_took(&op, ms);
  5253. }
  5254. }
  5255. // A submission of one list was never named here (`groups.len()
  5256. // > 1` was the test): the two 50 ms lists of the gameplay
  5257. // frame, each a submission of its own, printed nothing.
  5258. #[cfg(feature = "diagnostics")]
  5259. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  5260. // SAFETY: a plain query.
  5261. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  5262. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  5263. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  5264. for (ms, op) in runs[i].slowest(frequency, 6) {
  5265. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  5266. }
  5267. }
  5268. let _ = (i, started);
  5269. }
  5270. let _ = &firsts;
  5271. FINISHED.store(this_submission, Ordering::Release);
  5272. bury(this_submission);
  5273. let gpu = prepared.elapsed();
  5274. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  5275. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  5276. #[cfg(feature = "diagnostics")]
  5277. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  5278. let pipelines: std::collections::BTreeSet<String> = runs
  5279. .iter()
  5280. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  5281. .collect();
  5282. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  5283. text.chars().take(1200).collect()
  5284. });
  5285. // The host resets a device whose submission runs for about 2 s.
  5286. if gpu > std::time::Duration::from_millis(250) {
  5287. let pipelines: std::collections::BTreeSet<String> = runs
  5288. .iter()
  5289. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  5290. .collect();
  5291. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  5292. }
  5293. // SAFETY: a plain query.
  5294. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  5295. fail(format_args!(
  5296. "host GPU device removed after a submission of {} lists{}{}",
  5297. runs.len(),
  5298. self.removal_data(runs),
  5299. last_notes(runs)
  5300. ));
  5301. }
  5302. submitting(3, runs.len());
  5303. stage.next("submit: copying back");
  5304. // What shaders wrote goes back before the bottom-of-pipe writes,
  5305. // which tell the title the GPU is done; each range once per
  5306. // submission, however many dispatches declared it (the world's
  5307. // passes declare the same big ranges dozens of times).
  5308. let copying = std::time::Instant::now();
  5309. // For copies in the card's memory the compare has run there: the
  5310. // pieces that differ are fetched and merged.
  5311. if let Some(card) = &card {
  5312. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  5313. }
  5314. let back = crate::picked::with(declared_writes(runs), &picked.written);
  5315. hand_back(&back);
  5316. if let Some(card) = card {
  5317. self.card_done(card);
  5318. }
  5319. #[cfg(feature = "diagnostics")]
  5320. if !back.is_empty() {
  5321. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  5322. }
  5323. // Nothing of this submission goes back to the title: no range of
  5324. // shader writes, no value written when it is done. The wait for
  5325. // such a one is only for order and for what the card still holds.
  5326. #[cfg(feature = "diagnostics")]
  5327. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  5328. use crate::copystat::{C, add};
  5329. add(C::NothingBack, 1);
  5330. add(C::NothingBackUs, gpu.as_micros() as u64);
  5331. }
  5332. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  5333. for list in runs {
  5334. // Read backs first: a value written at the bottom of the pipe
  5335. // may be what tells the title that they are there.
  5336. read_backs(list);
  5337. for &(at, what, bytes) in &list.deferred().writes {
  5338. what.write(at as *mut u8, bytes);
  5339. }
  5340. }
  5341. self.log_messages();
  5342. submitting(0, 0);
  5343. #[cfg(feature = "diagnostics")]
  5344. crate::copystat::submission_ends(lock);
  5345. // With the relay: nothing is in the air now, so no fetch still to
  5346. // be merged is older than the sends to card copies so far, and
  5347. // their notes can go.
  5348. if relay() {
  5349. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  5350. }
  5351. working(was_working);
  5352. None
  5353. }
  5354. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  5355. /// it lies in (by the names we give them) or the title memory copy just
  5356. /// below it; for each list that did not finish, the command it stopped
  5357. /// at and what the draws and dispatches in flight there run (or, in
  5358. /// lists that never started, the pipelines they bind).
  5359. fn removal_data(&self, runs: &[&HostList]) -> String {
  5360. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  5361. return String::new();
  5362. };
  5363. let mut text = String::new();
  5364. let mut fault_va = None;
  5365. // SAFETY: the outputs are the runtime's, valid while the device
  5366. // lives; nodes are walked as linked, histories have their counts.
  5367. unsafe {
  5368. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  5369. && fault.PageFaultVA != 0
  5370. {
  5371. let va = fault.PageFaultVA;
  5372. fault_va = Some(va);
  5373. text.push_str(&format!("; page fault at {va:#x}"));
  5374. for (what, head) in [
  5375. ("inside", fault.pHeadExistingAllocationNode),
  5376. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  5377. ] {
  5378. let mut names = Vec::new();
  5379. let mut node = head;
  5380. while let Some(n) = node.as_ref()
  5381. && names.len() < 8
  5382. {
  5383. let name = if n.ObjectNameW.is_null() {
  5384. "unnamed".to_owned()
  5385. } else {
  5386. n.ObjectNameW.to_string().unwrap_or_default()
  5387. };
  5388. names.push(format!("{name} (type {})", n.AllocationType.0));
  5389. node = n.pNext;
  5390. }
  5391. if !names.is_empty() {
  5392. text.push_str(&format!("; {what} {names:?}"));
  5393. }
  5394. }
  5395. text.push_str(&crate::shadow::near(va));
  5396. text.push_str(&crate::descriptor::host::near_heaps(va));
  5397. #[cfg(feature = "diagnostics")]
  5398. text.push_str(&crate::book::at_loss(va));
  5399. }
  5400. // The plain output: the extended one (with marker texts) came
  5401. // back without stopped lists on this host.
  5402. if dred_faults() {
  5403. return text;
  5404. }
  5405. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  5406. Ok(crumbs) => crumbs,
  5407. Err(e) => {
  5408. text.push_str(&format!("; no breadcrumbs ({e})"));
  5409. return text;
  5410. }
  5411. };
  5412. // Every list's progress (done/count), in the runtime's order.
  5413. let mut progress = Vec::new();
  5414. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  5415. while let Some(p) = node.as_ref() {
  5416. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5417. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  5418. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  5419. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  5420. node = p.pNext;
  5421. }
  5422. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  5423. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  5424. while let Some(p) = plain.as_ref() {
  5425. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5426. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  5427. let history =
  5428. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  5429. text.push_str(&format!(
  5430. "; a list stopped at command {done} of {} (op {})",
  5431. p.BreadcrumbCount, history[done as usize].0
  5432. ));
  5433. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  5434. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  5435. let named = [
  5436. (!p.pCommandListDebugNameW.is_null()).then(|| p.pCommandListDebugNameW.to_string().unwrap_or_default()),
  5437. (!p.pCommandListDebugNameA.is_null()).then(|| {
  5438. std::ffi::CStr::from_ptr(p.pCommandListDebugNameA.cast()).to_string_lossy().into_owned()
  5439. }),
  5440. ]
  5441. .into_iter()
  5442. .flatten()
  5443. .next()
  5444. .unwrap_or_default();
  5445. text.push_str(&format!(" of \"{named}\""));
  5446. // Not one of the caller's: by the name.
  5447. #[cfg(feature = "diagnostics")]
  5448. let by_name = list_number(&named).and_then(|n| {
  5449. let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  5450. all.get(&n).map(|(notes, pipelines, _)| (notes.upgrade(), pipelines.upgrade()))
  5451. });
  5452. #[cfg(feature = "diagnostics")]
  5453. let indirects = run.map(|r| r.indirects.clone()).or_else(|| {
  5454. let n = list_number(&named)?;
  5455. LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()).get(&n)?.2.upgrade()
  5456. });
  5457. #[cfg(not(feature = "diagnostics"))]
  5458. #[allow(clippy::type_complexity)]
  5459. let by_name: Option<(Option<()>, Option<std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>>)> = None;
  5460. #[cfg(feature = "diagnostics")]
  5461. let noted = run.map(|r| r.notes.clone()).or_else(|| by_name.as_ref().and_then(|b| b.0.clone()));
  5462. let bound = run.map(|r| r.pipelines.clone()).or_else(|| by_name.as_ref().and_then(|b| b.1.clone()));
  5463. // The k-th marker command is the k-th note.
  5464. #[cfg(feature = "diagnostics")]
  5465. let markers: Vec<(u32, String)> = noted.map_or_else(Vec::new, |notes| {
  5466. let notes = notes.lock().unwrap_or_else(|e| e.into_inner());
  5467. history
  5468. .iter()
  5469. .enumerate()
  5470. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  5471. .zip(notes.iter())
  5472. .map(|((at, _), (note, range))| {
  5473. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  5474. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  5475. })
  5476. .collect()
  5477. });
  5478. #[cfg(not(feature = "diagnostics"))]
  5479. let markers: Vec<(u32, String)> = Vec::new();
  5480. #[cfg(not(feature = "diagnostics"))]
  5481. let _ = fault_va;
  5482. if done > 0 {
  5483. text.push_str(&in_flight(history, &markers, done as usize));
  5484. }
  5485. #[cfg(feature = "diagnostics")]
  5486. if let Some(indirects) = indirects {
  5487. text.push_str(&indirects_around(history, done as usize, &indirects));
  5488. }
  5489. // (Without markers a list that stopped midway says what
  5490. // it may have been at only by what it binds.)
  5491. if (done == 0 || markers.is_empty())
  5492. && let Some(bound) = bound
  5493. {
  5494. let pipelines = bound.lock().unwrap_or_else(|e| e.into_inner());
  5495. text.push_str(&format!(", its pipelines {pipelines:?}"));
  5496. }
  5497. }
  5498. plain = p.pNext;
  5499. }
  5500. }
  5501. text
  5502. }
  5503. /// Moves the debug layer's messages into our log; returns the first
  5504. /// error among them.
  5505. pub(crate) fn log_messages(&self) -> Option<String> {
  5506. let Some(queue) = &self.messages else {
  5507. return None;
  5508. };
  5509. let mut first_error = None;
  5510. // SAFETY: each message is read into a buffer of the size the queue
  5511. // reports, then the queue is emptied.
  5512. unsafe {
  5513. for i in 0..queue.GetNumStoredMessages() {
  5514. let mut size = 0;
  5515. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  5516. continue;
  5517. }
  5518. let mut buffer = vec![0u64; size.div_ceil(8)];
  5519. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  5520. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  5521. let m = &*message;
  5522. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  5523. let text = String::from_utf8_lossy(text);
  5524. let text = text.trim_end_matches('\0');
  5525. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  5526. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  5527. first_error = Some(text.to_owned());
  5528. }
  5529. }
  5530. }
  5531. queue.ClearStoredMessages();
  5532. }
  5533. first_error
  5534. }
  5535. /// A host render target view of `resource`, valid until it is recorded.
  5536. pub(crate) fn rtv(
  5537. &self,
  5538. resource: Option<&ID3D12Resource>,
  5539. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  5540. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5541. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5542. // SAFETY: a slot of our heap and a live resource, or none with a
  5543. // description (a typed null view).
  5544. unsafe {
  5545. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  5546. handle.ptr += (slot * self.rtv_size) as usize;
  5547. self.device
  5548. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  5549. handle
  5550. }
  5551. }
  5552. /// A host depth view of `resource`, valid until it is recorded.
  5553. pub(crate) fn dsv(
  5554. &self,
  5555. resource: &ID3D12Resource,
  5556. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  5557. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5558. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5559. // SAFETY: a slot of our heap and a live resource.
  5560. unsafe {
  5561. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  5562. handle.ptr += (slot * self.dsv_size) as usize;
  5563. self.device
  5564. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  5565. handle
  5566. }
  5567. }
  5568. }
  5569. impl HostList {
  5570. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  5571. #[cfg(feature = "diagnostics")]
  5572. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  5573. if !timing() {
  5574. return None;
  5575. }
  5576. self.stamps
  5577. .get_or_init(|| {
  5578. let device = &host()?.device;
  5579. let mut heap: Option<ID3D12QueryHeap> = None;
  5580. let mut back: Option<ID3D12Resource> = None;
  5581. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  5582. let desc = D3D12_RESOURCE_DESC {
  5583. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5584. Width: u64::from(STAMPS) * 8,
  5585. Height: 1,
  5586. DepthOrArraySize: 1,
  5587. MipLevels: 1,
  5588. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  5589. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5590. ..Default::default()
  5591. };
  5592. // SAFETY: plain object creation.
  5593. unsafe {
  5594. device
  5595. .CreateQueryHeap(
  5596. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  5597. &mut heap,
  5598. )
  5599. .ok()?;
  5600. device
  5601. .CreateCommittedResource(
  5602. &readback,
  5603. D3D12_HEAP_FLAG_NONE,
  5604. &desc,
  5605. D3D12_RESOURCE_STATE_COPY_DEST,
  5606. None,
  5607. &mut back,
  5608. )
  5609. .ok()?;
  5610. }
  5611. Some((heap?, back?))
  5612. })
  5613. .as_ref()
  5614. }
  5615. /// The noted commands that took longest on the GPU, longest first, as
  5616. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  5617. #[cfg(feature = "diagnostics")]
  5618. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  5619. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  5620. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  5621. return Vec::new();
  5622. };
  5623. let mut data = std::ptr::null_mut();
  5624. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  5625. // SAFETY: a read-back buffer the finished list resolved into.
  5626. let stamps: Vec<u64> = unsafe {
  5627. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  5628. return Vec::new();
  5629. }
  5630. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  5631. back.Unmap(0, None);
  5632. s
  5633. };
  5634. let mut times: Vec<(f64, String)> = (0..count)
  5635. .map(|i| {
  5636. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5637. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5638. })
  5639. .collect();
  5640. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5641. times.truncate(n);
  5642. times
  5643. }
  5644. pub(crate) fn close(&self) {
  5645. let _closing = crate::timeline::span("closing a host list");
  5646. self.twins_to_depth();
  5647. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5648. if let Some((scratch, _)) = scratch {
  5649. self.indirect_common(&scratch);
  5650. }
  5651. self.batches_common();
  5652. self.card_budget_out();
  5653. self.take_coming();
  5654. #[cfg(feature = "diagnostics")]
  5655. if let Some((heap, back)) = self.stamps() {
  5656. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5657. // SAFETY: an open list, our heap and read-back buffer.
  5658. unsafe {
  5659. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5660. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5661. }
  5662. }
  5663. // SAFETY: our list.
  5664. if let Err(e) = unsafe { self.list.Close() } {
  5665. fail(format_args!(
  5666. "a host command list did not close ({e}): a command recorded into it was invalid"
  5667. ));
  5668. }
  5669. }
  5670. /// `work` finds, on a thread of ours, refreshes that belong at this
  5671. /// place among the list's steps; they are there when the list is closed.
  5672. pub(crate) fn refreshes_coming(&self, work: impl FnOnce() -> Vec<aside::Refresh> + Send + 'static) {
  5673. self.take_coming();
  5674. let at = self.deferred().copies.len();
  5675. let coming = aside::begin(work);
  5676. *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = Some((at, coming));
  5677. }
  5678. /// The refreshes that were still to come are put among the steps.
  5679. fn take_coming(&self) {
  5680. let Some((at, coming)) = self.coming.lock().unwrap_or_else(|e| e.into_inner()).take() else {
  5681. return;
  5682. };
  5683. let found = coming.wait();
  5684. let mut deferred = self.deferred();
  5685. let at = at.min(deferred.copies.len());
  5686. deferred
  5687. .copies
  5688. .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize)));
  5689. }
  5690. /// Only after the list's last submission finished (every one is waited
  5691. /// for).
  5692. pub(crate) fn reset(&self) {
  5693. self.changed_something();
  5694. #[cfg(feature = "diagnostics")]
  5695. let started = std::time::Instant::now();
  5696. let _resetting = crate::timeline::span("resetting a host list");
  5697. self._alive.used();
  5698. *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None;
  5699. *self.deferred() = Deferred::default();
  5700. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5701. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5702. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5703. #[cfg(feature = "diagnostics")]
  5704. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5705. #[cfg(feature = "diagnostics")]
  5706. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5707. {
  5708. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5709. (scratch.current, scratch.used) = (0, 0);
  5710. // Every submission of the list has run: nothing reads its
  5711. // scratch memory any more, and the next list to ask takes it.
  5712. if scratch_pool() {
  5713. give_chunks(std::mem::take(&mut scratch.chunks));
  5714. }
  5715. }
  5716. // SAFETY: the list is not executing.
  5717. let reset = unsafe {
  5718. self.allocator
  5719. .Reset()
  5720. .and_then(|()| self.list.Reset(&self.allocator, None))
  5721. };
  5722. if let Err(e) = reset {
  5723. fail(format_args!("a host command list did not reset ({e})"));
  5724. }
  5725. #[cfg(feature = "diagnostics")]
  5726. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5727. }
  5728. /// Something changed in this list that bringing a draw's textures and
  5729. /// buffers up to date depends on: a texture's state, a twin, what was
  5730. /// refreshed.
  5731. pub(crate) fn changed_something(&self) {
  5732. self.epoch.store(next_epoch(), Ordering::Relaxed);
  5733. }
  5734. /// See [`HostList::changed_something`].
  5735. pub(crate) fn epoch(&self) -> u64 {
  5736. self.epoch.load(Ordering::Relaxed)
  5737. }
  5738. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5739. /// list: the host texture and the state it leaves, if that is a change.
  5740. /// The list's first use of a texture records nothing: its prelude brings
  5741. /// the texture there at submission.
  5742. pub(crate) fn transition(
  5743. &self,
  5744. resource: crate::object::This,
  5745. wanted: u32,
  5746. ) -> Option<(&'static ID3D12Resource, u32)> {
  5747. let copy = crate::resource::host_copy(resource)?;
  5748. // SAFETY: as in `crate::resource::host_resource`; the list's states
  5749. // hold the copy from here on.
  5750. let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(&copy.texture) };
  5751. let wanted = legal_for(copy.flags(), wanted);
  5752. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5753. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5754. std::collections::hash_map::Entry::Vacant(v) => {
  5755. v.insert((wanted, wanted, copy));
  5756. self.changed_something();
  5757. None
  5758. }
  5759. std::collections::hash_map::Entry::Occupied(mut o) => {
  5760. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5761. if before != wanted {
  5762. self.changed_something();
  5763. }
  5764. (before != wanted).then_some((texture, before))
  5765. }
  5766. }
  5767. }
  5768. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5769. /// as [`HostList::transition`] does a title resource's host copy, and
  5770. /// records the barrier: for textures that are not a title resource's
  5771. /// host copy (colour twins) and for the copies between the two.
  5772. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5773. let wanted = legal_for(copy.flags(), wanted);
  5774. self.changed_something();
  5775. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5776. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5777. std::collections::hash_map::Entry::Vacant(v) => {
  5778. v.insert((wanted, wanted, copy.clone()));
  5779. None
  5780. }
  5781. std::collections::hash_map::Entry::Occupied(mut o) => {
  5782. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5783. (before != wanted).then_some(before)
  5784. }
  5785. };
  5786. drop(states);
  5787. if let Some(before) = before {
  5788. let barrier = transition(
  5789. &copy.texture,
  5790. D3D12_RESOURCE_STATES(before as i32),
  5791. D3D12_RESOURCE_STATES(wanted as i32),
  5792. );
  5793. // SAFETY: an open list and a live texture.
  5794. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5795. }
  5796. }
  5797. /// A use of title texture `resource` about to be recorded, if it is a
  5798. /// depth texture with a colour twin (false if it is not): of the twin
  5799. /// (`colour`: unordered access) or of the depth texture (depth target,
  5800. /// clear, shader read, copy, resolve), writing it or only reading. The
  5801. /// side used is first brought up to date: by a copy recorded here if
  5802. /// this list wrote the other side since, by the list's prelude if the
  5803. /// list uses the side as it finds it. The twin is left in the
  5804. /// unordered access state; the caller moves the depth texture to the
  5805. /// state its use needs, as for any texture. A twin still ahead when the
  5806. /// list closes is copied then (`twins_to_depth`).
  5807. /// shortcut: every depth target bound for a draw counts as written
  5808. /// (also when the draw only tests), and every unordered access view a
  5809. /// shader names as written; views a shader picks from the heap by a
  5810. /// computed index are not seen here at all.
  5811. pub(crate) fn twin_use(
  5812. &self,
  5813. resource: crate::object::This,
  5814. colour: bool,
  5815. write: bool,
  5816. ) -> bool {
  5817. const UNORDERED_ACCESS: u32 = 0x8;
  5818. // Asked for every texture a draw reads: most have no twin.
  5819. let Some(twin) = crate::resource::twin(resource) else {
  5820. return false;
  5821. };
  5822. let Some(depth) = crate::resource::host_copy(resource) else {
  5823. return false;
  5824. };
  5825. let side = usize::from(colour);
  5826. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5827. let u = twins
  5828. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5829. .or_insert_with(|| TwinUse {
  5830. depth: depth.clone(),
  5831. twin: twin.clone(),
  5832. needs: [false; 2],
  5833. behind: [None; 2],
  5834. writing: false,
  5835. late: false,
  5836. });
  5837. let was = (u.needs, u.behind, u.writing);
  5838. let copy = match u.behind[side] {
  5839. Some(behind) => behind,
  5840. None => {
  5841. u.needs[side] = true;
  5842. false
  5843. }
  5844. };
  5845. u.behind[side] = Some(false);
  5846. match (write, colour) {
  5847. // Shaders write the twin when the draw or dispatch runs: what
  5848. // the same one reads of the depth texture is prepared before
  5849. // (`twins_written`).
  5850. (true, true) => u.writing = true,
  5851. (true, false) => u.behind[1] = Some(true),
  5852. (false, _) => {}
  5853. }
  5854. if was != (u.needs, u.behind, u.writing) || copy || colour {
  5855. self.changed_something();
  5856. }
  5857. // shortcut: the depth plane's twin is not drawn into the plane
  5858. // here: the pass sets a pipeline and a target of ours, which a list
  5859. // still recording the title's commands cannot take. This use sees
  5860. // the plane as it was; the pass runs when the list closes
  5861. // (`twins_to_depth`). Counted.
  5862. if copy && !colour && twin.plane.is_some() {
  5863. u.late = true;
  5864. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5865. }
  5866. drop(twins);
  5867. if copy {
  5868. self.twin_copy(&depth, &twin, colour);
  5869. } else if colour {
  5870. self.settle(&twin.colour, UNORDERED_ACCESS);
  5871. }
  5872. // The depth plane's twin is written through unordered access too.
  5873. if colour && let Some(plane) = &twin.plane {
  5874. self.settle(plane, UNORDERED_ACCESS);
  5875. }
  5876. true
  5877. }
  5878. /// Records the pass that draws the twin of the depth plane of `depth`
  5879. /// into the plane, if `twin` has one, with the moves to the states the
  5880. /// pass needs; the twin is left in the unordered access state. Only
  5881. /// for a list that records nothing of the title's afterwards
  5882. /// (`record_plane_pass`).
  5883. fn pass_plane(
  5884. &self,
  5885. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5886. twin: &crate::resource::Twin,
  5887. ) {
  5888. const UNORDERED_ACCESS: u32 = 0x8;
  5889. const DEPTH_WRITE: u32 = 0x10;
  5890. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5891. let Some(plane) = &twin.plane else { return };
  5892. self.settle(depth, DEPTH_WRITE);
  5893. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5894. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5895. self.settle(plane, UNORDERED_ACCESS);
  5896. }
  5897. /// Records the copy of a depth texture into its colour twin (`colour`)
  5898. /// or of the twin into the depth texture, with the moves to the copy
  5899. /// states. The twin is left in the unordered access state.
  5900. fn twin_copy(
  5901. &self,
  5902. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5903. twin: &crate::resource::Twin,
  5904. colour: bool,
  5905. ) {
  5906. const UNORDERED_ACCESS: u32 = 0x8;
  5907. const COPY_DEST: u32 = 0x400;
  5908. const COPY_SOURCE: u32 = 0x800;
  5909. let (from, to) = if colour {
  5910. (depth, &twin.colour)
  5911. } else {
  5912. (&twin.colour, depth)
  5913. };
  5914. self.settle(from, COPY_SOURCE);
  5915. self.settle(to, COPY_DEST);
  5916. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5917. self.settle(&twin.colour, UNORDERED_ACCESS);
  5918. }
  5919. /// Before the list closes: the depth textures whose twins it wrote last
  5920. /// are given what was written, and left readable by shaders. Shaders
  5921. /// that pick a view from the heap by a computed index are not seen by
  5922. /// `twin_use` and read the depth texture in lists that never name it
  5923. /// (in a captured frame of the title no table names a shadow
  5924. /// map for reading but the pass that fills the next one).
  5925. fn twins_to_depth(&self) {
  5926. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5927. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5928. let written: Vec<_> = twins
  5929. .values_mut()
  5930. .filter(|u| u.behind[0] == Some(true) || u.late)
  5931. .map(|u| {
  5932. // Not copied again if the list copied since the last write
  5933. // and only the depth plane's pass is left.
  5934. let copy = u.behind[0] == Some(true);
  5935. u.behind[0] = Some(false);
  5936. u.late = false;
  5937. (u.depth.clone(), u.twin.clone(), copy)
  5938. })
  5939. .collect();
  5940. drop(twins);
  5941. for (depth, twin, copy) in &written {
  5942. if *copy {
  5943. self.twin_copy(depth, twin, false);
  5944. }
  5945. // Nothing of the title's is recorded after this: the pass may
  5946. // leave its own pipeline and target set.
  5947. self.pass_plane(depth, twin);
  5948. self.settle(depth, SHADER_RESOURCE);
  5949. }
  5950. }
  5951. /// The draw or dispatch just prepared is recorded: the twins it writes
  5952. /// now hold what their depth textures lack.
  5953. pub(crate) fn twins_written(&self) {
  5954. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5955. for u in twins.values_mut().filter(|u| u.writing) {
  5956. u.writing = false;
  5957. u.behind[0] = Some(true);
  5958. self.changed_something();
  5959. }
  5960. }
  5961. /// At submission: the list that moves each texture this list uses from
  5962. /// its real state to the one the list starts with; the textures' real
  5963. /// states become those the list ends with. For depth textures with a
  5964. /// colour twin it first copies the side the list uses as it finds it
  5965. /// from the other, if a list submitted earlier left it behind.
  5966. fn prelude(&self) -> Option<ID3D12CommandList> {
  5967. const COPY_DEST: u32 = 0x400;
  5968. const COPY_SOURCE: u32 = 0x800;
  5969. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5970. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5971. // The copies (depth texture, twin, whether into the twin); the
  5972. // sides are then as this list leaves them.
  5973. let mut syncs = Vec::new();
  5974. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5975. for u in twins.values() {
  5976. let real = u.twin.behind.load(Ordering::Relaxed);
  5977. let mut behind = [real & 1 != 0, real & 2 != 0];
  5978. for side in [0, 1] {
  5979. if u.needs[side] && behind[side] {
  5980. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5981. behind = [false; 2];
  5982. }
  5983. }
  5984. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5985. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5986. u.twin.behind.store(left, Ordering::Relaxed);
  5987. }
  5988. drop(twins);
  5989. // A copy runs with its textures in the copy states: each moves
  5990. // there from its real state, and from there to the state the list
  5991. // starts with (back to its real state if the list does not use it).
  5992. let mut to_copy = Vec::new();
  5993. let mut barriers = Vec::new();
  5994. let mut copying = std::collections::HashMap::new();
  5995. for (depth, twin, colour) in &syncs {
  5996. let (from, to) = if *colour {
  5997. (depth, &twin.colour)
  5998. } else {
  5999. (&twin.colour, depth)
  6000. };
  6001. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  6002. let key = std::sync::Arc::as_ptr(texture) as usize;
  6003. let real = texture.state.load(Ordering::Relaxed);
  6004. copying.insert(key, state);
  6005. if real != state {
  6006. to_copy.push(transition(
  6007. &texture.texture,
  6008. host_state(real),
  6009. host_state(state),
  6010. ));
  6011. if !states.contains_key(&key) {
  6012. barriers.push(transition(
  6013. &texture.texture,
  6014. host_state(state),
  6015. host_state(real),
  6016. ));
  6017. }
  6018. }
  6019. }
  6020. }
  6021. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  6022. let real = copy.state.swap(*last, Ordering::Relaxed);
  6023. let real = copying.get(key).copied().unwrap_or(real);
  6024. (real != *first)
  6025. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  6026. }));
  6027. if barriers.is_empty() && syncs.is_empty() {
  6028. return None;
  6029. }
  6030. let Some((allocator, list)) = self
  6031. .prelude
  6032. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  6033. .as_ref()
  6034. else {
  6035. fail(format_args!("no host list for a state prelude"));
  6036. };
  6037. // SAFETY: the prelude is not executing (every submission is waited
  6038. // for); the textures are live.
  6039. let recorded = unsafe {
  6040. allocator.Reset().and_then(|()| {
  6041. list.Reset(allocator, None)?;
  6042. if !to_copy.is_empty() {
  6043. list.ResourceBarrier(&to_copy);
  6044. }
  6045. for (depth, twin, colour) in &syncs {
  6046. record_twin_copy(list, &depth.texture, twin, *colour);
  6047. }
  6048. if !barriers.is_empty() {
  6049. list.ResourceBarrier(&barriers);
  6050. }
  6051. list.Close()
  6052. })
  6053. };
  6054. if let Err(e) = recorded {
  6055. fail(format_args!("a host state prelude did not record ({e})"));
  6056. }
  6057. list.cast().ok()
  6058. }
  6059. /// Notes what the command about to be recorded does, as a marker
  6060. /// command whose text the list keeps (diagnostics, with device-removed
  6061. /// data on): the report pairs the breadcrumbs' marker commands with the
  6062. /// texts in order and names the commands a fault stopped among.
  6063. #[cfg(feature = "diagnostics")]
  6064. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  6065. self.note(what, None);
  6066. }
  6067. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  6068. /// `(address, bytes)`: the report places the faulting address in it.
  6069. #[cfg(feature = "diagnostics")]
  6070. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  6071. self.note(what, Some(range));
  6072. }
  6073. #[cfg(feature = "diagnostics")]
  6074. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  6075. if !dred_on() {
  6076. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  6077. return;
  6078. }
  6079. {
  6080. let started = std::time::Instant::now();
  6081. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  6082. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  6083. // SAFETY: an open list and our query heap.
  6084. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  6085. }
  6086. let what = what();
  6087. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  6088. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  6089. const UNICODE: u32 = 0;
  6090. // SAFETY: an open list; the marker is copied when recorded.
  6091. unsafe {
  6092. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  6093. };
  6094. self.notes
  6095. .lock()
  6096. .unwrap_or_else(|e| e.into_inner())
  6097. .push((what, range));
  6098. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  6099. }
  6100. }
  6101. /// Whether nothing recorded since the list was opened does any work:
  6102. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  6103. /// upload or resolve (they defer a step or move a texture's state), no
  6104. /// bottom-of-pipe write. State set on the list does not count.
  6105. pub(crate) fn untouched(&self) -> bool {
  6106. {
  6107. let deferred = self.deferred();
  6108. if !(deferred.copies.is_empty()
  6109. && deferred.uploads.is_empty()
  6110. && deferred.kept.is_empty()
  6111. && deferred.textures.is_empty()
  6112. && deferred.writes.is_empty()
  6113. && deferred.backs.is_empty())
  6114. {
  6115. return false;
  6116. }
  6117. }
  6118. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  6119. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  6120. }
  6121. /// Notes an indirect execution, while device-removed data is kept
  6122. /// ([`indirects`]).
  6123. #[cfg(feature = "diagnostics")]
  6124. pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) {
  6125. if dred_on() || dred_light() {
  6126. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user);
  6127. }
  6128. }
  6129. /// Notes a pipeline the list binds.
  6130. pub(crate) fn used_pipeline(&self, name: &str) {
  6131. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  6132. if !pipelines.contains(name) {
  6133. pipelines.insert(name.to_owned());
  6134. }
  6135. }
  6136. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  6137. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  6138. }
  6139. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  6140. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  6141. let mut deferred = self.deferred();
  6142. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  6143. // A copy that goes on where the one recorded just before it ended,
  6144. // source and destination both: with `join_copies` the two are one
  6145. // step.
  6146. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  6147. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  6148. {
  6149. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  6150. if join_copies() {
  6151. *n += len;
  6152. return;
  6153. }
  6154. }
  6155. deferred
  6156. .copies
  6157. .push(Step::Copy(dst as usize, src as usize, len));
  6158. deferred.refreshed.clear();
  6159. self.changed_something();
  6160. }
  6161. /// Copies `len` bytes of title memory at `src` into the list's upload
  6162. /// memory at `dst` when the list is submitted.
  6163. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  6164. self.deferred()
  6165. .copies
  6166. .push(Step::Fill(dst as usize, src as usize, len, None));
  6167. }
  6168. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  6169. /// title heap's address, and the slot) shows.
  6170. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  6171. self.deferred()
  6172. .copies
  6173. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  6174. }
  6175. /// As [`HostList::defer_fill`], for the beginning of a buffer
  6176. /// [`HostList::upload`] made.
  6177. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  6178. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  6179. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  6180. }
  6181. /// Brings `[address, address + len)` of a buffer's host copy up to date
  6182. /// when the list is submitted (once per range until a title copy
  6183. /// intervenes), keeping the copy alive until the list is reset.
  6184. pub(crate) fn defer_refresh(
  6185. &self,
  6186. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  6187. address: usize,
  6188. len: usize,
  6189. ) {
  6190. let mut deferred = self.deferred();
  6191. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  6192. if deferred.refreshed.insert(key) {
  6193. deferred
  6194. .copies
  6195. .push(Step::Refresh(shadow.clone(), address, len));
  6196. }
  6197. }
  6198. /// Shaders of the list write `[address, address + len)` of a buffer's
  6199. /// host copy: copied back into title memory once the list has run.
  6200. pub(crate) fn defer_gpu_write(
  6201. &self,
  6202. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  6203. address: usize,
  6204. len: usize,
  6205. ) {
  6206. self.deferred()
  6207. .copies
  6208. .push(Step::GpuWrite(shadow.clone(), address, len));
  6209. }
  6210. /// A read back: once the list has run, `rows` rows of `row` bytes go
  6211. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  6212. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  6213. /// the list is reset.
  6214. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  6215. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  6216. }
  6217. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  6218. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  6219. self.deferred().writes.push((dst as usize, what, bytes));
  6220. }
  6221. /// A mapped upload buffer of `size` bytes, alive until the list is
  6222. /// reset.
  6223. ///
  6224. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  6225. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6226. // With [`card_steps`] the card may be the one that fills it.
  6227. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  6228. name(&buffer, || format!("list upload {size:#x}"));
  6229. self.deferred().hold_upload(buffer.clone(), size);
  6230. Some((buffer, data))
  6231. }
  6232. /// `len` bytes of upload memory (256-byte aligned) until the list is
  6233. /// reset: the host GPU address and the CPU pointer.
  6234. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  6235. let (buffer, at, data) = self.scratch_at(len)?;
  6236. // SAFETY: a live buffer.
  6237. Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data))
  6238. }
  6239. /// [`HostList::scratch`] and the buffer it lies in, for a descriptor
  6240. /// slot to hold: the slot outlives the list's use of it.
  6241. pub(crate) fn scratch_held(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  6242. let (buffer, at, data) = self.scratch_at(len)?;
  6243. // SAFETY: a live buffer.
  6244. let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at;
  6245. Some((buffer, gpu, data))
  6246. }
  6247. /// [`HostList::scratch`]: the buffer, the offset in it and the CPU
  6248. /// pointer.
  6249. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  6250. let host = host()?;
  6251. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  6252. let len = len.max(1).next_multiple_of(256);
  6253. if len > SCRATCH_CHUNK {
  6254. let (buffer, data) = host.upload_buffer(len)?;
  6255. name(&buffer, || format!("list scratch {len:#x}"));
  6256. self.deferred().hold_upload(buffer.clone(), len);
  6257. return Some((buffer, 0, data));
  6258. }
  6259. // The chunk in use while `len` fits in what is left of it, else the
  6260. // next one (a list's first chunk may be a small one).
  6261. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  6262. (s.current, s.used) = (s.current + 1, 0);
  6263. }
  6264. if s.current == s.chunks.len() {
  6265. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  6266. SCRATCH_FIRST
  6267. } else {
  6268. SCRATCH_CHUNK
  6269. };
  6270. let chunk = take_chunk(host, size)?;
  6271. s.chunks.push((chunk, size));
  6272. s.used = 0;
  6273. }
  6274. let (data, buffer) = (s.chunks[s.current].0.data, s.chunks[s.current].0.buffer.clone());
  6275. let at = s.used;
  6276. s.used += len;
  6277. Some((buffer, at, (data + at as usize) as *mut u8))
  6278. }
  6279. /// The bytes of scratch chunks the list holds now (after a reset:
  6280. /// none while lists share their chunks).
  6281. pub(crate) fn scratch_kept(&self) -> u64 {
  6282. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  6283. scratch.chunks.iter().map(|c| c.1).sum()
  6284. }
  6285. /// The host address of the list's indirect-work budget, zeroed at each
  6286. /// submission of the list from the first use after a reset on.
  6287. pub(crate) fn budget(&self) -> Option<u64> {
  6288. let (buffer, data) = self
  6289. .budget
  6290. .get_or_init(|| {
  6291. let (b, d) = host()?.shared_buffer(256)?;
  6292. Some((b, d as usize))
  6293. })
  6294. .as_ref()?;
  6295. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  6296. let mut deferred = self.deferred();
  6297. if !deferred.budget_zeroed {
  6298. deferred.budget_zeroed = true;
  6299. let at = *data;
  6300. // SAFETY: the list's own mapped words, written before it runs.
  6301. // The words after the budget hold what the clamp noted about the
  6302. // list's last run (mesh dispatches: the largest group count
  6303. // asked for, the groups asked in all; with the card's copy, as
  6304. // the list's end copied them here): taken, then zeroed.
  6305. let notes = Box::new(move || unsafe {
  6306. let words = at as *mut u32;
  6307. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  6308. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  6309. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  6310. for k in 0..3 {
  6311. words.add(k).write_volatile(0);
  6312. }
  6313. });
  6314. deferred.copies.push(Step::Host(notes, (0, 0)));
  6315. drop(deferred);
  6316. if let Some(card) = card {
  6317. self.zero_card_budget(card);
  6318. }
  6319. }
  6320. // SAFETY: a live buffer.
  6321. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  6322. }
  6323. /// The budget's words in the card's own memory ([`card_budget`]), if
  6324. /// the list can zero them itself (`WriteBufferImmediate`).
  6325. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  6326. if !card_budget() {
  6327. return None;
  6328. }
  6329. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  6330. let buffer = host()?.uav_buffer(256)?;
  6331. name(&buffer, || "indirect budget".to_owned());
  6332. Some(buffer)
  6333. }
  6334. /// Records, before the list's first clamp, the zeroing of the card's
  6335. /// copy of the budget: common, written as a copy, then left for
  6336. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  6337. fn zero_card_budget(&self, card: &ID3D12Resource) {
  6338. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  6339. return;
  6340. };
  6341. // SAFETY: a live buffer.
  6342. let at = unsafe { card.GetGPUVirtualAddress() };
  6343. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  6344. Dest: at + offset,
  6345. Value: 0,
  6346. });
  6347. // SAFETY: an open list; the buffer is the list's own and in the
  6348. // common state at the start of every recording.
  6349. unsafe {
  6350. self.list.ResourceBarrier(&[transition(
  6351. card,
  6352. D3D12_RESOURCE_STATE_COMMON,
  6353. D3D12_RESOURCE_STATE_COPY_DEST,
  6354. )]);
  6355. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  6356. self.list.ResourceBarrier(&[transition(
  6357. card,
  6358. D3D12_RESOURCE_STATE_COPY_DEST,
  6359. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  6360. )]);
  6361. }
  6362. }
  6363. /// Before the list closes, if this recording charged the card's copy
  6364. /// of the budget: its notes on mesh records go to the mapped words
  6365. /// (read at the next submission), and it goes back to common.
  6366. fn card_budget_out(&self) {
  6367. if !self.deferred().budget_zeroed {
  6368. return;
  6369. }
  6370. let (Some(Some(card)), Some(Some((mapped, _)))) =
  6371. (self.card_budget.get(), self.budget.get())
  6372. else {
  6373. return;
  6374. };
  6375. // SAFETY: an open list; both buffers are the list's own. The
  6376. // mapped one is promoted from common to the copy destination.
  6377. unsafe {
  6378. self.list.ResourceBarrier(&[transition(
  6379. card,
  6380. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  6381. D3D12_RESOURCE_STATE_COPY_SOURCE,
  6382. )]);
  6383. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  6384. self.list.ResourceBarrier(&[transition(
  6385. card,
  6386. D3D12_RESOURCE_STATE_COPY_SOURCE,
  6387. D3D12_RESOURCE_STATE_COMMON,
  6388. )]);
  6389. }
  6390. }
  6391. /// A device-local unordered-access buffer of at least `size` bytes for
  6392. /// clamped indirect arguments, reused across executions and resets of the
  6393. /// list. Smaller buffers replaced mid-list stay alive until
  6394. /// [`HostList::reset`].
  6395. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  6396. let needed = size.max(64 << 10);
  6397. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  6398. if let Some((buffer, cap)) = &*slot
  6399. && *cap >= needed
  6400. {
  6401. return Some(buffer.clone());
  6402. }
  6403. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  6404. let alloc = prev
  6405. .saturating_mul(2)
  6406. .max(needed)
  6407. .next_multiple_of(64 << 10);
  6408. let buffer = host()?.uav_buffer(alloc)?;
  6409. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  6410. let old = slot.replace((buffer.clone(), alloc));
  6411. drop(slot);
  6412. if let Some((old_buf, _)) = old {
  6413. // It ends the list common, as every scratch buffer does.
  6414. self.indirect_common(&old_buf);
  6415. self.keep(&old_buf);
  6416. }
  6417. Some(buffer)
  6418. }
  6419. /// Where the next batch of clamped records goes: a device-local buffer
  6420. /// the list keeps from recording to recording, the batch's place in it
  6421. /// and the state the buffer is in. Every batch of a recording has a place
  6422. /// of its own: the executions before it may still read theirs.
  6423. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  6424. use crate::indirect::batch::{JOBS, SLOT};
  6425. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6426. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  6427. if buffer == args.0.len() {
  6428. let size = u64::from(BATCHES * JOBS * SLOT);
  6429. let made = host()?.uav_buffer(size)?;
  6430. name(&made, || format!("indirect batches {size:#x}"));
  6431. args.0.push(made);
  6432. }
  6433. args.1 += 1;
  6434. // (Its first batch finds it as the recording before left it:
  6435. // `batches_common`.)
  6436. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  6437. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  6438. }
  6439. /// Before the list closes: the scratch buffers of the batched clamps go
  6440. /// back to the common state, where the next recording expects them.
  6441. fn batches_common(&self) {
  6442. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6443. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  6444. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  6445. .iter()
  6446. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  6447. .collect();
  6448. if !barriers.is_empty() {
  6449. // SAFETY: an open list and live buffers this recording left in
  6450. // `INDIRECT_ARGUMENT`.
  6451. unsafe { self.list.ResourceBarrier(&barriers) };
  6452. }
  6453. }
  6454. /// Moves `scratch` back to the common state if a clamp left it readable
  6455. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  6456. /// list's first clamp expects it. Done before the list closes and before
  6457. /// a bigger scratch buffer replaces it: one barrier per list (where
  6458. /// there was one per indirect execution), and the list ends as it
  6459. /// begins however it is submitted.
  6460. fn indirect_common(&self, scratch: &ID3D12Resource) {
  6461. {
  6462. let mut deferred = self.deferred();
  6463. if deferred.indirect_readable != scratch.as_raw() as usize {
  6464. return;
  6465. }
  6466. deferred.indirect_readable = 0;
  6467. }
  6468. let barrier = transition(
  6469. scratch,
  6470. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  6471. D3D12_RESOURCE_STATE_COMMON,
  6472. );
  6473. // SAFETY: an open list and a live buffer this recording left in
  6474. // `INDIRECT_ARGUMENT`.
  6475. unsafe { self.list.ResourceBarrier(&[barrier]) };
  6476. }
  6477. /// The state the list's indirect scratch buffer `scratch` is in at this
  6478. /// point of the recording: indirect arguments if a clamp in this
  6479. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  6480. /// common: the state a buffer is made in, and the one a recording
  6481. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  6482. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  6483. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  6484. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  6485. } else {
  6486. D3D12_RESOURCE_STATE_COMMON
  6487. }
  6488. }
  6489. /// A clamp recorded in this list left `scratch` readable as indirect
  6490. /// arguments. It stays so for every execution that reads it, until the
  6491. /// next clamp moves it back to unordered access.
  6492. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  6493. self.deferred().indirect_readable = scratch.as_raw() as usize;
  6494. }
  6495. /// Keeps `object` alive until the list is reset.
  6496. pub(crate) fn keep(&self, object: &impl Interface) {
  6497. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  6498. self.deferred().kept.push(object);
  6499. }
  6500. }
  6501. /// Whether this is the first time since the reset that the list asks
  6502. /// about `key` (a texture to bring up to date).
  6503. pub(crate) fn first_use(&self, key: usize) -> bool {
  6504. self.deferred().textures.insert(key)
  6505. }
  6506. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  6507. /// reset.
  6508. pub(crate) fn used(&self, key: usize) -> bool {
  6509. self.deferred().textures.contains(&key)
  6510. }
  6511. /// Runs `work` when the list is submitted, in order with its copies.
  6512. /// `work` may write title memory (refreshes after it copy again).
  6513. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  6514. self.deferred().copies.push(Step::Run(Box::new(work)));
  6515. self.deferred().refreshed.clear();
  6516. self.changed_something();
  6517. }
  6518. /// As [`HostList::defer`], for work that writes only host memory.
  6519. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  6520. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  6521. }
  6522. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  6523. /// memory at `from`.
  6524. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  6525. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  6526. }
  6527. /// Brings a texture's staging buffer up to date when the list is
  6528. /// submitted, keeping it alive until the list is reset.
  6529. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  6530. self.deferred().copies.push(Step::Texture(staging));
  6531. }
  6532. /// Runs the list's submission-time steps; refreshes go into `batch`
  6533. /// (the title's big buffers, a 174 MB one among them, are read by most
  6534. /// lists of a submission, through many ranges). Copies and fills that
  6535. /// `taken` names (by their place) are left out: they are done on the
  6536. /// card ([`card_steps`]).
  6537. fn run_deferred(&self, batch: &mut Batch, air: &[(usize, usize)], taken: impl Fn(usize) -> bool) {
  6538. #[cfg(feature = "diagnostics")]
  6539. use crate::copystat::{C, add};
  6540. // The time and the bytes of the copies and fills, some 13,000 a
  6541. // frame between 20,000 refreshes: summed here and added once.
  6542. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  6543. #[cfg(feature = "diagnostics")]
  6544. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  6545. for (i, step) in self.deferred().copies.iter().enumerate() {
  6546. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  6547. continue;
  6548. }
  6549. let (started, copied) = match step {
  6550. &Step::Copy(dst, src, len) => {
  6551. let started = std::time::Instant::now();
  6552. #[cfg(feature = "diagnostics")]
  6553. {
  6554. copies += 1;
  6555. }
  6556. batch.fill();
  6557. batch.title_written();
  6558. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  6559. // With the submission's one asking: the journal learns it.
  6560. crate::watch::wrote(dst, len);
  6561. // What the card holds there may be another value although
  6562. // ours did not change.
  6563. if send::own() {
  6564. crate::shadow::send_copied(dst, len);
  6565. }
  6566. (started, len)
  6567. }
  6568. &Step::Fill(dst, src, len, _) => {
  6569. #[cfg(feature = "diagnostics")]
  6570. {
  6571. copies += 1;
  6572. }
  6573. if wide_fills() {
  6574. batch.fills.push((dst, src, len));
  6575. bytes += len as u64;
  6576. continue;
  6577. }
  6578. let started = std::time::Instant::now();
  6579. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6580. (started, len)
  6581. }
  6582. Step::Placed(p) => {
  6583. let started = std::time::Instant::now();
  6584. let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len);
  6585. batch.fill();
  6586. if free {
  6587. batch.title_written();
  6588. }
  6589. if let Some(bytes) = p.prepare(free) {
  6590. batch.placed.push((p.shadow.clone(), p.dst, bytes));
  6591. }
  6592. (started, p.len)
  6593. }
  6594. Step::Refresh(shadow, address, len) => {
  6595. #[cfg(feature = "diagnostics")]
  6596. {
  6597. refreshes += 1;
  6598. refreshed += *len as u64;
  6599. }
  6600. batch.add(shadow, *address, *len);
  6601. continue;
  6602. }
  6603. Step::Run(work) | Step::Host(work, _) => {
  6604. batch.fill();
  6605. #[cfg(feature = "diagnostics")]
  6606. let started = std::time::Instant::now();
  6607. if matches!(step, Step::Run(_)) {
  6608. batch.title_written();
  6609. }
  6610. let _step = crate::timeline::span("a step of ours");
  6611. work();
  6612. // It wrote title memory, where is not known here: the
  6613. // submission's one asking ends, later refreshes ask anew.
  6614. if matches!(step, Step::Run(_)) {
  6615. crate::watch::ask_once_end();
  6616. }
  6617. #[cfg(feature = "diagnostics")]
  6618. {
  6619. add(C::Runs, 1);
  6620. add(C::RunUs, started.elapsed().as_micros() as u64);
  6621. }
  6622. continue;
  6623. }
  6624. Step::GpuWrite(shadow, address, len) => {
  6625. // The shaders start from the title's data: this copy's
  6626. // pending refresh first. The other copies' wait for
  6627. // the next flush of all (flushing all of them at every
  6628. // range a dispatch writes made thousands of write-watch
  6629. // askings a frame).
  6630. batch.flush_one(shadow);
  6631. #[cfg(feature = "diagnostics")]
  6632. let snapshot = std::time::Instant::now();
  6633. shadow.writing(*address, *len);
  6634. #[cfg(feature = "diagnostics")]
  6635. {
  6636. add(C::GpuWrites, 1);
  6637. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  6638. }
  6639. continue;
  6640. }
  6641. Step::Texture(staging) => {
  6642. if batch.texture_due(staging) {
  6643. batch.due.push(staging.clone());
  6644. if !wide_textures() {
  6645. batch.refresh_textures();
  6646. }
  6647. }
  6648. continue;
  6649. }
  6650. };
  6651. us += started.elapsed();
  6652. bytes += copied as u64;
  6653. }
  6654. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  6655. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  6656. #[cfg(feature = "diagnostics")]
  6657. {
  6658. add(C::Copies, copies);
  6659. add(C::CopyBytes, bytes);
  6660. add(C::Refreshes, refreshes);
  6661. add(C::RefreshBytes, refreshed);
  6662. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  6663. }
  6664. }
  6665. }
  6666. /// The numbers of [`HostList::epoch`].
  6667. fn next_epoch() -> u64 {
  6668. static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
  6669. NEXT.fetch_add(1, Ordering::Relaxed)
  6670. }
  6671. /// A table by a copy's address.
  6672. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  6673. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  6674. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  6675. /// but our own.
  6676. #[derive(Default)]
  6677. pub(crate) struct AddressHash(u64);
  6678. impl std::hash::Hasher for AddressHash {
  6679. fn finish(&self) -> u64 {
  6680. self.0
  6681. }
  6682. fn write(&mut self, bytes: &[u8]) {
  6683. for &b in bytes {
  6684. self.write_usize(usize::from(b));
  6685. }
  6686. }
  6687. fn write_usize(&mut self, n: usize) {
  6688. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  6689. self.0 = h ^ (h >> 32);
  6690. }
  6691. fn write_u64(&mut self, n: u64) {
  6692. self.write_usize(n as usize);
  6693. }
  6694. fn write_u32(&mut self, n: u32) {
  6695. self.write_usize(n as usize);
  6696. }
  6697. }
  6698. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  6699. /// preparing: the write-watch asking for a submission; the title's bytes put
  6700. /// in under flights' writes; the lists' steps, the refreshes among them; the
  6701. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  6702. /// of the steps: the refreshes, and the copies and fills (those with the
  6703. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  6704. /// is of. Of the refreshes, those before ranges are given to shaders, one
  6705. /// copy at a time: nanoseconds, and how many. Ahead of all that: the wait for
  6706. /// the submission lock, the steps done on the card planned ([`card_steps`]),
  6707. /// the flights waited for, the heaps' records and what is swept; and, at the
  6708. /// end, the wait for the heaps' records.
  6709. #[cfg(feature = "diagnostics")]
  6710. static SPLIT: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16];
  6711. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  6712. /// those known to copy nothing, and those done on several threads.
  6713. #[cfg(feature = "diagnostics")]
  6714. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  6715. /// Counts into [`SPLIT`].
  6716. #[cfg(feature = "diagnostics")]
  6717. struct Split(std::cell::Cell<std::time::Instant>);
  6718. #[cfg(feature = "diagnostics")]
  6719. impl Split {
  6720. fn begin() -> Split {
  6721. Split(std::cell::Cell::new(std::time::Instant::now()))
  6722. }
  6723. /// Nanoseconds since the last part.
  6724. fn so_far(&self) -> u64 {
  6725. self.0.get().elapsed().as_nanos() as u64
  6726. }
  6727. /// What came since the last part was part `i`.
  6728. fn part(&self, i: usize) {
  6729. let now = std::time::Instant::now();
  6730. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  6731. }
  6732. }
  6733. /// The split of the preparing, per frame, for the frame-rate line.
  6734. #[cfg(feature = "diagnostics")]
  6735. fn split_line(frames: f64) {
  6736. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6737. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  6738. let e: Vec<f64> = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect();
  6739. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  6740. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6741. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
  6742. tracing::info!(
  6743. "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' \
  6744. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  6745. 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 \
  6746. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the submission lock, {:.1} \
  6747. planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is swept; at the end {:.1} waiting \
  6748. for the heaps' records; asked early by a thread of its own {:.0} pieces of 2 MiB, {:.1} ms (VICTORY_ASK_EARLY)",
  6749. ms[0],
  6750. ms[8],
  6751. ms[1],
  6752. ms[2],
  6753. ms[6],
  6754. f[0],
  6755. f[1],
  6756. f[2],
  6757. f[3],
  6758. ms[9],
  6759. ms[10] * 1e6,
  6760. ms[7],
  6761. ms[3],
  6762. ms[4],
  6763. ms[5],
  6764. if crate::watch::light() { "on" } else { "off" },
  6765. ms[11],
  6766. ms[12],
  6767. ms[13],
  6768. ms[14],
  6769. ms[15],
  6770. e[0],
  6771. e[1] / 1e3,
  6772. );
  6773. tracing::info!(
  6774. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6775. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6776. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6777. waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
  6778. as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
  6779. a[0],
  6780. a[1] / 1024.0,
  6781. a[11] / 1e6,
  6782. a[12],
  6783. a[10],
  6784. a[9],
  6785. a[2],
  6786. a[3],
  6787. a[4],
  6788. a[5],
  6789. a[6],
  6790. a[7] / 1e6,
  6791. a[8] / 1e6,
  6792. s[0] / 1048576.0,
  6793. s[1] / 1048576.0,
  6794. s[2] / 1048576.0,
  6795. s[3],
  6796. );
  6797. tracing::info!(
  6798. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures; the \
  6799. first two beside the recording (VICTORY_HEAP_PASS_ASIDE), {:.1} ms waited for at the lists' close",
  6800. h[0],
  6801. h[1],
  6802. h[2],
  6803. aside::WAITED.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames,
  6804. );
  6805. }
  6806. /// Whether a submission's refreshes of host copies run on several threads,
  6807. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6808. ///
  6809. /// A submission brings some sixty copies up to date, one after the other
  6810. /// on the submitting thread: for each, the pages the title wrote are asked
  6811. /// for and read through the kernel into the copy. That is the frame line's
  6812. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6813. /// another: each refresh writes its own copy and its own notes, and reads
  6814. /// title memory. With the switch the copies of a flush (four or more) are
  6815. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6816. /// The write-watch journal and the guards are behind their own locks, as
  6817. /// they are for the title's threads.
  6818. fn wide_refresh() -> bool {
  6819. static ON: OnceLock<bool> = OnceLock::new();
  6820. *ON.get_or_init(|| {
  6821. wide_refresh_enabled(
  6822. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6823. std::thread::available_parallelism().ok().map(|n| n.get()),
  6824. )
  6825. })
  6826. }
  6827. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6828. match setting {
  6829. Some("1") => true,
  6830. Some("0") => false,
  6831. _ => logical_cpus.is_some_and(|n| n >= 4),
  6832. }
  6833. }
  6834. #[cfg(test)]
  6835. mod wide_refresh_tests {
  6836. use super::wide_refresh_enabled;
  6837. #[test]
  6838. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6839. assert!(wide_refresh_enabled(None, Some(4)));
  6840. assert!(wide_refresh_enabled(None, Some(16)));
  6841. assert!(!wide_refresh_enabled(None, Some(2)));
  6842. assert!(!wide_refresh_enabled(None, None));
  6843. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6844. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6845. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6846. }
  6847. }
  6848. /// A submission's refreshes not done yet, merged per buffer copy into the
  6849. /// range that covers them: done before a step that writes title memory or
  6850. /// gives a range to shaders, and before the lists run.
  6851. ///
  6852. /// Also the textures brought up to date in the submission so far: most
  6853. /// lists of a world submission sample the same textures, and a texture in
  6854. /// physical-page memory is hashed whole each time it is checked. Checked
  6855. /// once, it is checked again only after a step that writes title memory.
  6856. #[derive(Default)]
  6857. struct Batch {
  6858. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6859. /// Where each copy (by address) is in `refreshes`: the list that makes
  6860. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6861. /// for every refresh of a submission was tens of millions of
  6862. /// comparisons a frame.
  6863. index: ByCopy<usize>,
  6864. /// Staging buffers (by address) refreshed since the last title write,
  6865. /// or due to be.
  6866. textures: std::collections::HashSet<usize>,
  6867. /// Those due ([`Batch::refresh_textures`]).
  6868. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6869. /// What copies at their place in the submission's lists put into title
  6870. /// memory ([`place`]): the host copy, the title address, the bytes.
  6871. placed: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, Vec<u8>)>,
  6872. /// Fills not done yet (destination, source, bytes): [`wide_fills`].
  6873. fills: Vec<(usize, usize, usize)>,
  6874. /// Copies (by address) brought up to date ahead of the steps, and the
  6875. /// range (from, to) ([`Batch::refresh_ahead`]).
  6876. ahead: ByCopy<(usize, usize)>,
  6877. }
  6878. /// Whether the copies that a submission's shaders write are brought up to
  6879. /// date together, on several threads, ahead of its steps
  6880. /// (`VICTORY_REFRESH_AHEAD=0`: each before the step that gives it to them).
  6881. ///
  6882. /// 580 copies a frame, one after the other on the submitting thread, 3.4 to
  6883. /// 6.5 ms (session play-1125-0203).
  6884. fn ahead_of_writes() -> bool {
  6885. static ON: OnceLock<bool> = OnceLock::new();
  6886. *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_AHEAD").is_none_or(|v| v != "0") && wide_refresh() && crate::watch::light())
  6887. }
  6888. /// What a step is to the copies' refreshes, for [`written_spans`].
  6889. enum Touch {
  6890. /// A refresh of a copy (by address), from, to.
  6891. Refresh(usize, usize, usize),
  6892. /// The copy is given to shaders.
  6893. Write(usize),
  6894. /// Title memory is written.
  6895. Title,
  6896. Nothing,
  6897. }
  6898. /// Of `steps`, up to the first that writes title memory: the copies given to
  6899. /// shaders, each with the range its refreshes before that cover.
  6900. fn written_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> {
  6901. // (From, to, given to shaders.)
  6902. let mut spans: ByCopy<(usize, usize, bool)> = ByCopy::default();
  6903. for step in steps {
  6904. match step {
  6905. Touch::Refresh(copy, from, to) => {
  6906. let span = spans.entry(copy).or_insert((from, to, false));
  6907. if !span.2 {
  6908. (span.0, span.1) = (span.0.min(from), span.1.max(to));
  6909. }
  6910. }
  6911. // (Not refreshed before: nothing of it is due.)
  6912. Touch::Write(copy) => {
  6913. if let Some(span) = spans.get_mut(&copy) {
  6914. span.2 = true;
  6915. }
  6916. }
  6917. Touch::Title => break,
  6918. Touch::Nothing => {}
  6919. }
  6920. }
  6921. spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect()
  6922. }
  6923. #[cfg(test)]
  6924. mod written_spans_tests {
  6925. use super::{Touch, written_spans};
  6926. #[test]
  6927. fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() {
  6928. use Touch::{Nothing, Refresh, Title, Write};
  6929. let mut found = written_spans(
  6930. [
  6931. Refresh(1, 10, 20),
  6932. Refresh(2, 0, 5),
  6933. Nothing,
  6934. Refresh(1, 30, 40),
  6935. Write(1),
  6936. Refresh(1, 0, 100),
  6937. Write(3),
  6938. Refresh(3, 1, 2),
  6939. Refresh(4, 7, 9),
  6940. Write(4),
  6941. Title,
  6942. Write(2),
  6943. ]
  6944. .into_iter(),
  6945. );
  6946. found.sort_unstable();
  6947. assert_eq!(found, [(1, 10, 40), (4, 7, 9)]);
  6948. }
  6949. }
  6950. /// Whether the fills of a submission's upload memory are done together on
  6951. /// several threads (`VICTORY_WIDE_FILLS=0`: one after the other, where the
  6952. /// lists name them).
  6953. ///
  6954. /// They are 7,000 to 12,000 a frame, some 500 bytes each, 5 ms of the
  6955. /// submitting thread. Each reads title memory and writes memory of its own
  6956. /// that the card alone reads, when the lists run; they are done before the
  6957. /// next step that writes title memory or runs code of ours, and before the
  6958. /// submission goes on from its steps.
  6959. fn wide_fills() -> bool {
  6960. static ON: OnceLock<bool> = OnceLock::new();
  6961. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_FILLS").is_none_or(|v| v != "0") && wide_refresh())
  6962. }
  6963. /// Whether a submission's textures are brought up to date on several
  6964. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6965. /// name them, as before).
  6966. ///
  6967. /// They are read, hashed and, if they changed, detiled into their staging
  6968. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6969. /// its own buffer, notes and lock, and is refreshed by the title's own
  6970. /// threads as it is. They are done before the next step that writes title
  6971. /// memory, as the copies' refreshes are, and before the lists go to the
  6972. /// card. What is new: the note of a list that its upload takes what the
  6973. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6974. /// an earlier list of the submission asked for, not behind it. The texture
  6975. /// is then uploaded by a later list too, once more than needed.
  6976. fn wide_textures() -> bool {
  6977. static ON: OnceLock<bool> = OnceLock::new();
  6978. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6979. }
  6980. impl Batch {
  6981. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6982. let end = address + len;
  6983. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6984. if self.ahead.get(&key).is_some_and(|&(from, to)| from <= address && end <= to) {
  6985. return;
  6986. }
  6987. match self.index.get(&key) {
  6988. Some(&at) => {
  6989. let r = &mut self.refreshes[at];
  6990. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6991. }
  6992. None => {
  6993. self.index.insert(key, self.refreshes.len());
  6994. self.refreshes.push((shadow.clone(), address, end));
  6995. }
  6996. }
  6997. }
  6998. /// Before shaders are given a range of `shadow`'s copy: its pending
  6999. /// refresh is done, the others stay pending.
  7000. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  7001. // From here on it is refreshed around what the shaders write.
  7002. self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize));
  7003. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  7004. return;
  7005. };
  7006. let (shadow, from, to) = self.refreshes.swap_remove(at);
  7007. // The last entry took its place.
  7008. if let Some(moved) = self.refreshes.get(at) {
  7009. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  7010. }
  7011. #[cfg(feature = "diagnostics")]
  7012. let started = std::time::Instant::now();
  7013. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  7014. Self::update(&shadow, from, to);
  7015. }
  7016. #[cfg(feature = "diagnostics")]
  7017. {
  7018. let ns = started.elapsed().as_nanos() as u64;
  7019. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  7020. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  7021. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  7022. }
  7023. }
  7024. /// Brings `[from, to)` of a copy up to date, timed.
  7025. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  7026. let started = std::time::Instant::now();
  7027. let _one = crate::timeline::span("a copy's refresh");
  7028. let copied = shadow.update(from, to - from);
  7029. let us = started.elapsed().as_micros() as u64;
  7030. #[cfg(feature = "diagnostics")]
  7031. crate::copystat::range(from, to - from, us, 0);
  7032. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  7033. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  7034. }
  7035. /// Whether `staging` is still to be refreshed in this submission (and
  7036. /// notes it refreshed).
  7037. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  7038. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  7039. }
  7040. /// Before a step that writes title memory: pending refreshes are done
  7041. /// first, and textures are checked again after it.
  7042. fn title_written(&mut self) {
  7043. self.flush();
  7044. self.ahead.clear();
  7045. self.textures.clear();
  7046. }
  7047. /// Before the steps of `runs` ([`ahead_of_writes`]); copies and fills
  7048. /// that `taken` names are not done on the CPU.
  7049. fn refresh_ahead(&mut self, runs: &[&HostList], taken: impl Fn(&HostList, usize) -> bool) {
  7050. let mut copies: ByCopy<std::sync::Arc<crate::shadow::Shadow>> = ByCopy::default();
  7051. let mut touches = Vec::new();
  7052. 'steps: for list in runs {
  7053. for (i, step) in list.deferred().copies.iter().enumerate() {
  7054. touches.push(match step {
  7055. Step::Refresh(shadow, at, len) => {
  7056. let key = std::sync::Arc::as_ptr(shadow) as usize;
  7057. copies.entry(key).or_insert_with(|| shadow.clone());
  7058. Touch::Refresh(key, *at, *at + *len)
  7059. }
  7060. Step::GpuWrite(shadow, ..) => Touch::Write(std::sync::Arc::as_ptr(shadow) as usize),
  7061. Step::Copy(..) if taken(list, i) => Touch::Nothing,
  7062. Step::Copy(..) | Step::Run(_) | Step::Placed(_) => break 'steps,
  7063. _ => Touch::Nothing,
  7064. });
  7065. }
  7066. }
  7067. let due: Vec<_> = written_spans(touches.into_iter())
  7068. .into_iter()
  7069. .filter_map(|(key, from, to)| Some((copies.get(&key)?.clone(), from, to)))
  7070. .collect();
  7071. for (shadow, from, to) in &due {
  7072. self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to));
  7073. }
  7074. #[cfg(feature = "diagnostics")]
  7075. let began = std::time::Instant::now();
  7076. let started = std::time::Instant::now();
  7077. let before = PREPARING[0].load(Ordering::Relaxed);
  7078. crate::shadow::wide_each(due.len(), move |i| {
  7079. let (shadow, from, to) = &due[i];
  7080. if !shadow.nothing_new(*from, *to - *from) {
  7081. Self::update(shadow, *from, *to);
  7082. }
  7083. });
  7084. // The time counted is the time it took, not the threads' sum.
  7085. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  7086. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  7087. #[cfg(feature = "diagnostics")]
  7088. {
  7089. let ns = began.elapsed().as_nanos() as u64;
  7090. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  7091. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  7092. }
  7093. }
  7094. /// The fills noted are done.
  7095. fn fill(&mut self) {
  7096. // Below this many the threads cost more than they save.
  7097. const FEW: usize = 96;
  7098. const PART: usize = 64;
  7099. if self.fills.is_empty() {
  7100. return;
  7101. }
  7102. let started = std::time::Instant::now();
  7103. if self.fills.len() < FEW {
  7104. for (dst, src, len) in self.fills.drain(..) {
  7105. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  7106. }
  7107. } else {
  7108. let fills = std::mem::take(&mut self.fills);
  7109. crate::shadow::wide_each(fills.len().div_ceil(PART), move |i| {
  7110. for &(dst, src, len) in fills.iter().skip(i * PART).take(PART) {
  7111. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  7112. }
  7113. });
  7114. }
  7115. let took = started.elapsed();
  7116. PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed);
  7117. #[cfg(feature = "diagnostics")]
  7118. SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed);
  7119. }
  7120. /// The textures due are brought up to date.
  7121. fn refresh_textures(&mut self) {
  7122. if self.due.len() < 2 || !wide_textures() {
  7123. self.due.drain(..).for_each(|staging| staging.refresh());
  7124. return;
  7125. }
  7126. let _textures = crate::timeline::span("textures brought up to date");
  7127. // The time counted is the time it took, not the threads' sum.
  7128. let started = std::time::Instant::now();
  7129. let before = PREPARING[2].load(Ordering::Relaxed);
  7130. let due = std::mem::take(&mut self.due);
  7131. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  7132. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  7133. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  7134. }
  7135. fn flush(&mut self) {
  7136. self.refresh_textures();
  7137. self.index.clear();
  7138. if self.refreshes.is_empty() {
  7139. return;
  7140. }
  7141. #[cfg(feature = "diagnostics")]
  7142. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  7143. let _flush = crate::timeline::span("refreshes of copies");
  7144. self.flush_all();
  7145. #[cfg(feature = "diagnostics")]
  7146. {
  7147. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  7148. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  7149. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  7150. }
  7151. }
  7152. fn flush_all(&mut self) {
  7153. // Most of a flush's copies are as they were: they are told so here,
  7154. // from what the submission's asking found, before anything is asked
  7155. // and any thread woken. (Thousands of them, the heap's buffer views
  7156. // once a frame: on the threads, below.)
  7157. const FEW: usize = 256;
  7158. let light = crate::watch::light();
  7159. if light && self.refreshes.len() <= FEW {
  7160. let started = std::time::Instant::now();
  7161. #[cfg(feature = "diagnostics")]
  7162. let all = self.refreshes.len();
  7163. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  7164. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  7165. #[cfg(feature = "diagnostics")]
  7166. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  7167. }
  7168. // One write-watch asking for the copies that lie close together,
  7169. // not one per copy.
  7170. let ahead = self.refreshes.len() > 1;
  7171. if ahead {
  7172. let started = std::time::Instant::now();
  7173. let ranges: Vec<(usize, usize)> = self
  7174. .refreshes
  7175. .iter()
  7176. .filter(|r| r.0.asked_ahead())
  7177. .map(|r| (r.1, r.2))
  7178. .collect();
  7179. crate::watch::ask_ahead(&ranges);
  7180. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  7181. }
  7182. if wide_refresh() && self.refreshes.len() >= 4 {
  7183. // Each copy on its own, several at a time: a copy's refresh
  7184. // writes that copy and reads title memory, nothing of another's.
  7185. // The time counted is the time it took, not the threads' sum.
  7186. let started = std::time::Instant::now();
  7187. let before = PREPARING[0].load(Ordering::Relaxed);
  7188. #[cfg(feature = "diagnostics")]
  7189. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  7190. if light {
  7191. // A number to a free thread, not a job to each copy.
  7192. let refreshes = std::mem::take(&mut self.refreshes);
  7193. crate::shadow::wide_each(refreshes.len(), move |i| {
  7194. let (shadow, from, to) = &refreshes[i];
  7195. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  7196. #[cfg(feature = "diagnostics")]
  7197. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  7198. return;
  7199. }
  7200. Self::update(shadow, *from, *to);
  7201. });
  7202. } else {
  7203. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  7204. .refreshes
  7205. .drain(..)
  7206. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  7207. .collect();
  7208. crate::shadow::wide_run(jobs);
  7209. }
  7210. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  7211. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  7212. } else {
  7213. for (shadow, from, to) in self.refreshes.drain(..) {
  7214. Self::update(&shadow, from, to);
  7215. }
  7216. }
  7217. if ahead {
  7218. crate::watch::ask_ahead_done();
  7219. }
  7220. }
  7221. }
  7222. /// Copies title memory at submission. The ranges were checked against their
  7223. /// resources when recorded, but the title may since have unmapped pages of
  7224. /// them (tiled memory, page mappings), which read as zeros here; a title
  7225. /// destination (`title_dst`) that is not all mapped is left alone.
  7226. ///
  7227. /// The source is read through the kernel (`ReadProcessMemory`), which
  7228. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  7229. /// cost about 2 ms per copy in the title's big pools (it walks the page
  7230. /// tables to the region's end), which made copies run at 100-200 MB/s.
  7231. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  7232. #[cfg(feature = "diagnostics")]
  7233. match crate::copystat::mode() {
  7234. 1 => {
  7235. // SAFETY: timing only: the caller vouches for the source.
  7236. unsafe { std::ptr::copy(src, dst, len) };
  7237. return;
  7238. }
  7239. 2 => return,
  7240. _ => {}
  7241. }
  7242. if len == 0 {
  7243. return;
  7244. }
  7245. // A title destination that is not all mapped is left alone. Asking
  7246. // Windows first (`VirtualQuery`) walks the page tables to the end of
  7247. // the destination's region: in the title's big blocks that is
  7248. // milliseconds a copy, and it was a seventh of the submitting thread's
  7249. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  7250. // says the same when it fails, so the question is only asked then.
  7251. // `VICTORY_COPY_ASK=1` asks first, as before.
  7252. static ASK: OnceLock<bool> = OnceLock::new();
  7253. let ask_first = title_dst
  7254. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  7255. if ask_first && !crate::texture::committed(dst, len) {
  7256. return;
  7257. }
  7258. if title_dst {
  7259. // The kernel writes the destination: it must not be guarded.
  7260. crate::watch::writing(dst as usize, len);
  7261. }
  7262. #[cfg(feature = "diagnostics")]
  7263. let moved = std::time::Instant::now();
  7264. let since = crate::watch::changes();
  7265. // (A title destination that is away only while the runtime changes a
  7266. // mapping beside it is written when that is done.)
  7267. let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
  7268. #[cfg(feature = "diagnostics")]
  7269. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  7270. if whole {
  7271. return;
  7272. }
  7273. // The copy failed: a source page is not there, or the destination is
  7274. // not all mapped. Then the destination stays as it is (the kernel may
  7275. // have written its first pages).
  7276. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  7277. crate::watch::lost("a copy of the title's", dst as usize, len);
  7278. return;
  7279. }
  7280. #[cfg(feature = "diagnostics")]
  7281. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  7282. #[cfg(feature = "diagnostics")]
  7283. let sparse = std::time::Instant::now();
  7284. if !title_dst && len >= 64 << 10 {
  7285. read_sparse(src, dst, len);
  7286. } else {
  7287. read_pieces(src, dst, len);
  7288. }
  7289. #[cfg(feature = "diagnostics")]
  7290. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  7291. }
  7292. /// After a failed bulk read into host memory, skip contiguous holes. Never
  7293. /// cache the query across copies: the title may remap the same address.
  7294. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  7295. use windows_sys::Win32::System::Memory::{
  7296. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  7297. };
  7298. let mut offset = 0;
  7299. while offset < len {
  7300. let at = src.wrapping_add(offset);
  7301. let to = dst.wrapping_add(offset);
  7302. let remaining = len - offset;
  7303. // SAFETY: the query inspects an address and fills a local structure.
  7304. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  7305. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  7306. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  7307. .saturating_sub(at as usize).min(remaining);
  7308. if size != size_of_val(&info) || n == 0 {
  7309. read_pieces(at, to, remaining);
  7310. break;
  7311. }
  7312. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  7313. #[cfg(feature = "diagnostics")]
  7314. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  7315. // SAFETY: this path is only used with a writable host destination.
  7316. unsafe { to.write_bytes(0, n) };
  7317. } else if !read(at, to, n) {
  7318. // A mapping may change between query and read.
  7319. read_pieces(at, to, n);
  7320. }
  7321. offset += n;
  7322. }
  7323. }
  7324. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  7325. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  7326. // that fails), zeros for what cannot be read.
  7327. for_pieces(src as usize, len, 64 << 10, |at, n| {
  7328. let to = dst.wrapping_add(at - src as usize);
  7329. if !read(at as *const u8, to, n) {
  7330. for_pieces(at, n, 4 << 10, |at, n| {
  7331. let to = dst.wrapping_add(at - src as usize);
  7332. if !read(at as *const u8, to, n) {
  7333. #[cfg(feature = "diagnostics")]
  7334. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  7335. zero(to, n);
  7336. }
  7337. });
  7338. }
  7339. });
  7340. }
  7341. /// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
  7342. /// destination of a title's copy), which can go between the question whether
  7343. /// it is there and this.
  7344. fn zero(to: *mut u8, n: usize) {
  7345. static ZEROS: [u8; 4096] = [0; 4096];
  7346. if n <= ZEROS.len() && crate::safecopy::on() {
  7347. // SAFETY: a destination that is not there fails the copy.
  7348. if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
  7349. crate::watch::lost("zeros", to as usize, n);
  7350. }
  7351. return;
  7352. }
  7353. // SAFETY: inside the destination, which is mapped.
  7354. unsafe { to.write_bytes(0, n) };
  7355. }
  7356. /// Reads title memory at `src` into `dst`; false if a page of it is not
  7357. /// readable.
  7358. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  7359. read(src, dst.as_mut_ptr(), dst.len())
  7360. }
  7361. /// Reads what is there of the `dst.len()` bytes of title memory at `src`,
  7362. /// zeros for the rest; returns how many bytes were there. Safe while the
  7363. /// runtime remaps title memory (the kernel, or a copy that takes the fault,
  7364. /// reads). What the runtime's record says is mapped is read in one go each,
  7365. /// and by pieces where that fails; memory it has no record of by pieces.
  7366. pub(crate) fn read_there(src: *const u8, dst: &mut [u8]) -> usize {
  7367. dst.fill(0);
  7368. let (start, len) = (src as usize, dst.len());
  7369. let mut got = 0;
  7370. let mut runs = crate::inplace::shown_runs(start, len);
  7371. if runs.is_empty() {
  7372. runs.push((start, len));
  7373. }
  7374. for (at, n) in runs {
  7375. let piece = &mut dst[at - start..at - start + n];
  7376. if read_into(at as *const u8, piece) {
  7377. got += n;
  7378. continue;
  7379. }
  7380. // (What failed may have written its first pages.)
  7381. piece.fill(0);
  7382. for_pieces(at, n, 64 << 10, |from, n| {
  7383. let piece = &mut dst[from - start..from - start + n];
  7384. if read_into(from as *const u8, piece) {
  7385. got += n;
  7386. return;
  7387. }
  7388. piece.fill(0);
  7389. for_pieces(from, n, 4 << 10, |from, n| {
  7390. let piece = &mut dst[from - start..from - start + n];
  7391. if read_into(from as *const u8, piece) {
  7392. got += n;
  7393. } else {
  7394. piece.fill(0);
  7395. }
  7396. });
  7397. });
  7398. }
  7399. got
  7400. }
  7401. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  7402. /// readable.
  7403. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  7404. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  7405. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7406. if crate::safecopy::on() {
  7407. // SAFETY: the destination is mapped writable memory of `len` bytes;
  7408. // a source page that is not there fails the copy.
  7409. return unsafe { crate::safecopy::copy(dst, src, len) };
  7410. }
  7411. let mut done = 0;
  7412. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  7413. // kernel checks the source.
  7414. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  7415. }
  7416. #[link(name = "ntdll", kind = "raw-dylib")]
  7417. unsafe extern "system" {
  7418. /// The kernel's write into a process's memory, `(process, address,
  7419. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  7420. /// the range is not there or not writable. It changes no protection.
  7421. fn NtWriteVirtualMemory(
  7422. process: *mut std::ffi::c_void,
  7423. base: *mut std::ffi::c_void,
  7424. buffer: *const std::ffi::c_void,
  7425. size: usize,
  7426. written: *mut usize,
  7427. ) -> i32;
  7428. }
  7429. /// Whether title memory is written with the kernel's own call
  7430. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  7431. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  7432. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  7433. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  7434. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  7435. fn direct_writes() -> bool {
  7436. static ON: OnceLock<bool> = OnceLock::new();
  7437. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  7438. }
  7439. /// Copies host memory into title memory after a submission (what shaders
  7440. /// wrote), leaving pages that are not mapped alone.
  7441. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  7442. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  7443. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7444. let direct = direct_writes();
  7445. let since = crate::watch::changes();
  7446. let write = |at: usize, n: usize| {
  7447. let from = src.wrapping_add(at - dst as usize);
  7448. if crate::safecopy::on() {
  7449. // SAFETY: the source is ours; a destination page that is not
  7450. // there, or not writable, fails the copy.
  7451. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  7452. }
  7453. let mut done = 0;
  7454. if direct {
  7455. // SAFETY: as below; the kernel checks the destination and
  7456. // writes nothing it cannot (the caller opened its guards:
  7457. // `crate::watch::writing`).
  7458. return unsafe {
  7459. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  7460. };
  7461. }
  7462. // SAFETY: the source is our mapped host copy; the kernel checks the
  7463. // destination.
  7464. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  7465. };
  7466. if len == 0 || write(dst as usize, len) {
  7467. return;
  7468. }
  7469. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  7470. if !write(at, n) {
  7471. for_pieces(at, n, 4 << 10, |at, n| {
  7472. if write(at, n) {
  7473. return;
  7474. }
  7475. // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
  7476. // refresh guarded the block again since the caller opened
  7477. // it; and any where the runtime was changing a mapping.
  7478. crate::watch::writing(at, n);
  7479. if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
  7480. crate::watch::lost("a host copy's bytes", at, n);
  7481. }
  7482. });
  7483. }
  7484. });
  7485. }
  7486. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  7487. /// `step`.
  7488. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  7489. let end = start + len;
  7490. let mut at = start;
  7491. while at < end {
  7492. let next = ((at / step + 1) * step).min(end);
  7493. f(at, next - at);
  7494. at = next;
  7495. }
  7496. }
  7497. impl Host {
  7498. /// The queue everything of ours runs on, for a call that must go to it
  7499. /// in order with the lists (`crate::tiles`: a texture's levels are
  7500. /// given memory ahead of the list that uploads them).
  7501. pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
  7502. &self.queue
  7503. }
  7504. /// A buffer in the upload heap, mapped for writing.
  7505. /// A buffer of `size` bytes the card writes and we read (a read back),
  7506. /// in the state copies into it need.
  7507. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7508. let heap = D3D12_HEAP_PROPERTIES {
  7509. Type: D3D12_HEAP_TYPE_READBACK,
  7510. ..Default::default()
  7511. };
  7512. let desc = D3D12_RESOURCE_DESC {
  7513. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7514. Width: size.max(1),
  7515. Height: 1,
  7516. DepthOrArraySize: 1,
  7517. MipLevels: 1,
  7518. SampleDesc: DXGI_SAMPLE_DESC {
  7519. Count: 1,
  7520. Quality: 0,
  7521. },
  7522. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7523. ..Default::default()
  7524. };
  7525. let mut buffer: Option<ID3D12Resource> = None;
  7526. // SAFETY: plain creation of a read-back buffer.
  7527. let made = unsafe {
  7528. self.device.CreateCommittedResource(
  7529. &heap,
  7530. D3D12_HEAP_FLAG_NONE,
  7531. &desc,
  7532. D3D12_RESOURCE_STATE_COPY_DEST,
  7533. None,
  7534. &mut buffer,
  7535. )
  7536. };
  7537. match made {
  7538. Ok(()) => buffer,
  7539. Err(e) => {
  7540. tracing::warn!(error = %e, size, "no read-back buffer");
  7541. None
  7542. }
  7543. }
  7544. }
  7545. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7546. MADE[0].fetch_add(1, Ordering::Relaxed);
  7547. MADE[1].fetch_add(size, Ordering::Relaxed);
  7548. let heap = D3D12_HEAP_PROPERTIES {
  7549. Type: D3D12_HEAP_TYPE_UPLOAD,
  7550. ..Default::default()
  7551. };
  7552. let desc = D3D12_RESOURCE_DESC {
  7553. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7554. Width: size.max(1),
  7555. Height: 1,
  7556. DepthOrArraySize: 1,
  7557. MipLevels: 1,
  7558. SampleDesc: DXGI_SAMPLE_DESC {
  7559. Count: 1,
  7560. Quality: 0,
  7561. },
  7562. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7563. ..Default::default()
  7564. };
  7565. let mut buffer: Option<ID3D12Resource> = None;
  7566. let mut data = std::ptr::null_mut();
  7567. // SAFETY: plain creation and mapping of an upload buffer.
  7568. let made = unsafe {
  7569. self.device
  7570. .CreateCommittedResource(
  7571. &heap,
  7572. not_resident(),
  7573. &desc,
  7574. D3D12_RESOURCE_STATE_GENERIC_READ,
  7575. None,
  7576. &mut buffer,
  7577. )
  7578. .and_then(|()| {
  7579. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7580. resident(&self.device, b)?;
  7581. b.Map(0, None, Some(&mut data))
  7582. })
  7583. };
  7584. #[cfg(feature = "diagnostics")]
  7585. if made.is_ok()
  7586. && let Some(b) = &buffer
  7587. {
  7588. crate::book::made(b, || "an upload buffer".into());
  7589. }
  7590. match made {
  7591. Ok(()) => Some((buffer?, data.cast())),
  7592. Err(e) => {
  7593. tracing::warn!(error = %e, size, "no upload buffer");
  7594. None
  7595. }
  7596. }
  7597. }
  7598. }
  7599. /// The swap chain formats a presented texture can be copied into: its own
  7600. /// family's.
  7601. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  7602. Some(match format.0 {
  7603. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  7604. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  7605. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  7606. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  7607. _ => return None,
  7608. })
  7609. }
  7610. const BUFFERS: u32 = 2;
  7611. struct Presenter {
  7612. swap_chain: IDXGISwapChain3,
  7613. width: u32,
  7614. height: u32,
  7615. format: DXGI_FORMAT,
  7616. copy: HostList,
  7617. /// With presents sent ahead ([`late_free_present`]): a list for each
  7618. /// present in the air, and the submission it last flew as (it is used
  7619. /// again once that one has finished).
  7620. ahead: Vec<(HostList, u64)>,
  7621. hwnd: HWND,
  7622. meter: Meter,
  7623. }
  7624. /// The frame rate, shown in the window's caption every second and logged
  7625. /// every few seconds.
  7626. struct Meter {
  7627. since: std::time::Instant,
  7628. frames: u32,
  7629. #[cfg(feature = "diagnostics")]
  7630. copy_stats_frames: u64,
  7631. drawn: u64,
  7632. logged: std::time::Instant,
  7633. /// The caption the window had, once read.
  7634. caption: Option<Vec<u16>>,
  7635. }
  7636. impl Meter {
  7637. fn new() -> Self {
  7638. let now = std::time::Instant::now();
  7639. Meter {
  7640. since: now,
  7641. frames: 0,
  7642. #[cfg(feature = "diagnostics")]
  7643. copy_stats_frames: 0,
  7644. drawn: crate::draw::drawn(),
  7645. logged: now,
  7646. caption: None,
  7647. }
  7648. }
  7649. /// Counts a presented frame.
  7650. fn frame(&mut self, hwnd: HWND) {
  7651. #[cfg(feature = "diagnostics")]
  7652. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  7653. #[cfg(feature = "diagnostics")]
  7654. crate::copystat::presented();
  7655. self.frames += 1;
  7656. #[cfg(feature = "diagnostics")]
  7657. {
  7658. self.copy_stats_frames += 1;
  7659. }
  7660. let elapsed = self.since.elapsed();
  7661. if elapsed < std::time::Duration::from_secs(1) {
  7662. return;
  7663. }
  7664. let drawn = crate::draw::drawn();
  7665. let frames = f64::from(self.frames);
  7666. let fps = frames / elapsed.as_secs_f64();
  7667. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  7668. let draws = (drawn - self.drawn) as f64 / frames;
  7669. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  7670. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  7671. let [cpu, gpu] = [0, 1].map(|i| {
  7672. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  7673. });
  7674. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  7675. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  7676. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  7677. });
  7678. let [back_ms, back_mb] = [0, 1].map(|i| {
  7679. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  7680. });
  7681. let dropped = crate::draw::take_dropped() as f64 / frames;
  7682. let indirect = crate::list::take_indirect() as f64 / frames;
  7683. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  7684. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  7685. tracing::info!(
  7686. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  7687. );
  7688. crate::shadow::exact_line(frames);
  7689. crate::descriptor::sync_line(frames);
  7690. late_line(frames);
  7691. crate::queue::behind_line(frames);
  7692. card_clock_line(frames, ms);
  7693. #[cfg(feature = "diagnostics")]
  7694. spans::line(frames);
  7695. crate::shadow::back_line(frames);
  7696. #[cfg(feature = "diagnostics")]
  7697. split_line(frames);
  7698. {
  7699. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7700. if passes + compares > 0.0 {
  7701. tracing::info!(
  7702. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  7703. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  7704. if rehash_runs() { "on" } else { "off" }
  7705. );
  7706. }
  7707. }
  7708. {
  7709. let [own, asking, still, all] =
  7710. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  7711. if all >= 1.0 {
  7712. tracing::info!(
  7713. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  7714. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  7715. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  7716. );
  7717. }
  7718. let [through, left, filled, short] =
  7719. [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7720. if through + left + filled > 0.0 {
  7721. tracing::info!(
  7722. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  7723. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \
  7724. {filled:.1} first fillings from the pages there (VICTORY_TEXTURE_FILL=0: left empty), {short:.1} of them \
  7725. with less than was mapped (looked at again)"
  7726. );
  7727. }
  7728. }
  7729. {
  7730. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7731. if copies > 0.0 {
  7732. tracing::info!(
  7733. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  7734. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  7735. if join_copies() { "on" } else { "off" }
  7736. );
  7737. }
  7738. }
  7739. // Passes over the heap's buffer views for shaders that pick them by index.
  7740. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  7741. let picked_ms =
  7742. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  7743. // Copies between depth textures and their colour twins, each way.
  7744. let [twin_to_depth, twin_to_colour] =
  7745. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7746. // Depth planes drawn from their twins.
  7747. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  7748. // Copies in the card's memory (`crate::shadow::cards`).
  7749. let card = crate::shadow::card_stats();
  7750. #[cfg(feature = "diagnostics")]
  7751. let slow = crate::watch::slow_asks();
  7752. // Over the same frames as the counts above.
  7753. #[cfg(feature = "diagnostics")]
  7754. let drops = crate::pipeline::take_drops();
  7755. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  7756. self.logged = std::time::Instant::now();
  7757. tracing::info!(
  7758. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  7759. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  7760. );
  7761. crate::tiles::status();
  7762. {
  7763. let [queued, due, away, partly, oldest] =
  7764. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  7765. let [same, parts, tails] =
  7766. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  7767. tracing::info!(
  7768. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  7769. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  7770. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  7771. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  7772. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  7773. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  7774. {} made slots found unmapped and made null",
  7775. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  7776. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  7777. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  7778. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  7779. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  7780. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  7781. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  7782. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  7783. );
  7784. }
  7785. if crate::resource::held_only() {
  7786. let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed));
  7787. let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed));
  7788. tracing::info!(
  7789. "textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \
  7790. levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \
  7791. {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \
  7792. out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free; \
  7793. {} looks for textures to let go, {:.2} ms each, the longest {:.1}",
  7794. bytes >> 20,
  7795. whole >> 20,
  7796. crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed),
  7797. crate::pool::texture_room() >> 20,
  7798. crate::resource::SWEPT_US[0].load(Ordering::Relaxed),
  7799. crate::resource::SWEPT_US[1].load(Ordering::Relaxed) as f64
  7800. / 1e3
  7801. / crate::resource::SWEPT_US[0].load(Ordering::Relaxed).max(1) as f64,
  7802. crate::resource::SWEPT_US[2].load(Ordering::Relaxed) as f64 / 1e3
  7803. );
  7804. }
  7805. {
  7806. let mode = crate::watch::page_writes();
  7807. let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
  7808. let [kept, dropped, slots, uploaded] =
  7809. [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
  7810. tracing::info!(
  7811. "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset or guards opens the guarded blocks, 0 counts only, 1, slots, all)",
  7812. bytes >> 20,
  7813. if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
  7814. if mode & 4 != 0 { "told as well" } else { "counted only" },
  7815. if mode & 2 != 0 { "made due again" } else { "left as they were" }
  7816. );
  7817. }
  7818. #[cfg(feature = "diagnostics")]
  7819. tracing::info!(
  7820. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  7821. slow[0] as f64 / frames,
  7822. slow[1] as f64 / 1e3 / frames,
  7823. slow[2] as f64 / 1e3
  7824. );
  7825. if crate::shadow::cards() {
  7826. let per_frame = |i: usize| card[i] as f64 / frames;
  7827. tracing::info!(
  7828. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  7829. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  7830. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  7831. card[7],
  7832. card[8] >> 20,
  7833. card[9] >> 20,
  7834. per_frame(0) / 1e6,
  7835. per_frame(1),
  7836. per_frame(2),
  7837. per_frame(3),
  7838. per_frame(4) / 1e6,
  7839. per_frame(5),
  7840. per_frame(6) / 1e3
  7841. );
  7842. }
  7843. tracing::info!(
  7844. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  7845. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  7846. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  7847. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  7848. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  7849. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  7850. {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}",
  7851. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  7852. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  7853. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  7854. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  7855. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  7856. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  7857. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  7858. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  7859. refused = format!(
  7860. "{} ({} copies made of views off their buffer's elements); depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass",
  7861. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  7862. crate::shadow::OWN_MADE.load(Ordering::Relaxed),
  7863. crate::resource::TWINS[0].load(Ordering::Relaxed),
  7864. crate::resource::TWINS[1].load(Ordering::Relaxed),
  7865. crate::resource::PLANES[1].load(Ordering::Relaxed),
  7866. crate::resource::PLANES[2].load(Ordering::Relaxed)
  7867. ),
  7868. making = crate::pipeline::making(),
  7869. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  7870. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  7871. );
  7872. #[cfg(feature = "diagnostics")]
  7873. {
  7874. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7875. tracing::info!(
  7876. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  7877. put[0],
  7878. put[1],
  7879. put[2] / 1e6,
  7880. put[3]
  7881. );
  7882. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  7883. for (why, n) in drops.iter().take(40) {
  7884. tracing::info!(
  7885. "dropped {:.1}/frame without a host pipeline: {why}",
  7886. *n as f64 / frames
  7887. );
  7888. }
  7889. }
  7890. }
  7891. if self.caption.is_none() {
  7892. // The window's own text, read without a message.
  7893. let mut buffer = vec![0u16; 512];
  7894. // SAFETY: a window handle and a buffer of that length.
  7895. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  7896. buffer.truncate(n.max(0) as usize);
  7897. self.caption = Some(buffer);
  7898. }
  7899. let Some(caption) = &self.caption else { return };
  7900. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  7901. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  7902. text.push(0);
  7903. // Setting the text waits for the window's thread (a title thread,
  7904. // which may not pump for a while), so a thread of ours does it and
  7905. // presenting never waits; it takes the newest text when free.
  7906. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  7907. static SETTER: std::sync::Once = std::sync::Once::new();
  7908. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  7909. SETTER.call_once(|| {
  7910. let _ = std::thread::Builder::new()
  7911. .name("victory-caption".into())
  7912. .spawn(|| {
  7913. loop {
  7914. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  7915. match next {
  7916. // SAFETY: a window handle and a NUL-terminated text.
  7917. Some((hwnd, text)) => unsafe {
  7918. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  7919. },
  7920. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  7921. }
  7922. }
  7923. });
  7924. });
  7925. }
  7926. }
  7927. impl Host {
  7928. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  7929. /// as frame `frame` (saved if captures are on). `None` if nothing was
  7930. /// shown; else, in diagnostics builds, whether the frame was black.
  7931. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  7932. // SAFETY: a live resource.
  7933. let desc = unsafe { texture.GetDesc() };
  7934. let Some(format) = swap_format(desc.Format) else {
  7935. tracing::warn!(format = desc.Format.0, "cannot present this format");
  7936. return None;
  7937. };
  7938. let (width, height) = (desc.Width as u32, desc.Height);
  7939. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  7940. if presenter.is_none() {
  7941. *presenter = match self.presenter(width, height, format) {
  7942. Ok(p) => Some(p),
  7943. Err(e) => {
  7944. tracing::warn!(error = %e, "no swap chain");
  7945. return None;
  7946. }
  7947. };
  7948. }
  7949. let p = presenter.as_mut()?;
  7950. if (p.width, p.height, p.format) != (width, height, format) {
  7951. // Presents sent ahead hold back buffers until they have run.
  7952. settle_now(WHY_SYNC);
  7953. // SAFETY: no back buffer is held; every submission was waited for.
  7954. let resized = unsafe {
  7955. p.swap_chain
  7956. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  7957. };
  7958. match resized {
  7959. Ok(()) => {
  7960. (p.width, p.height, p.format) = (width, height, format);
  7961. tracing::info!(
  7962. width,
  7963. height,
  7964. format = format.0,
  7965. frame,
  7966. "the swap chain's buffers were made again for another size or format"
  7967. );
  7968. self.log_video_memory("right after the swap chain's buffers were made again");
  7969. }
  7970. Err(e) => {
  7971. tracing::warn!(error = %e, width, height, "swap chain not resized");
  7972. return None;
  7973. }
  7974. }
  7975. }
  7976. let state = D3D12_RESOURCE_STATES(state as i32);
  7977. // SAFETY: our swap chain, list and a live source texture.
  7978. unsafe {
  7979. let index = p.swap_chain.GetCurrentBackBufferIndex();
  7980. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  7981. return None;
  7982. };
  7983. // Sent ahead ([`late_free_present`]) unless the frame is to be
  7984. // read back at once (a saved or listed frame): then a list of
  7985. // its own, one whose last flight has finished or a new one.
  7986. #[cfg(feature = "diagnostics")]
  7987. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  7988. #[cfg(not(feature = "diagnostics"))]
  7989. let read_now = false;
  7990. let slot = if late_free_present() && !read_now {
  7991. let finished = FINISHED.load(Ordering::Acquire);
  7992. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  7993. let list = self.new_list().ok()?;
  7994. list.close();
  7995. p.ahead.push((list, 0));
  7996. Some(p.ahead.len() - 1)
  7997. })
  7998. } else {
  7999. None
  8000. };
  8001. let copy = match slot {
  8002. Some(i) => &p.ahead[i].0,
  8003. None => &p.copy,
  8004. };
  8005. copy.reset();
  8006. let list = &copy.list;
  8007. list.ResourceBarrier(&[
  8008. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  8009. transition(
  8010. &back,
  8011. D3D12_RESOURCE_STATE_PRESENT,
  8012. D3D12_RESOURCE_STATE_COPY_DEST,
  8013. ),
  8014. ]);
  8015. list.CopyResource(&back, texture);
  8016. #[cfg(feature = "diagnostics")]
  8017. let capture = crate::capture::wanted(frame)
  8018. .then(|| crate::capture::read_back(&self.device, list, texture))
  8019. .flatten();
  8020. #[cfg(feature = "diagnostics")]
  8021. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  8022. #[cfg(not(feature = "diagnostics"))]
  8023. let _ = frame;
  8024. list.ResourceBarrier(&[
  8025. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  8026. transition(
  8027. &back,
  8028. D3D12_RESOURCE_STATE_COPY_DEST,
  8029. D3D12_RESOURCE_STATE_PRESENT,
  8030. ),
  8031. ]);
  8032. copy.close();
  8033. match slot {
  8034. Some(i) => {
  8035. let flown = self.execute_own(copy);
  8036. p.ahead[i].1 = flown;
  8037. }
  8038. None => self.execute(&[copy]),
  8039. }
  8040. #[cfg(feature = "diagnostics")]
  8041. if let Some((buffer, footprint)) = capture {
  8042. crate::capture::save_read_back(frame, &buffer, &footprint);
  8043. }
  8044. #[cfg(feature = "diagnostics")]
  8045. crate::replay::record::present(texture, state);
  8046. let mut showing = crate::timeline::span("the host's Present");
  8047. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  8048. showing.next("the frame meter");
  8049. p.meter.frame(p.hwnd);
  8050. showing.end();
  8051. #[cfg(feature = "diagnostics")]
  8052. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  8053. #[cfg(not(feature = "diagnostics"))]
  8054. Some(false)
  8055. }
  8056. }
  8057. fn presenter(
  8058. &self,
  8059. width: u32,
  8060. height: u32,
  8061. format: DXGI_FORMAT,
  8062. ) -> windows::core::Result<Presenter> {
  8063. let hwnd = match title_window() {
  8064. Some(hwnd) => hwnd,
  8065. None => window(width, height)?,
  8066. };
  8067. self.log_video_memory("right before the swap chain is made");
  8068. // SAFETY: plain object creation for our window.
  8069. unsafe {
  8070. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  8071. let desc = DXGI_SWAP_CHAIN_DESC1 {
  8072. Width: width,
  8073. Height: height,
  8074. Format: format,
  8075. SampleDesc: DXGI_SAMPLE_DESC {
  8076. Count: 1,
  8077. Quality: 0,
  8078. },
  8079. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  8080. BufferCount: BUFFERS,
  8081. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  8082. ..Default::default()
  8083. };
  8084. let swap_chain = factory
  8085. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  8086. .cast::<IDXGISwapChain3>()?;
  8087. let copy = self.new_list()?;
  8088. copy.close();
  8089. tracing::info!(width, height, format = format.0, "presenting to a window");
  8090. self.log_video_memory("right after the swap chain is made");
  8091. Ok(Presenter {
  8092. swap_chain,
  8093. width,
  8094. height,
  8095. format,
  8096. copy,
  8097. ahead: Vec::new(),
  8098. hwnd,
  8099. meter: Meter::new(),
  8100. })
  8101. }
  8102. }
  8103. }
  8104. /// A visible top-level window of this process: the one the title made, if
  8105. /// it made one.
  8106. fn title_window() -> Option<HWND> {
  8107. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  8108. let mut process = 0;
  8109. // SAFETY: a window handle from the enumeration; `found` is ours.
  8110. unsafe {
  8111. GetWindowThreadProcessId(hwnd, Some(&mut process));
  8112. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  8113. && IsWindowVisible(hwnd).as_bool()
  8114. {
  8115. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  8116. return false.into();
  8117. }
  8118. }
  8119. true.into()
  8120. }
  8121. let mut found: Option<HWND> = None;
  8122. // SAFETY: the callback only writes `found`, which outlives the call.
  8123. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  8124. found
  8125. }
  8126. /// `state` without the bits the host texture's flags forbid: the console
  8127. /// lets the title name states its own resources allow (unordered access on
  8128. /// a depth target, whose host copy cannot have both).
  8129. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  8130. // SAFETY: a plain query.
  8131. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  8132. }
  8133. /// [`legal_state`] for a texture with resource flags `flags`.
  8134. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  8135. // (flag, set or clear forbids, state bits): render target, unordered
  8136. // access, depth, denied shader resource.
  8137. const FORBIDDEN: [(u32, bool, u32); 4] = [
  8138. (0x1, false, 0x4),
  8139. (0x4, false, 0x8),
  8140. (0x2, false, 0x10 | 0x20),
  8141. (0x8, true, 0x40 | 0x80),
  8142. ];
  8143. FORBIDDEN
  8144. .iter()
  8145. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  8146. .fold(state, |s, &(_, _, bits)| s & !bits)
  8147. }
  8148. impl Host {
  8149. /// The card's memory as the system accounts it to this process, in
  8150. /// bytes: the budget and the use of the card's own memory, then of the
  8151. /// PC's memory shared with the card (where the system moves what does
  8152. /// not fit on the card).
  8153. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  8154. let adapter = self.adapter.as_ref()?;
  8155. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  8156. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  8157. // SAFETY: plain queries that fill our structures.
  8158. unsafe {
  8159. adapter
  8160. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  8161. .ok()?;
  8162. adapter
  8163. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  8164. .ok()?;
  8165. }
  8166. // The card's budget moved by 256 MB or more since the last look:
  8167. // said at once, with what was in use at the last look, so the log
  8168. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  8169. // the first world frame in runs 179 to 185, and the memory line,
  8170. // seconds later, was the first to show it. We reserve nothing
  8171. // and make the swap chain once, at the start.)
  8172. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  8173. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  8174. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  8175. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  8176. tracing::info!(
  8177. "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",
  8178. last[0] >> 20,
  8179. own.Budget >> 20,
  8180. crate::frame::current(),
  8181. last[1] >> 20,
  8182. last[2] >> 20
  8183. );
  8184. self.log_video_memory("right after that change");
  8185. }
  8186. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  8187. }
  8188. /// Both of the system's memory groups for this process, in bytes: for
  8189. /// the card's own memory and then for the PC's memory shared with the
  8190. /// card, the budget, the use, what could still be reserved and what
  8191. /// is reserved (the layer reserves none).
  8192. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  8193. let adapter = self.adapter.as_ref()?;
  8194. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  8195. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  8196. // SAFETY: plain queries that fill our structures.
  8197. unsafe {
  8198. adapter
  8199. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  8200. .ok()?;
  8201. adapter
  8202. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  8203. .ok()?;
  8204. }
  8205. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  8206. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  8207. };
  8208. Some([all(&own), all(&shared)])
  8209. }
  8210. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  8211. pub(crate) fn log_video_memory(&self, when: &str) {
  8212. let Some([own, shared]) = self.video_memory_groups() else {
  8213. return;
  8214. };
  8215. tracing::info!(
  8216. "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)",
  8217. when,
  8218. own[0] >> 20,
  8219. own[1] >> 20,
  8220. own[2] >> 20,
  8221. own[3] >> 20,
  8222. shared[0] >> 20,
  8223. shared[1] >> 20,
  8224. shared[2] >> 20,
  8225. shared[3] >> 20
  8226. );
  8227. }
  8228. /// A buffer in system memory that the CPU maps (write-back, so reading
  8229. /// it is fast too) and shaders read and write: for host copies of title
  8230. /// memory that shaders write, which upload memory cannot be. Starts in
  8231. /// the common state (buffers move out of it implicitly).
  8232. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  8233. MADE[2].fetch_add(1, Ordering::Relaxed);
  8234. MADE[3].fetch_add(size, Ordering::Relaxed);
  8235. let heap = D3D12_HEAP_PROPERTIES {
  8236. Type: D3D12_HEAP_TYPE_CUSTOM,
  8237. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  8238. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  8239. ..Default::default()
  8240. };
  8241. let desc = D3D12_RESOURCE_DESC {
  8242. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  8243. Width: size.max(1),
  8244. Height: 1,
  8245. DepthOrArraySize: 1,
  8246. MipLevels: 1,
  8247. SampleDesc: DXGI_SAMPLE_DESC {
  8248. Count: 1,
  8249. Quality: 0,
  8250. },
  8251. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  8252. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  8253. ..Default::default()
  8254. };
  8255. let mut buffer: Option<ID3D12Resource> = None;
  8256. let mut data = std::ptr::null_mut();
  8257. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  8258. let made = unsafe {
  8259. self.device
  8260. .CreateCommittedResource(
  8261. &heap,
  8262. not_resident(),
  8263. &desc,
  8264. D3D12_RESOURCE_STATE_COMMON,
  8265. None,
  8266. &mut buffer,
  8267. )
  8268. .and_then(|()| {
  8269. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  8270. resident(&self.device, b)?;
  8271. mapped(&self.device)?;
  8272. b.Map(0, None, Some(&mut data))
  8273. })
  8274. };
  8275. #[cfg(feature = "diagnostics")]
  8276. if made.is_ok()
  8277. && let Some(b) = &buffer
  8278. {
  8279. crate::book::made(b, || "a shared buffer".into());
  8280. }
  8281. match made {
  8282. Ok(()) => Some((buffer?, data.cast())),
  8283. Err(e) => {
  8284. tracing::warn!(error = %e, size, "no shared buffer");
  8285. None
  8286. }
  8287. }
  8288. }
  8289. /// Whether buffers can lie in the card's memory and be mapped by the CPU
  8290. /// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver
  8291. /// that offer it); logged once.
  8292. pub(crate) fn mapped_card_memory(&self) -> bool {
  8293. static THERE: OnceLock<bool> = OnceLock::new();
  8294. *THERE.get_or_init(|| {
  8295. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default();
  8296. // SAFETY: writes `options` of the given size.
  8297. let ok = unsafe {
  8298. self.device
  8299. .CheckFeatureSupport(
  8300. D3D12_FEATURE_D3D12_OPTIONS16,
  8301. (&raw mut options).cast(),
  8302. size_of_val(&options) as u32,
  8303. )
  8304. .is_ok()
  8305. };
  8306. let supported = ok && options.GPUUploadHeapSupported.as_bool();
  8307. tracing::info!(supported, "card memory the CPU maps");
  8308. supported
  8309. })
  8310. }
  8311. /// A buffer in the card's own memory that the CPU maps, shaders read and
  8312. /// (with `written`) may write. The CPU should only write it: a read of the
  8313. /// mapping crosses the bus a few bytes at a time.
  8314. pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> {
  8315. if !self.mapped_card_memory() {
  8316. return None;
  8317. }
  8318. MADE[4].fetch_add(1, Ordering::Relaxed);
  8319. MADE[5].fetch_add(size, Ordering::Relaxed);
  8320. let heap = D3D12_HEAP_PROPERTIES {
  8321. Type: D3D12_HEAP_TYPE_GPU_UPLOAD,
  8322. ..Default::default()
  8323. };
  8324. let desc = D3D12_RESOURCE_DESC {
  8325. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  8326. Width: size.max(1),
  8327. Height: 1,
  8328. DepthOrArraySize: 1,
  8329. MipLevels: 1,
  8330. SampleDesc: DXGI_SAMPLE_DESC {
  8331. Count: 1,
  8332. Quality: 0,
  8333. },
  8334. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  8335. Flags: if written {
  8336. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
  8337. } else {
  8338. D3D12_RESOURCE_FLAG_NONE
  8339. },
  8340. ..Default::default()
  8341. };
  8342. let mut buffer: Option<ID3D12Resource> = None;
  8343. let mut data = std::ptr::null_mut();
  8344. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  8345. let made = unsafe {
  8346. self.device
  8347. .CreateCommittedResource(
  8348. &heap,
  8349. not_resident(),
  8350. &desc,
  8351. D3D12_RESOURCE_STATE_COMMON,
  8352. None,
  8353. &mut buffer,
  8354. )
  8355. .and_then(|()| {
  8356. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  8357. resident(&self.device, b)?;
  8358. mapped(&self.device)?;
  8359. b.Map(0, None, Some(&mut data))
  8360. })
  8361. };
  8362. match made {
  8363. Ok(()) => Some((buffer?, data.cast())),
  8364. Err(e) => {
  8365. tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps");
  8366. None
  8367. }
  8368. }
  8369. }
  8370. /// A device-local buffer shaders may write (unordered access) and indirect
  8371. /// execution may read, starting in the common state.
  8372. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  8373. MADE[4].fetch_add(1, Ordering::Relaxed);
  8374. MADE[5].fetch_add(size, Ordering::Relaxed);
  8375. let heap = D3D12_HEAP_PROPERTIES {
  8376. Type: D3D12_HEAP_TYPE_DEFAULT,
  8377. ..Default::default()
  8378. };
  8379. let desc = D3D12_RESOURCE_DESC {
  8380. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  8381. Width: size.max(1),
  8382. Height: 1,
  8383. DepthOrArraySize: 1,
  8384. MipLevels: 1,
  8385. SampleDesc: DXGI_SAMPLE_DESC {
  8386. Count: 1,
  8387. Quality: 0,
  8388. },
  8389. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  8390. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  8391. ..Default::default()
  8392. };
  8393. let mut buffer: Option<ID3D12Resource> = None;
  8394. // SAFETY: plain creation of a device-local buffer.
  8395. let made = unsafe {
  8396. self.device.CreateCommittedResource(
  8397. &heap,
  8398. not_resident(),
  8399. &desc,
  8400. D3D12_RESOURCE_STATE_COMMON,
  8401. None,
  8402. &mut buffer,
  8403. )
  8404. };
  8405. #[cfg(feature = "diagnostics")]
  8406. if let Some(b) = &buffer {
  8407. crate::book::made(b, || "an unordered access buffer".into());
  8408. }
  8409. let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))).and_then(|()| mapped(&self.device));
  8410. match made {
  8411. Ok(()) => buffer,
  8412. Err(e) => {
  8413. tracing::warn!(error = %e, size, "no unordered-access buffer");
  8414. None
  8415. }
  8416. }
  8417. }
  8418. }
  8419. /// For adapters without device-removed data (the software one): the last
  8420. /// commands each list of the failed submission noted (diagnostics, with
  8421. /// `VICTORY_D3D12_DRED`).
  8422. fn last_notes(runs: &[&HostList]) -> String {
  8423. #[cfg(feature = "diagnostics")]
  8424. {
  8425. let mut text = String::new();
  8426. for (i, r) in runs.iter().enumerate() {
  8427. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  8428. for (n, _) in notes.iter().rev().take(6).rev() {
  8429. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  8430. }
  8431. }
  8432. text
  8433. }
  8434. #[cfg(not(feature = "diagnostics"))]
  8435. {
  8436. let _ = runs;
  8437. String::new()
  8438. }
  8439. }
  8440. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  8441. /// command reads (diagnostics).
  8442. #[cfg(feature = "diagnostics")]
  8443. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  8444. let end = start + bytes;
  8445. if va < start {
  8446. format!(" (fault {:#x} below its source)", start - va)
  8447. } else if va < end {
  8448. format!(" (fault at source +{:#x})", va - start)
  8449. } else {
  8450. format!(" (fault {:#x} past its source's end)", va - end)
  8451. }
  8452. }
  8453. /// The commands that may have been running where a list stopped at
  8454. /// command `done`: those between the barriers around it (work between
  8455. /// barriers overlaps on the GPU), by kind, and what the markers just
  8456. /// before them say (`HostList::note_op`: diagnostics builds with
  8457. /// device-removed data on).
  8458. /// For a list that stopped at command `done`: what the indirect executions
  8459. /// there ran, from the one before it to the next barrier (four at most), and
  8460. /// what the heap slots their user data names hold now.
  8461. #[cfg(feature = "diagnostics")]
  8462. fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &indirects::Shared) -> String {
  8463. let indirect = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT;
  8464. let all = all.lock().unwrap_or_else(|e| e.into_inner());
  8465. let mut text = String::new();
  8466. let mut shown = 0;
  8467. let mesh = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_DISPATCHMESH;
  8468. for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) {
  8469. if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) {
  8470. break;
  8471. }
  8472. if !indirect(op) && !mesh(op) {
  8473. continue;
  8474. }
  8475. shown += 1;
  8476. let direct = mesh(op);
  8477. let nth = if direct { indirects::before(history, at, mesh) } else { indirects::before(history, at, indirect) };
  8478. let Some((what, words)) = all.nth(nth, direct) else {
  8479. continue;
  8480. };
  8481. text.push_str(&format!("; command {at} ran {what}"));
  8482. for (word, slot, what) in crate::descriptor::host::describe_slots(words) {
  8483. text.push_str(&format!(", word {word} slot {slot}: {what}"));
  8484. }
  8485. }
  8486. text
  8487. }
  8488. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  8489. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  8490. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  8491. let to = history[done..]
  8492. .iter()
  8493. .position(barrier)
  8494. .map_or(history.len(), |b| (done + b).max(done + 1));
  8495. let mut text = format!(", commands {from}..{to} between its barriers:");
  8496. let mut shown = 0;
  8497. // From just before the command the GPU had not finished: the first
  8498. // twelve after the barrier named draws long done when a list of 79
  8499. // mesh draws stopped at its 45th (run 41).
  8500. for i in from.max(done.saturating_sub(4))..to {
  8501. let op = history[i];
  8502. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  8503. continue;
  8504. }
  8505. shown += 1;
  8506. let marker = i
  8507. .checked_sub(1)
  8508. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  8509. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  8510. .map_or("no marker", |(_, s)| s.as_str());
  8511. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  8512. }
  8513. text
  8514. }
  8515. pub(crate) fn transition(
  8516. resource: &ID3D12Resource,
  8517. before: D3D12_RESOURCE_STATES,
  8518. after: D3D12_RESOURCE_STATES,
  8519. ) -> D3D12_RESOURCE_BARRIER {
  8520. D3D12_RESOURCE_BARRIER {
  8521. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  8522. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  8523. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  8524. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  8525. // SAFETY: a borrowed pointer; the barrier never releases it.
  8526. pResource: unsafe { std::mem::transmute_copy(resource) },
  8527. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  8528. StateBefore: before,
  8529. StateAfter: after,
  8530. }),
  8531. },
  8532. }
  8533. }
  8534. /// A window of the given client size, owned by its own message thread.
  8535. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  8536. let (sender, receiver) = std::sync::mpsc::channel();
  8537. std::thread::Builder::new()
  8538. .name("victory-window".into())
  8539. .spawn(move || {
  8540. let made = make_window(width, height);
  8541. let ok = made.is_ok();
  8542. let _ = sender.send(made.map(|h| h.0 as usize));
  8543. if ok {
  8544. pump();
  8545. }
  8546. })
  8547. .map_err(|_| windows::core::Error::empty())?;
  8548. let hwnd = receiver
  8549. .recv()
  8550. .map_err(|_| windows::core::Error::empty())??;
  8551. Ok(HWND(hwnd as *mut _))
  8552. }
  8553. extern "system" fn window_proc(
  8554. hwnd: HWND,
  8555. message: u32,
  8556. wparam: WPARAM,
  8557. lparam: LPARAM,
  8558. ) -> LRESULT {
  8559. // SAFETY: the default handling for our window.
  8560. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  8561. }
  8562. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  8563. const CLASS: PCWSTR = w!("VIctory");
  8564. // SAFETY: registers our class once and creates a window of it.
  8565. unsafe {
  8566. let instance = GetModuleHandleW(None)?;
  8567. let class = WNDCLASSEXW {
  8568. cbSize: size_of::<WNDCLASSEXW>() as u32,
  8569. lpfnWndProc: Some(window_proc),
  8570. hInstance: instance.into(),
  8571. lpszClassName: CLASS,
  8572. hCursor: LoadCursorW(None, IDC_ARROW)?,
  8573. ..Default::default()
  8574. };
  8575. RegisterClassExW(&class);
  8576. let mut rect = RECT {
  8577. left: 0,
  8578. top: 0,
  8579. right: width as i32,
  8580. bottom: height as i32,
  8581. };
  8582. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  8583. CreateWindowExW(
  8584. WINDOW_EX_STYLE(0),
  8585. CLASS,
  8586. w!("VIctory"),
  8587. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  8588. CW_USEDEFAULT,
  8589. CW_USEDEFAULT,
  8590. rect.right - rect.left,
  8591. rect.bottom - rect.top,
  8592. None,
  8593. None,
  8594. Some(instance.into()),
  8595. None,
  8596. )
  8597. }
  8598. }
  8599. fn pump() {
  8600. let mut message = MSG::default();
  8601. // SAFETY: the standard message loop of this thread's window.
  8602. unsafe {
  8603. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  8604. let _ = TranslateMessage(&message);
  8605. DispatchMessageW(&message);
  8606. }
  8607. }
  8608. }
  8609. #[cfg(test)]
  8610. mod trail {
  8611. /// The trail keeps the newest things, and the report made when the
  8612. /// host device is removed says them and the pipeline library's state
  8613. /// (no card is asked for any of it).
  8614. #[test]
  8615. fn the_removal_report_says_the_newest_things_done() {
  8616. for n in 0..super::TRAIL_MOST + 5 {
  8617. super::trail(|| format!("thing {n} done"));
  8618. }
  8619. let text = super::removal_context();
  8620. assert!(text.contains("the submitting thread was"));
  8621. assert!(text.contains("pipeline library: no call running"));
  8622. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  8623. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  8624. }
  8625. }
  8626. #[cfg(test)]
  8627. mod spare {
  8628. use super::Spare;
  8629. /// Kept things come back by size, the last given first, and nothing is
  8630. /// kept past the limit.
  8631. #[test]
  8632. fn kept_things_come_back_by_size_within_the_limit() {
  8633. let mut spare: Spare<u32> = Spare::new();
  8634. assert_eq!(spare.take(4), None);
  8635. assert_eq!(spare.give(1, 4, 10), None);
  8636. assert_eq!(spare.give(2, 1, 10), None);
  8637. assert_eq!(spare.give(3, 4, 10), None);
  8638. assert_eq!(spare.bytes, 9);
  8639. // Past the limit: handed back, nothing changes.
  8640. assert_eq!(spare.give(4, 4, 10), Some(4));
  8641. assert_eq!(spare.bytes, 9);
  8642. assert_eq!(spare.take(2), None, "no thing of that size");
  8643. assert_eq!(spare.take(4), Some(3));
  8644. assert_eq!(spare.take(4), Some(1));
  8645. assert_eq!(spare.take(4), None);
  8646. assert_eq!(spare.take(1), Some(2));
  8647. assert_eq!(spare.bytes, 0);
  8648. assert!(spare.kept.is_empty());
  8649. }
  8650. }
  8651. #[cfg(test)]
  8652. mod refresh_tests {
  8653. use super::Batch;
  8654. use crate::shadow::Shadow;
  8655. use std::sync::Arc;
  8656. use windows_sys::Win32::System::Memory::{
  8657. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  8658. VirtualAlloc,
  8659. };
  8660. const PAGE: usize = 64 << 10;
  8661. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  8662. /// Title memory for the tests (never given back: copies of it stay in
  8663. /// the guards): write-watched, or a view of a section.
  8664. fn title(len: usize, view: bool) -> usize {
  8665. // SAFETY: plain allocations.
  8666. let at = unsafe {
  8667. if view {
  8668. let section =
  8669. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  8670. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  8671. // As the runtime tells of it.
  8672. crate::title_memory_section(section as usize, len as u64, true);
  8673. crate::title_memory_remapped(at, len);
  8674. crate::title_memory_view(at, len, section as usize, 0);
  8675. at
  8676. } else {
  8677. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  8678. }
  8679. };
  8680. assert_ne!(at, 0);
  8681. at
  8682. }
  8683. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  8684. /// and every fourth page not there: as a title that streams has it.
  8685. fn with_holes(blocks: usize) -> usize {
  8686. use windows_sys::Win32::System::Memory::{
  8687. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  8688. VirtualAlloc2, VirtualFree,
  8689. };
  8690. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  8691. // SAFETY: a placeholder and a section of our own.
  8692. unsafe {
  8693. let at = VirtualAlloc2(
  8694. GetCurrentProcess(),
  8695. std::ptr::null(),
  8696. blocks * PAGE,
  8697. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  8698. PAGE_NOACCESS,
  8699. std::ptr::null_mut(),
  8700. 0,
  8701. ) as usize;
  8702. assert_ne!(at, 0);
  8703. let len = blocks * PAGE;
  8704. let section =
  8705. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  8706. for block in (0..blocks).filter(|b| b % 4 != 3) {
  8707. let to = at + block * PAGE;
  8708. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  8709. let view = MapViewOfFile3(
  8710. section,
  8711. GetCurrentProcess(),
  8712. to as *const _,
  8713. (block * PAGE) as u64,
  8714. PAGE,
  8715. MEM_REPLACE_PLACEHOLDER,
  8716. PAGE_READWRITE,
  8717. std::ptr::null_mut(),
  8718. 0,
  8719. );
  8720. assert_eq!(view.Value as usize, to);
  8721. crate::title_memory_remapped(to, PAGE);
  8722. }
  8723. at
  8724. }
  8725. }
  8726. fn memory(len: usize) -> *mut u8 {
  8727. // SAFETY: a plain allocation.
  8728. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  8729. }
  8730. struct Random(u64);
  8731. impl Random {
  8732. fn below(&mut self, n: usize) -> usize {
  8733. self.0 ^= self.0 << 13;
  8734. self.0 ^= self.0 >> 7;
  8735. self.0 ^= self.0 << 17;
  8736. (self.0 >> 11) as usize % n
  8737. }
  8738. }
  8739. /// Prepares as a submission does: one asking for all the ranges, the
  8740. /// refreshes in several flushes, the asking's end.
  8741. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  8742. // One at a time, as submissions are.
  8743. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  8744. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  8745. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  8746. crate::watch::ask_once(&asked);
  8747. let mut batch = Batch::default();
  8748. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  8749. for (shadow, at, len) in part {
  8750. batch.add(shadow, *at, *len);
  8751. }
  8752. batch.flush();
  8753. }
  8754. crate::watch::ask_once_end();
  8755. }
  8756. /// Whatever is written where, by the title or by us, and whichever
  8757. /// copies (of both kinds of memory, over one another, none on a page
  8758. /// line) are refreshed in which ranges: a refreshed range holds what
  8759. /// title memory holds.
  8760. #[test]
  8761. fn refreshed_ranges_hold_title_memory() {
  8762. // SAFETY (all blocks): title memory and copies of the test's own,
  8763. // written by this thread and, in `Batch::flush`, by the threads that
  8764. // refresh, which are done when it returns.
  8765. let mut random = Random(0x1234_5678_9ABC_DEF1);
  8766. const LEN: usize = 24 * PAGE;
  8767. let regions = [title(LEN, false), title(LEN, true)];
  8768. let mut copies = Vec::new();
  8769. for &region in &regions {
  8770. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  8771. let data = memory(to - from);
  8772. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  8773. }
  8774. }
  8775. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  8776. for round in 0..600 {
  8777. for _ in 0..random.below(4) {
  8778. let at = regions[random.below(2)] + random.below(LEN - 64);
  8779. let n = 1 + random.below(60);
  8780. if random.below(3) == 0 {
  8781. // What shaders wrote.
  8782. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  8783. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  8784. Shadow::put(at, &was, &now);
  8785. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  8786. continue;
  8787. }
  8788. for i in 0..n {
  8789. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  8790. }
  8791. }
  8792. let mut ranges = Vec::new();
  8793. for (shadow, _) in &copies {
  8794. if random.below(3) == 0 {
  8795. continue;
  8796. }
  8797. let (start, len) = shadow.span();
  8798. let (start, len) = (start as usize, len as usize);
  8799. // Often the range of the time before, as a list's is.
  8800. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  8801. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  8802. ranges.push((shadow.clone(), start + from, n));
  8803. }
  8804. if ranges.is_empty() {
  8805. continue;
  8806. }
  8807. let flushes = 1 + random.below(3);
  8808. submission(&ranges, flushes);
  8809. for (shadow, at, n) in &ranges {
  8810. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  8811. let start = shadow.span().0 as usize;
  8812. let same = unsafe {
  8813. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  8814. };
  8815. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  8816. }
  8817. }
  8818. }
  8819. /// A copy in the card's memory, with the card's side and the sends to it
  8820. /// played by the test.
  8821. struct Carded {
  8822. shadow: Arc<Shadow>,
  8823. data: usize,
  8824. start: usize,
  8825. len: usize,
  8826. /// The last send, the last send every fetch to come is behind, and
  8827. /// the card's bytes: the queue's order is the order it is locked in.
  8828. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  8829. /// Whether a flight that writes it has not landed.
  8830. flying: std::sync::atomic::AtomicBool,
  8831. /// The dword of each eight its shaders write.
  8832. class: usize,
  8833. }
  8834. impl Carded {
  8835. fn new(start: usize, len: usize, class: usize) -> Carded {
  8836. let data = memory(len);
  8837. Carded {
  8838. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  8839. data: data as usize,
  8840. start,
  8841. len,
  8842. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  8843. flying: std::sync::atomic::AtomicBool::new(false),
  8844. class,
  8845. }
  8846. }
  8847. /// What changed on the CPU's side goes up.
  8848. fn send(&self) {
  8849. let mut card = self.card.lock().unwrap();
  8850. card.0 += 1;
  8851. let (number, merged) = (card.0, card.1);
  8852. for (a, b) in self.shadow.send_up(number, merged) {
  8853. // SAFETY: the copy's bytes; nothing writes those that are to
  8854. // go up.
  8855. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  8856. }
  8857. }
  8858. }
  8859. /// Everything at once: the title writes its memory on two threads, the
  8860. /// submitting thread puts its bytes in under shader writes
  8861. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  8862. /// the card's memory, one not), sends up what changed and declares what
  8863. /// the next flight's shaders write, and what flights wrote is landed
  8864. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  8865. /// still and the copies are refreshed once more, each of them, and the
  8866. /// card's side of those that have one, hold what title memory holds, and
  8867. /// title memory what was written last.
  8868. ///
  8869. /// Into the first copy shaders write besides through a view nobody
  8870. /// declared, words the title does not write: nothing that goes up ever
  8871. /// puts an older value over those.
  8872. ///
  8873. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  8874. /// only takes the block out of the guards' clean ones and leaves its bit,
  8875. /// or if a fault leaves the bit; in some thousand rounds,
  8876. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  8877. #[test]
  8878. fn landings_title_writes_and_light_refreshes_at_once() {
  8879. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  8880. assert!(crate::safecopy::on());
  8881. const LEN: usize = 24 * PAGE;
  8882. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  8883. let region = title(LEN, true);
  8884. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  8885. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  8886. let plain = {
  8887. let (start, len) = (region + 700, LEN - 9000);
  8888. let data = memory(len);
  8889. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  8890. };
  8891. // What was last written so, by offset.
  8892. let mut undeclared = std::collections::HashMap::new();
  8893. let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0");
  8894. let stop = AtomicBool::new(false);
  8895. // Also when an assertion fails on one of the threads.
  8896. struct Stop<'a>(&'a AtomicBool);
  8897. impl Drop for Stop<'_> {
  8898. fn drop(&mut self) {
  8899. self.0.store(true, Ordering::Relaxed);
  8900. }
  8901. }
  8902. // Held shared by who writes title memory, alone while it is looked at.
  8903. let still = std::sync::RwLock::new(());
  8904. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  8905. std::thread::scope(|s| {
  8906. for t in 0..2usize {
  8907. let (stop, still) = (&stop, &still);
  8908. s.spawn(move || {
  8909. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  8910. let mut value = 0u32;
  8911. while !stop.load(Ordering::Relaxed) {
  8912. {
  8913. let _moving = still.read().unwrap();
  8914. for _ in 0..3 {
  8915. value += 1;
  8916. // Of each eight dwords, one a thread.
  8917. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  8918. dword(at).store(value, Ordering::Relaxed);
  8919. }
  8920. }
  8921. std::thread::sleep(std::time::Duration::from_micros(20));
  8922. }
  8923. });
  8924. }
  8925. // Lands flights.
  8926. {
  8927. let (carded, stop) = (&carded, &stop);
  8928. s.spawn(move || {
  8929. let _stop = Stop(stop);
  8930. while let Ok((which, ranges, value)) = flights.recv() {
  8931. let c = &carded[which];
  8932. // Fetched: the card's bytes, behind every send so far.
  8933. let (after, now) = {
  8934. let card = c.card.lock().unwrap();
  8935. (card.0, card.2.clone())
  8936. };
  8937. // By piece: 64 KiB of title memory.
  8938. let mut pieces = Vec::new();
  8939. for &(from, to) in &ranges {
  8940. let mut at = from;
  8941. while at < to {
  8942. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  8943. pieces.push((at, next, now.as_ptr() as usize + at));
  8944. at = next;
  8945. }
  8946. }
  8947. let parts: Vec<_> = pieces.chunks(3).collect();
  8948. crate::land::each(parts.len(), &|i| {
  8949. let mut notes = crate::land::Notes::default();
  8950. // SAFETY: the bytes of `now`; each piece once.
  8951. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  8952. notes.flush();
  8953. });
  8954. for &(from, to) in &ranges {
  8955. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8956. // (The next fetch may have brought more.)
  8957. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  8958. }
  8959. }
  8960. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  8961. c.shadow.copy_back_done(&done);
  8962. c.card.lock().unwrap().1 = after;
  8963. c.flying.store(false, Ordering::Release);
  8964. }
  8965. });
  8966. }
  8967. let _stop = Stop(&stop);
  8968. let mut random = Random(0xABCD_EF01_2345_6789);
  8969. let check = |round: usize, random: &mut Random, quiet: bool| {
  8970. for c in &carded {
  8971. if c.shadow.writes_pending() {
  8972. let mut runs = usize::MAX;
  8973. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  8974. }
  8975. }
  8976. let mut ranges = Vec::new();
  8977. for (shadow, start, len) in
  8978. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  8979. {
  8980. // All of it, or a part; often the same part.
  8981. let (from, n) = match random.below(3) {
  8982. _ if quiet => (0, len),
  8983. 0 => (0, len),
  8984. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  8985. _ => {
  8986. let from = random.below(len / 4) * 4;
  8987. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  8988. }
  8989. };
  8990. ranges.push((shadow.clone(), start + from, n));
  8991. }
  8992. submission(&ranges, 1 + random.below(3));
  8993. carded.iter().for_each(Carded::send);
  8994. };
  8995. let mut value = 1u32;
  8996. for round in 0..rounds {
  8997. check(round, &mut random, false);
  8998. if exact {
  8999. let c = &carded[0];
  9000. let mut card = c.card.lock().unwrap();
  9001. for _ in 0..40 {
  9002. value += 1;
  9003. let at = random.below(LEN / 32) * 32 + 4 * 6;
  9004. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  9005. undeclared.insert(at, value);
  9006. }
  9007. }
  9008. // The flight of this submission: its shaders' writes.
  9009. for (which, c) in carded.iter().enumerate() {
  9010. if c.flying.swap(true, Ordering::Acquire) {
  9011. continue;
  9012. }
  9013. value += 1;
  9014. let mut ranges: Vec<(usize, usize)> = Vec::new();
  9015. let first = random.below(6) * PAGE / 2;
  9016. for k in 0..2 {
  9017. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  9018. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  9019. if from < to {
  9020. ranges.push((from, to));
  9021. }
  9022. }
  9023. for &(from, to) in &ranges {
  9024. c.shadow.writing(c.start + from, to - from);
  9025. }
  9026. {
  9027. let mut card = c.card.lock().unwrap();
  9028. for &(from, to) in &ranges {
  9029. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  9030. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  9031. }
  9032. }
  9033. }
  9034. fly.send((which, ranges, value)).unwrap();
  9035. }
  9036. if round % 20 != 19 {
  9037. continue;
  9038. }
  9039. // Still: no flight in the air, no title write.
  9040. let _still = still.write().unwrap();
  9041. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  9042. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  9043. std::thread::yield_now();
  9044. }
  9045. check(round, &mut random, true);
  9046. // SAFETY: the test's own memory, written by nobody now.
  9047. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  9048. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  9049. for c in &carded {
  9050. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  9051. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  9052. let card = c.card.lock().unwrap();
  9053. let mut side = card.2.clone();
  9054. if c.class == carded[0].class {
  9055. // (They may have been landed meanwhile, by a flight
  9056. // that declared their range, and may not.)
  9057. for (&at, &value) in &undeclared {
  9058. let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
  9059. assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
  9060. side[at..at + 4].copy_from_slice(&there[at..at + 4]);
  9061. }
  9062. }
  9063. assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
  9064. }
  9065. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  9066. }
  9067. drop(fly);
  9068. });
  9069. }
  9070. /// The title's bytes put in under shader writes, for a copy of 174 MB
  9071. /// whose shader writes were declared as 40 ranges that overlap, with 12
  9072. /// pages written since. Run with `--ignored --nocapture`, and with
  9073. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  9074. #[test]
  9075. #[ignore]
  9076. fn bytes_under_overlapping_ranges() {
  9077. const BIG: usize = 174 << 20;
  9078. let big = title(BIG, true);
  9079. // SAFETY (both): the test's own memory.
  9080. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  9081. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  9082. copy.update(big, BIG);
  9083. copy.take_dirty();
  9084. for i in 0..40 {
  9085. copy.writing(big + i * 5920, BIG - i * 5920);
  9086. }
  9087. let mut best = f64::MAX;
  9088. for round in 0..30 {
  9089. for i in 0..12 {
  9090. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  9091. }
  9092. let started = std::time::Instant::now();
  9093. let mut runs = usize::MAX;
  9094. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  9095. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  9096. copy.take_dirty();
  9097. }
  9098. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  9099. }
  9100. /// A range nothing wrote is known to be as it was, at its ends too, and
  9101. /// is so no more once something wrote it.
  9102. #[test]
  9103. fn unchanged_ranges_are_known() {
  9104. for view in [false, true] {
  9105. let region = title(8 * PAGE, view);
  9106. // (A page read for the first time counts as written.)
  9107. // SAFETY: the test's own memory.
  9108. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  9109. let data = memory(8 * PAGE);
  9110. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  9111. // Ends in the middle of pages.
  9112. let (at, len) = (region + 500, 5 * PAGE);
  9113. let look = |expected: bool, what: &str| {
  9114. // The submission's one asking, which takes two ranges. (Again
  9115. // if a submission of another test ended it.)
  9116. let mut known = false;
  9117. for _ in 0..100 {
  9118. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  9119. known = copy.nothing_new(at, len);
  9120. if known || !expected {
  9121. break;
  9122. }
  9123. }
  9124. assert_eq!(known, expected, "view {view}: {what}");
  9125. let copied = copy.update(at, len);
  9126. crate::watch::ask_once_end();
  9127. copied
  9128. };
  9129. assert_eq!(look(false, "never taken"), len);
  9130. assert_eq!(look(true, "taken"), 0);
  9131. assert_eq!(look(true, "taken"), 0);
  9132. // SAFETY: the test's own memory.
  9133. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  9134. // (The kernel names the 4 KiB, the guards only the block.)
  9135. assert_eq!(look(false, "written at its end"), if view { PAGE } else { 4096 } - 500);
  9136. assert_eq!(look(true, "taken again"), 0);
  9137. // Outside the range, on its last page.
  9138. // SAFETY: as above.
  9139. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  9140. assert_eq!(look(false, "written on its last page"), 500);
  9141. // A longer range was never taken whole.
  9142. assert!(!copy.nothing_new(region, 6 * PAGE));
  9143. }
  9144. }
  9145. /// Of a copy in the card's memory only the dwords title memory changed go
  9146. /// up, and none beside them, not even between two in 64 bytes; a page
  9147. /// never taken goes up whole.
  9148. #[test]
  9149. fn only_what_differs_goes_up() {
  9150. let region = title(4 * PAGE, true);
  9151. let data = memory(4 * PAGE);
  9152. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  9153. copy.update(region, 4 * PAGE);
  9154. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  9155. // What the relay does: shader writes into title memory, and into the
  9156. // CPU's side.
  9157. crate::watch::landing(region + PAGE + 640, 64);
  9158. // SAFETY: the test's own memory.
  9159. unsafe {
  9160. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  9161. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  9162. }
  9163. copy.update(region, 4 * PAGE);
  9164. let again = copy.take_dirty();
  9165. // SAFETY: as above.
  9166. unsafe {
  9167. ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
  9168. ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
  9169. ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
  9170. // The value that was there.
  9171. ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
  9172. }
  9173. copy.update(region, 4 * PAGE);
  9174. let written = copy.take_dirty();
  9175. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") {
  9176. assert_eq!(again, []);
  9177. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
  9178. } else {
  9179. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  9180. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  9181. }
  9182. // SAFETY: as above.
  9183. assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
  9184. }
  9185. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  9186. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  9187. /// big copy that 55 landed pieces and 9 title writes opened, while a
  9188. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  9189. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  9190. #[test]
  9191. #[ignore]
  9192. fn frame_of_refreshes() {
  9193. let mut random = Random(0x9876_5432_1234_5671);
  9194. const EACH: usize = 224 << 10;
  9195. const BIG: usize = 174 << 20;
  9196. let watched = title(3000 * EACH, false);
  9197. // `VICTORY_BENCH_HOLES=0`: views without holes.
  9198. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  9199. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  9200. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  9201. let big = title(BIG, true);
  9202. // SAFETY: the test's own memory.
  9203. unsafe {
  9204. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  9205. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  9206. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  9207. }
  9208. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  9209. }
  9210. let mut small = Vec::new();
  9211. for i in 0..4400 {
  9212. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  9213. let data = memory(EACH);
  9214. // The range views read, not all of the copy.
  9215. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  9216. }
  9217. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  9218. // The same memory, as another copy: what is landed is landed through
  9219. // it, and the refreshes are of the first.
  9220. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  9221. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  9222. let (mut sum, mut landing) = (0.0, 0.0);
  9223. const FRAMES: usize = 12;
  9224. for frame in 0..FRAMES {
  9225. let mut took = [0f64; 2];
  9226. for i in 0..30 {
  9227. // The title's writes, and the relay's beside the submission.
  9228. for _ in 0..9 {
  9229. let at = views + random.below(1400 * EACH / 8) * 8;
  9230. if there(at) {
  9231. // SAFETY: the test's own memory.
  9232. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  9233. }
  9234. }
  9235. for _ in 0..60 {
  9236. let at = watched + random.below(3000 * EACH / 8) * 8;
  9237. // SAFETY: the test's own memory.
  9238. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  9239. }
  9240. let first = random.below(BIG / PAGE - 60);
  9241. let lands = lands.clone();
  9242. let land = std::thread::spawn(move || {
  9243. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  9244. let started = std::time::Instant::now();
  9245. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  9246. let pieces: Vec<_> =
  9247. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  9248. let mut notes = crate::land::Notes::default();
  9249. // SAFETY: the bytes of `now`; nothing else lands here.
  9250. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  9251. notes.flush();
  9252. }
  9253. started.elapsed().as_secs_f64() * 1e3
  9254. });
  9255. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  9256. small.iter().cloned().chain([heap.clone()]).collect()
  9257. } else {
  9258. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  9259. };
  9260. let started = std::time::Instant::now();
  9261. submission(&ranges, 3);
  9262. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  9263. let put = land.join().unwrap();
  9264. if frame >= 2 {
  9265. landing += put;
  9266. }
  9267. heap.0.take_dirty();
  9268. }
  9269. if frame >= 2 {
  9270. sum += took[0] + took[1];
  9271. for k in 0..2 {
  9272. best[k] = best[k].min(took[k]);
  9273. asking[k] += took[k];
  9274. }
  9275. }
  9276. }
  9277. println!(
  9278. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  9279. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  9280. crate::watch::light(),
  9281. sum / (FRAMES - 2) as f64,
  9282. asking[0] / (FRAMES - 2) as f64,
  9283. best[0],
  9284. asking[1] / (FRAMES - 2) as f64,
  9285. best[1],
  9286. landing / (FRAMES - 2) as f64,
  9287. );
  9288. #[cfg(feature = "diagnostics")]
  9289. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  9290. }
  9291. }
  9292. #[cfg(test)]
  9293. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  9294. use super::Batch;
  9295. use std::sync::Arc;
  9296. #[test]
  9297. fn a_texture_is_checked_once_per_submission() {
  9298. let mut batch = Batch::default();
  9299. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  9300. // The first list sampling each texture checks it ...
  9301. assert!(batch.texture_due(&a));
  9302. assert!(batch.texture_due(&b));
  9303. // ... later lists of the same submission do not.
  9304. assert!(!batch.texture_due(&a));
  9305. assert!(!batch.texture_due(&a.clone()));
  9306. assert!(!batch.texture_due(&b));
  9307. }
  9308. #[test]
  9309. fn title_writes_make_textures_due_again() {
  9310. let mut batch = Batch::default();
  9311. let a = Arc::new(1u32);
  9312. assert!(batch.texture_due(&a));
  9313. assert!(!batch.texture_due(&a));
  9314. // A copy into title memory or work that may write it may have
  9315. // changed the texture's memory.
  9316. batch.title_written();
  9317. assert!(batch.texture_due(&a));
  9318. assert!(!batch.texture_due(&a));
  9319. // A fresh submission starts over.
  9320. let mut next = Batch::default();
  9321. assert!(next.texture_due(&a));
  9322. }
  9323. /// The hashing a submission does for textures in physical-page memory,
  9324. /// with every list checking the textures it samples (before) and with
  9325. /// each checked once (after). Run with
  9326. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  9327. #[test]
  9328. #[ignore = "benchmark"]
  9329. fn texture_checks_per_submission() {
  9330. const TEXTURES: usize = 48;
  9331. const SIZE: usize = 4 << 20;
  9332. const LISTS: usize = 12;
  9333. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  9334. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  9335. .collect();
  9336. let submit = |dedupe: bool| {
  9337. let mut batch = Batch::default();
  9338. let mut hashed = 0usize;
  9339. let started = std::time::Instant::now();
  9340. for _ in 0..LISTS {
  9341. for t in &textures {
  9342. if !dedupe || batch.texture_due(t) {
  9343. std::hint::black_box(blake3::hash(t));
  9344. hashed += 1;
  9345. }
  9346. }
  9347. }
  9348. (started.elapsed(), hashed)
  9349. };
  9350. submit(false); // warm up
  9351. let (before, n_before) = submit(false);
  9352. let (after, n_after) = submit(true);
  9353. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  9354. println!(
  9355. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  9356. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  9357. SIZE >> 20,
  9358. before.as_secs_f64() / after.as_secs_f64()
  9359. );
  9360. }
  9361. #[test]
  9362. fn vram_idle_ms_scales_with_pressure() {
  9363. let vram_idle_ms = |memory| super::vram_idle_for(memory, false);
  9364. let keeps = |memory| super::vram_idle_for(memory, true);
  9365. let gib = 1024 * 1024 * 1024;
  9366. assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000);
  9367. assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000);
  9368. assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500);
  9369. assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000);
  9370. assert_eq!(keeps(None), 5_000);
  9371. // Normal (< 75%)
  9372. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  9373. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  9374. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  9375. // Moderate (75%..85%)
  9376. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  9377. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  9378. // High (>= 85%, including over-budget)
  9379. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  9380. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  9381. // Missing or zero budget falls back to normal
  9382. assert_eq!(vram_idle_ms(None), 5_000);
  9383. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  9384. }
  9385. #[test]
  9386. fn textures_are_kept_while_the_card_has_room() {
  9387. use super::vram_keep;
  9388. let gib = 1 << 30;
  9389. assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000);
  9390. // Past it: the longest idle ones, enough to come down to 85 %.
  9391. let (ms, bytes) = vram_keep(100 * gib, 90 * gib);
  9392. assert_eq!((ms, bytes), (5_000, 5 * gib));
  9393. assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib));
  9394. assert_eq!(vram_keep(0, 7).0, 5_000);
  9395. }
  9396. #[test]
  9397. fn ram_idle_ms_scales_with_pressure() {
  9398. let ram_idle_ms = |avail| super::ram_idle_for(avail, false);
  9399. assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000);
  9400. assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000);
  9401. assert_eq!(super::ram_idle_for(None, true), 10_000);
  9402. let gib = 1024 * 1024 * 1024;
  9403. // Normal (>= 4 GiB)
  9404. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  9405. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  9406. // Moderate (2 GiB..4 GiB)
  9407. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  9408. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  9409. // High (< 2 GiB)
  9410. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  9411. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  9412. // Missing falls back to normal
  9413. assert_eq!(ram_idle_ms(None), 10_000);
  9414. }
  9415. }