host.rs 403 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189
  1. //! The host GPU: one D3D12 device and direct queue (decision 0007), and a
  2. //! window to present on.
  3. //!
  4. //! shortcut: every submission is waited for, so CPU and GPU never overlap
  5. //! (unless `VICTORY_LATE_WAIT=1`, see [`late`]);
  6. //! overlap them with per-submission fences once more than clears run.
  7. use std::sync::atomic::{AtomicU32, Ordering};
  8. use std::sync::{Mutex, OnceLock};
  9. use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
  10. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  11. use windows::Win32::Graphics::Direct3D12::*;
  12. use windows::Win32::Graphics::Dxgi::Common::*;
  13. use windows::Win32::Graphics::Dxgi::*;
  14. use windows::Win32::System::LibraryLoader::GetModuleHandleW;
  15. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  16. use windows::Win32::UI::WindowsAndMessaging::*;
  17. use windows::core::{Interface, PCWSTR, w};
  18. /// Resource states without the console's own bits (compression hints from
  19. /// bit 25 up), which the host rejects.
  20. pub(crate) fn pc_state(state: u32) -> u32 {
  21. state & 0x01ff_ffff
  22. }
  23. /// A console state as a host texture state: PC bits only, and none of the
  24. /// buffer-only ones the console allows on textures (vertex, constant and
  25. /// index buffer, stream out, indirect arguments, as in "generic read").
  26. pub(crate) fn texture_state(state: u32) -> u32 {
  27. const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
  28. pc_state(state) & !BUFFER_ONLY
  29. }
  30. /// Render target views live only until their command is recorded, so a
  31. /// ring of host descriptors is enough.
  32. const RTV_RING: u32 = 1024;
  33. pub(crate) struct Host {
  34. pub(crate) device: ID3D12Device,
  35. queue: ID3D12CommandQueue,
  36. fence: ID3D12Fence,
  37. /// The last value signalled on `fence`, behind the submission lock.
  38. submitted: Mutex<u64>,
  39. event: HANDLE,
  40. rtvs: ID3D12DescriptorHeap,
  41. rtv_size: u32,
  42. /// A ring of depth views, used as `rtvs`.
  43. dsvs: ID3D12DescriptorHeap,
  44. dsv_size: u32,
  45. next_dsv: AtomicU32,
  46. /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug
  47. /// layer's messages.
  48. messages: Option<ID3D12InfoQueue>,
  49. next_rtv: AtomicU32,
  50. presenter: Mutex<Option<Presenter>>,
  51. /// The adapter the device is on, for its memory budget
  52. /// ([`Host::video_memory`]); `None` if the system does not name it.
  53. adapter: Option<IDXGIAdapter3>,
  54. }
  55. // SAFETY: D3D12 devices, queues, fences and descriptor heaps are
  56. // free-threaded; the event handle is only waited on under `submitted`.
  57. unsafe impl Send for Host {}
  58. // SAFETY: as above.
  59. unsafe impl Sync for Host {}
  60. /// Host objects the title let go of while a submission may still use them
  61. /// (a texture its descriptors name, a descriptor slot's old resource), by
  62. /// the submission count they wait for. The title's descriptor writes and
  63. /// releases reach the host at once, from its own threads, while the host
  64. /// runs a submission: freeing there is a GPU page fault on the freed
  65. /// texture (a device hang).
  66. static RETIRED: Mutex<Vec<(u64, Retired)>> = Mutex::new(Vec::new());
  67. /// Submissions started and finished (waited for).
  68. static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  69. static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  70. /// A retired object, dropped on whatever thread finishes the submission.
  71. struct Retired(#[allow(dead_code)] Box<dyn std::any::Any>);
  72. // SAFETY: what is retired is D3D12 objects (free-threaded) and the
  73. // reference-counted wrappers holding them, dropped once.
  74. unsafe impl Send for Retired {}
  75. /// Milliseconds since the first call.
  76. pub(crate) fn now_ms() -> u64 {
  77. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  78. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  79. }
  80. /// This moment, for telling later how long ago it was ([`long_ago`]): the
  81. /// frames begun so far (high half, `crate::frame::current`) and tenths of a
  82. /// second since the start. Host copies of title memory, staging buffers and
  83. /// host textures note when they were last used with it.
  84. pub(crate) fn moment() -> u64 {
  85. (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff)
  86. }
  87. /// Whether `moment` lies at least `ms` milliseconds and `frames` frames
  88. /// back. Both: at seconds per frame, what every frame uses is not touched
  89. /// for seconds, and at many frames per second not for many frames. (A title
  90. /// that never waits for frames has no frame count: nothing is then idle.)
  91. pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
  92. let now = self::moment();
  93. let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
  94. (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
  95. }
  96. /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
  97. pub(crate) fn available_physical_ram() -> Option<u64> {
  98. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  99. // SAFETY: plain data the call fills in.
  100. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  101. m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
  102. // SAFETY: a sized structure.
  103. let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
  104. ok.then_some(m.ullAvailPhys)
  105. }
  106. /// How long host copies of textures the title fills must have been idle to
  107. /// be let go, in milliseconds, and how many bytes of them go at most (the
  108. /// longest idle first): none but those of ten minutes while what is in use
  109. /// of the card (`used`: without what our own blocks have free, with what is
  110. /// kept free for others) is under 88 % of its budget, else enough to come
  111. /// down to 85 %. `VICTORY_TEXTURE_KEEP=0`: [`vram_idle_ms`]' older rule,
  112. /// all that are idle; `=1`: that rule with its two longer times.
  113. ///
  114. /// (By those times everything idle for 2.5 s went from 75 % of the budget
  115. /// on: 61,000 of them in the first 300 s of session play-1125-0203, at 78 to
  116. /// 80 %, of which 13,000 were made and uploaded again.)
  117. pub(crate) fn vram_keep(budget: u64, used: u64) -> (u64, u64) {
  118. const KEPT_MS: u64 = 600_000;
  119. const IDLE_MS: u64 = 5_000;
  120. const SHORT_MS: u64 = 1_500;
  121. if budget == 0 {
  122. return (IDLE_MS, u64::MAX);
  123. }
  124. let share = |percent: u64| budget / 100 * percent;
  125. if used < share(88) {
  126. (KEPT_MS, u64::MAX)
  127. } else if used < share(95) {
  128. (IDLE_MS, used - share(85))
  129. } else {
  130. (SHORT_MS, used - share(85))
  131. }
  132. }
  133. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  134. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  135. /// handles not yet recorded into a list or slot remain protected.
  136. ///
  137. /// With room on the card nothing has to go: in session play-1125-0127 88,000
  138. /// of them (31 GB) went after 5 s with 7 GB of the card free, and 24,700
  139. /// (12 GB) had to be made and uploaded again.
  140. /// `VICTORY_TEXTURE_KEEP=0`: 5 s there too, as before.
  141. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  142. static KEEP: OnceLock<bool> = OnceLock::new();
  143. let keep = *KEEP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_KEEP").is_none_or(|v| v != "0"));
  144. vram_idle_for(video_memory, keep)
  145. }
  146. fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 {
  147. const KEPT_MS: u64 = 600_000;
  148. const LONG_MS: u64 = 30_000;
  149. const NORMAL_MS: u64 = 5_000;
  150. const MODERATE_MS: u64 = 2_500;
  151. const HIGH_MS: u64 = 1_000;
  152. let Some([budget, used, ..]) = video_memory else {
  153. return NORMAL_MS;
  154. };
  155. if budget == 0 {
  156. return NORMAL_MS;
  157. }
  158. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  159. if used_pct >= 85 {
  160. HIGH_MS
  161. } else if used_pct >= 75 {
  162. MODERATE_MS
  163. } else if !keep {
  164. NORMAL_MS
  165. } else if used_pct >= 68 {
  166. LONG_MS
  167. } else {
  168. KEPT_MS
  169. }
  170. }
  171. /// Whether memory the card was given stays with it while there is room (on
  172. /// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader
  173. /// that reads past a view (a raw load through a typed, structured or
  174. /// constant buffer view has no end on AMD: `indirect::tests::raw_loads_past_views`)
  175. /// or through a slot that shows wrong data reads whatever lies there, and
  176. /// nothing happens; where memory was given back it is a page fault, and the
  177. /// device is lost. Both losses of 2026-11-25 were reads in memory given back
  178. /// seconds before (a block of textures; a list's scratch and a window of
  179. /// title memory). Kept are: empty blocks of textures ([`crate::pool`]) below
  180. /// 85 % of the card's budget, windows of title memory and staging buffers
  181. /// for five minutes with 12 GiB of the PC's memory free, and 1 GiB of
  182. /// scratch chunks.
  183. pub(crate) fn keep_freed() -> bool {
  184. static ON: OnceLock<bool> = OnceLock::new();
  185. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_FREED").is_none_or(|v| v != "0"))
  186. }
  187. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  188. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  189. /// when free physical RAM is low. Never returns less than 2,000 ms.
  190. /// With plenty of it five minutes ([`keep_freed`]).
  191. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  192. ram_idle_for(avail_phys, keep_freed())
  193. }
  194. fn ram_idle_for(avail_phys: Option<u64>, keep: bool) -> u64 {
  195. const GIB: u64 = 1024 * 1024 * 1024;
  196. const KEPT_MS: u64 = 300_000;
  197. if keep && avail_phys.is_some_and(|avail| avail >= 12 * GIB) {
  198. return KEPT_MS;
  199. }
  200. const NORMAL_MS: u64 = 10_000;
  201. const MODERATE_MS: u64 = 5_000;
  202. const HIGH_MS: u64 = 2_000;
  203. let Some(avail) = avail_phys else {
  204. return NORMAL_MS;
  205. };
  206. if avail < 2 * GIB {
  207. HIGH_MS
  208. } else if avail < 4 * GIB {
  209. MODERATE_MS
  210. } else {
  211. NORMAL_MS
  212. }
  213. }
  214. /// How many references are held on a host object (its COM count): ours
  215. /// all, since the host's views and commands hold none. A buffer or texture
  216. /// with one is held by its owner alone: no descriptor slot keeps it
  217. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  218. pub(crate) fn references(object: &impl Interface) -> u32 {
  219. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  220. let raw = object.as_raw();
  221. // SAFETY: a live COM object, whose first three methods are those of
  222. // `IUnknown` (query, add a reference, release one); the pair leaves the
  223. // count as it was, and the release returns it. The first is not called.
  224. unsafe {
  225. let methods = *raw.cast::<*const [Method; 3]>();
  226. ((*methods)[1])(raw);
  227. ((*methods)[2])(raw)
  228. }
  229. }
  230. /// Once a second, before a submission starts: lets go of what nothing
  231. /// names any more (copies of windows of title memory, staging buffers,
  232. /// host copies of textures the title fills).
  233. /// `VICTORY_SWEEP=0` keeps everything, as before.
  234. fn sweep() {
  235. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  236. crate::inplace::tick();
  237. static ON: OnceLock<bool> = OnceLock::new();
  238. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  239. return;
  240. }
  241. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  242. let now = now_ms();
  243. let last = LAST.load(Ordering::Relaxed);
  244. if now < last + 1000
  245. || LAST
  246. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  247. .is_err()
  248. {
  249. return;
  250. }
  251. crate::pool::room(host().and_then(|h| h.video_memory()));
  252. crate::pipeline::trim_library();
  253. crate::shadow::let_go_idle();
  254. crate::texture::let_go_idle();
  255. crate::resource::let_go_idle();
  256. }
  257. /// The number of the newest submission begun, and of the newest of which all
  258. /// before it have finished too.
  259. pub(crate) fn submissions() -> (u64, u64) {
  260. (STARTED.load(Ordering::Acquire), FINISHED.load(Ordering::Acquire))
  261. }
  262. /// Drops `object` once every submission running now has finished: at once
  263. /// if none is.
  264. pub(crate) fn retire<T: 'static>(object: T) {
  265. let started = STARTED.load(Ordering::Acquire);
  266. if started <= FINISHED.load(Ordering::Acquire) {
  267. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  268. drop(object);
  269. return;
  270. }
  271. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  272. RETIRED
  273. .lock()
  274. .unwrap_or_else(|e| e.into_inner())
  275. .push((started, Retired(Box::new(object))));
  276. }
  277. /// Drops what waited for submissions up to `finished`.
  278. fn bury(finished: u64) {
  279. let done: Vec<(u64, Retired)> = {
  280. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  281. if retired.is_empty() {
  282. return;
  283. }
  284. let (done, keep) = std::mem::take(&mut *retired)
  285. .into_iter()
  286. .partition(|(at, _)| *at <= finished);
  287. *retired = keep;
  288. done
  289. };
  290. drop(done);
  291. }
  292. /// Objects [`retire`] dropped at once (no submission was running) and
  293. /// kept until a running submission finished, since the start.
  294. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  295. /// What the layer did to the host's objects lately, newest last (sweeps
  296. /// that let host copies go, pipeline library calls, saves and trims): said
  297. /// once when the host device is removed ([`log_removal_context`]), with
  298. /// what the submitting thread and the pipeline workers were doing at that
  299. /// moment. A device the driver removes "internally" names no command, and
  300. /// the pass that happens to notice first names only the view it was at:
  301. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  302. /// pipeline library call that no line of the log tied to them.
  303. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  304. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  305. /// The entries kept.
  306. const TRAIL_MOST: usize = 96;
  307. fn trail_on() -> bool {
  308. static ON: OnceLock<bool> = OnceLock::new();
  309. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  310. }
  311. /// Microseconds since the first call.
  312. pub(crate) fn now_us() -> u64 {
  313. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  314. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  315. }
  316. /// The calling thread, as the log's other lines name threads.
  317. pub(crate) fn thread_id() -> u32 {
  318. // SAFETY: a plain query.
  319. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  320. }
  321. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  322. /// run when the trail is kept.
  323. pub(crate) fn trail(what: impl FnOnce() -> String) {
  324. if !trail_on() {
  325. return;
  326. }
  327. let entry = (now_us(), thread_id(), what());
  328. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  329. if trail.len() >= TRAIL_MOST {
  330. trail.pop_front();
  331. }
  332. trail.push_back(entry);
  333. }
  334. /// What the submitting thread is doing (0 nothing: between submissions,
  335. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  336. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  337. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  338. fn submitting(phase: u64, lists: usize) {
  339. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  340. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  341. SUBMITTING[0].store(phase, Ordering::Relaxed);
  342. }
  343. /// What was going on when the host device went: whether a submission was
  344. /// on the card, the pipeline library's state and the calls running in it,
  345. /// and the trail.
  346. pub(crate) fn removal_context() -> String {
  347. use std::fmt::Write;
  348. let now = now_us();
  349. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  350. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  351. 0 => "between submissions (nothing of ours was running on the card)",
  352. 1 => "preparing a submission (nothing of ours was running on the card)",
  353. 2 => "waiting for the card to run a submission",
  354. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  355. };
  356. let mut text = format!(
  357. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  358. SUBMITTING[1].load(Ordering::Relaxed),
  359. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  360. crate::pipeline::library_removal_note(),
  361. RETIREMENTS[0].load(Ordering::Relaxed),
  362. RETIREMENTS[1].load(Ordering::Relaxed),
  363. STARTED.load(Ordering::Relaxed),
  364. FINISHED.load(Ordering::Relaxed),
  365. );
  366. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  367. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  368. for (at, thread, what) in trail.iter() {
  369. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  370. }
  371. text
  372. }
  373. /// Says [`removal_context`] in the log, once: called by whoever finds the
  374. /// host device removed.
  375. pub(crate) fn log_removal_context() {
  376. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  377. if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) {
  378. return;
  379. }
  380. tracing::error!("when the host device went: {}", removal_context());
  381. if dred_any() {
  382. let data = host().map(|h| h.removal_data(&[])).unwrap_or_default();
  383. tracing::error!("device-removed data{}", if data.is_empty() { "; none" } else { &data });
  384. }
  385. }
  386. /// Time spent in submissions since the last frame-rate line, in
  387. /// microseconds: preparing them on the CPU (title memory copies, texture
  388. /// detiling), then waiting for the GPU.
  389. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  390. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  391. /// After submissions: shader-written ranges compared and copied back into
  392. /// title memory (microseconds, bytes that differed), since the last
  393. /// frame-rate line.
  394. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  395. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  396. /// The card's clock, for the frame line of every run, in microseconds since
  397. /// the last one: how long the card had nothing of ours queued; how much of
  398. /// that while the thread that holds the submission lock was working (the
  399. /// card idle behind us: preparing and copying back are done with the card
  400. /// standing); and how long that thread stood waiting for the card.
  401. ///
  402. /// Every send of lists to the queue is followed by a signal on a fence of
  403. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  404. /// the newest signal and notes the moment the card reached it with nothing
  405. /// newer sent; the next send ends that idle stretch.
  406. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  407. /// Of the thread that holds the submission lock: the microseconds it has
  408. /// worked so far (preparing, copying back; not its waits for the card), and
  409. /// since when it works now ([`now_us`] plus one; 0: it does not).
  410. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  411. /// The thread that holds the submission lock starts (`on`) or stops
  412. /// working; whether it worked until now.
  413. fn working(on: bool) -> bool {
  414. let now = now_us() + 1;
  415. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  416. if since != 0 {
  417. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  418. }
  419. since != 0
  420. }
  421. /// [`WORKING`] as of now: microseconds worked so far.
  422. fn worked() -> u64 {
  423. let since = WORKING[1].load(Ordering::Relaxed);
  424. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  425. WORKING[0].load(Ordering::Relaxed) + now
  426. }
  427. /// The thread that holds the submission lock stood waiting for the card
  428. /// from `since` until now ([`CARD_CLOCK_US`]).
  429. fn stood(since: std::time::Instant) {
  430. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  431. }
  432. /// What [`CARD_CLOCK_US`] is measured with.
  433. struct CardClock {
  434. fence: ID3D12Fence,
  435. /// Signals sent so far; and, while the card has reached the last of
  436. /// them, since when and what [`worked`] said then.
  437. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  438. sent: std::sync::Condvar,
  439. }
  440. // SAFETY: a fence (free-threaded) behind a lock.
  441. unsafe impl Send for CardClock {}
  442. // SAFETY: as above.
  443. unsafe impl Sync for CardClock {}
  444. /// The clock's thread: waits for the newest signal sent and notes when the
  445. /// card got there with nothing newer behind it.
  446. fn card_clock_watch(clock: &'static CardClock) {
  447. // SAFETY: a plain event of our own.
  448. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  449. return;
  450. };
  451. let mut seen = 0;
  452. loop {
  453. let target = {
  454. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  455. while state.0 == seen {
  456. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  457. }
  458. state.0
  459. };
  460. // SAFETY: the clock's fence and this thread's event.
  461. unsafe {
  462. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  463. WaitForSingleObject(event, INFINITE);
  464. }
  465. }
  466. seen = target;
  467. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  468. if state.0 == target && state.1.is_none() {
  469. state.1 = Some((std::time::Instant::now(), worked()));
  470. }
  471. }
  472. }
  473. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  474. /// frame's time.
  475. fn card_clock_line(frames: f64, ms: f64) {
  476. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  477. tracing::info!(
  478. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  479. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  480. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  481. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  482. );
  483. }
  484. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  485. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  486. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  487. std::sync::atomic::AtomicU64::new(0),
  488. std::sync::atomic::AtomicU64::new(0),
  489. std::sync::atomic::AtomicU64::new(0),
  490. std::sync::atomic::AtomicU64::new(0),
  491. ];
  492. /// Host buffers made since the start, as (count, bytes): in the upload heap
  493. /// (staging, list scratch), shared with the processor (host copies of title
  494. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  495. /// For the memory line: against what is alive, they show what was let go.
  496. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  497. /// What of that is alive now, for the memory line (`MADE` counts what was
  498. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  499. /// and nothing said how many were alive): host lists; the lists' scratch
  500. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  501. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  502. /// instead of made, since the start; and the lists' other upload buffers
  503. /// (texture data copied from buffers, scratch too big for a chunk) and
  504. /// their bytes.
  505. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  506. /// About host lists, for the memory line: lists made by the host since the
  507. /// start; preludes made (a list's second allocator and list, made when it
  508. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  509. /// bytes the process's private memory grew by while lists were being made
  510. /// (what a list costs: host objects with the driver's command memory; 631
  511. /// lists were alive in run 65, each with a prelude it may never use).
  512. /// Then the lists alive that were never reset since they were made: the
  513. /// host sides of title lists the title made and has not used (a host list
  514. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  515. /// makes at its start).
  516. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  517. /// The process's private bytes (diagnostics: around the making of lists).
  518. #[cfg(feature = "diagnostics")]
  519. fn private_bytes() -> u64 {
  520. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  521. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  522. let mut c = PROCESS_MEMORY_COUNTERS {
  523. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  524. ..Default::default()
  525. };
  526. // SAFETY: our own process and a sized structure.
  527. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  528. c.PagefileUsage as u64
  529. }
  530. /// What the runtime does when the host GPU fails for good: report it like a
  531. /// crash and end the run. The console has no such state, and carrying on
  532. /// draws nothing at seconds per frame.
  533. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  534. /// Sets what a host GPU failure does (the runtime's crash report).
  535. pub fn on_failure(report: fn(&str) -> !) {
  536. let _ = ON_FAILURE.set(report);
  537. }
  538. /// Ends the run on a host GPU failure: what failed, the removal reason and
  539. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  540. /// diagnostics build names the command).
  541. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  542. let mut text = what.to_string();
  543. if let Some(host) = host() {
  544. // SAFETY: a plain query.
  545. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  546. text.push_str(&format!("; device removed: {e}"));
  547. log_removal_context();
  548. }
  549. match host.log_messages() {
  550. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  551. None if host.messages.is_none() => text.push_str(
  552. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  553. ),
  554. None => {}
  555. }
  556. }
  557. tracing::error!("{text}");
  558. // Tests have no log: the reason goes to their output.
  559. #[cfg(test)]
  560. eprintln!("host GPU failure: {text}");
  561. match ON_FAILURE.get() {
  562. Some(report) => report(&text),
  563. None => std::process::abort(),
  564. }
  565. }
  566. /// The host GPU, created on first use; `None` without one (a run then
  567. /// behaves as before: nothing executes).
  568. pub(crate) fn host() -> Option<&'static Host> {
  569. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  570. HOST.get_or_init(|| match create() {
  571. Ok(host) => Some(host),
  572. Err(e) => {
  573. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  574. None
  575. }
  576. })
  577. .as_ref()
  578. }
  579. fn create() -> windows::core::Result<Host> {
  580. // SAFETY: plain D3D12 object creation with valid descriptions.
  581. unsafe {
  582. // The debug layer only in builds with diagnostics.
  583. let debug = cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DEBUG");
  584. if debug {
  585. let mut layer: Option<ID3D12Debug> = None;
  586. match D3D12GetDebugInterface(&mut layer) {
  587. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  588. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  589. }
  590. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  591. // descriptor heap indices and the like become messages naming
  592. // the command instead of page faults. Without state tracking
  593. // (directly indexed textures are not transitioned).
  594. if crate::switch::on("VICTORY_D3D12_GBV")
  595. && let Some(l) = &layer
  596. {
  597. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  598. d1.SetEnableGPUBasedValidation(true);
  599. }
  600. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  601. d2.SetGPUBasedValidationFlags(
  602. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  603. );
  604. }
  605. tracing::info!("GPU-based validation on");
  606. }
  607. }
  608. // Diagnostics: device-removed data (the command that faulted, the
  609. // faulting address), read when the device is removed.
  610. if dred_any() {
  611. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  612. if D3D12GetDebugInterface(&mut dred).is_ok()
  613. && let Some(dred) = dred
  614. {
  615. if dred_on() || dred_light() {
  616. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  617. }
  618. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  619. tracing::info!(
  620. breadcrumbs = dred_on() || dred_light(),
  621. markers = dred_on(),
  622. "crash tracing on (device-removed data)"
  623. );
  624. } else {
  625. tracing::warn!("crash tracing asked for and not there: no device-removed data settings");
  626. }
  627. }
  628. let mut device: Option<ID3D12Device> = None;
  629. // Diagnostics: the software adapter, on which a shader's wild access
  630. // is an access violation in this process (a crash report with the
  631. // address and instruction) instead of a GPU fault and driver reset.
  632. if cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_WARP") {
  633. let adapter = warp_adapter()?;
  634. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  635. tracing::info!("host device on the software adapter (WARP)");
  636. } else {
  637. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  638. // Whether a GPU hang ends the run or freezes the PC (#1054).
  639. crate::tdr::log();
  640. }
  641. let device = device.ok_or_else(windows::core::Error::empty)?;
  642. // Before anything is made with it (`VICTORY_RECORD`).
  643. #[cfg(feature = "diagnostics")]
  644. crate::replay::record::from_env(&device);
  645. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  646. // driver compiling shaders again on the "D3D Background Thread"s,
  647. // for minutes after pipelines were made or loaded) is switched off.
  648. // An experiment: while those threads ran, the same shot took
  649. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  650. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  651. // whether the card is slower with the shaders it then keeps is not
  652. // known.
  653. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  654. && let Ok(device6) = device.cast::<ID3D12Device6>()
  655. {
  656. let set = device6.SetBackgroundProcessingMode(
  657. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  658. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  659. None,
  660. None,
  661. );
  662. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  663. }
  664. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  665. // cross-lane code stays in 32-lane halves translated for waves of 32
  666. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  667. if device
  668. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  669. .is_ok()
  670. {
  671. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  672. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  673. }
  674. let messages = debug
  675. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  676. .flatten();
  677. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  678. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  679. ..Default::default()
  680. })?;
  681. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  682. let event = CreateEventW(None, false, false, None)?;
  683. let rtvs: ID3D12DescriptorHeap =
  684. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  685. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  686. NumDescriptors: RTV_RING,
  687. ..Default::default()
  688. })?;
  689. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  690. let dsvs: ID3D12DescriptorHeap =
  691. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  692. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  693. NumDescriptors: RTV_RING,
  694. ..Default::default()
  695. })?;
  696. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  697. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  698. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  699. .ok();
  700. tracing::info!("host D3D12 device ready");
  701. Ok(Host {
  702. device,
  703. queue,
  704. fence,
  705. submitted: Mutex::new(0),
  706. event,
  707. rtvs,
  708. rtv_size,
  709. dsvs,
  710. dsv_size,
  711. next_dsv: AtomicU32::new(0),
  712. messages,
  713. next_rtv: AtomicU32::new(0),
  714. presenter: Mutex::new(None),
  715. adapter,
  716. })
  717. }
  718. }
  719. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  720. /// Reject it before creating a device in diagnostics' software-only mode.
  721. pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  722. // SAFETY: plain DXGI adapter queries.
  723. unsafe {
  724. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  725. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  726. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  727. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  728. tracing::warn!(
  729. vendor = format_args!("{:#x}", desc.VendorId),
  730. flags = format_args!("{:#x}", desc.Flags),
  731. "DXGI did not identify the WARP adapter as software; refusing device"
  732. );
  733. return Err(windows::core::Error::from_hresult(
  734. windows::Win32::Foundation::E_FAIL,
  735. ));
  736. }
  737. Ok(adapter)
  738. }
  739. }
  740. #[cfg(test)]
  741. mod tests {
  742. /// A list of ours is found by its name, with the debug layer's note or not.
  743. #[cfg(feature = "diagnostics")]
  744. #[test]
  745. fn a_list_is_found_by_the_number_in_its_name() {
  746. assert_eq!(super::list_number("victory host list 7"), Some(7));
  747. assert_eq!(super::list_number("victory host list 158 (debug layer indirect)"), Some(158));
  748. assert_eq!(super::list_number("victory host list 7x"), None);
  749. assert_eq!(super::list_number("victory host list 7 x"), None);
  750. assert_eq!(super::list_number("another list 7"), None);
  751. assert_eq!(super::list_number(""), None);
  752. }
  753. /// What is there of a range some of whose pages are not: those bytes,
  754. /// counted, and zeros for the rest, whatever the buffer held.
  755. #[test]
  756. fn what_is_there_is_read_and_the_rest_is_zeros() {
  757. use windows_sys::Win32::System::Memory::*;
  758. const SIZE: usize = 0x8_0000;
  759. // SAFETY: a reservation of ours; only committed pages are written.
  760. unsafe {
  761. let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  762. assert!(!at.is_null());
  763. // 0-0x1_1000 and 0x3_0000-0x4_0000 are there.
  764. for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] {
  765. assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null());
  766. at.add(from).write_bytes(0x5a, len);
  767. }
  768. // From an address inside a page, as textures are packed.
  769. let mut out = vec![0x77u8; SIZE - 0x300];
  770. assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000);
  771. for (i, &b) in out.iter().enumerate() {
  772. let from = i + 0x300;
  773. let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from);
  774. assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}");
  775. }
  776. // All there: one read.
  777. let mut out = vec![0x77u8; 0x1_0000];
  778. assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000);
  779. assert!(out.iter().all(|&b| b == 0x5a));
  780. // Nothing there.
  781. let mut out = vec![0x77u8; 0x1_0000];
  782. assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0);
  783. assert!(out.iter().all(|&b| b == 0));
  784. assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0);
  785. }
  786. }
  787. /// Zeros for a title destination that went meanwhile are no fault.
  788. #[test]
  789. fn zeros_where_nothing_is_are_lost() {
  790. use windows_sys::Win32::System::Memory::*;
  791. // SAFETY: a reservation of ours, its first page committed.
  792. unsafe {
  793. let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  794. assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
  795. at.write_bytes(7, 4096);
  796. super::zero(at, 4096);
  797. assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
  798. super::zero(at.add(4096), 4096);
  799. VirtualFree(at.cast(), 0, MEM_RELEASE);
  800. }
  801. }
  802. #[test]
  803. fn sparse_copies_preserve_islands_and_observe_remaps() {
  804. use windows_sys::Win32::System::Memory::*;
  805. const N: usize = 5 << 16;
  806. // SAFETY: we reserve a private region, commit selected pages inside it,
  807. // and only directly access the pages while they are writable.
  808. unsafe {
  809. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  810. assert!(!base.is_null());
  811. let mut expected = vec![0; N];
  812. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  813. let at = base.add(offset);
  814. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  815. at.write_bytes(value, 4096);
  816. expected[offset..offset + 4096].fill(value);
  817. }
  818. for remap in [false, true] {
  819. if remap {
  820. let mut old = 0;
  821. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  822. expected[..4096].fill(0);
  823. let at = base.add(1 << 16);
  824. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  825. at.write_bytes(0xc7, 4096);
  826. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  827. }
  828. let mut out = vec![0xee; N];
  829. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  830. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  831. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  832. }
  833. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  834. }
  835. }
  836. use super::*;
  837. #[test]
  838. fn warp_adapter_accepts_only_software() {
  839. // This probes DXGI without creating a D3D12 device or running a title.
  840. // SAFETY: plain DXGI adapter queries.
  841. let raw = unsafe {
  842. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  843. else {
  844. return;
  845. };
  846. factory.EnumWarpAdapter::<IDXGIAdapter>()
  847. };
  848. let Ok(raw) = raw else { return };
  849. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  850. // IDXGIAdapter1; `raw` owns that interface.
  851. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  852. eprintln!(
  853. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  854. desc.VendorId, desc.Flags
  855. );
  856. assert_eq!(
  857. warp_adapter().is_ok(),
  858. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  859. );
  860. }
  861. }
  862. /// The batches of clamped records in one scratch buffer
  863. /// ([`HostList::batch_place`]).
  864. const BATCHES: u32 = 8;
  865. /// A host command list and its allocator, always used together.
  866. pub(crate) struct HostList {
  867. allocator: ID3D12CommandAllocator,
  868. pub(crate) list: ID3D12GraphicsCommandList,
  869. /// Work for submission time, in recorded order.
  870. deferred: Mutex<Deferred>,
  871. /// Upload memory for data the list's draws make (expanded vertices),
  872. /// reused after a reset.
  873. scratch: Mutex<Scratch>,
  874. /// Host texture states the list assumes, by host copy: at its start and
  875. /// at its end. Lists are recorded on many threads and run in submission
  876. /// order, so the transitions from a texture's real state are made at
  877. /// submission, in `prelude`. Holding the copies keeps every texture the
  878. /// list names alive until it is reset, even if the title releases the
  879. /// resource first.
  880. states: Mutex<States>,
  881. /// What the list does with depth textures that have a colour twin, by
  882. /// twin ([`TwinUse`]).
  883. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  884. /// The list that runs those transitions just before this one, made
  885. /// when the list first has such transitions ([`lazy_prelude`]).
  886. prelude: OnceLock<Option<Prelude>>,
  887. /// The pipelines the list binds, for reports of slow submissions.
  888. pipelines: std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>,
  889. /// What its indirect executions ran, for the report of a removed device.
  890. #[cfg(feature = "diagnostics")]
  891. indirects: indirects::Shared,
  892. /// The work its indirect executions may still do (`indirect`): a
  893. /// shader-writable word, zeroed when the list is submitted, and after
  894. /// it what the clamp notes about mesh records. In memory the CPU maps.
  895. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  896. /// The same words in the card's own memory ([`card_budget`]), which the
  897. /// clamp uses instead when there is one: zeroed in the list before its
  898. /// first clamp, its notes copied to `budget` when the list closes.
  899. card_budget: OnceLock<Option<ID3D12Resource>>,
  900. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  901. /// grown to the largest indirect execution recorded on the list.
  902. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  903. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  904. /// how many batches of this recording have a place in them.
  905. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  906. /// Counts the list in [`ALIVE`] while it lives.
  907. _alive: Counted,
  908. /// The texts of the markers `note_op` set, in order (for device-removed
  909. /// data without marker texts), with the host GPU range a copy reads.
  910. #[cfg(feature = "diagnostics")]
  911. notes: std::sync::Arc<Mutex<Vec<Note>>>,
  912. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  913. /// and at the end, and where they are read back.
  914. #[cfg(feature = "diagnostics")]
  915. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  916. }
  917. /// A list's prelude: an allocator and a closed list.
  918. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  919. /// Whether a host list's prelude is made when the list first needs one. A
  920. /// prelude runs the texture transitions and twin copies a list needs before
  921. /// it; lists that name no texture never have one, and every host list was
  922. /// made with one all the same: twice the host objects per list, for the
  923. /// title's 630 lists and for every list made anew.
  924. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  925. fn lazy_prelude() -> bool {
  926. static ON: OnceLock<bool> = OnceLock::new();
  927. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  928. }
  929. /// Timestamps per list (diagnostics); commands past them are not timed.
  930. #[cfg(feature = "diagnostics")]
  931. const STAMPS: u32 = 4096;
  932. /// A marker's text and the host range its command reads (diagnostics).
  933. #[cfg(feature = "diagnostics")]
  934. type Note = (String, Option<(u64, u64)>);
  935. type States = std::collections::HashMap<
  936. usize,
  937. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  938. >;
  939. /// What a list does with a depth texture that has a colour twin
  940. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  941. /// in submission order, so a list cannot know which side an earlier list
  942. /// leaves behind: it notes which sides it uses as it finds them, and its
  943. /// prelude copies one side into the other at submission if that side is
  944. /// behind then. From its first use of a side on, the list knows.
  945. struct TwinUse {
  946. /// The depth texture (the title resource's host copy) and its twin.
  947. depth: std::sync::Arc<crate::resource::HostTexture>,
  948. twin: std::sync::Arc<crate::resource::Twin>,
  949. /// The sides (depth texture, twin) the list uses as it finds them.
  950. needs: [bool; 2],
  951. /// Whether each side lacks what the other was written last, where the
  952. /// list is now; `None`: as the list found it.
  953. behind: [Option<bool>; 2],
  954. /// The draw or dispatch being prepared writes the twin.
  955. writing: bool,
  956. /// The depth plane's twin holds what the plane lacks although the list
  957. /// copied the twins since: the plane's pass waits for the list's close.
  958. late: bool,
  959. }
  960. /// The pass that draws the twin of a depth plane into the plane: one
  961. /// triangle over each mip of each slice, its pixel shader writing the
  962. /// twin's texel as the depth, with the depth test "always" and no stencil
  963. /// (the stencil plane is copied through a buffer and not touched here).
  964. ///
  965. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  966. /// the step times the float nearest 1/65535 (0x37800080). That is how
  967. /// The title's tiled lighting computes the depth of the
  968. /// rectangles it then draws with the test "equal", one class of materials
  969. /// a draw (all six of its vertex shaders multiply the class number by that
  970. /// constant), so the pass and the draw give the host the same float, and
  971. /// the host turns the same float into the same 24 bits. The step divided
  972. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  973. /// and lands in another 24-bit step for 127 of them (none under 385).
  974. const PLANE_CORNERS: &str = r#"
  975. float4 corner(uint i : SV_VertexID) : SV_Position {
  976. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  977. }
  978. "#;
  979. const PLANE_STEPS: &str = r#"
  980. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  981. Texture2DArray<uint> twin : register(t0);
  982. [RootSignature(RS)]
  983. float plane(float4 p : SV_Position) : SV_Depth {
  984. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  985. }
  986. "#;
  987. const PLANE_FLOATS: &str = r#"
  988. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  989. Texture2DArray<float> twin : register(t0);
  990. [RootSignature(RS)]
  991. float plane(float4 p : SV_Position) : SV_Depth {
  992. return twin.Load(int4(int2(p.xy), 0, 0));
  993. }
  994. "#;
  995. /// Views of twins the pass reads, in a heap of ours used as a ring.
  996. /// shortcut: a view must last until its list has run; with one or two
  997. /// passes a frame the ring is far from coming round.
  998. const PLANE_VIEWS: u32 = 256;
  999. /// What the pass draws with: the heap of its views of twins, and per kind
  1000. /// of twin (16-bit steps or floats) and depth format the root signature
  1001. /// and pipeline, made when first needed (`None`: the host refused).
  1002. struct PlanePass {
  1003. views: ID3D12DescriptorHeap,
  1004. cpu: usize,
  1005. gpu: u64,
  1006. step: u32,
  1007. next: AtomicU32,
  1008. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  1009. }
  1010. /// The pass's root signature and pipeline for one kind of twin and one
  1011. /// depth format.
  1012. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  1013. // SAFETY: D3D12 objects are free-threaded.
  1014. unsafe impl Send for PlanePass {}
  1015. // SAFETY: as above.
  1016. unsafe impl Sync for PlanePass {}
  1017. fn plane_pass() -> Option<&'static PlanePass> {
  1018. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  1019. PASS.get_or_init(|| {
  1020. let host = host()?;
  1021. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1022. // SAFETY: plain heap creation and queries.
  1023. unsafe {
  1024. let views: ID3D12DescriptorHeap = host
  1025. .device
  1026. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  1027. Type: kind,
  1028. NumDescriptors: PLANE_VIEWS,
  1029. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  1030. NodeMask: 0,
  1031. })
  1032. .ok()?;
  1033. Some(PlanePass {
  1034. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  1035. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  1036. step: host.device.GetDescriptorHandleIncrementSize(kind),
  1037. views,
  1038. next: AtomicU32::new(0),
  1039. made: Mutex::default(),
  1040. })
  1041. }
  1042. })
  1043. .as_ref()
  1044. }
  1045. /// Compiles function `entry` of `source` for `target` with the system's
  1046. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  1047. pub(crate) fn compile(
  1048. source: &str,
  1049. entry: windows::core::PCSTR,
  1050. target: windows::core::PCSTR,
  1051. ) -> windows::core::Result<Vec<u8>> {
  1052. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  1053. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  1054. let mut code: Option<ID3DBlob> = None;
  1055. let mut errors: Option<ID3DBlob> = None;
  1056. // SAFETY: the source and names live through the call; out pointers ours.
  1057. let compiled = unsafe {
  1058. D3DCompile(
  1059. source.as_ptr().cast(),
  1060. source.len(),
  1061. windows::core::s!("victory"),
  1062. None,
  1063. None,
  1064. entry,
  1065. target,
  1066. 0,
  1067. 0,
  1068. &mut code,
  1069. Some(&mut errors),
  1070. )
  1071. };
  1072. if let Err(e) = compiled {
  1073. if let Some(errors) = errors {
  1074. // SAFETY: the blob's own bytes.
  1075. let text = unsafe {
  1076. std::slice::from_raw_parts(
  1077. errors.GetBufferPointer().cast::<u8>(),
  1078. errors.GetBufferSize(),
  1079. )
  1080. };
  1081. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  1082. }
  1083. return Err(e);
  1084. }
  1085. let code = code.ok_or_else(windows::core::Error::empty)?;
  1086. // SAFETY: the blob's own bytes.
  1087. let bytes = unsafe {
  1088. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  1089. };
  1090. Ok(bytes.to_vec())
  1091. }
  1092. impl PlanePass {
  1093. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  1094. /// or of floats and the depth format `format`.
  1095. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  1096. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1097. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  1098. return pipeline.clone();
  1099. }
  1100. let pipeline = match Self::make(steps, format) {
  1101. Ok(pipeline) => Some(pipeline),
  1102. Err(e) => {
  1103. tracing::warn!(
  1104. error = %e,
  1105. steps,
  1106. format = format.0,
  1107. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  1108. );
  1109. None
  1110. }
  1111. };
  1112. made.push((steps, format.0, pipeline.clone()));
  1113. pipeline
  1114. }
  1115. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  1116. use windows::core::s;
  1117. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  1118. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  1119. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  1120. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  1121. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  1122. pShaderBytecode: bytes.as_ptr().cast(),
  1123. BytecodeLength: bytes.len(),
  1124. };
  1125. // SAFETY: the root signature is inside the pixel shader; the
  1126. // description points at live data and never releases its pointer.
  1127. unsafe {
  1128. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  1129. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1130. pRootSignature: std::mem::transmute_copy(&root),
  1131. VS: code(&vs[..]),
  1132. PS: code(&ps[..]),
  1133. SampleMask: u32::MAX,
  1134. RasterizerState: D3D12_RASTERIZER_DESC {
  1135. FillMode: D3D12_FILL_MODE_SOLID,
  1136. CullMode: D3D12_CULL_MODE_NONE,
  1137. DepthClipEnable: true.into(),
  1138. ..Default::default()
  1139. },
  1140. // Every texel is written; stencil stays off.
  1141. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1142. DepthEnable: true.into(),
  1143. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  1144. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1145. ..Default::default()
  1146. },
  1147. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1148. DSVFormat: format,
  1149. SampleDesc: DXGI_SAMPLE_DESC {
  1150. Count: 1,
  1151. Quality: 0,
  1152. },
  1153. ..Default::default()
  1154. };
  1155. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1156. Ok((root, pipeline))
  1157. }
  1158. }
  1159. }
  1160. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1161. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1162. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1163. /// heap, graphics root signature, pipeline, depth target, viewport,
  1164. /// scissor and topology and puts none of them back: it is for a list that
  1165. /// records nothing of the title's after it.
  1166. fn record_plane_pass(
  1167. list: &ID3D12GraphicsCommandList,
  1168. depth: &ID3D12Resource,
  1169. plane: &ID3D12Resource,
  1170. ) {
  1171. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1172. return;
  1173. };
  1174. // SAFETY: live resources.
  1175. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1176. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1177. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1178. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1179. let steps = twin.Format.0 == 53;
  1180. let format = DXGI_FORMAT(match of.Format.0 {
  1181. 44 => 45,
  1182. 19 => 20,
  1183. typed => typed,
  1184. });
  1185. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1186. return;
  1187. };
  1188. for slice in 0..u32::from(of.DepthOrArraySize) {
  1189. for mip in 0..u32::from(of.MipLevels) {
  1190. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1191. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1192. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1193. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1194. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1195. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1196. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1197. MostDetailedMip: mip,
  1198. MipLevels: 1,
  1199. FirstArraySlice: slice,
  1200. ArraySize: 1,
  1201. ..Default::default()
  1202. },
  1203. },
  1204. };
  1205. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1206. Format: format,
  1207. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1208. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1209. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1210. MipSlice: mip,
  1211. FirstArraySlice: slice,
  1212. ArraySize: 1,
  1213. },
  1214. },
  1215. ..Default::default()
  1216. };
  1217. let target = host.dsv(depth, Some(&target));
  1218. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1219. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1220. ptr: pass.cpu + (slot * pass.step) as usize,
  1221. };
  1222. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1223. ptr: pass.gpu + u64::from(slot * pass.step),
  1224. };
  1225. // SAFETY: an open list; a slot of our heap; live resources and
  1226. // objects (the pass's own live as long as the process).
  1227. unsafe {
  1228. host.device
  1229. .CreateShaderResourceView(plane, Some(&view), cpu);
  1230. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1231. list.SetGraphicsRootSignature(&root);
  1232. list.SetPipelineState(&pipeline);
  1233. list.SetGraphicsRootDescriptorTable(0, gpu);
  1234. list.OMSetRenderTargets(0, None, false, Some(&target));
  1235. list.RSSetViewports(&[D3D12_VIEWPORT {
  1236. TopLeftX: 0.0,
  1237. TopLeftY: 0.0,
  1238. Width: width as f32,
  1239. Height: height as f32,
  1240. MinDepth: 0.0,
  1241. MaxDepth: 1.0,
  1242. }]);
  1243. list.RSSetScissorRects(&[RECT {
  1244. left: 0,
  1245. top: 0,
  1246. right: width as i32,
  1247. bottom: height as i32,
  1248. }]);
  1249. list.IASetPrimitiveTopology(
  1250. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1251. );
  1252. list.DrawInstanced(3, 1, 0, 0);
  1253. }
  1254. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1255. }
  1256. }
  1257. }
  1258. /// Records into `list` the copy of a depth texture into its colour twin
  1259. /// (`colour`) or of the twin into the depth texture, both already in their
  1260. /// copy states: whole textures of one size in one format family, which the
  1261. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1262. /// alone, through the twin's buffer.
  1263. fn record_twin_copy(
  1264. list: &ID3D12GraphicsCommandList,
  1265. depth: &ID3D12Resource,
  1266. twin: &crate::resource::Twin,
  1267. colour: bool,
  1268. ) {
  1269. let (from, to) = if colour {
  1270. (depth, &twin.colour.texture)
  1271. } else {
  1272. (&twin.colour.texture, depth)
  1273. };
  1274. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1275. // shortcut: the depth plane's twin is not given the plane (that is a
  1276. // pass the other way: the plane read by a shader, the twin as its
  1277. // target). The twin then lacks what draws and clears wrote to the
  1278. // plane since shaders last wrote the twin. In the title
  1279. // nothing writes that plane but the twin's pass (its 192 draws against
  1280. // it only test, run 29), so the twin lacks nothing. Counted.
  1281. if colour && twin.plane.is_some() {
  1282. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1283. }
  1284. let Some(through) = &twin.through else {
  1285. // SAFETY: an open list and two live textures.
  1286. unsafe { list.CopyResource(to, from) };
  1287. return;
  1288. };
  1289. // A stencil plane and its twin: each mip and slice of the plane goes
  1290. // into the buffer, laid out as the host lays the plane out for copies,
  1291. // and from the buffer into the other texture, whole subresources both
  1292. // times. In the depth texture the stencil plane's subresources follow
  1293. // the depth plane's; the twin has the one plane.
  1294. let Some(host) = host() else { return };
  1295. // SAFETY: a live texture.
  1296. let of = unsafe { depth.GetDesc() };
  1297. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1298. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1299. // SAFETY: a plain query writing `planes` footprints.
  1300. unsafe {
  1301. host.device.GetCopyableFootprints(
  1302. &of,
  1303. planes,
  1304. planes,
  1305. 0,
  1306. Some(rows.as_mut_ptr()),
  1307. None,
  1308. None,
  1309. None,
  1310. );
  1311. }
  1312. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1313. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1314. // SAFETY: a borrowed pointer the location never releases.
  1315. pResource: unsafe { std::mem::transmute_copy(texture) },
  1316. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1317. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1318. SubresourceIndex: index,
  1319. },
  1320. };
  1321. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1322. // SAFETY: as above.
  1323. pResource: unsafe { std::mem::transmute_copy(through) },
  1324. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1325. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1326. PlacedFootprint: *row,
  1327. },
  1328. };
  1329. let (common, source, dest) = (
  1330. D3D12_RESOURCE_STATE_COMMON,
  1331. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1332. D3D12_RESOURCE_STATE_COPY_DEST,
  1333. );
  1334. // SAFETY: an open list and live resources; the buffer was made as big
  1335. // as these footprints, and rests in the common state between copies.
  1336. unsafe {
  1337. list.ResourceBarrier(&[transition(through, common, dest)]);
  1338. for (i, row) in rows.iter().enumerate() {
  1339. let index = first_from + i as u32;
  1340. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1341. }
  1342. list.ResourceBarrier(&[transition(through, dest, source)]);
  1343. for (i, row) in rows.iter().enumerate() {
  1344. let index = first_to + i as u32;
  1345. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1346. }
  1347. list.ResourceBarrier(&[transition(through, source, common)]);
  1348. }
  1349. }
  1350. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1351. /// builds).
  1352. pub(crate) fn dred_on() -> bool {
  1353. static ON: OnceLock<bool> = OnceLock::new();
  1354. *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED") && !dred_faults() && !dred_light())
  1355. }
  1356. /// Breadcrumbs and the faulting address, but no markers and no texts
  1357. /// (`VICTORY_D3D12_DRED=light`): which list a removed device stopped in, at
  1358. /// which of its commands, and the pipelines the list binds; formatting a text
  1359. /// for every command is what makes the whole of it slow.
  1360. pub(crate) fn dred_light() -> bool {
  1361. static ON: OnceLock<bool> = OnceLock::new();
  1362. *ON.get_or_init(|| {
  1363. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "light")
  1364. })
  1365. }
  1366. /// Any of the three.
  1367. pub(crate) fn dred_any() -> bool {
  1368. dred_on() || dred_light() || dred_faults()
  1369. }
  1370. /// Whether only the faulting address of a removed device is kept
  1371. /// (`VICTORY_D3D12_DRED=faults`): no breadcrumbs, no markers and no texts, so
  1372. /// it costs next to nothing and can stay on while the title is played.
  1373. pub(crate) fn dred_faults() -> bool {
  1374. static ON: OnceLock<bool> = OnceLock::new();
  1375. *ON.get_or_init(|| {
  1376. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "faults")
  1377. })
  1378. }
  1379. /// The lists alive while device-removed data is on, by the number their name
  1380. /// ends in, with their marker texts and the pipelines they bind: a report made
  1381. /// on another thread than the one that submits has no lists of its own.
  1382. #[cfg(feature = "diagnostics")]
  1383. #[allow(clippy::type_complexity)]
  1384. static LIST_NOTES: Mutex<
  1385. std::collections::BTreeMap<
  1386. u32,
  1387. (
  1388. std::sync::Weak<Mutex<Vec<Note>>>,
  1389. std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>,
  1390. std::sync::Weak<Mutex<indirects::Indirects>>,
  1391. ),
  1392. >,
  1393. > = Mutex::new(std::collections::BTreeMap::new());
  1394. /// The number in the name of a list of ours ("victory host list 7", which the
  1395. /// debug layer ends with a note of its own in brackets).
  1396. #[cfg(feature = "diagnostics")]
  1397. fn list_number(name: &str) -> Option<u32> {
  1398. let rest = name.strip_prefix("victory host list ")?;
  1399. let digits = rest.split(' ').next()?;
  1400. (rest.len() == digits.len() || rest[digits.len()..].starts_with(" (")).then(|| digits.parse().ok()).flatten()
  1401. }
  1402. /// Indirect mesh dispatches since the last frame line: the largest group
  1403. /// count a record asked for, and the groups asked in all (from the lists'
  1404. /// budget buffers, a run late).
  1405. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1406. /// Whether a list's indirect-work budget lives in the card's own memory
  1407. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1408. /// before). The clamp charges it with atomics, at least two in a row for
  1409. /// every clamp; in mapped memory on a card of its own each of them
  1410. /// crosses the bus.
  1411. fn card_budget() -> bool {
  1412. static ON: OnceLock<bool> = OnceLock::new();
  1413. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1414. }
  1415. /// Whether each list of a submission runs and is timed on its own, slow
  1416. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1417. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1418. #[cfg(feature = "diagnostics")]
  1419. fn timing() -> bool {
  1420. static ON: OnceLock<bool> = OnceLock::new();
  1421. *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING"))
  1422. }
  1423. /// Names a host object for the device-removed report, which names the
  1424. /// allocations a page fault hit (only with device-removed data on), or for
  1425. /// the frame recorder (`VICTORY_RECORD`).
  1426. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1427. #[cfg(feature = "diagnostics")]
  1428. if crate::replay::record::on() {
  1429. let text = text();
  1430. crate::replay::record::name(object, &text);
  1431. if dred_any()
  1432. && let Ok(object) = object.cast::<ID3D12Object>()
  1433. {
  1434. // SAFETY: a plain call on a live object.
  1435. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1436. }
  1437. return;
  1438. }
  1439. if dred_any()
  1440. && let Ok(object) = object.cast::<ID3D12Object>()
  1441. {
  1442. // SAFETY: a plain call on a live object.
  1443. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1444. }
  1445. }
  1446. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1447. /// [`LISTS`]`[3]` until it is first reset.
  1448. struct Counted {
  1449. /// Not reset since it was made.
  1450. fresh: std::sync::atomic::AtomicBool,
  1451. }
  1452. impl Counted {
  1453. fn new() -> Counted {
  1454. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1455. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1456. Counted {
  1457. fresh: std::sync::atomic::AtomicBool::new(true),
  1458. }
  1459. }
  1460. /// The list is reset: it is in use.
  1461. fn used(&self) {
  1462. if self.fresh.swap(false, Ordering::Relaxed) {
  1463. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1464. }
  1465. }
  1466. }
  1467. impl Drop for Counted {
  1468. fn drop(&mut self) {
  1469. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1470. self.used();
  1471. }
  1472. }
  1473. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1474. /// mapping.
  1475. struct Chunk {
  1476. buffer: ID3D12Resource,
  1477. data: usize,
  1478. }
  1479. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1480. // written only by the list that holds the chunk.
  1481. unsafe impl Send for Chunk {}
  1482. /// Upload chunks handed out front to back: the chunks (each with its
  1483. /// bytes), the one in use and the bytes used in it.
  1484. #[derive(Default)]
  1485. struct Scratch {
  1486. chunks: Vec<(Chunk, u64)>,
  1487. current: usize,
  1488. used: u64,
  1489. }
  1490. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1491. unsafe impl Send for Scratch {}
  1492. impl Drop for Scratch {
  1493. fn drop(&mut self) {
  1494. give_chunks(std::mem::take(&mut self.chunks));
  1495. }
  1496. }
  1497. const SCRATCH_CHUNK: u64 = 4 << 20;
  1498. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1499. /// lists put a few constants or a rectangle's corners there, and every
  1500. /// list that did took 4 MiB of the PC's memory for it.
  1501. const SCRATCH_FIRST: u64 = 256 << 10;
  1502. /// The most bytes of chunks kept while no list holds them.
  1503. const SPARE_MOST: u64 = 128 << 20;
  1504. /// The same with [`keep_freed`].
  1505. const SPARE_KEPT: u64 = 1 << 30;
  1506. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1507. /// first needs one, a small one first, and gives all of them back when it
  1508. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1509. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1510. /// host lists of held submissions, which live for one submission, each
  1511. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1512. /// freed per frame of gameplay (run 60).
  1513. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1514. fn scratch_pool() -> bool {
  1515. static ON: OnceLock<bool> = OnceLock::new();
  1516. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1517. }
  1518. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1519. /// for one of the same size.
  1520. struct Spare<T> {
  1521. kept: Vec<(T, u64)>,
  1522. bytes: u64,
  1523. }
  1524. impl<T> Spare<T> {
  1525. const fn new() -> Self {
  1526. Spare { kept: Vec::new(), bytes: 0 }
  1527. }
  1528. /// A kept thing of `size` bytes, the one given last.
  1529. fn take(&mut self, size: u64) -> Option<T> {
  1530. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1531. self.bytes -= size;
  1532. Some(self.kept.remove(at).0)
  1533. }
  1534. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1535. /// `most`: then it comes back.
  1536. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1537. if self.bytes + size > most {
  1538. return Some(thing);
  1539. }
  1540. self.bytes += size;
  1541. self.kept.push((thing, size));
  1542. None
  1543. }
  1544. }
  1545. /// Scratch chunks no list holds.
  1546. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1547. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1548. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1549. if scratch_pool()
  1550. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1551. {
  1552. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1553. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1554. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1555. return Some(chunk);
  1556. }
  1557. let (buffer, data) = host.upload_buffer(size)?;
  1558. name(&buffer, || "list scratch".into());
  1559. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1560. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1561. Some(Chunk {
  1562. buffer,
  1563. data: data as usize,
  1564. })
  1565. }
  1566. /// A list is done with `chunks` (it was reset after its submissions ran,
  1567. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1568. /// without the pool.
  1569. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1570. if chunks.is_empty() {
  1571. return;
  1572. }
  1573. let mut freed = Vec::new();
  1574. {
  1575. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1576. for (chunk, size) in chunks {
  1577. let back = if scratch_pool() {
  1578. spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST })
  1579. } else {
  1580. Some(chunk)
  1581. };
  1582. match back {
  1583. None => {
  1584. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1585. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1586. }
  1587. Some(chunk) => {
  1588. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1589. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1590. freed.push(chunk);
  1591. }
  1592. }
  1593. }
  1594. }
  1595. // Freed outside the lock.
  1596. drop(freed);
  1597. }
  1598. /// What the host keeps for copies in the card's own memory
  1599. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1600. struct CardWork {
  1601. /// Before a submission's lists: what changed on the copies' CPU side
  1602. /// goes to their card side. Those not in use: a plan takes one and
  1603. /// gives it back when its submission has run (`Host::card_done`), so
  1604. /// that submissions sent ahead ([`late`]) each have their own.
  1605. sync: Vec<Prelude>,
  1606. /// After them, in the same submission: the compare of the declared
  1607. /// ranges with their bytes from before. As `sync`.
  1608. check: Vec<Prelude>,
  1609. /// After it ran: the pieces that differ come down.
  1610. fetch: Prelude,
  1611. root: ID3D12RootSignature,
  1612. pso: ID3D12PipelineState,
  1613. /// One dword per piece compared, odd where the piece differs: PC
  1614. /// memory, mapped (buffer, mapping, bytes).
  1615. differs: (ID3D12Resource, usize, u64),
  1616. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1617. fetched: Option<(ID3D12Resource, usize, u64)>,
  1618. /// The dwords of `differs` taken by plans whose results were not read
  1619. /// yet.
  1620. taken: u32,
  1621. /// Plans made and not done with (`Host::card_done`).
  1622. out: u32,
  1623. }
  1624. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1625. // under the submission lock.
  1626. unsafe impl Send for CardWork {}
  1627. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1628. /// The compare of a declared range of a copy in the card's memory with
  1629. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1630. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1631. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1632. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1633. /// byte just outside the range costs a fetch that finds nothing.
  1634. ///
  1635. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1636. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1637. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1638. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1639. /// those steps.
  1640. pub(crate) const CARD_COMPARE: &str = r#"
  1641. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1642. cbuffer Span : register(b0) {
  1643. uint first; // the first piece
  1644. uint skew; // where the copy starts in its piece 0
  1645. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1646. uint pieces;
  1647. uint out_at; // the first piece's dword in `differs`, in bytes
  1648. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1649. };
  1650. ByteAddressBuffer now : register(t0);
  1651. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1652. // last sent up (or hashed whole, the first time).
  1653. RWByteAddressBuffer hashes : register(u0);
  1654. RWByteAddressBuffer differs : register(u1);
  1655. groupshared uint4 parts[64];
  1656. [RootSignature(RS)]
  1657. [numthreads(64, 1, 1)]
  1658. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1659. uint piece = first + id.x;
  1660. uint lo = piece * 65536u;
  1661. lo = lo > skew ? lo - skew : 0u;
  1662. uint hi = min((piece + 1u) * 65536u - skew, size);
  1663. lo = lo & ~15u;
  1664. hi = (hi + 15u) & ~15u;
  1665. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1666. [loop]
  1667. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1668. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1669. h = h.yzwx ^ (h >> 15);
  1670. }
  1671. parts[thread] = h;
  1672. GroupMemoryBarrierWithGroupSync();
  1673. if (thread != 0u) return;
  1674. h = parts[0];
  1675. [loop]
  1676. for (uint i = 1u; i < 64u; ++i) {
  1677. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1678. h = h.yzwx ^ (h >> 15);
  1679. }
  1680. if (compare != 0u) {
  1681. // The flag, and above it 31 bits of the hash (`torn`).
  1682. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1683. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1684. // With the copy-back on its own thread: the next compare of the
  1685. // piece finds what is written from here on.
  1686. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1687. } else {
  1688. hashes.Store4(piece * 16u, h);
  1689. }
  1690. }
  1691. "#;
  1692. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1693. #[cfg(test)]
  1694. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1695. torn::hash(bytes)
  1696. }
  1697. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1698. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1699. /// parts a dispatch can hold.
  1700. ///
  1701. /// # Safety
  1702. /// The list is open with the compare's root signature, pipeline and buffers
  1703. /// set, and the pieces lie in the buffer.
  1704. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1705. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1706. let mut done = 0;
  1707. while done < span.pieces {
  1708. let n = (span.pieces - done).min(MOST);
  1709. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1710. // SAFETY: the caller's.
  1711. unsafe {
  1712. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1713. list.Dispatch(n, 1, 1);
  1714. }
  1715. done += n;
  1716. }
  1717. }
  1718. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1719. /// the card's memory are hashed in runs of pieces that touch, each piece
  1720. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1721. /// per range sent up.
  1722. ///
  1723. /// These passes are ours, they run on the card before every submission's
  1724. /// lists: a pass takes the time of one piece however few its pieces are.
  1725. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1726. /// a piece hashed when it need not be, or not hashed when it should, costs
  1727. /// a fetch that finds nothing and loses no shader write.
  1728. fn rehash_runs() -> bool {
  1729. static ON: OnceLock<bool> = OnceLock::new();
  1730. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1731. }
  1732. /// Since the last frame-rate line, of our own passes over copies in the
  1733. /// card's memory: hash passes after ranges were sent up, the pieces they
  1734. /// hashed, and compare passes after the lists.
  1735. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1736. /// Whether what shaders wrote to copies in the card's memory is merged
  1737. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1738. /// default). The pieces the card's compare found differing come down in
  1739. /// one fetch and were then merged one after the other on the thread that
  1740. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1741. /// with the copy's CPU side byte by byte and put into title memory through
  1742. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1743. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1744. /// landings do not come here: `crate::land` has threads of its own.)
  1745. fn wide_merge() -> bool {
  1746. static ON: OnceLock<bool> = OnceLock::new();
  1747. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1748. }
  1749. /// One declared range of a copy in the card's memory, in a submission.
  1750. struct CardRange {
  1751. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1752. /// As declared (title addresses), for the statistics.
  1753. declared: (usize, usize),
  1754. span: crate::shadow::CardSpan,
  1755. /// Its first piece's dword in the compare's results.
  1756. at: u32,
  1757. /// Whether the card compares it; else every piece is fetched.
  1758. compared: bool,
  1759. /// Looked at by `crate::picked`, and not declared: what is found changed
  1760. /// there was written through a view nobody declared. Not landed.
  1761. picked: bool,
  1762. }
  1763. impl CardPlan {
  1764. /// `crate::picked` is told where what it looked at changed, by the
  1765. /// compare's results.
  1766. fn picked_found(&self, differs: &[u32]) {
  1767. for r in self.ranges.iter().filter(|r| r.picked) {
  1768. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1769. if let Some(p) = changed {
  1770. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1771. }
  1772. }
  1773. }
  1774. }
  1775. /// What a submission does for copies in the card's memory.
  1776. struct CardPlan {
  1777. ranges: Vec<CardRange>,
  1778. /// The compare, run after the submission's lists.
  1779. check: Option<ID3D12CommandList>,
  1780. /// The copies whose card side was brought up to date, alive until the
  1781. /// submission has run.
  1782. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1783. /// The lists of ours the plan recorded (whether the compare, the
  1784. /// list), given back by `Host::card_done`.
  1785. lists: Vec<(bool, Prelude)>,
  1786. /// With [`relay`]: the number of the send to copies in the card's memory
  1787. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1788. sent_as: u64,
  1789. /// With [`upcheck`]: the look at what it sent up.
  1790. looks: Option<upcheck::Looks>,
  1791. /// With [`send`]: the memory its sends come from.
  1792. sends: Option<send::Memory>,
  1793. }
  1794. /// One piece of submission-time work, in recorded order.
  1795. enum Step {
  1796. /// A copy into title memory (destination, source, bytes): the title's
  1797. /// buffer copies, which later refreshes must see.
  1798. Copy(usize, usize, usize),
  1799. /// A copy of title memory into the list's own upload memory, and how
  1800. /// the card could bring the bytes instead.
  1801. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  1802. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1803. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1804. /// intervenes.
  1805. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1806. /// Work that may write title memory.
  1807. Run(Box<dyn Fn() + Send>),
  1808. /// Work that writes host memory only, and the title memory it reads
  1809. /// (from, to; empty for none).
  1810. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1811. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1812. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1813. /// Brings a texture's staging buffer up to date: once per submission,
  1814. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1815. Texture(std::sync::Arc<crate::texture::Staging>),
  1816. /// A title buffer copy that the list does on the card ([`place`]): what
  1817. /// is done on the CPU for it.
  1818. Placed(place::Placed),
  1819. }
  1820. /// What a list does on the CPU when it is submitted: copies between host
  1821. /// memory regions (title buffers, upload buffers and buffer copies), and
  1822. /// the upload buffers its GPU commands read, kept until the list is reset.
  1823. #[derive(Default)]
  1824. struct Deferred {
  1825. /// Destination, source, bytes.
  1826. copies: Vec<Step>,
  1827. uploads: Vec<ID3D12Resource>,
  1828. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1829. upload_bytes: u64,
  1830. /// Host objects the list's commands name (pipelines, root signatures,
  1831. /// descriptor heaps): the title may release its objects before it
  1832. /// submits the list.
  1833. kept: Vec<windows::core::IUnknown>,
  1834. /// Buffer ranges refreshed since the last title copy (host copy,
  1835. /// address, bytes): refreshing them again would find the same bytes.
  1836. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1837. /// Textures whose contents the list brings up to date.
  1838. textures: std::collections::HashSet<usize>,
  1839. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1840. /// bytes.
  1841. writes: Vec<(usize, crate::queue::Written, usize)>,
  1842. /// Textures read back (texture to buffer copies), done once the list
  1843. /// has run: the host buffer the list copies the texels into, the title
  1844. /// memory they go to, the bytes of a row, the rows, the title's row
  1845. /// pitch.
  1846. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1847. /// Whether the indirect-work budget is zeroed for this recording (a
  1848. /// step on the CPU, or in the list for the card's copy).
  1849. budget_zeroed: bool,
  1850. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1851. /// interface pointer) that a clamp in this recording left readable as
  1852. /// indirect arguments; 0 if none. It stays readable until the next
  1853. /// clamp into it ([`HostList::indirect_state`]).
  1854. indirect_readable: usize,
  1855. }
  1856. impl Deferred {
  1857. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1858. /// reset.
  1859. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1860. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1861. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1862. self.upload_bytes += size;
  1863. self.uploads.push(buffer);
  1864. }
  1865. }
  1866. impl Drop for Deferred {
  1867. fn drop(&mut self) {
  1868. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1869. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1870. }
  1871. }
  1872. /// Whether a queue's submissions go to the card without a wait for each
  1873. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1874. /// waits for every list on its own).
  1875. ///
  1876. /// Every submission was prepared, sent, waited for and copied back before
  1877. /// the next one was looked at, so the card stood idle while we prepared
  1878. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1879. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1880. /// other, on the one thread that submits.
  1881. ///
  1882. /// With the switch a queue's submission is sent and joins a line of
  1883. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1884. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1885. /// for the card, what their shaders wrote copied back once per byte, then
  1886. /// their bottom-of-pipe writes and the fence signals behind them, in
  1887. /// order) at the next point where the title, or our own preparing, can
  1888. /// observe what they do. Those points, exactly:
  1889. ///
  1890. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1891. /// read-back or map of a texture, a clear or upload run at once;
  1892. /// 2. the next submission reads title memory that a flight's shaders may
  1893. /// write: a title buffer copy, a fill of upload memory, a texture's
  1894. /// memory, any step that runs code of ours on title memory
  1895. /// ([`late_blocked`]);
  1896. /// 3. the next submission refreshes a range of a host copy that a flight's
  1897. /// shaders may write, and the title wrote a page of it since it was last
  1898. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1899. /// alone until the flight's writes are back, as it always did within a
  1900. /// submission;
  1901. /// 4. a queue stands at a wait for a memory value that no flight's
  1902. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1903. /// write ([`late_met`]);
  1904. /// 5. the title blocks on a fence without an event;
  1905. /// 6. the card has run every flight (a thread of ours waits for that:
  1906. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1907. ///
  1908. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1909. /// when the card has really run the work, later than before and never
  1910. /// earlier; a fence signalled on a queue while flights are in the air is
  1911. /// set behind them. A wait for a memory value that a flight's
  1912. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1913. /// the card behind that flight, which is the order the wait asks for.
  1914. ///
  1915. /// What it assumes beyond today: memory the title rewrites between two of
  1916. /// its submissions, without waiting for the first, may be seen by the
  1917. /// first's shaders (as on the console, where the card reads title memory
  1918. /// when it runs, not when the list is submitted).
  1919. pub(crate) fn late() -> bool {
  1920. late_stage() > 0
  1921. }
  1922. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1923. fn late_stage() -> u8 {
  1924. static STAGE: OnceLock<u8> = OnceLock::new();
  1925. *STAGE.get_or_init(|| {
  1926. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1927. return 0;
  1928. }
  1929. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1930. Ok("1") => 1,
  1931. Ok("2") => 2,
  1932. Ok("3") => 3,
  1933. // The relay alone: on top of stage 3.
  1934. Err(_) if crate::shadow::relay() => 3,
  1935. _ => 0,
  1936. }
  1937. })
  1938. }
  1939. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1940. /// longer a point. Where the title wrote a page that lies in a range a
  1941. /// flight's shaders may write, the bytes the title changed are found (the
  1942. /// page as it is now against what the copy held when the flight was
  1943. /// prepared) and put into the copy, and only those: what the flight's
  1944. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1945. /// flights are settled for it only where that cannot be done: memory that
  1946. /// is not write-watched, or a copy in the card's memory with more changed
  1947. /// runs than a submission should send up one by one.
  1948. ///
  1949. /// In run 92 (stage 1) this point settled the flights five times a frame
  1950. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1951. /// frame of waiting were left of 200.
  1952. ///
  1953. /// What differs from settling first: a byte both the title and a flight's
  1954. /// shader wrote is the title's if the shader wrote it first, the shader's
  1955. /// if it wrote it afterwards; settled first it was always the shader's.
  1956. /// The title writing a byte a shader of its own is writing is a race on
  1957. /// the console too.
  1958. fn late_exact() -> bool {
  1959. late_stage() > 1
  1960. }
  1961. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1962. /// no longer a point where flights are settled). The copy to the back
  1963. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1964. /// its own for each present in the air) and the swap chain is told to
  1965. /// present behind it; the queue's call returns, and the card finishes the
  1966. /// frame while the title records the next one. What the title is told
  1967. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1968. /// has run it, by the settling thread.
  1969. ///
  1970. /// What is left out with it: the look whether the presented frame is black
  1971. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1972. /// or listed is presented the old way. Once every second and a half a
  1973. /// submission settles the flights all the same, for the sweep that lets
  1974. /// idle host objects go (it needs nothing in the air).
  1975. pub(crate) fn late_free_present() -> bool {
  1976. late_stage() > 2
  1977. }
  1978. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1979. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1980. /// and is off with it, in the timing run and with kept snapshots).
  1981. ///
  1982. /// With [`late`] alone every settle does three things on the thread that
  1983. /// holds the submission lock: it waits for everything in the air, copies
  1984. /// back with the card standing, and only then goes on preparing. The frame
  1985. /// stays a relay: the card works about 242 ms of it and one thread
  1986. /// prepares, waits and copies back for about 220.
  1987. ///
  1988. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1989. /// soon as the card has run them, in the order they were sent and without
  1990. /// the submission lock: it fetches and merges what their shaders wrote to
  1991. /// copies in the card's memory, compares and merges the other copies,
  1992. /// frees the flights' ranges, and then does their read-backs, their
  1993. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1994. /// order. The submitting thread meanwhile prepares and sends the next
  1995. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  1996. /// that thread has landed everything in the air, at the same points as
  1997. /// before (the list in [`late`]), so whoever can observe title memory, a
  1998. /// fence or a present still does so only after the flights before it are
  1999. /// merged.
  2000. ///
  2001. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  2002. /// flight; a merge that never stores into memory the card may be writing;
  2003. /// sends to card copies numbered) and here: flights land in the order of
  2004. /// [`LINE`] by one thread, so a later flight's results never reach title
  2005. /// memory before an earlier flight's; the compare on the card stores the
  2006. /// hash it made, so each flight's compare flags exactly what changed since
  2007. /// the compare before it, however late the pieces are fetched; the fetch
  2008. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  2009. /// title bytes the card had received when it ran.
  2010. pub(crate) fn relay() -> bool {
  2011. static ON: OnceLock<bool> = OnceLock::new();
  2012. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  2013. }
  2014. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  2015. /// title memory a flight's shaders may write (a title buffer copy, a fill
  2016. /// of upload memory, a texture) waits only until the flights that declared
  2017. /// that memory have landed, not for everything in the air; and at
  2018. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  2019. /// both wait for everything.
  2020. fn relay_exact() -> bool {
  2021. static ON: OnceLock<bool> = OnceLock::new();
  2022. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  2023. // since the walls of the first room were found drawn in every run with
  2024. // this set and in fewer than half without it).
  2025. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  2026. }
  2027. /// Whether the pieces the relay fetches from the card's memory come over the
  2028. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  2029. /// draws.
  2030. ///
  2031. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  2032. /// and with the relay that is most of a frame: the thread that lands flights
  2033. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  2034. /// a few milliseconds of copying, and everything that waits for a landing
  2035. /// (the title's fences, reads of memory flights may write) waited with it.
  2036. ///
  2037. /// What changes: the fetch runs when its flights are done and beside later
  2038. /// submissions, so of the sends of title bytes it is only known to have run
  2039. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  2040. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  2041. /// the title's, newer than what the flights wrote. A later flight's bytes
  2042. /// may be in what is fetched, as before.
  2043. fn relay_copy() -> bool {
  2044. static ON: OnceLock<bool> = OnceLock::new();
  2045. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  2046. }
  2047. /// Told when something joins [`LINE`], for the thread that lands flights
  2048. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  2049. /// what queues hold.
  2050. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2051. /// Told when flights have landed ([`relay`]): who waits for that looks
  2052. /// again.
  2053. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  2054. /// With [`relay`], the order of what we put on the queue: the number of
  2055. /// sends of changed ranges to copies in the card's memory so far
  2056. /// (`Host::card_before`). Held from the taking of the ranges until their
  2057. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  2058. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  2059. /// later one.
  2060. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  2061. /// Since the last frame-rate line, of the thread that lands flights
  2062. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  2063. /// card with nothing to land, microseconds it waited for fetches of card
  2064. /// copies' pieces, microseconds of landing in all.
  2065. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  2066. /// Of the line's things in order (a flight: the value signalled on the
  2067. /// host's fence behind it; a write or a signal behind a flight: `None`):
  2068. /// how many, from the front, can be landed when the card has reached
  2069. /// `completed`: everything ahead of the first flight it has not run. A
  2070. /// later flight never lands before an earlier one, and what follows a
  2071. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  2072. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  2073. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  2074. }
  2075. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  2076. /// holds, for every piece of every range of the plan, the copy, the
  2077. /// piece's number in the copy and whether the compare flagged it there (or
  2078. /// did not run). The pieces to fetch, under whichever range, in order: all
  2079. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  2080. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  2081. /// the hash, so the second of them may find it stored already and not
  2082. /// flag it.
  2083. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  2084. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  2085. pieces.sort_unstable();
  2086. pieces.dedup();
  2087. pieces
  2088. }
  2089. #[cfg(test)]
  2090. mod relay_tests {
  2091. use super::{flagged_pieces, landable};
  2092. /// Two flights and what follows each: nothing of the second lands
  2093. /// before the card has run it, and nothing behind a flight lands
  2094. /// before the flight.
  2095. #[test]
  2096. fn flights_land_in_the_order_they_were_sent() {
  2097. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  2098. let line = [Some(5), None, None, Some(6), None];
  2099. assert_eq!(landable(&line, 4), 0);
  2100. assert_eq!(landable(&line, 5), 3);
  2101. assert_eq!(landable(&line, 6), 5);
  2102. assert_eq!(landable(&line, u64::MAX), 5);
  2103. // Signals with no flight ahead land at once; behind one they wait.
  2104. assert_eq!(landable(&[None, None], 0), 2);
  2105. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  2106. assert_eq!(landable(&[], 3), 0);
  2107. // After the first three landed, the rest when its turn comes.
  2108. assert_eq!(landable(&line[3..], 5), 0);
  2109. assert_eq!(landable(&line[3..], 6), 2);
  2110. }
  2111. /// A piece flagged under one range of a plan is fetched under every
  2112. /// range that holds a part of it; pieces of other copies are not.
  2113. #[test]
  2114. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  2115. let (a, b) = (0x1000usize, 0x2000usize);
  2116. // Copy a: piece 3 under two ranges, flagged under the first only;
  2117. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  2118. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  2119. let fetch = flagged_pieces(&flags);
  2120. assert!(fetch.contains(&(a, 3)));
  2121. assert!(!fetch.contains(&(a, 4)));
  2122. assert!(!fetch.contains(&(b, 3)));
  2123. assert!(fetch.contains(&(b, 9)));
  2124. assert_eq!(fetch.len(), 2);
  2125. }
  2126. }
  2127. /// The most host lists in the air before the flights are settled
  2128. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  2129. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  2130. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  2131. /// 32 settled the flights three times a
  2132. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  2133. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  2134. /// descriptor slots, upload
  2135. /// memory and scratch chunks are held until then, and a frame's lists held
  2136. /// all at once ran the slots out before (run 45).
  2137. fn late_most() -> usize {
  2138. static MOST: OnceLock<usize> = OnceLock::new();
  2139. *MOST.get_or_init(|| {
  2140. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  2141. })
  2142. }
  2143. /// Whether a submission with bottom-of-pipe writes may fly
  2144. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  2145. /// the title is told at once, as before; for telling a title that polls
  2146. /// such a value from one that does not).
  2147. fn late_writes() -> bool {
  2148. static ON: OnceLock<bool> = OnceLock::new();
  2149. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  2150. }
  2151. /// Per host copy, the ranges a submission's shaders may write, as declared
  2152. /// (address, end).
  2153. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  2154. /// What [`Host::submit`] hands back for a submission it sent and did not
  2155. /// wait for.
  2156. struct Sent {
  2157. /// Its number among the submissions started.
  2158. number: u64,
  2159. card: Option<CardPlan>,
  2160. back: Vec<Declared>,
  2161. /// What was taken off it to be done on the card.
  2162. own: Option<card_steps::Taken>,
  2163. /// Its bottom-of-pipe writes.
  2164. writes: Vec<(usize, crate::queue::Written, usize)>,
  2165. }
  2166. /// A submission on the card that has not been waited for ([`late`]): its
  2167. /// host lists, taken from the title's (which it may reset meanwhile), and
  2168. /// what is to be done once it has run.
  2169. struct Flight {
  2170. number: u64,
  2171. /// The value signalled on the host's fence behind it.
  2172. fence: u64,
  2173. lists: Vec<crate::list::Detached>,
  2174. order: Vec<usize>,
  2175. card: Option<CardPlan>,
  2176. back: Vec<Declared>,
  2177. /// The list of ours that ran ahead of them ([`card_steps`]).
  2178. own: Option<card_steps::Taken>,
  2179. }
  2180. /// One thing in the line of what waits for the card, in order.
  2181. enum Late {
  2182. Run(Flight),
  2183. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  2184. Write(usize, crate::queue::Written, usize),
  2185. /// A fence (its address) signalled behind the flights before it.
  2186. Signal(usize, u64),
  2187. }
  2188. struct Line {
  2189. line: Vec<Late>,
  2190. /// The title memory the flights' shaders may write (address, end), in
  2191. /// order and joined.
  2192. written: Vec<(usize, usize)>,
  2193. /// Host lists in the flights.
  2194. lists: usize,
  2195. /// The value signalled on the host's fence behind the last flight.
  2196. target: u64,
  2197. /// A settle has taken the line and is not done: a signal still goes
  2198. /// behind it.
  2199. settling: bool,
  2200. /// Something was settled away from a queue's own calls: the helper
  2201. /// thread looks at what queues hold.
  2202. poke: bool,
  2203. /// Host lists of settled flights, reset and given back outside the
  2204. /// submission lock ([`land`]: a settle may run under a caller's own
  2205. /// locks).
  2206. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2207. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2208. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2209. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2210. /// With [`card_steps`]: what the flights being landed write.
  2211. landing: Vec<card_steps::Writer>,
  2212. }
  2213. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2214. // into; touched under the lock.
  2215. unsafe impl Send for Line {}
  2216. static LINE: Mutex<Line> = Mutex::new(Line {
  2217. line: Vec::new(),
  2218. written: Vec::new(),
  2219. lists: 0,
  2220. target: 0,
  2221. settling: false,
  2222. poke: false,
  2223. landed: Vec::new(),
  2224. in_hand: Vec::new(),
  2225. landing: Vec::new(),
  2226. });
  2227. /// Told when a flight joins [`LINE`] or it is poked.
  2228. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2229. fn line() -> std::sync::MutexGuard<'static, Line> {
  2230. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2231. }
  2232. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2233. const WHY_SYNC: usize = 2;
  2234. const WHY_CARD_DONE: usize = 3;
  2235. const WHY_VALUE: usize = 4;
  2236. const WHY_STALE: usize = 5;
  2237. const WHY_READ: usize = 6;
  2238. const WHY_RUN: usize = 7;
  2239. const WHY_MOST: usize = 8;
  2240. const WHY_WRITES: usize = 9;
  2241. const WHY_FENCE: usize = 10;
  2242. /// Since the last frame-rate line: submissions sent without a wait;
  2243. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2244. /// microseconds settles waited for the card; value waits met by a flight's
  2245. /// bottom-of-pipe write; fence signals set behind flights.
  2246. /// Then: the settles for title memory read, by what read it (a buffer
  2247. /// copy, a fill of upload memory, a texture).
  2248. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2249. /// Since the last frame-rate line: the microseconds settles waited for the
  2250. /// card, by why they settled (the `WHY_` places).
  2251. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2252. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2253. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2254. if from >= to {
  2255. return false;
  2256. }
  2257. let at = ranges.partition_point(|r| r.1 <= from);
  2258. ranges.get(at).is_some_and(|r| r.0 < to)
  2259. }
  2260. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2261. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2262. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2263. ranges.sort_unstable();
  2264. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2265. for &(from, to) in ranges.iter() {
  2266. match out.last_mut() {
  2267. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2268. _ => out.push((from, to)),
  2269. }
  2270. }
  2271. *ranges = out;
  2272. }
  2273. /// Whether anything is in the air.
  2274. fn flying() -> bool {
  2275. if !late() {
  2276. return false;
  2277. }
  2278. let line = line();
  2279. // (With the relay: also while flights are being landed.)
  2280. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2281. }
  2282. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2283. /// before they are settled, if so. Preparing reads title memory on the
  2284. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2285. /// runs steps of ours that may read or write it anywhere; what the
  2286. /// flights' shaders write is not there yet.
  2287. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2288. let (written, copies) = {
  2289. let line = line();
  2290. if line.written.is_empty() {
  2291. return None;
  2292. }
  2293. (line.written.clone(), card_steps::copies(&line))
  2294. };
  2295. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2296. }
  2297. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2298. /// flights when the title itself wrote the memory since they were given it
  2299. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2300. ///
  2301. /// The title's 174 MB heap is declared written as a whole (a root view has
  2302. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2303. /// bytes a frame, at a new place each time, waited for every flight's
  2304. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2305. /// named). The title writes those bytes just before the draw that reads
  2306. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2307. ///
  2308. /// Or no shader's write went into that page in the last 600 frames
  2309. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2310. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2311. /// before the page was taken.
  2312. ///
  2313. /// What can go wrong: a constant a flight's shader really writes, in a
  2314. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2315. /// for the first time, is read as it was before that flight.
  2316. fn fill_is_titles(src: usize, len: usize) -> bool {
  2317. const SMALL: usize = 64 << 10;
  2318. static ON: OnceLock<bool> = OnceLock::new();
  2319. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2320. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2321. }
  2322. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2323. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2324. /// in (start, bytes).
  2325. #[cfg(feature = "diagnostics")]
  2326. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2327. /// How often and how long, and the address the last one read.
  2328. #[cfg(feature = "diagnostics")]
  2329. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2330. /// What the wait that comes next is for, and why not on the card.
  2331. #[cfg(feature = "diagnostics")]
  2332. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2333. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2334. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2335. /// shaders.
  2336. #[cfg(feature = "diagnostics")]
  2337. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2338. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2339. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2340. /// raw address (1).
  2341. #[cfg(feature = "diagnostics")]
  2342. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2343. if len < 1 << 20 {
  2344. return;
  2345. }
  2346. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2347. let e = all
  2348. .get_or_insert_with(Default::default)
  2349. .entry((address as usize, (address + len) as usize, pipeline))
  2350. .or_insert_with(|| {
  2351. let shaders = match pipeline {
  2352. 0 => "a view in a table".into(),
  2353. 1 => "a raw address".into(),
  2354. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2355. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2356. }),
  2357. };
  2358. (0, shaders)
  2359. });
  2360. e.0 += 1;
  2361. }
  2362. #[cfg(feature = "diagnostics")]
  2363. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2364. let i = written.partition_point(|r| r.1 <= at);
  2365. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2366. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2367. let why = blamed.1;
  2368. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2369. }
  2370. /// Why [`card_steps`] left the submission to the wait that comes next.
  2371. #[cfg(feature = "diagnostics")]
  2372. fn refused(why: &'static str) {
  2373. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2374. }
  2375. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2376. #[cfg(feature = "diagnostics")]
  2377. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2378. if let Some((shadow, from, _)) = stale.first() {
  2379. let (start, len) = shadow.span();
  2380. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2381. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2382. }
  2383. }
  2384. /// The wait for what [`blame`] last named, or a wait of another reason than
  2385. /// title memory read, took `us`.
  2386. #[cfg(feature = "diagnostics")]
  2387. fn blamed(why: usize, us: u64) {
  2388. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2389. let (key, at) = match (why, named) {
  2390. (WHY_READ | WHY_STALE, Some(named)) => named,
  2391. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2392. _ => {
  2393. let kind = match why {
  2394. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2395. WHY_VALUE => "a memory value",
  2396. WHY_STALE => "title memory changed under shader writes",
  2397. WHY_RUN => "a step of ours",
  2398. WHY_MOST => "lists in the air",
  2399. WHY_FENCE => "a blocking fence wait",
  2400. _ => "another reason",
  2401. };
  2402. ((kind, "", 0, 0, 0), 0)
  2403. }
  2404. };
  2405. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2406. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2407. *e = (e.0 + 1, e.1 + us, at);
  2408. }
  2409. /// For the frame-rate line: the five that waited longest.
  2410. #[cfg(feature = "diagnostics")]
  2411. fn log_blame(frames: f64) {
  2412. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2413. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2414. let mut all: Vec<_> = all.into_iter().collect();
  2415. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2416. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2417. // The passes that declare it written, the ones that do so most.
  2418. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2419. for ((a, b, _), (n, shaders)) in &wide {
  2420. if *a < at + len && at < *b {
  2421. *passes.entry(shaders).or_default() += n;
  2422. }
  2423. }
  2424. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2425. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2426. let passes: Vec<String> =
  2427. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2428. tracing::info!(
  2429. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2430. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2431. us as f64 / 1e3 / frames,
  2432. n as f64 / frames,
  2433. passes.join(", "),
  2434. match (why.is_empty(), kind) {
  2435. (true, _) => "",
  2436. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2437. _ => "; not done on the card: ",
  2438. },
  2439. );
  2440. }
  2441. }
  2442. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2443. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2444. touches(written, src, src + len) && !fill_is_titles(src, len)
  2445. }
  2446. /// Whether they stop a title buffer copy, and if so whether by its source.
  2447. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2448. let read = read_blocked(written, src, len);
  2449. (read || touches(written, dst, dst + len)).then_some(read)
  2450. }
  2451. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2452. /// may write (in order, joined); `count` whether the kind of read is
  2453. /// counted for the frame line.
  2454. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2455. if written.is_empty() {
  2456. return None;
  2457. }
  2458. // Destinations of copies at their place, if a step reads them.
  2459. let mut placed: Vec<(usize, usize)> = Vec::new();
  2460. for list in runs {
  2461. for step in &list.deferred().copies {
  2462. match step {
  2463. &Step::Copy(dst, src, len) => {
  2464. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2465. if count {
  2466. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2467. #[cfg(feature = "diagnostics")]
  2468. if _read {
  2469. blame("a buffer copy's source", written, src, len);
  2470. } else {
  2471. blame("a buffer copy's destination", written, dst, len);
  2472. }
  2473. }
  2474. return Some(WHY_READ);
  2475. }
  2476. }
  2477. &Step::Fill(_, src, len, _) => {
  2478. if read_blocked(written, src, len) {
  2479. if count {
  2480. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2481. #[cfg(feature = "diagnostics")]
  2482. blame("a fill of upload memory", written, src, len);
  2483. }
  2484. return Some(WHY_READ);
  2485. }
  2486. }
  2487. Step::Texture(staging) => {
  2488. let (at, len) = staging.memory();
  2489. if touches(written, at, at + len) {
  2490. if count {
  2491. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2492. #[cfg(feature = "diagnostics")]
  2493. blame("a texture", written, at, len);
  2494. }
  2495. return Some(WHY_READ);
  2496. }
  2497. }
  2498. Step::Run(_) => return Some(WHY_RUN),
  2499. Step::Placed(p) => match p.waits(written) {
  2500. place::Waits::No => {}
  2501. place::Waits::ForReaders => placed.push((p.dst, p.dst + p.len)),
  2502. place::Waits::Yes => {
  2503. if count {
  2504. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2505. #[cfg(feature = "diagnostics")]
  2506. blame("a buffer copy at its place", written, p.src, p.len);
  2507. }
  2508. return Some(WHY_READ);
  2509. }
  2510. },
  2511. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2512. }
  2513. }
  2514. }
  2515. (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ)
  2516. }
  2517. /// With flights in the air, after the submission's write-watch asking:
  2518. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2519. /// may write and that the title wrote since it was last copied. The
  2520. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2521. /// the title's bytes there would reach the card a submission late.
  2522. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2523. use std::sync::Arc;
  2524. // Per copy, the span of what is refreshed (a flush brings that much
  2525. // up to date at most).
  2526. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2527. // Where each copy is in it, if shaders may be writing it (none begins to
  2528. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2529. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2530. for list in runs {
  2531. for step in &list.deferred().copies {
  2532. if let Step::Refresh(shadow, address, len) = step {
  2533. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2534. shadow.writes_pending().then(|| {
  2535. spans.push((shadow.clone(), *address, *address + *len));
  2536. spans.len() - 1
  2537. })
  2538. });
  2539. if let Some(i) = *place {
  2540. let s = &mut spans[i];
  2541. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2542. }
  2543. }
  2544. }
  2545. }
  2546. if late_exact() {
  2547. // The title's bytes are put in beside the flights' writes; a
  2548. // settle is still due where that could not be done. At most this
  2549. // many changed runs go up to copies in the card's memory, each a
  2550. // copy of its own there. With [`card_steps`] the pages of the
  2551. // title's ring of constants come here too, which were waited for
  2552. // before: hundreds of short runs each, at about 1.5 us a run.
  2553. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2554. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2555. return spans;
  2556. }
  2557. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2558. spans
  2559. }
  2560. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2561. /// air, if there are any, and is set when they are settled. Whether it
  2562. /// did; if not the caller sets the fence now.
  2563. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2564. if !late() {
  2565. return false;
  2566. }
  2567. let mut line = line();
  2568. if line.line.is_empty() && !line.settling {
  2569. return false;
  2570. }
  2571. line.line.push(Late::Signal(fence, value));
  2572. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2573. drop(line);
  2574. // A signal alone (behind a settle under way) has no flight to wake
  2575. // the helper thread for it.
  2576. LINE_MOVED.notify_one();
  2577. RELAY_MOVED.notify_one();
  2578. true
  2579. }
  2580. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2581. /// whether it is met once the flights in the air have run. A flight's
  2582. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2583. /// for the card: the part behind the wait goes to the card behind that
  2584. /// flight, which is the order the wait asks for. If the flights may write
  2585. /// the value in a way not known here (shaders, a timestamp, another
  2586. /// width), they are settled and memory is asked again.
  2587. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2588. let (address, bytes) = wait.place();
  2589. {
  2590. let line = line();
  2591. if line.line.is_empty() && line.in_hand.is_empty() {
  2592. return false;
  2593. }
  2594. let mut unsure = touches(&line.written, address, address + bytes);
  2595. // (With the relay: first the writes of flights being landed.)
  2596. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2597. Late::Write(at, what, n) => Some((at, what, n)),
  2598. _ => None,
  2599. }));
  2600. for (at, what, n) in writes {
  2601. if *at >= address + bytes || address >= *at + *n {
  2602. continue;
  2603. }
  2604. match what {
  2605. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2606. if wait.holds_for(*v) {
  2607. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2608. return true;
  2609. }
  2610. }
  2611. _ => unsure = true,
  2612. }
  2613. }
  2614. if !unsure {
  2615. return false;
  2616. }
  2617. }
  2618. settle_now(WHY_VALUE);
  2619. wait.met()
  2620. }
  2621. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2622. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2623. pub(crate) fn settle_now(why: usize) {
  2624. if !late() {
  2625. return;
  2626. }
  2627. let Some(host) = host() else {
  2628. return;
  2629. };
  2630. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2631. host.settle(&mut submitted, why);
  2632. }
  2633. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2634. pub(crate) fn settle_for_present() {
  2635. settle_now(WHY_SYNC);
  2636. }
  2637. pub(crate) fn settle_for_fence() {
  2638. settle_now(WHY_FENCE);
  2639. }
  2640. /// Resets the host lists of settled flights and keeps them for reuse, as
  2641. /// a queue does for the lists it ran (`crate::list::recycle`).
  2642. fn land() {
  2643. let landed = std::mem::take(&mut line().landed);
  2644. for (lists, order) in landed {
  2645. crate::list::recycle(lists, &order);
  2646. }
  2647. }
  2648. /// The thread that settles the flights once the card has run them all
  2649. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2650. /// at the next call that settles, and a title thread that polls such a
  2651. /// value while the submitting thread waits for that thread would never
  2652. /// see it.
  2653. fn late_helper() {
  2654. let Some(host) = host() else {
  2655. return;
  2656. };
  2657. // SAFETY: a plain event of our own.
  2658. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2659. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2660. return;
  2661. };
  2662. loop {
  2663. let target = {
  2664. let mut line = line();
  2665. loop {
  2666. if line.poke {
  2667. line.poke = false;
  2668. break None;
  2669. }
  2670. // (With the relay the flights are another thread's.)
  2671. if !relay() && !line.line.is_empty() && !line.settling {
  2672. break Some(line.target);
  2673. }
  2674. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2675. }
  2676. };
  2677. let Some(target) = target else {
  2678. land();
  2679. crate::queue::release_held(false);
  2680. continue;
  2681. };
  2682. // The card first, without the submission lock: the submitting
  2683. // thread prepares and sends meanwhile.
  2684. // SAFETY: our fence and event.
  2685. unsafe {
  2686. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2687. WaitForSingleObject(event, INFINITE);
  2688. }
  2689. }
  2690. {
  2691. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2692. // Something newer went up meanwhile: the card is waited for
  2693. // again, the submitting thread is not held up for it.
  2694. if line().target != target {
  2695. continue;
  2696. }
  2697. host.settle(&mut submitted, WHY_CARD_DONE);
  2698. }
  2699. land();
  2700. crate::queue::release_held(false);
  2701. }
  2702. }
  2703. /// Starts the threads of [`late`], once: the one that settles flights when
  2704. /// the card has run them and looks at what queues hold, and with [`relay`]
  2705. /// the one that lands flights.
  2706. fn late_threads() {
  2707. static HELPER: std::sync::Once = std::sync::Once::new();
  2708. HELPER.call_once(|| {
  2709. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2710. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2711. }
  2712. tracing::info!(
  2713. most = late_most(),
  2714. writes = late_writes(),
  2715. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2716. );
  2717. if relay() {
  2718. // Without it nothing would ever land.
  2719. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2720. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2721. }
  2722. tracing::info!(
  2723. exact = relay_exact(),
  2724. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2725. );
  2726. }
  2727. });
  2728. }
  2729. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2730. /// time flights have landed. Counted as a settle for `why`, and its time
  2731. /// as waiting for the card. The caller may hold the submission lock: the
  2732. /// thread that lands flights never takes it.
  2733. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2734. let mut line = line();
  2735. if done(&line) {
  2736. return;
  2737. }
  2738. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2739. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2740. let was_working = working(false);
  2741. let waiting = std::time::Instant::now();
  2742. while !done(&line) {
  2743. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2744. }
  2745. drop(line);
  2746. stood(waiting);
  2747. working(was_working);
  2748. let us = waiting.elapsed().as_micros() as u64;
  2749. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2750. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2751. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2752. #[cfg(feature = "diagnostics")]
  2753. blamed(why, us);
  2754. }
  2755. /// What the thread that lands flights fetches card copies' pieces with
  2756. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2757. /// behind the submission lock), and the memory the pieces come down to.
  2758. struct RelayFetch {
  2759. list: Prelude,
  2760. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2761. queue: Option<ID3D12CommandQueue>,
  2762. fence: ID3D12Fence,
  2763. event: HANDLE,
  2764. /// The last value signalled on `fence`.
  2765. sent: u64,
  2766. /// Buffer, mapping, bytes.
  2767. buffer: Option<(ID3D12Resource, usize, u64)>,
  2768. /// Pieces caught while a later flight was writing them.
  2769. suspects: torn::Suspects,
  2770. /// What earlier fetches brought of flights not landed yet.
  2771. had: crate::land::Had,
  2772. }
  2773. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2774. /// the first flights of the line it takes them, with what follows them,
  2775. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2776. /// the card, or for a flight. It takes neither the submission lock nor
  2777. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2778. /// lists and looking at what queues hold are left to [`late_helper`].
  2779. fn relay_worker() {
  2780. let Some(host) = host() else {
  2781. return;
  2782. };
  2783. // SAFETY: a plain event of our own.
  2784. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2785. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2786. };
  2787. let mut fetch: Option<RelayFetch> = None;
  2788. loop {
  2789. let next = {
  2790. let mut line = line();
  2791. loop {
  2792. if line.line.is_empty() {
  2793. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2794. continue;
  2795. }
  2796. let fences: Vec<Option<u64>> = line
  2797. .line
  2798. .iter()
  2799. .map(|l| match l {
  2800. Late::Run(flight) => Some(flight.fence),
  2801. _ => None,
  2802. })
  2803. .collect();
  2804. // SAFETY: a plain query.
  2805. let completed = unsafe { host.fence.GetCompletedValue() };
  2806. let n = landable(&fences, completed);
  2807. if n == 0 {
  2808. // The first thing is a flight the card has not run.
  2809. break Err(fences[0].unwrap_or(0));
  2810. }
  2811. line.settling = true;
  2812. let items: Vec<Late> = line.line.drain(..n).collect();
  2813. line.in_hand = items
  2814. .iter()
  2815. .filter_map(|l| match l {
  2816. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2817. _ => None,
  2818. })
  2819. .collect();
  2820. if card_steps::stage() > 0 {
  2821. line.landing = card_steps::writers(&items);
  2822. }
  2823. break Ok(items);
  2824. }
  2825. };
  2826. match next {
  2827. Ok(items) => host.relay_land(items, &mut fetch),
  2828. Err(target) => {
  2829. let waiting = std::time::Instant::now();
  2830. // SAFETY: the host's fence and this thread's event.
  2831. let waited = unsafe {
  2832. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2833. WaitForSingleObject(event, INFINITE);
  2834. })
  2835. };
  2836. if waited.is_err() {
  2837. std::thread::sleep(std::time::Duration::from_millis(1));
  2838. }
  2839. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2840. }
  2841. }
  2842. }
  2843. }
  2844. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2845. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2846. /// once, the pieces that differ found on several threads; but the merge is
  2847. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2848. /// are not done with here (each flight's are, afterwards). In two steps:
  2849. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  2850. /// which needs nothing that the fetch from the card's memory brings), and
  2851. /// the merge.
  2852. struct RelayBack {
  2853. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  2854. found: Option<Vec<Vec<(usize, usize)>>>,
  2855. }
  2856. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  2857. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2858. for (shadow, declared) in back {
  2859. if shadow.carded() {
  2860. continue;
  2861. }
  2862. let mut spans: Vec<(usize, usize)> = Vec::new();
  2863. join_ranges(&mut spans, declared.iter().copied());
  2864. for &(from, to) in &spans {
  2865. shadow.relay_compared(from, to - from);
  2866. }
  2867. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2868. }
  2869. RelayBack { work, found: None }
  2870. }
  2871. impl RelayBack {
  2872. /// Looks the ranges through, once; its time counts as `stat`.
  2873. fn look(&mut self, stat: usize) {
  2874. if self.work.is_empty() || self.found.is_some() {
  2875. return;
  2876. }
  2877. let scanning = std::time::Instant::now();
  2878. // Looked through without a lock: a piece that changes meanwhile (a
  2879. // later flight writing, the title's bytes going in) is found now or
  2880. // by that flight's landing, and the merge looks again under the
  2881. // lock.
  2882. self.found = Some(crate::shadow::find_all(&self.work));
  2883. crate::land::spent(stat, scanning);
  2884. #[cfg(feature = "diagnostics")]
  2885. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2886. }
  2887. /// What differs goes into title memory.
  2888. fn merge(mut self) {
  2889. use crate::land;
  2890. self.look(land::stat::SCAN);
  2891. let Some(found) = self.found else {
  2892. return;
  2893. };
  2894. let merging = std::time::Instant::now();
  2895. let mut written: Vec<u64> = Vec::new();
  2896. if land::on() {
  2897. // Pieces in the same block of title memory in one job, in order.
  2898. let pieces: Vec<(usize, usize, usize)> =
  2899. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  2900. let start = |i: usize| self.work[i].0.span().0 as usize;
  2901. let mut order: Vec<usize> = (0..pieces.len()).collect();
  2902. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  2903. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  2904. let jobs = land::jobs(&cut);
  2905. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  2906. land::each(jobs.len(), &|j| {
  2907. let working = std::time::Instant::now();
  2908. let mut notes = land::Notes::default();
  2909. for &p in &order[jobs[j].clone()] {
  2910. let (i, at, n) = pieces[p];
  2911. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  2912. }
  2913. notes.flush();
  2914. land::spent(land::stat::BACK_ALL, working);
  2915. });
  2916. land::count(land::stat::JOBS, jobs.len() as u64);
  2917. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  2918. } else {
  2919. let (mut now, mut title) = (Vec::new(), Vec::new());
  2920. for ((shadow, ..), found) in self.work.iter().zip(found) {
  2921. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  2922. written.push(found.into_iter().map(merge).sum());
  2923. }
  2924. }
  2925. land::spent(land::stat::BACK, merging);
  2926. for ((_, from, to), written) in self.work.iter().zip(written) {
  2927. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  2928. #[cfg(feature = "diagnostics")]
  2929. crate::copystat::compared(*from, to - from, written as usize);
  2930. let _ = (from, to);
  2931. }
  2932. }
  2933. }
  2934. /// For the frame-rate line, with [`late`]: what the line of flights did
  2935. /// per frame since the last one.
  2936. fn late_line(frames: f64) {
  2937. if !late() {
  2938. return;
  2939. }
  2940. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2941. tracing::info!(
  2942. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2943. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2944. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2945. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2946. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2947. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2948. s[0],
  2949. s[1],
  2950. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2951. s[12] / 1000.0,
  2952. s[WHY_SYNC],
  2953. s[WHY_CARD_DONE],
  2954. s[WHY_VALUE],
  2955. s[WHY_STALE],
  2956. s[WHY_READ],
  2957. s[15],
  2958. s[16],
  2959. s[17],
  2960. s[WHY_RUN],
  2961. late_most(),
  2962. s[WHY_MOST],
  2963. s[WHY_WRITES],
  2964. s[WHY_FENCE],
  2965. s[13],
  2966. s[14],
  2967. );
  2968. {
  2969. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2970. tracing::info!(
  2971. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2972. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2973. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2974. w[WHY_SYNC],
  2975. w[WHY_CARD_DONE],
  2976. w[WHY_VALUE],
  2977. w[WHY_STALE],
  2978. w[WHY_READ],
  2979. w[WHY_RUN],
  2980. w[WHY_MOST],
  2981. w[WHY_WRITES],
  2982. w[WHY_FENCE],
  2983. );
  2984. }
  2985. if relay() {
  2986. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2987. tracing::info!(
  2988. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2989. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2990. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2991. \"settles\" above are waits of other threads for it)",
  2992. r[1],
  2993. r[0],
  2994. r[2] / 1000.0,
  2995. r[3] / 1000.0,
  2996. r[4] / 1000.0,
  2997. );
  2998. if send::own() {
  2999. let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3000. tracing::info!(
  3001. "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
  3002. taking them out of the CPU sides",
  3003. t[0] / (1 << 20) as f64,
  3004. t[1],
  3005. t[2],
  3006. t[3] / 1000.0,
  3007. );
  3008. }
  3009. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3010. if t[0] > 0.0 {
  3011. tracing::info!(
  3012. "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",
  3013. t[0],
  3014. t[1],
  3015. t[2],
  3016. );
  3017. }
  3018. }
  3019. crate::land::log(frames);
  3020. if place::on() {
  3021. let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3022. tracing::info!(
  3023. "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",
  3024. t[0],
  3025. t[1] / 1024.0,
  3026. t[2],
  3027. t[3],
  3028. );
  3029. }
  3030. card_steps::log(frames);
  3031. crate::picked::log(frames);
  3032. #[cfg(feature = "diagnostics")]
  3033. log_blame(frames);
  3034. if late_exact() {
  3035. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  3036. tracing::info!(
  3037. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  3038. {runs:.0} changed runs, {:.2} MB",
  3039. bytes / (1 << 20) as f64
  3040. );
  3041. }
  3042. }
  3043. pub(crate) mod awake;
  3044. mod card_steps;
  3045. pub(crate) mod indirects;
  3046. mod place;
  3047. mod send;
  3048. #[cfg(feature = "diagnostics")]
  3049. pub(crate) mod spans;
  3050. mod torn;
  3051. pub(crate) mod upcheck;
  3052. #[cfg(test)]
  3053. mod late_tests {
  3054. use super::{continues, join_ranges, touches};
  3055. /// Copies join only when both ends continue and the whole does not
  3056. /// overlap itself.
  3057. #[test]
  3058. fn copies_join_only_end_to_end_and_apart() {
  3059. // (destination, source, bytes)
  3060. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  3061. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  3062. // A gap, or only one side continues.
  3063. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  3064. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  3065. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  3066. // Together they would overlap: the second reads what the first wrote.
  3067. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  3068. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  3069. // They touch without overlapping.
  3070. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  3071. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  3072. }
  3073. /// Ranges are found by what they hold, not by where they start, and a
  3074. /// range that only touches another's end does not touch it.
  3075. #[test]
  3076. fn ranges_touch_where_they_overlap() {
  3077. let mut ranges = Vec::new();
  3078. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  3079. assert_eq!(ranges, [(10, 25), (40, 60)]);
  3080. join_ranges(&mut ranges, [(25, 40)]);
  3081. assert_eq!(ranges, [(10, 60)]);
  3082. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  3083. for (from, to, hit) in [
  3084. (0, 10, false),
  3085. (0, 11, true),
  3086. (24, 25, true),
  3087. (25, 40, false),
  3088. (25, 41, true),
  3089. (59, 200, true),
  3090. (60, 100, false),
  3091. (100, 101, true),
  3092. (101, 500, false),
  3093. (30, 30, false),
  3094. (50, 50, false),
  3095. ] {
  3096. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  3097. }
  3098. assert!(!touches(&[], 0, usize::MAX));
  3099. }
  3100. }
  3101. /// Whether a title buffer copy that continues the one recorded before it
  3102. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  3103. /// default).
  3104. ///
  3105. /// Each copy is done at submission through the kernel, which reports a
  3106. /// page that is not there instead of faulting (`copy_mapped`), tells the
  3107. /// write watch and the guards, and ends the refreshes gathered so far: a
  3108. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  3109. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  3110. /// continue the one before is counted either way and said on its own line
  3111. /// with the frame rate; the switch is worth that many kernel calls.
  3112. ///
  3113. /// Joined, the same bytes move: [`continues`] joins only copies whose
  3114. /// ranges, taken together, do not overlap, and nothing is recorded between
  3115. /// two steps that follow each other. What differs: a page that is not
  3116. /// mapped now fails the joined copy as a whole (it then goes page by page,
  3117. /// zeros for what cannot be read, as a single copy does), where before
  3118. /// only the copy that held it did.
  3119. fn join_copies() -> bool {
  3120. static ON: OnceLock<bool> = OnceLock::new();
  3121. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  3122. }
  3123. /// Since the last frame-rate line: title buffer copies recorded, and those
  3124. /// that continue the one before ([`join_copies`]).
  3125. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  3126. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  3127. /// where `last` ended, source and destination both, and the two as one do
  3128. /// not overlap (source over destination): then one copy of both moves the
  3129. /// bytes the two would move in turn.
  3130. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  3131. let ((d, s, n), (dst, src, len)) = (last, next);
  3132. let Some(all) = n.checked_add(len) else {
  3133. return false;
  3134. };
  3135. d.checked_add(n) == Some(dst)
  3136. && s.checked_add(n) == Some(src)
  3137. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  3138. }
  3139. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  3140. /// One list's lock at a time: a submission may name a list twice.
  3141. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  3142. let mut back: Vec<Declared> = Vec::new();
  3143. // Where each copy is in it, and the ranges seen: dispatches declare the
  3144. // same ranges thousands of times a frame.
  3145. let mut places: ByCopy<usize> = ByCopy::default();
  3146. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  3147. for list in runs {
  3148. for step in &list.deferred().copies {
  3149. if let Step::GpuWrite(shadow, address, len) = step {
  3150. let key = std::sync::Arc::as_ptr(shadow) as usize;
  3151. if !seen.insert((key, *address, *len)) {
  3152. continue;
  3153. }
  3154. let i = *places.entry(key).or_insert_with(|| {
  3155. back.push((shadow.clone(), Vec::new()));
  3156. back.len() - 1
  3157. });
  3158. back[i].1.push((*address, *address + *len));
  3159. }
  3160. }
  3161. }
  3162. back
  3163. }
  3164. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  3165. /// lines that say what the title's CPU was given while it decided whether
  3166. /// the camera is in a room. The values of the small read-backs
  3167. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  3168. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  3169. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  3170. /// copies found stale after their refresh (`shadow.rs`; only with
  3171. /// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
  3172. /// runtime, the read requests that fail (with 2: every request).
  3173. pub(crate) fn walls_trace() -> bool {
  3174. static ON: OnceLock<bool> = OnceLock::new();
  3175. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  3176. }
  3177. /// After `list` has run: the texels its read-backs copied into host
  3178. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  3179. ///
  3180. /// A submission that is waited for did this itself. One sent ahead
  3181. /// ([`late`]) did not, at any stage: the flights' lists were settled
  3182. /// without it, so the title read a buffer nobody wrote, as before read-backs
  3183. /// were made (the exposure metering's two small float targets, every frame).
  3184. fn read_backs(list: &HostList) {
  3185. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  3186. let mut data = std::ptr::null_mut();
  3187. // SAFETY: a read-back buffer of ours, written by the list that has
  3188. // run; the title's destination holds every row (checked when the
  3189. // copy was recorded).
  3190. unsafe {
  3191. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  3192. let from = data.cast::<u8>().cast_const();
  3193. for line in 0..*rows {
  3194. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  3195. }
  3196. // The walls trace: what the title is handed (one row of at
  3197. // most 24 values: its 5x1 and 1x1 float targets).
  3198. if walls_trace() && *rows == 1 && *row <= 96 {
  3199. let mut values = [0f32; 24];
  3200. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  3201. tracing::info!(
  3202. frame = crate::frame::current(),
  3203. to = format_args!("{:#x}", *at),
  3204. bytes = *row,
  3205. values = ?&values[..*row / 4],
  3206. "walls trace: a read-back lands in title memory"
  3207. );
  3208. }
  3209. buffer.Unmap(0, None);
  3210. }
  3211. }
  3212. }
  3213. }
  3214. /// After the card ran what declared `back`: what shaders wrote there goes
  3215. /// into title memory, and the ranges are done with.
  3216. fn hand_back(back: &[Declared]) {
  3217. if crate::shadow::wide_back() {
  3218. // Every range first (the pieces that differ, found on several
  3219. // threads), then the merges, in order, as below.
  3220. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3221. for (shadow, declared) in back {
  3222. if shadow.carded() {
  3223. continue;
  3224. }
  3225. let mut sorted = declared.clone();
  3226. sorted.sort_unstable();
  3227. let mut spans: Vec<(usize, usize)> = Vec::new();
  3228. for (from, to) in sorted {
  3229. match spans.last_mut() {
  3230. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3231. _ => spans.push((from, to)),
  3232. }
  3233. }
  3234. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3235. }
  3236. #[cfg(feature = "diagnostics")]
  3237. let scanning = std::time::Instant::now();
  3238. let found = crate::shadow::find_all(&work);
  3239. #[cfg(feature = "diagnostics")]
  3240. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3241. for ((shadow, from, to), found) in work.iter().zip(found) {
  3242. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3243. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3244. #[cfg(feature = "diagnostics")]
  3245. crate::copystat::compared(*from, to - from, written);
  3246. }
  3247. for (shadow, declared) in back {
  3248. shadow.copy_back_done(declared);
  3249. }
  3250. return;
  3251. }
  3252. for (shadow, declared) in back {
  3253. if shadow.carded() {
  3254. // Done before (`Host::card_back`).
  3255. shadow.copy_back_done(declared);
  3256. continue;
  3257. }
  3258. // Each byte compared once: the world declares dozens of views
  3259. // of its 174 MB heap that overlap almost entirely, and comparing
  3260. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3261. // MB shaders wrote. Only ranges that overlap or touch are
  3262. // joined: what lies between two was not given to shaders (the
  3263. // snapshot does not hold it).
  3264. let mut sorted = declared.clone();
  3265. sorted.sort_unstable();
  3266. let mut spans: Vec<(usize, usize)> = Vec::new();
  3267. for (from, to) in sorted {
  3268. match spans.last_mut() {
  3269. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3270. _ => spans.push((from, to)),
  3271. }
  3272. }
  3273. for (from, to) in spans {
  3274. let written = shadow.copy_back(from, to - from);
  3275. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3276. #[cfg(feature = "diagnostics")]
  3277. crate::copystat::compared(from, to - from, written);
  3278. }
  3279. shadow.copy_back_done(declared);
  3280. }
  3281. }
  3282. impl Host {
  3283. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3284. /// mesh shaders need both); logged once.
  3285. pub(crate) fn mesh_shaders(&self) -> bool {
  3286. static MESH: OnceLock<bool> = OnceLock::new();
  3287. *MESH.get_or_init(|| {
  3288. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3289. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3290. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3291. };
  3292. // SAFETY: each query writes its own structure of the given size.
  3293. let ok = unsafe {
  3294. self.device
  3295. .CheckFeatureSupport(
  3296. D3D12_FEATURE_D3D12_OPTIONS7,
  3297. (&raw mut options).cast(),
  3298. size_of_val(&options) as u32,
  3299. )
  3300. .is_ok()
  3301. && self
  3302. .device
  3303. .CheckFeatureSupport(
  3304. D3D12_FEATURE_SHADER_MODEL,
  3305. (&raw mut model).cast(),
  3306. size_of_val(&model) as u32,
  3307. )
  3308. .is_ok()
  3309. };
  3310. let mesh = ok
  3311. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3312. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3313. tracing::info!(mesh, "host mesh shader support");
  3314. mesh
  3315. })
  3316. }
  3317. /// Whether the host GPU supports the depth bounds test; logged once.
  3318. pub(crate) fn depth_bounds(&self) -> bool {
  3319. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3320. *BOUNDS.get_or_init(|| {
  3321. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3322. // SAFETY: writes `options` of the given size.
  3323. let ok = unsafe {
  3324. self.device
  3325. .CheckFeatureSupport(
  3326. D3D12_FEATURE_D3D12_OPTIONS2,
  3327. (&raw mut options).cast(),
  3328. size_of_val(&options) as u32,
  3329. )
  3330. .is_ok()
  3331. };
  3332. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3333. tracing::info!(supported, "host depth bounds support");
  3334. supported
  3335. })
  3336. }
  3337. /// A new list, open for recording.
  3338. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3339. #[cfg(feature = "diagnostics")]
  3340. let started = std::time::Instant::now();
  3341. #[cfg(feature = "diagnostics")]
  3342. let before = private_bytes();
  3343. let list = self.make_list();
  3344. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3345. // (May shrink while a list is made, on another thread's account:
  3346. // added as it is, the sum is what counts.)
  3347. #[cfg(feature = "diagnostics")]
  3348. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3349. #[cfg(feature = "diagnostics")]
  3350. {
  3351. use crate::copystat::{C, add};
  3352. add(C::HostLists, 1);
  3353. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3354. }
  3355. list
  3356. }
  3357. /// An allocator and a closed list for a prelude.
  3358. fn make_prelude(&self) -> Option<Prelude> {
  3359. // SAFETY: plain object creation.
  3360. let made: windows::core::Result<Prelude> = unsafe {
  3361. (|| {
  3362. let allocator: ID3D12CommandAllocator =
  3363. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3364. let list: ID3D12GraphicsCommandList =
  3365. self.device
  3366. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3367. list.Close()?;
  3368. Ok((allocator, list))
  3369. })()
  3370. };
  3371. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3372. match made {
  3373. Ok(prelude) => Some(prelude),
  3374. Err(e) => {
  3375. tracing::warn!(error = %e, "no host list for a prelude");
  3376. None
  3377. }
  3378. }
  3379. }
  3380. fn make_list(&self) -> windows::core::Result<HostList> {
  3381. // SAFETY: plain object creation.
  3382. unsafe {
  3383. let allocator: ID3D12CommandAllocator = self
  3384. .device
  3385. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3386. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3387. 0,
  3388. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3389. &allocator,
  3390. None,
  3391. )?;
  3392. let prelude = OnceLock::new();
  3393. if !lazy_prelude() {
  3394. let _ = prelude.set(self.make_prelude());
  3395. }
  3396. #[cfg(feature = "diagnostics")]
  3397. let notes = std::sync::Arc::<Mutex<Vec<Note>>>::default();
  3398. let pipelines = std::sync::Arc::<Mutex<std::collections::BTreeSet<String>>>::default();
  3399. #[cfg(feature = "diagnostics")]
  3400. let indirects = indirects::Shared::default();
  3401. #[cfg(feature = "diagnostics")]
  3402. if dred_on() || dred_light() {
  3403. static NUMBER: AtomicU32 = AtomicU32::new(0);
  3404. let number = NUMBER.fetch_add(1, Ordering::Relaxed);
  3405. name(&list, || format!("victory host list {number}"));
  3406. let mut all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  3407. if number.is_multiple_of(256) {
  3408. all.retain(|_, l| l.0.strong_count() > 0);
  3409. }
  3410. all.insert(
  3411. number,
  3412. (
  3413. std::sync::Arc::downgrade(&notes),
  3414. std::sync::Arc::downgrade(&pipelines),
  3415. std::sync::Arc::downgrade(&indirects),
  3416. ),
  3417. );
  3418. }
  3419. Ok(HostList {
  3420. allocator,
  3421. list,
  3422. deferred: Mutex::default(),
  3423. scratch: Mutex::default(),
  3424. states: Mutex::default(),
  3425. twins: Mutex::default(),
  3426. prelude,
  3427. pipelines,
  3428. #[cfg(feature = "diagnostics")]
  3429. indirects,
  3430. budget: OnceLock::new(),
  3431. card_budget: OnceLock::new(),
  3432. indirect_args: Mutex::default(),
  3433. batch_args: Mutex::default(),
  3434. _alive: Counted::new(),
  3435. #[cfg(feature = "diagnostics")]
  3436. notes,
  3437. #[cfg(feature = "diagnostics")]
  3438. stamps: OnceLock::new(),
  3439. })
  3440. }
  3441. }
  3442. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3443. fn card_clock(&self) -> Option<&'static CardClock> {
  3444. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3445. static WATCH: std::sync::Once = std::sync::Once::new();
  3446. let clock = CLOCK
  3447. .get_or_init(|| {
  3448. // SAFETY: a plain fence on our device.
  3449. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3450. Some(CardClock {
  3451. fence,
  3452. state: Mutex::new((0, None)),
  3453. sent: std::sync::Condvar::new(),
  3454. })
  3455. })
  3456. .as_ref()?;
  3457. WATCH.call_once(|| {
  3458. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3459. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3460. }
  3461. });
  3462. Some(clock)
  3463. }
  3464. /// Lists of ours just went to the queue: the clock's signal goes
  3465. /// behind them, and an idle stretch of the card, if one was under way,
  3466. /// ends here ([`CARD_CLOCK_US`]).
  3467. fn card_sent(&self) {
  3468. let Some(clock) = self.card_clock() else {
  3469. return;
  3470. };
  3471. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3472. state.0 += 1;
  3473. // SAFETY: our queue and the clock's fence.
  3474. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3475. if let Some((since, worked_then)) = state.1.take() {
  3476. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3477. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3478. }
  3479. drop(state);
  3480. clock.sent.notify_one();
  3481. }
  3482. /// Whether the host has what copies in the card's memory need (three
  3483. /// lists and the compare); made at the first ask. A copy goes to the
  3484. /// card's memory only if it has.
  3485. pub(crate) fn card_ready(&self) -> bool {
  3486. static READY: OnceLock<bool> = OnceLock::new();
  3487. *READY.get_or_init(|| match self.make_card_work() {
  3488. Ok(work) => {
  3489. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3490. true
  3491. }
  3492. Err(e) => {
  3493. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3494. false
  3495. }
  3496. })
  3497. }
  3498. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3499. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3500. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3501. let mut code: Option<ID3DBlob> = None;
  3502. // SAFETY: the source and names live through the call; the out
  3503. // pointer is ours.
  3504. unsafe {
  3505. D3DCompile(
  3506. CARD_COMPARE.as_ptr().cast(),
  3507. CARD_COMPARE.len(),
  3508. windows::core::s!("card compare"),
  3509. None,
  3510. None,
  3511. windows::core::s!("main"),
  3512. windows::core::s!("cs_5_1"),
  3513. 0,
  3514. 0,
  3515. &mut code,
  3516. None,
  3517. )?;
  3518. }
  3519. let code = code.ok_or_else(windows::core::Error::empty)?;
  3520. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3521. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3522. // in one submission.
  3523. const RESULTS: u64 = 1 << 20;
  3524. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3525. name(&differs, || "card compare results".into());
  3526. // SAFETY: the blob's own bytes; the root signature is inside the
  3527. // shader.
  3528. unsafe {
  3529. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3530. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3531. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3532. pRootSignature: std::mem::transmute_copy(&root),
  3533. CS: D3D12_SHADER_BYTECODE {
  3534. pShaderBytecode: bytes.as_ptr().cast(),
  3535. BytecodeLength: bytes.len(),
  3536. },
  3537. ..Default::default()
  3538. })?;
  3539. #[cfg(feature = "diagnostics")]
  3540. name(&pso, || crate::replay::play::COMPARE.into());
  3541. Ok(CardWork {
  3542. sync: vec![list()?],
  3543. check: vec![list()?],
  3544. fetch: list()?,
  3545. root,
  3546. pso,
  3547. differs: (differs, data as usize, RESULTS),
  3548. fetched: None,
  3549. taken: 0,
  3550. out: 0,
  3551. })
  3552. }
  3553. }
  3554. /// Before a submission's lists run, for copies in the card's memory
  3555. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3556. /// the last submission goes to their card side (a list of ours, run
  3557. /// now; the submission's lists follow it on the queue), and the ranges
  3558. /// this submission's shaders may write get a compare to run after its
  3559. /// lists. `None` if there is nothing to do.
  3560. ///
  3561. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3562. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3563. /// `relay`).
  3564. /// `picked`: ranges that may be written too, and ranges to look at
  3565. /// (`crate::picked`).
  3566. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3567. use std::sync::Arc;
  3568. if !crate::shadow::cards() {
  3569. return None;
  3570. }
  3571. // The ranges this submission's shaders may write, per copy.
  3572. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3573. for list in runs {
  3574. for step in &list.deferred().copies {
  3575. if let Step::GpuWrite(shadow, address, len) = step
  3576. && shadow.carded()
  3577. {
  3578. let range = (*address, *address + *len);
  3579. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3580. Some((_, ranges)) => {
  3581. if !ranges.contains(&range) {
  3582. ranges.push(range);
  3583. }
  3584. }
  3585. None => declared.push((shadow.clone(), vec![range])),
  3586. }
  3587. }
  3588. }
  3589. }
  3590. let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
  3591. // (Of a copy with a declared range here, that says it.)
  3592. let looked: Vec<&crate::picked::Range> =
  3593. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3594. // With the relay: the order of the queue is held from here until
  3595. // what is taken is on the queue, and the taking is numbered.
  3596. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3597. let sent_as = match order.as_mut() {
  3598. Some(order) => {
  3599. **order += 1;
  3600. **order
  3601. }
  3602. None => 0,
  3603. };
  3604. let mut dirty = crate::shadow::card_dirty(sent_as);
  3605. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3606. return None;
  3607. }
  3608. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3609. let work = work.as_mut()?;
  3610. // A copy whose shader writes are declared for the first time gets
  3611. // its bytes from before, whole.
  3612. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3613. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3614. if shadow.card_make_before(|size| {
  3615. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3616. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3617. Some(before)
  3618. }) {
  3619. whole.push(shadow.clone());
  3620. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3621. dirty.push((shadow.clone(), Vec::new()));
  3622. }
  3623. }
  3624. }
  3625. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3626. let mut looks = None;
  3627. // The bytes as they are now, whatever later submissions put there.
  3628. let own = if send::own() { send::take(self, &dirty) } else { None };
  3629. if !dirty.is_empty() {
  3630. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3631. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3632. };
  3633. let (allocator, list) = &sync;
  3634. // SAFETY: the list's last run finished (it ran ahead of a
  3635. // submission that was waited for, and came back after that);
  3636. // live buffers, and the ranges lie in them.
  3637. let recorded = unsafe {
  3638. (|| -> windows::core::Result<()> {
  3639. allocator.Reset()?;
  3640. list.Reset(allocator, None)?;
  3641. if upcheck::on() {
  3642. looks = upcheck::record(self, list, &dirty);
  3643. }
  3644. // Every copy first, then one barrier call, then every
  3645. // pass: a wait between each copy and its pass had the
  3646. // card do them one after the other.
  3647. let mut sent = Vec::new();
  3648. if let Some(own) = &own {
  3649. own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
  3650. }
  3651. for (shadow, ranges) in &dirty {
  3652. let Some((staging, before, _)) = shadow.card_sides() else {
  3653. continue;
  3654. };
  3655. for &(a, b) in ranges {
  3656. if own.is_none() {
  3657. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3658. }
  3659. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3660. }
  3661. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3662. if own.is_none() && before.is_some() && !ranges.is_empty() {
  3663. sent.push(transition(
  3664. &shadow.buffer,
  3665. D3D12_RESOURCE_STATE_COPY_DEST,
  3666. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3667. ));
  3668. }
  3669. }
  3670. if !sent.is_empty() {
  3671. list.ResourceBarrier(&sent);
  3672. }
  3673. list.SetComputeRootSignature(&work.root);
  3674. list.SetPipelineState(&work.pso);
  3675. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3676. for (shadow, ranges) in &dirty {
  3677. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3678. continue;
  3679. };
  3680. // No twin (it cost the card the copy's size again,
  3681. // 399 MB in run 75): `before` holds a 128-bit hash
  3682. // of each 64 KiB piece. The pieces just sent up are
  3683. // hashed again, all of them the first time; the
  3684. // compare after the lists hashes the declared
  3685. // pieces and flags those whose hash is another.
  3686. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3687. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3688. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3689. vec![shadow.card_run(0, usize::MAX)]
  3690. } else {
  3691. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3692. };
  3693. // The same pieces in fewer passes (`rehash_runs`).
  3694. let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3695. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3696. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3697. for run in runs {
  3698. card_pass(list, &run, size as u32, 0, 0);
  3699. }
  3700. }
  3701. list.Close()?;
  3702. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3703. Ok(())
  3704. })()
  3705. };
  3706. if let Err(e) = recorded {
  3707. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3708. }
  3709. used.push((false, sync));
  3710. }
  3711. drop(order);
  3712. let mut plan = CardPlan {
  3713. ranges: Vec::new(),
  3714. check: None,
  3715. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3716. lists: used,
  3717. sent_as,
  3718. looks,
  3719. sends: own.map(send::Own::memory),
  3720. };
  3721. // Each byte once, as the copy-back joins the declared ranges. The
  3722. // results go behind those of plans still in the air.
  3723. let mut at = work.taken;
  3724. for (shadow, ranges) in &declared {
  3725. let mut sorted = ranges.clone();
  3726. sorted.sort_unstable();
  3727. let mut spans: Vec<(usize, usize)> = Vec::new();
  3728. for (from, to) in sorted {
  3729. match spans.last_mut() {
  3730. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3731. _ => spans.push((from, to)),
  3732. }
  3733. }
  3734. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3735. for (from, to) in spans {
  3736. let Some(span) = shadow.card_span(from, to) else {
  3737. continue;
  3738. };
  3739. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3740. plan.ranges.push(CardRange {
  3741. shadow: shadow.clone(),
  3742. declared: (from, to),
  3743. span,
  3744. at,
  3745. compared,
  3746. picked: false,
  3747. });
  3748. if compared {
  3749. at += span.pieces;
  3750. }
  3751. }
  3752. }
  3753. for (shadow, from, len) in looked {
  3754. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3755. if let Some(span) = shadow.card_span(*from, from + len)
  3756. && twin
  3757. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3758. {
  3759. plan.ranges.push(CardRange {
  3760. shadow: shadow.clone(),
  3761. declared: (*from, from + len),
  3762. span,
  3763. at,
  3764. compared: true,
  3765. picked: true,
  3766. });
  3767. at += span.pieces;
  3768. }
  3769. }
  3770. work.taken = at;
  3771. if plan.ranges.iter().any(|r| r.compared) {
  3772. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3773. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3774. };
  3775. let (allocator, list) = &check;
  3776. // SAFETY: the list's last run finished (its submission was
  3777. // waited for, and it came back after that); live buffers; the
  3778. // compare's own root signature.
  3779. let recorded = unsafe {
  3780. (|| -> windows::core::Result<ID3D12CommandList> {
  3781. allocator.Reset()?;
  3782. list.Reset(allocator, None)?;
  3783. // What the submission's shaders wrote, first.
  3784. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3785. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3786. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3787. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3788. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3789. pResource: std::mem::ManuallyDrop::new(None),
  3790. }),
  3791. },
  3792. }]);
  3793. list.SetComputeRootSignature(&work.root);
  3794. list.SetPipelineState(&work.pso);
  3795. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3796. for r in plan.ranges.iter().filter(|r| r.compared) {
  3797. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3798. continue;
  3799. };
  3800. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3801. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3802. // (What is only looked at keeps its hashes: what
  3803. // changed there is the next declared range's to land.)
  3804. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  3805. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3806. }
  3807. list.Close()?;
  3808. list.cast()
  3809. })()
  3810. };
  3811. match recorded {
  3812. Ok(list) => plan.check = Some(list),
  3813. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3814. }
  3815. plan.lists.push((true, check));
  3816. }
  3817. work.out += 1;
  3818. Some(plan)
  3819. }
  3820. /// With [`relay`]: whether the compare's result area is half taken by
  3821. /// plans in the air. It starts from the beginning only when no plan is
  3822. /// out, so the caller lets the flights land first.
  3823. fn card_results_low(&self) -> bool {
  3824. CARD_WORK
  3825. .lock()
  3826. .unwrap_or_else(|e| e.into_inner())
  3827. .as_ref()
  3828. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3829. }
  3830. /// The plan's submission has run and its results were read
  3831. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3832. /// when nothing of ours is on the card, so the compare's results start
  3833. /// from the beginning again.
  3834. fn card_done(&self, plan: CardPlan) {
  3835. if let Some(looks) = plan.looks {
  3836. looks.read();
  3837. }
  3838. if let Some(memory) = plan.sends {
  3839. send::give_back(memory);
  3840. }
  3841. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3842. let Some(work) = work.as_mut() else {
  3843. return;
  3844. };
  3845. for (check, list) in plan.lists {
  3846. if check { work.check.push(list) } else { work.sync.push(list) }
  3847. }
  3848. work.out = work.out.saturating_sub(1);
  3849. // With the relay other plans may be on the card, their results
  3850. // not read yet: the area starts again only when none is out.
  3851. if !relay() || work.out == 0 {
  3852. work.taken = 0;
  3853. }
  3854. }
  3855. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3856. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3857. // SAFETY: plain object creation.
  3858. let copying = relay_copy().then(|| unsafe {
  3859. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3860. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3861. let list: ID3D12GraphicsCommandList =
  3862. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3863. list.Close()?;
  3864. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3865. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3866. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3867. ..Default::default()
  3868. })?;
  3869. Ok(((allocator, list), queue))
  3870. })()
  3871. });
  3872. let (list, queue) = match copying {
  3873. Some(Ok((list, queue))) => (list, Some(queue)),
  3874. Some(Err(e)) => {
  3875. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3876. (self.make_prelude()?, None)
  3877. }
  3878. None => (self.make_prelude()?, None),
  3879. };
  3880. // SAFETY: plain objects of our own.
  3881. unsafe {
  3882. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3883. let event = CreateEventW(None, false, false, None).ok()?;
  3884. Some(RelayFetch {
  3885. list,
  3886. queue,
  3887. fence,
  3888. event,
  3889. sent: 0,
  3890. buffer: None,
  3891. suspects: torn::Suspects::default(),
  3892. had: crate::land::Had::default(),
  3893. })
  3894. }
  3895. }
  3896. /// [`relay`], on the thread that lands flights: for the plans of the
  3897. /// flights being landed (the card has run them), the pieces their
  3898. /// compares flagged are fetched, once each, with a list and a wait of
  3899. /// this thread's own, and what shaders wrote in them goes into title
  3900. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3901. /// no submission lock; a piece flagged under one range of a plan is
  3902. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3903. /// whatever was sent meanwhile, so it may bring a later flight's
  3904. /// bytes, which that flight's landing then finds merged already; and
  3905. /// nothing is sent back up. `plans` come with the value signalled behind
  3906. /// their flight. `meanwhile` is called while the fetch is on its way, if
  3907. /// there is one.
  3908. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  3909. use crate::land;
  3910. let gathering = std::time::Instant::now();
  3911. let differs = {
  3912. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3913. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3914. };
  3915. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3916. let mut total = 0u64;
  3917. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  3918. fetch.had.landing(first);
  3919. }
  3920. // SAFETY: the mapping of the results. The compares of these plans
  3921. // have run, and their dwords are given to no other plan before these
  3922. // are done with (`card_done`).
  3923. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  3924. if let Some(differs) = differs {
  3925. // Pieces caught while a later flight was at them (`torn`).
  3926. let suspects = fetch.as_ref().map(|f| &f.suspects);
  3927. let mut seen = std::collections::HashSet::new();
  3928. for &(plan, behind) in plans {
  3929. plan.picked_found(differs);
  3930. let flags: Vec<(usize, u32, bool)> = plan
  3931. .ranges
  3932. .iter()
  3933. .filter(|r| !r.picked)
  3934. .flat_map(|r| {
  3935. (0..r.span.pieces).map(move |p| {
  3936. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  3937. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  3938. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  3939. })
  3940. })
  3941. .collect();
  3942. let fetched = flagged_pieces(&flags);
  3943. for r in plan.ranges.iter().filter(|r| !r.picked) {
  3944. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3945. if upcheck::on() {
  3946. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  3947. }
  3948. for p in 0..r.span.pieces {
  3949. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  3950. continue;
  3951. }
  3952. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3953. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  3954. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  3955. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  3956. land::count(land::stat::HAD, 1);
  3957. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  3958. if land::skip_on() {
  3959. continue;
  3960. }
  3961. }
  3962. if upcheck::on() {
  3963. upcheck::fetched(r.shadow.id(), lo);
  3964. }
  3965. seen.insert((copy, lo, hi));
  3966. pieces.push((r.shadow.clone(), lo, hi, total));
  3967. total += (hi - lo) as u64;
  3968. }
  3969. }
  3970. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3971. }
  3972. }
  3973. }
  3974. if land::on() {
  3975. // In the order they are landed, each byte of a copy once.
  3976. let keys: Vec<land::Piece> =
  3977. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  3978. total = 0;
  3979. pieces = land::ordered(&keys)
  3980. .into_iter()
  3981. .map(|(i, title, len)| {
  3982. let shadow = &pieces[i].0;
  3983. let lo = title - shadow.span().0 as usize;
  3984. let at = total;
  3985. total += len as u64;
  3986. (shadow.clone(), lo, lo + len, at)
  3987. })
  3988. .collect();
  3989. }
  3990. land::spent(land::stat::GATHER, gathering);
  3991. if fetch.is_none() {
  3992. *fetch = self.make_relay_fetch();
  3993. }
  3994. // On the copy queue a later flight may be at a piece while it is
  3995. // fetched: the pieces come down whole, to be hashed.
  3996. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  3997. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  3998. if let Some(check) = &check {
  3999. total = check.total;
  4000. }
  4001. // The sends these flights ran behind, all a fetch on the copy queue
  4002. // is known to have run behind.
  4003. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  4004. if pieces.is_empty() {
  4005. // Nothing to fetch: every send so far is older than the next
  4006. // fetch, if that goes to the queue the sends went to.
  4007. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  4008. true => behind,
  4009. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  4010. };
  4011. crate::shadow::relay_fetched(after);
  4012. return;
  4013. }
  4014. let Some(f) = fetch.as_mut() else {
  4015. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  4016. };
  4017. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  4018. let size = total.next_multiple_of(16 << 20);
  4019. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4020. }
  4021. let Some((buffer, data, _)) = f.buffer.clone() else {
  4022. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  4023. };
  4024. f.sent += 1;
  4025. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  4026. let copy_queue = f.queue.clone();
  4027. let waiting = std::time::Instant::now();
  4028. // The flights the fetch runs behind: those in the line by now have
  4029. // been given to the queue. On the copy queue, those landed here.
  4030. let ahead = match copy_queue {
  4031. Some(_) => 0,
  4032. None => line().target,
  4033. };
  4034. // SAFETY: the list's last run was waited for by this thread; live
  4035. // buffers (the copies are held by the plans); the fence and the
  4036. // event are this thread's.
  4037. let ran = unsafe {
  4038. (|| -> windows::core::Result<u64> {
  4039. allocator.Reset()?;
  4040. list.Reset(&allocator, None)?;
  4041. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  4042. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  4043. }
  4044. list.Close()?;
  4045. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  4046. if let Some(queue) = &copy_queue {
  4047. queue.ExecuteCommandLists(&lists);
  4048. queue.Signal(&fence, sent)?;
  4049. meanwhile();
  4050. fence.SetEventOnCompletion(sent, event)?;
  4051. WaitForSingleObject(event, INFINITE);
  4052. return Ok(behind);
  4053. }
  4054. // In the order of the queue: the sends of title bytes so
  4055. // far are ahead of this fetch, every later one behind it.
  4056. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  4057. self.queue.ExecuteCommandLists(&lists);
  4058. let after = *order;
  4059. drop(order);
  4060. self.card_sent();
  4061. self.queue.Signal(&fence, sent)?;
  4062. meanwhile();
  4063. fence.SetEventOnCompletion(sent, event)?;
  4064. WaitForSingleObject(event, INFINITE);
  4065. Ok(after)
  4066. })()
  4067. };
  4068. let after = match ran {
  4069. Ok(after) => after,
  4070. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  4071. };
  4072. let us = waiting.elapsed().as_micros() as u64;
  4073. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  4074. {
  4075. use crate::shadow::CARD_STATS;
  4076. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4077. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4078. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4079. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  4080. }
  4081. let merging = std::time::Instant::now();
  4082. let mut written = 0;
  4083. if land::on() {
  4084. let titles: Vec<(usize, usize)> =
  4085. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  4086. let jobs = land::jobs(&titles);
  4087. let put = std::sync::atomic::AtomicU64::new(0);
  4088. land::each(jobs.len(), &|j| {
  4089. let working = std::time::Instant::now();
  4090. if let Some(check) = &check {
  4091. for i in jobs[j].clone() {
  4092. // SAFETY: as below.
  4093. unsafe { check.look(i, data) };
  4094. }
  4095. }
  4096. let mut notes = land::Notes::default();
  4097. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  4098. let addressed: Vec<(usize, usize, usize)> =
  4099. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  4100. // SAFETY: the mapping of the fetched bytes, `total` of
  4101. // them; the copy into it has run, and the next waits
  4102. // for this call.
  4103. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  4104. }
  4105. notes.flush();
  4106. land::spent(land::stat::CARD_ALL, working);
  4107. });
  4108. land::count(land::stat::JOBS, jobs.len() as u64);
  4109. written = put.into_inner();
  4110. } else {
  4111. let mut title = Vec::new();
  4112. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  4113. if let Some(check) = &check {
  4114. // SAFETY: as below.
  4115. unsafe { check.look(i, data) };
  4116. }
  4117. // SAFETY: the mapping of the fetched bytes, `total` of them;
  4118. // the copy into it has run.
  4119. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  4120. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  4121. shadow.walls_merged(gpu.len(), merged);
  4122. written += merged as u64;
  4123. }
  4124. }
  4125. land::spent(land::stat::CARD, merging);
  4126. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  4127. if let Some(f) = fetch.as_mut() {
  4128. if let Some(check) = &check {
  4129. check.done(&mut f.suspects);
  4130. }
  4131. f.had.fetched(
  4132. ahead,
  4133. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  4134. );
  4135. }
  4136. // Sends up to `after` are of no use to any later merge.
  4137. crate::shadow::relay_fetched(after);
  4138. }
  4139. /// [`relay`], on the thread that lands flights: `items` are the first
  4140. /// things of the line, flights the card has run and what follows them.
  4141. /// What their shaders wrote goes into title memory (copies in the
  4142. /// card's memory first, then the others, each byte once whichever
  4143. /// flights declared it); then every flight's ranges are done with;
  4144. /// then, in the line's order, each flight's read-backs, its
  4145. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  4146. /// is complete before the title is told anything.
  4147. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  4148. let landing = std::time::Instant::now();
  4149. {
  4150. let flights: Vec<&Flight> = items
  4151. .iter()
  4152. .filter_map(|l| match l {
  4153. Late::Run(flight) => Some(flight),
  4154. _ => None,
  4155. })
  4156. .collect();
  4157. if !flights.is_empty() {
  4158. // SAFETY: a plain query.
  4159. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4160. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  4161. fail(format_args!(
  4162. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  4163. flights.len(),
  4164. runs.len(),
  4165. self.removal_data(&runs),
  4166. last_notes(&runs)
  4167. ));
  4168. }
  4169. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  4170. // (Each byte once: the ranges are joined.)
  4171. let mut back: Vec<Declared> = Vec::new();
  4172. for flight in &flights {
  4173. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  4174. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4175. Some((_, all)) => all.extend_from_slice(ranges),
  4176. None => back.push((shadow.clone(), ranges.clone())),
  4177. }
  4178. }
  4179. }
  4180. let mut hand_back = relay_hand_back(&back);
  4181. self.relay_card_back(&plans, fetch, &mut || {
  4182. if crate::land::on() {
  4183. hand_back.look(crate::land::stat::SCAN_BESIDE);
  4184. }
  4185. });
  4186. hand_back.merge();
  4187. let finishing = std::time::Instant::now();
  4188. // Only now, and flight by flight: a range another flight
  4189. // in the air declared too stays closed to refreshes.
  4190. for flight in &flights {
  4191. for (shadow, ranges) in &flight.back {
  4192. shadow.copy_back_done(ranges);
  4193. }
  4194. }
  4195. crate::land::spent(crate::land::stat::DONE, finishing);
  4196. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4197. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  4198. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  4199. }
  4200. }
  4201. // In the order given: what tells the title the card is done.
  4202. let mut last = 0;
  4203. let mut landed = Vec::new();
  4204. let mut telling = std::time::Instant::now();
  4205. for item in items {
  4206. telling = match item {
  4207. Late::Run(flight) => {
  4208. last = flight.number;
  4209. for &i in &flight.order {
  4210. read_backs(flight.lists[i].host());
  4211. }
  4212. if let Some(card) = flight.card {
  4213. self.card_done(card);
  4214. }
  4215. if let Some(own) = flight.own {
  4216. own.landed();
  4217. }
  4218. landed.push((flight.lists, flight.order));
  4219. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  4220. }
  4221. Late::Write(at, what, bytes) => {
  4222. what.write(at as *mut u8, bytes);
  4223. crate::land::spent(crate::land::stat::TOLD, telling)
  4224. }
  4225. Late::Signal(fence, value) => {
  4226. crate::fence::set(fence as crate::object::This, value);
  4227. crate::land::spent(crate::land::stat::TOLD, telling)
  4228. }
  4229. };
  4230. }
  4231. if last > 0 {
  4232. FINISHED.store(last, Ordering::Release);
  4233. bury(last);
  4234. }
  4235. self.log_messages();
  4236. crate::land::spent(crate::land::stat::REST, telling);
  4237. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4238. {
  4239. let mut line = line();
  4240. let Line {
  4241. line: items,
  4242. written,
  4243. lists,
  4244. settling,
  4245. poke,
  4246. landed: kept,
  4247. in_hand,
  4248. landing,
  4249. ..
  4250. } = &mut *line;
  4251. kept.extend(landed);
  4252. in_hand.clear();
  4253. landing.clear();
  4254. // What is still in the air, from the flights that are.
  4255. written.clear();
  4256. *lists = 0;
  4257. let mut ranges = Vec::new();
  4258. for item in items.iter() {
  4259. if let Late::Run(flight) = item {
  4260. *lists += flight.order.len().max(1);
  4261. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  4262. }
  4263. }
  4264. join_ranges(written, ranges);
  4265. *settling = false;
  4266. // The landed lists are reset, and what queues hold looked at,
  4267. // by the helper thread (they take locks a waiter may hold).
  4268. *poke = true;
  4269. }
  4270. LINE_MOVED.notify_all();
  4271. LINE_LANDED.notify_all();
  4272. }
  4273. /// After a submission ran, for copies in the card's memory: the pieces
  4274. /// of the declared ranges that the compare found differing (all of a
  4275. /// range it did not compare) are fetched, with one more wait for the
  4276. /// card, and what shaders wrote in them goes into title memory.
  4277. /// `submitted` is the last value signalled on the fence. `seen` holds
  4278. /// the pieces fetched already since the card was last waited for
  4279. /// (several submissions settled together name the same ones).
  4280. fn card_back(
  4281. &self,
  4282. plan: &CardPlan,
  4283. submitted: &mut u64,
  4284. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4285. ) {
  4286. if plan.ranges.is_empty() {
  4287. return;
  4288. }
  4289. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4290. let Some(work) = work.as_mut() else {
  4291. return;
  4292. };
  4293. // SAFETY: the mapping of the results, which the compare (it has
  4294. // run) wrote.
  4295. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4296. // The pieces to fetch: the range, the offsets in its copy, and
  4297. // where the bytes come down.
  4298. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4299. let mut total = 0u64;
  4300. plan.picked_found(differs);
  4301. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4302. for p in 0..r.span.pieces {
  4303. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4304. continue;
  4305. }
  4306. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4307. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4308. pieces.push((i, lo, hi, total));
  4309. total += (hi - lo) as u64;
  4310. }
  4311. }
  4312. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4313. }
  4314. let mut written = vec![0usize; plan.ranges.len()];
  4315. if !pieces.is_empty() {
  4316. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4317. let size = total.next_multiple_of(16 << 20);
  4318. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4319. }
  4320. let Some((fetched, data, _)) = &work.fetched else {
  4321. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4322. };
  4323. let waiting = std::time::Instant::now();
  4324. let (allocator, list) = &work.fetch;
  4325. // SAFETY: the list's last run was waited for; live buffers; the
  4326. // fence and event are ours, under the submission lock.
  4327. let ran = unsafe {
  4328. (|| -> windows::core::Result<()> {
  4329. allocator.Reset()?;
  4330. list.Reset(allocator, None)?;
  4331. for &(i, lo, hi, at) in &pieces {
  4332. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4333. }
  4334. list.Close()?;
  4335. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4336. self.card_sent();
  4337. *submitted += 1;
  4338. self.queue.Signal(&self.fence, *submitted)?;
  4339. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4340. let was_working = working(false);
  4341. WaitForSingleObject(self.event, INFINITE);
  4342. stood(waiting);
  4343. working(was_working);
  4344. Ok(())
  4345. })()
  4346. };
  4347. if let Err(e) = ran {
  4348. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4349. }
  4350. {
  4351. use crate::shadow::CARD_STATS;
  4352. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4353. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4354. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4355. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4356. }
  4357. if wide_merge() && pieces.len() >= 8 {
  4358. // The pieces are apart from one another (each its own bytes
  4359. // of its copy and of title memory): several at a time.
  4360. let fetched = *data;
  4361. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4362. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4363. let each = pieces.len().div_ceil(8);
  4364. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4365. .chunks(each)
  4366. .map(|chunk| {
  4367. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4368. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4369. let counts = counts.clone();
  4370. Box::new(move || {
  4371. let mut title = Vec::new();
  4372. for (shadow, i, lo, hi, at) in chunk {
  4373. // SAFETY: the mapping of the fetched bytes;
  4374. // the copy into it has run, and the caller
  4375. // waits for this job.
  4376. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4377. let merged = shadow.card_merge(lo, gpu, &mut title);
  4378. shadow.walls_merged(gpu.len(), merged);
  4379. counts[i].fetch_add(merged, Ordering::Relaxed);
  4380. }
  4381. }) as Box<dyn FnOnce() + Send>
  4382. })
  4383. .collect();
  4384. crate::shadow::wide_run(jobs);
  4385. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4386. *written += count.load(Ordering::Relaxed);
  4387. }
  4388. } else {
  4389. let mut title = Vec::new();
  4390. for &(i, lo, hi, at) in &pieces {
  4391. // SAFETY: the mapping of the fetched bytes, `total` of
  4392. // them; the copy into it has run.
  4393. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4394. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4395. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4396. written[i] += merged;
  4397. }
  4398. }
  4399. }
  4400. for (r, written) in plan.ranges.iter().zip(written) {
  4401. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4402. let (from, to) = r.declared;
  4403. #[cfg(feature = "diagnostics")]
  4404. crate::copystat::compared(from, to - from, written);
  4405. let _ = (from, to);
  4406. }
  4407. }
  4408. /// Runs closed lists and waits for them, and with [`late`] for
  4409. /// everything sent to the card before them, which is settled first.
  4410. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4411. let _ = self.submit(runs, false);
  4412. }
  4413. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4414. /// from the title's, go to the card in `order` and are not waited for.
  4415. /// They join the line of flights and are settled, with the others in
  4416. /// the air, at the next point where what they do can be observed
  4417. /// ([`late`] lists those points); their host lists are reset and kept
  4418. /// for reuse then, as a queue does for the lists it ran.
  4419. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4420. if order.is_empty() {
  4421. crate::list::recycle(lists, &order);
  4422. return;
  4423. }
  4424. late_threads();
  4425. let sent = {
  4426. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4427. self.submit(&runs, true)
  4428. };
  4429. let Some((mut submitted, sent)) = sent else {
  4430. // (Not reached: a submission sent ahead always comes back.)
  4431. crate::list::recycle(lists, &order);
  4432. return;
  4433. };
  4434. let told = !sent.writes.is_empty();
  4435. let most = {
  4436. let mut line = line();
  4437. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4438. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4439. *flying += order.len();
  4440. *target = *submitted;
  4441. items.push(Late::Run(Flight {
  4442. number: sent.number,
  4443. fence: *target,
  4444. lists,
  4445. order,
  4446. card: sent.card,
  4447. back: sent.back,
  4448. own: sent.own,
  4449. }));
  4450. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4451. *flying >= late_most()
  4452. };
  4453. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4454. RELAY_MOVED.notify_one();
  4455. if told && !late_writes() {
  4456. self.settle(&mut submitted, WHY_WRITES);
  4457. } else if most && relay_exact() {
  4458. // Until there are fewer, not until there are none.
  4459. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4460. } else if most {
  4461. self.settle(&mut submitted, WHY_MOST);
  4462. } else {
  4463. LINE_MOVED.notify_one();
  4464. }
  4465. drop(submitted);
  4466. land();
  4467. }
  4468. /// Sends `list`, a closed list of ours (the present's copy), as a
  4469. /// flight ([`late_free_present`]): not waited for, settled with the
  4470. /// others. The caller keeps the list and does not reset it before the
  4471. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4472. /// it ran and was waited for after all.
  4473. fn execute_own(&self, list: &HostList) -> u64 {
  4474. late_threads();
  4475. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4476. return 0;
  4477. };
  4478. let number = sent.number;
  4479. {
  4480. let mut line = line();
  4481. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4482. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4483. *flying += 1;
  4484. *target = *submitted;
  4485. items.push(Late::Run(Flight {
  4486. number,
  4487. fence: *target,
  4488. lists: Vec::new(),
  4489. order: Vec::new(),
  4490. card: sent.card,
  4491. back: sent.back,
  4492. own: sent.own,
  4493. }));
  4494. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4495. }
  4496. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4497. LINE_MOVED.notify_one();
  4498. RELAY_MOVED.notify_one();
  4499. drop(submitted);
  4500. number
  4501. }
  4502. /// Waits for the card to run every flight in the air ([`late`]) and
  4503. /// does what they left to do, as [`Host::execute`] does for one
  4504. /// submission after its wait: the pieces their shaders wrote in copies
  4505. /// in the card's memory are fetched and merged (each once), the ranges
  4506. /// they declared in the other copies are compared and copied back
  4507. /// (each byte once, whichever flights declared it), and then, in the
  4508. /// order they were given: their bottom-of-pipe writes and the fence
  4509. /// signals behind them. `submitted` is the submission lock's value;
  4510. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4511. ///
  4512. /// Everything in the air is settled, never the first flights alone:
  4513. /// the merge writes the copies' CPU side, which a flight still on the
  4514. /// card may be writing too.
  4515. fn settle(&self, submitted: &mut u64, why: usize) {
  4516. if !late() {
  4517. return;
  4518. }
  4519. if relay() {
  4520. // Nothing is settled here: the thread that lands flights does
  4521. // it, in order, and this waits until nothing is in the air and
  4522. // nothing is being landed. Every point that settled before
  4523. // comes here, so each still sees title memory, fences and
  4524. // bottom-of-pipe values as after a settle.
  4525. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4526. return;
  4527. }
  4528. let was_working = working(true);
  4529. let mut counted = false;
  4530. loop {
  4531. let items = {
  4532. let mut line = line();
  4533. if line.line.is_empty() {
  4534. line.settling = false;
  4535. break;
  4536. }
  4537. line.settling = true;
  4538. line.written.clear();
  4539. line.lists = 0;
  4540. std::mem::take(&mut line.line)
  4541. };
  4542. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4543. if !counted {
  4544. counted = true;
  4545. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4546. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4547. }
  4548. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4549. if flights > 0 {
  4550. submitting(2, flights);
  4551. let waiting = std::time::Instant::now();
  4552. // SAFETY: the fence and event are ours, under the
  4553. // submission lock; `submitted` is the last value signalled.
  4554. unsafe {
  4555. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4556. Ok(()) => {
  4557. working(false);
  4558. WaitForSingleObject(self.event, INFINITE);
  4559. stood(waiting);
  4560. working(true);
  4561. }
  4562. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4563. }
  4564. }
  4565. let gpu = waiting.elapsed();
  4566. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4567. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4568. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4569. #[cfg(feature = "diagnostics")]
  4570. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4571. format!("{flights} submissions sent ahead, settled together")
  4572. });
  4573. // SAFETY: a plain query.
  4574. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4575. let runs: Vec<&HostList> = items
  4576. .iter()
  4577. .filter_map(|i| match i {
  4578. Late::Run(f) => Some(f),
  4579. _ => None,
  4580. })
  4581. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4582. .collect();
  4583. fail(format_args!(
  4584. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4585. runs.len(),
  4586. self.removal_data(&runs),
  4587. last_notes(&runs)
  4588. ));
  4589. }
  4590. submitting(3, flights);
  4591. let copying = std::time::Instant::now();
  4592. let mut seen = std::collections::HashSet::new();
  4593. let mut back: Vec<Declared> = Vec::new();
  4594. for item in &items {
  4595. let Late::Run(flight) = item else {
  4596. continue;
  4597. };
  4598. if let Some(card) = &flight.card {
  4599. self.card_back(card, submitted, &mut seen);
  4600. }
  4601. for (shadow, ranges) in &flight.back {
  4602. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4603. Some((_, all)) => {
  4604. for range in ranges {
  4605. if !all.contains(range) {
  4606. all.push(*range);
  4607. }
  4608. }
  4609. }
  4610. None => back.push((shadow.clone(), ranges.clone())),
  4611. }
  4612. }
  4613. }
  4614. hand_back(&back);
  4615. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4616. }
  4617. // In the order given: what tells the title the card is done.
  4618. let mut last = 0;
  4619. let mut landed = Vec::new();
  4620. for item in items {
  4621. match item {
  4622. Late::Run(flight) => {
  4623. last = flight.number;
  4624. for &i in &flight.order {
  4625. read_backs(flight.lists[i].host());
  4626. }
  4627. if let Some(card) = flight.card {
  4628. self.card_done(card);
  4629. }
  4630. landed.push((flight.lists, flight.order));
  4631. }
  4632. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4633. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4634. }
  4635. }
  4636. if last > 0 {
  4637. FINISHED.store(last, Ordering::Release);
  4638. bury(last);
  4639. }
  4640. line().landed.extend(landed);
  4641. }
  4642. if counted {
  4643. self.log_messages();
  4644. submitting(0, 0);
  4645. // What was settled may be what a queue stands at, and the
  4646. // caller may not be one that looks (a read-back, a present).
  4647. if why != WHY_CARD_DONE {
  4648. line().poke = true;
  4649. LINE_MOVED.notify_one();
  4650. }
  4651. }
  4652. working(was_working);
  4653. }
  4654. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4655. /// copies, which flights may be writing and the title wrote too
  4656. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4657. /// those of the submission's one asking, which is made again.
  4658. ///
  4659. /// With [`card_steps`] only the flights that declared them: a range of
  4660. /// a copy nobody declared any more is refreshed like any other. What
  4661. /// they landed is title memory written, so everything is asked and
  4662. /// looked at again; what is left after three times waits as before.
  4663. fn settle_stale(
  4664. &self,
  4665. submitted: &mut u64,
  4666. runs: &[&HostList],
  4667. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4668. ranges: &[(usize, usize)],
  4669. ) {
  4670. if relay_exact() && card_steps::stage() > 0 {
  4671. for _ in 0..3 {
  4672. #[cfg(feature = "diagnostics")]
  4673. blame_stale(&stale);
  4674. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4675. crate::watch::ask_once(ranges);
  4676. stale = stale_under_flights(runs);
  4677. if stale.is_empty() {
  4678. return;
  4679. }
  4680. }
  4681. }
  4682. #[cfg(feature = "diagnostics")]
  4683. blame_stale(&stale);
  4684. self.settle(submitted, WHY_STALE);
  4685. crate::watch::ask_once(ranges);
  4686. }
  4687. /// [`Host::execute`], or with `late` the first half of
  4688. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4689. /// to be done once they have run comes back with the submission lock
  4690. /// still held.
  4691. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4692. #[cfg(feature = "diagnostics")]
  4693. let called = std::time::Instant::now();
  4694. #[cfg(feature = "diagnostics")]
  4695. crate::copystat::submission_begins();
  4696. // One submission at a time from preparation to copy-back: snapshots
  4697. // and the ranges shaders write are per host copy, not per submission.
  4698. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4699. let was_working = working(true);
  4700. submitting(1, runs.len());
  4701. // Flights in the air ([`late`]): a submission that is waited for
  4702. // settles them first, one sent ahead only if preparing it reads
  4703. // what they write.
  4704. // Or the reads are done on the card, behind the flights.
  4705. let own = if late { self.card_steps(runs) } else { None };
  4706. if !late {
  4707. self.settle(&mut submitted, WHY_SYNC);
  4708. } else if own.is_none()
  4709. && let Some(why) = late_blocked(runs)
  4710. {
  4711. if relay_exact() && why == WHY_READ {
  4712. // Only until the flights that may write what is read have
  4713. // landed: their copy-back's end, not the card's other work.
  4714. relay_wait(why, |line| {
  4715. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4716. });
  4717. } else {
  4718. self.settle(&mut submitted, why);
  4719. }
  4720. }
  4721. // Descriptors the title copied into placed heaps directly, before
  4722. // command lists that index those slots are submitted.
  4723. crate::descriptor::sync_heaps();
  4724. // That list runs first, and is one of the submission's from here on.
  4725. let with: Vec<&HostList>;
  4726. let runs = match &own {
  4727. Some(own) => {
  4728. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4729. &with[..]
  4730. }
  4731. None => runs,
  4732. };
  4733. let behind = late && flying();
  4734. // Before this submission counts as started: what the sweep lets go
  4735. // of is named by no list, and nothing runs now (behind flights the
  4736. // sweep waits for a submission that finds none in the air: there is
  4737. // one at every present).
  4738. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4739. if !behind {
  4740. if upcheck::on() {
  4741. upcheck::at_rest(self);
  4742. }
  4743. sweep();
  4744. SWEPT.store(now_ms(), Ordering::Relaxed);
  4745. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4746. // With the present sent ahead nothing else brings a moment
  4747. // with nothing in the air: one is made for the sweep.
  4748. self.settle(&mut submitted, WHY_SYNC);
  4749. if upcheck::on() {
  4750. upcheck::at_rest(self);
  4751. }
  4752. sweep();
  4753. SWEPT.store(now_ms(), Ordering::Relaxed);
  4754. }
  4755. let behind = late && flying();
  4756. // The slots that waited for a texture's host copy, before the
  4757. // lists that may read them run.
  4758. crate::descriptor::make_waiting();
  4759. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4760. // The ranges shaders write are counted for it (with the relay).
  4761. crate::shadow::preparing(this_submission);
  4762. let started = std::time::Instant::now();
  4763. #[cfg(feature = "diagnostics")]
  4764. let lock = (started - called).as_micros() as u64;
  4765. #[cfg(feature = "diagnostics")]
  4766. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4767. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4768. // Where each run's lists start in `lists`.
  4769. let mut firsts = Vec::with_capacity(runs.len());
  4770. let mut batch = Batch::default();
  4771. #[cfg(feature = "diagnostics")]
  4772. let split = Split::begin();
  4773. // The time a settle of flights takes inside this preparing: the
  4774. // wait for the card and the copy-back have their own places on the
  4775. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4776. let mut settled = std::time::Duration::ZERO;
  4777. // One write-watch asking for everything the submission refreshes
  4778. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4779. if crate::watch::once() {
  4780. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  4781. for list in runs {
  4782. for step in &list.deferred().copies {
  4783. if let Step::Refresh(shadow, address, len) = step
  4784. && shadow.asked_ahead()
  4785. {
  4786. let span = spans
  4787. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4788. .or_insert((*address, *address + *len));
  4789. *span = (span.0.min(*address), span.1.max(*address + *len));
  4790. }
  4791. }
  4792. }
  4793. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4794. #[cfg(feature = "diagnostics")]
  4795. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  4796. crate::watch::ask_once(&ranges);
  4797. #[cfg(feature = "diagnostics")]
  4798. split.part(0);
  4799. // Behind flights: the title wrote memory that a flight's shaders
  4800. // may write too, and this submission refreshes it. The flights
  4801. // are settled, and the asking made again: the copy-back wrote
  4802. // title memory, which other copies of it must see.
  4803. if upcheck::on() {
  4804. upcheck::order(runs);
  4805. if behind {
  4806. upcheck::reads(runs);
  4807. }
  4808. }
  4809. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  4810. if !stale.is_empty() {
  4811. let settling = std::time::Instant::now();
  4812. self.settle_stale(&mut submitted, runs, stale, &ranges);
  4813. settled += settling.elapsed();
  4814. }
  4815. } else if behind && !stale_under_flights(runs).is_empty() {
  4816. let settling = std::time::Instant::now();
  4817. self.settle(&mut submitted, WHY_STALE);
  4818. settled += settling.elapsed();
  4819. }
  4820. #[cfg(feature = "diagnostics")]
  4821. split.part(1);
  4822. // What flights in the air may write.
  4823. let air = line().written.clone();
  4824. for list in runs {
  4825. list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4826. firsts.push(lists.len());
  4827. if let Some(prelude) = list.prelude() {
  4828. lists.push(Some(prelude));
  4829. }
  4830. lists.push(list.list.cast().ok());
  4831. }
  4832. batch.flush();
  4833. crate::watch::ask_once_end();
  4834. #[cfg(feature = "diagnostics")]
  4835. split.part(2);
  4836. // The snapshots of the ranges shaders may write, if they were left
  4837. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4838. // lists have not gone to the card.
  4839. {
  4840. #[cfg(feature = "diagnostics")]
  4841. let snapshots = std::time::Instant::now();
  4842. crate::shadow::take_snapshots();
  4843. #[cfg(feature = "diagnostics")]
  4844. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4845. }
  4846. #[cfg(feature = "diagnostics")]
  4847. split.part(3);
  4848. // Copies in the card's memory: what changed on their CPU side goes
  4849. // up ahead of the lists, and a compare of what the shaders may
  4850. // write follows them in the same submission.
  4851. let flown = late && relay();
  4852. if flown && self.card_results_low() {
  4853. let settling = std::time::Instant::now();
  4854. self.settle(&mut submitted, WHY_MOST);
  4855. settled += settling.elapsed();
  4856. }
  4857. // What shaders may write through views they pick: last, so that no
  4858. // refresh of this submission leaves it alone.
  4859. let picked = crate::picked::declare(runs);
  4860. for (shadow, at, len) in &picked.written {
  4861. shadow.writing(*at, *len);
  4862. }
  4863. let card = self.card_before(runs, &picked, flown);
  4864. // The sends are taken: from here on the references hold what the
  4865. // copies in the lists put.
  4866. for (shadow, at, bytes) in batch.placed.drain(..) {
  4867. shadow.placed_copy(at, &bytes);
  4868. }
  4869. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4870. lists.push(Some(check));
  4871. }
  4872. #[cfg(feature = "diagnostics")]
  4873. split.part(4);
  4874. let prepared = std::time::Instant::now();
  4875. if late {
  4876. *submitted += 1;
  4877. #[cfg(feature = "diagnostics")]
  4878. if let Some([front, behind]) = self.span_lists() {
  4879. lists.insert(0, Some(front));
  4880. lists.push(Some(behind));
  4881. }
  4882. // SAFETY: closed lists; the fence is ours.
  4883. let signalled = unsafe {
  4884. self.queue.ExecuteCommandLists(&lists);
  4885. self.queue.Signal(&self.fence, *submitted)
  4886. };
  4887. awake::sent(&self.device);
  4888. self.card_sent();
  4889. if let Err(e) = signalled {
  4890. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4891. }
  4892. #[cfg(feature = "diagnostics")]
  4893. split.part(5);
  4894. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4895. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4896. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4897. submitting(0, 0);
  4898. #[cfg(feature = "diagnostics")]
  4899. crate::copystat::submission_ends(lock);
  4900. let sent = Sent {
  4901. number: this_submission,
  4902. card,
  4903. back,
  4904. own,
  4905. writes,
  4906. };
  4907. working(was_working);
  4908. return Some((submitted, sent));
  4909. }
  4910. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4911. #[cfg(feature = "diagnostics")]
  4912. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4913. firsts
  4914. .iter()
  4915. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4916. .map(|(&a, &b)| &lists[a..b])
  4917. .collect()
  4918. } else {
  4919. vec![&lists[..]]
  4920. };
  4921. #[cfg(not(feature = "diagnostics"))]
  4922. let groups = [&lists[..]];
  4923. submitting(2, runs.len());
  4924. for (i, group) in groups.iter().enumerate() {
  4925. *submitted += 1;
  4926. let started = std::time::Instant::now();
  4927. // SAFETY: closed lists; the fence and event are ours.
  4928. unsafe {
  4929. self.queue.ExecuteCommandLists(group);
  4930. self.card_sent();
  4931. let waited = self
  4932. .queue
  4933. .Signal(&self.fence, *submitted)
  4934. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4935. match waited {
  4936. Ok(()) => {
  4937. working(false);
  4938. WaitForSingleObject(self.event, INFINITE);
  4939. stood(started);
  4940. working(true);
  4941. }
  4942. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4943. }
  4944. }
  4945. // With timing on each group is one of `runs` (and the compare
  4946. // of copies in the card's memory, with the last): every
  4947. // command's time on the card goes to the sums by pipeline.
  4948. #[cfg(feature = "diagnostics")]
  4949. if timing() {
  4950. // SAFETY: a plain query.
  4951. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4952. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4953. crate::copystat::command_took(&op, ms);
  4954. }
  4955. }
  4956. // A submission of one list was never named here (`groups.len()
  4957. // > 1` was the test): the two 50 ms lists of the gameplay
  4958. // frame, each a submission of its own, printed nothing.
  4959. #[cfg(feature = "diagnostics")]
  4960. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4961. // SAFETY: a plain query.
  4962. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4963. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4964. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4965. for (ms, op) in runs[i].slowest(frequency, 6) {
  4966. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4967. }
  4968. }
  4969. let _ = (i, started);
  4970. }
  4971. let _ = &firsts;
  4972. FINISHED.store(this_submission, Ordering::Release);
  4973. bury(this_submission);
  4974. let gpu = prepared.elapsed();
  4975. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4976. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4977. #[cfg(feature = "diagnostics")]
  4978. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4979. let pipelines: std::collections::BTreeSet<String> = runs
  4980. .iter()
  4981. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4982. .collect();
  4983. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  4984. text.chars().take(1200).collect()
  4985. });
  4986. // The host resets a device whose submission runs for about 2 s.
  4987. if gpu > std::time::Duration::from_millis(250) {
  4988. let pipelines: std::collections::BTreeSet<String> = runs
  4989. .iter()
  4990. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4991. .collect();
  4992. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  4993. }
  4994. // SAFETY: a plain query.
  4995. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4996. fail(format_args!(
  4997. "host GPU device removed after a submission of {} lists{}{}",
  4998. runs.len(),
  4999. self.removal_data(runs),
  5000. last_notes(runs)
  5001. ));
  5002. }
  5003. submitting(3, runs.len());
  5004. // What shaders wrote goes back before the bottom-of-pipe writes,
  5005. // which tell the title the GPU is done; each range once per
  5006. // submission, however many dispatches declared it (the world's
  5007. // passes declare the same big ranges dozens of times).
  5008. let copying = std::time::Instant::now();
  5009. // For copies in the card's memory the compare has run there: the
  5010. // pieces that differ are fetched and merged.
  5011. if let Some(card) = &card {
  5012. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  5013. }
  5014. let back = crate::picked::with(declared_writes(runs), &picked.written);
  5015. hand_back(&back);
  5016. if let Some(card) = card {
  5017. self.card_done(card);
  5018. }
  5019. #[cfg(feature = "diagnostics")]
  5020. if !back.is_empty() {
  5021. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  5022. }
  5023. // Nothing of this submission goes back to the title: no range of
  5024. // shader writes, no value written when it is done. The wait for
  5025. // such a one is only for order and for what the card still holds.
  5026. #[cfg(feature = "diagnostics")]
  5027. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  5028. use crate::copystat::{C, add};
  5029. add(C::NothingBack, 1);
  5030. add(C::NothingBackUs, gpu.as_micros() as u64);
  5031. }
  5032. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  5033. for list in runs {
  5034. // Read backs first: a value written at the bottom of the pipe
  5035. // may be what tells the title that they are there.
  5036. read_backs(list);
  5037. for &(at, what, bytes) in &list.deferred().writes {
  5038. what.write(at as *mut u8, bytes);
  5039. }
  5040. }
  5041. self.log_messages();
  5042. submitting(0, 0);
  5043. #[cfg(feature = "diagnostics")]
  5044. crate::copystat::submission_ends(lock);
  5045. // With the relay: nothing is in the air now, so no fetch still to
  5046. // be merged is older than the sends to card copies so far, and
  5047. // their notes can go.
  5048. if relay() {
  5049. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  5050. }
  5051. working(was_working);
  5052. None
  5053. }
  5054. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  5055. /// it lies in (by the names we give them) or the title memory copy just
  5056. /// below it; for each list that did not finish, the command it stopped
  5057. /// at and what the draws and dispatches in flight there run (or, in
  5058. /// lists that never started, the pipelines they bind).
  5059. fn removal_data(&self, runs: &[&HostList]) -> String {
  5060. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  5061. return String::new();
  5062. };
  5063. let mut text = String::new();
  5064. let mut fault_va = None;
  5065. // SAFETY: the outputs are the runtime's, valid while the device
  5066. // lives; nodes are walked as linked, histories have their counts.
  5067. unsafe {
  5068. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  5069. && fault.PageFaultVA != 0
  5070. {
  5071. let va = fault.PageFaultVA;
  5072. fault_va = Some(va);
  5073. text.push_str(&format!("; page fault at {va:#x}"));
  5074. for (what, head) in [
  5075. ("inside", fault.pHeadExistingAllocationNode),
  5076. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  5077. ] {
  5078. let mut names = Vec::new();
  5079. let mut node = head;
  5080. while let Some(n) = node.as_ref()
  5081. && names.len() < 8
  5082. {
  5083. let name = if n.ObjectNameW.is_null() {
  5084. "unnamed".to_owned()
  5085. } else {
  5086. n.ObjectNameW.to_string().unwrap_or_default()
  5087. };
  5088. names.push(format!("{name} (type {})", n.AllocationType.0));
  5089. node = n.pNext;
  5090. }
  5091. if !names.is_empty() {
  5092. text.push_str(&format!("; {what} {names:?}"));
  5093. }
  5094. }
  5095. text.push_str(&crate::shadow::near(va));
  5096. text.push_str(&crate::descriptor::host::near_heaps(va));
  5097. }
  5098. // The plain output: the extended one (with marker texts) came
  5099. // back without stopped lists on this host.
  5100. if dred_faults() {
  5101. return text;
  5102. }
  5103. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  5104. Ok(crumbs) => crumbs,
  5105. Err(e) => {
  5106. text.push_str(&format!("; no breadcrumbs ({e})"));
  5107. return text;
  5108. }
  5109. };
  5110. // Every list's progress (done/count), in the runtime's order.
  5111. let mut progress = Vec::new();
  5112. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  5113. while let Some(p) = node.as_ref() {
  5114. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5115. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  5116. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  5117. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  5118. node = p.pNext;
  5119. }
  5120. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  5121. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  5122. while let Some(p) = plain.as_ref() {
  5123. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5124. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  5125. let history =
  5126. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  5127. text.push_str(&format!(
  5128. "; a list stopped at command {done} of {} (op {})",
  5129. p.BreadcrumbCount, history[done as usize].0
  5130. ));
  5131. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  5132. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  5133. let named = [
  5134. (!p.pCommandListDebugNameW.is_null()).then(|| p.pCommandListDebugNameW.to_string().unwrap_or_default()),
  5135. (!p.pCommandListDebugNameA.is_null()).then(|| {
  5136. std::ffi::CStr::from_ptr(p.pCommandListDebugNameA.cast()).to_string_lossy().into_owned()
  5137. }),
  5138. ]
  5139. .into_iter()
  5140. .flatten()
  5141. .next()
  5142. .unwrap_or_default();
  5143. text.push_str(&format!(" of \"{named}\""));
  5144. // Not one of the caller's: by the name.
  5145. #[cfg(feature = "diagnostics")]
  5146. let by_name = list_number(&named).and_then(|n| {
  5147. let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  5148. all.get(&n).map(|(notes, pipelines, _)| (notes.upgrade(), pipelines.upgrade()))
  5149. });
  5150. #[cfg(feature = "diagnostics")]
  5151. let indirects = run.map(|r| r.indirects.clone()).or_else(|| {
  5152. let n = list_number(&named)?;
  5153. LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()).get(&n)?.2.upgrade()
  5154. });
  5155. #[cfg(not(feature = "diagnostics"))]
  5156. #[allow(clippy::type_complexity)]
  5157. let by_name: Option<(Option<()>, Option<std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>>)> = None;
  5158. #[cfg(feature = "diagnostics")]
  5159. let noted = run.map(|r| r.notes.clone()).or_else(|| by_name.as_ref().and_then(|b| b.0.clone()));
  5160. let bound = run.map(|r| r.pipelines.clone()).or_else(|| by_name.as_ref().and_then(|b| b.1.clone()));
  5161. // The k-th marker command is the k-th note.
  5162. #[cfg(feature = "diagnostics")]
  5163. let markers: Vec<(u32, String)> = noted.map_or_else(Vec::new, |notes| {
  5164. let notes = notes.lock().unwrap_or_else(|e| e.into_inner());
  5165. history
  5166. .iter()
  5167. .enumerate()
  5168. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  5169. .zip(notes.iter())
  5170. .map(|((at, _), (note, range))| {
  5171. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  5172. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  5173. })
  5174. .collect()
  5175. });
  5176. #[cfg(not(feature = "diagnostics"))]
  5177. let markers: Vec<(u32, String)> = Vec::new();
  5178. #[cfg(not(feature = "diagnostics"))]
  5179. let _ = fault_va;
  5180. if done > 0 {
  5181. text.push_str(&in_flight(history, &markers, done as usize));
  5182. }
  5183. #[cfg(feature = "diagnostics")]
  5184. if let Some(indirects) = indirects {
  5185. text.push_str(&indirects_around(history, done as usize, &indirects));
  5186. }
  5187. // (Without markers a list that stopped midway says what
  5188. // it may have been at only by what it binds.)
  5189. if (done == 0 || markers.is_empty())
  5190. && let Some(bound) = bound
  5191. {
  5192. let pipelines = bound.lock().unwrap_or_else(|e| e.into_inner());
  5193. text.push_str(&format!(", its pipelines {pipelines:?}"));
  5194. }
  5195. }
  5196. plain = p.pNext;
  5197. }
  5198. }
  5199. text
  5200. }
  5201. /// Moves the debug layer's messages into our log; returns the first
  5202. /// error among them.
  5203. pub(crate) fn log_messages(&self) -> Option<String> {
  5204. let Some(queue) = &self.messages else {
  5205. return None;
  5206. };
  5207. let mut first_error = None;
  5208. // SAFETY: each message is read into a buffer of the size the queue
  5209. // reports, then the queue is emptied.
  5210. unsafe {
  5211. for i in 0..queue.GetNumStoredMessages() {
  5212. let mut size = 0;
  5213. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  5214. continue;
  5215. }
  5216. let mut buffer = vec![0u64; size.div_ceil(8)];
  5217. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  5218. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  5219. let m = &*message;
  5220. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  5221. let text = String::from_utf8_lossy(text);
  5222. let text = text.trim_end_matches('\0');
  5223. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  5224. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  5225. first_error = Some(text.to_owned());
  5226. }
  5227. }
  5228. }
  5229. queue.ClearStoredMessages();
  5230. }
  5231. first_error
  5232. }
  5233. /// A host render target view of `resource`, valid until it is recorded.
  5234. pub(crate) fn rtv(
  5235. &self,
  5236. resource: Option<&ID3D12Resource>,
  5237. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  5238. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5239. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5240. // SAFETY: a slot of our heap and a live resource, or none with a
  5241. // description (a typed null view).
  5242. unsafe {
  5243. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  5244. handle.ptr += (slot * self.rtv_size) as usize;
  5245. self.device
  5246. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  5247. handle
  5248. }
  5249. }
  5250. /// A host depth view of `resource`, valid until it is recorded.
  5251. pub(crate) fn dsv(
  5252. &self,
  5253. resource: &ID3D12Resource,
  5254. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  5255. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5256. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5257. // SAFETY: a slot of our heap and a live resource.
  5258. unsafe {
  5259. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  5260. handle.ptr += (slot * self.dsv_size) as usize;
  5261. self.device
  5262. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  5263. handle
  5264. }
  5265. }
  5266. }
  5267. impl HostList {
  5268. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  5269. #[cfg(feature = "diagnostics")]
  5270. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  5271. if !timing() {
  5272. return None;
  5273. }
  5274. self.stamps
  5275. .get_or_init(|| {
  5276. let device = &host()?.device;
  5277. let mut heap: Option<ID3D12QueryHeap> = None;
  5278. let mut back: Option<ID3D12Resource> = None;
  5279. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  5280. let desc = D3D12_RESOURCE_DESC {
  5281. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5282. Width: u64::from(STAMPS) * 8,
  5283. Height: 1,
  5284. DepthOrArraySize: 1,
  5285. MipLevels: 1,
  5286. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  5287. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5288. ..Default::default()
  5289. };
  5290. // SAFETY: plain object creation.
  5291. unsafe {
  5292. device
  5293. .CreateQueryHeap(
  5294. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  5295. &mut heap,
  5296. )
  5297. .ok()?;
  5298. device
  5299. .CreateCommittedResource(
  5300. &readback,
  5301. D3D12_HEAP_FLAG_NONE,
  5302. &desc,
  5303. D3D12_RESOURCE_STATE_COPY_DEST,
  5304. None,
  5305. &mut back,
  5306. )
  5307. .ok()?;
  5308. }
  5309. Some((heap?, back?))
  5310. })
  5311. .as_ref()
  5312. }
  5313. /// The noted commands that took longest on the GPU, longest first, as
  5314. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  5315. #[cfg(feature = "diagnostics")]
  5316. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  5317. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  5318. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  5319. return Vec::new();
  5320. };
  5321. let mut data = std::ptr::null_mut();
  5322. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  5323. // SAFETY: a read-back buffer the finished list resolved into.
  5324. let stamps: Vec<u64> = unsafe {
  5325. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  5326. return Vec::new();
  5327. }
  5328. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  5329. back.Unmap(0, None);
  5330. s
  5331. };
  5332. let mut times: Vec<(f64, String)> = (0..count)
  5333. .map(|i| {
  5334. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5335. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5336. })
  5337. .collect();
  5338. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5339. times.truncate(n);
  5340. times
  5341. }
  5342. pub(crate) fn close(&self) {
  5343. self.twins_to_depth();
  5344. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5345. if let Some((scratch, _)) = scratch {
  5346. self.indirect_common(&scratch);
  5347. }
  5348. self.batches_common();
  5349. self.card_budget_out();
  5350. #[cfg(feature = "diagnostics")]
  5351. if let Some((heap, back)) = self.stamps() {
  5352. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5353. // SAFETY: an open list, our heap and read-back buffer.
  5354. unsafe {
  5355. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5356. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5357. }
  5358. }
  5359. // SAFETY: our list.
  5360. if let Err(e) = unsafe { self.list.Close() } {
  5361. fail(format_args!(
  5362. "a host command list did not close ({e}): a command recorded into it was invalid"
  5363. ));
  5364. }
  5365. }
  5366. /// Only after the list's last submission finished (every one is waited
  5367. /// for).
  5368. pub(crate) fn reset(&self) {
  5369. #[cfg(feature = "diagnostics")]
  5370. let started = std::time::Instant::now();
  5371. self._alive.used();
  5372. *self.deferred() = Deferred::default();
  5373. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5374. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5375. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5376. #[cfg(feature = "diagnostics")]
  5377. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5378. #[cfg(feature = "diagnostics")]
  5379. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5380. {
  5381. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5382. (scratch.current, scratch.used) = (0, 0);
  5383. // Every submission of the list has run: nothing reads its
  5384. // scratch memory any more, and the next list to ask takes it.
  5385. if scratch_pool() {
  5386. give_chunks(std::mem::take(&mut scratch.chunks));
  5387. }
  5388. }
  5389. // SAFETY: the list is not executing.
  5390. let reset = unsafe {
  5391. self.allocator
  5392. .Reset()
  5393. .and_then(|()| self.list.Reset(&self.allocator, None))
  5394. };
  5395. if let Err(e) = reset {
  5396. fail(format_args!("a host command list did not reset ({e})"));
  5397. }
  5398. #[cfg(feature = "diagnostics")]
  5399. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5400. }
  5401. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5402. /// list: the host texture and the state it leaves, if that is a change.
  5403. /// The list's first use of a texture records nothing: its prelude brings
  5404. /// the texture there at submission.
  5405. pub(crate) fn transition(
  5406. &self,
  5407. resource: crate::object::This,
  5408. wanted: u32,
  5409. ) -> Option<(&'static ID3D12Resource, u32)> {
  5410. let copy = crate::resource::host_copy(resource)?;
  5411. // SAFETY: as in `crate::resource::host_resource`; the list's states
  5412. // hold the copy from here on.
  5413. let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(&copy.texture) };
  5414. let wanted = legal_state(texture, wanted);
  5415. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5416. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5417. std::collections::hash_map::Entry::Vacant(v) => {
  5418. v.insert((wanted, wanted, copy));
  5419. None
  5420. }
  5421. std::collections::hash_map::Entry::Occupied(mut o) => {
  5422. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5423. (before != wanted).then_some((texture, before))
  5424. }
  5425. }
  5426. }
  5427. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5428. /// as [`HostList::transition`] does a title resource's host copy, and
  5429. /// records the barrier: for textures that are not a title resource's
  5430. /// host copy (colour twins) and for the copies between the two.
  5431. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5432. let wanted = legal_state(&copy.texture, wanted);
  5433. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5434. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5435. std::collections::hash_map::Entry::Vacant(v) => {
  5436. v.insert((wanted, wanted, copy.clone()));
  5437. None
  5438. }
  5439. std::collections::hash_map::Entry::Occupied(mut o) => {
  5440. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5441. (before != wanted).then_some(before)
  5442. }
  5443. };
  5444. drop(states);
  5445. if let Some(before) = before {
  5446. let barrier = transition(
  5447. &copy.texture,
  5448. D3D12_RESOURCE_STATES(before as i32),
  5449. D3D12_RESOURCE_STATES(wanted as i32),
  5450. );
  5451. // SAFETY: an open list and a live texture.
  5452. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5453. }
  5454. }
  5455. /// A use of title texture `resource` about to be recorded, if it is a
  5456. /// depth texture with a colour twin (false if it is not): of the twin
  5457. /// (`colour`: unordered access) or of the depth texture (depth target,
  5458. /// clear, shader read, copy, resolve), writing it or only reading. The
  5459. /// side used is first brought up to date: by a copy recorded here if
  5460. /// this list wrote the other side since, by the list's prelude if the
  5461. /// list uses the side as it finds it. The twin is left in the
  5462. /// unordered access state; the caller moves the depth texture to the
  5463. /// state its use needs, as for any texture. A twin still ahead when the
  5464. /// list closes is copied then (`twins_to_depth`).
  5465. /// shortcut: every depth target bound for a draw counts as written
  5466. /// (also when the draw only tests), and every unordered access view a
  5467. /// shader names as written; views a shader picks from the heap by a
  5468. /// computed index are not seen here at all.
  5469. pub(crate) fn twin_use(
  5470. &self,
  5471. resource: crate::object::This,
  5472. colour: bool,
  5473. write: bool,
  5474. ) -> bool {
  5475. const UNORDERED_ACCESS: u32 = 0x8;
  5476. // Asked for every texture a draw reads: most have no twin.
  5477. let Some(twin) = crate::resource::twin(resource) else {
  5478. return false;
  5479. };
  5480. let Some(depth) = crate::resource::host_copy(resource) else {
  5481. return false;
  5482. };
  5483. let side = usize::from(colour);
  5484. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5485. let u = twins
  5486. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5487. .or_insert_with(|| TwinUse {
  5488. depth: depth.clone(),
  5489. twin: twin.clone(),
  5490. needs: [false; 2],
  5491. behind: [None; 2],
  5492. writing: false,
  5493. late: false,
  5494. });
  5495. let copy = match u.behind[side] {
  5496. Some(behind) => behind,
  5497. None => {
  5498. u.needs[side] = true;
  5499. false
  5500. }
  5501. };
  5502. u.behind[side] = Some(false);
  5503. match (write, colour) {
  5504. // Shaders write the twin when the draw or dispatch runs: what
  5505. // the same one reads of the depth texture is prepared before
  5506. // (`twins_written`).
  5507. (true, true) => u.writing = true,
  5508. (true, false) => u.behind[1] = Some(true),
  5509. (false, _) => {}
  5510. }
  5511. // shortcut: the depth plane's twin is not drawn into the plane
  5512. // here: the pass sets a pipeline and a target of ours, which a list
  5513. // still recording the title's commands cannot take. This use sees
  5514. // the plane as it was; the pass runs when the list closes
  5515. // (`twins_to_depth`). Counted.
  5516. if copy && !colour && twin.plane.is_some() {
  5517. u.late = true;
  5518. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5519. }
  5520. drop(twins);
  5521. if copy {
  5522. self.twin_copy(&depth, &twin, colour);
  5523. } else if colour {
  5524. self.settle(&twin.colour, UNORDERED_ACCESS);
  5525. }
  5526. // The depth plane's twin is written through unordered access too.
  5527. if colour && let Some(plane) = &twin.plane {
  5528. self.settle(plane, UNORDERED_ACCESS);
  5529. }
  5530. true
  5531. }
  5532. /// Records the pass that draws the twin of the depth plane of `depth`
  5533. /// into the plane, if `twin` has one, with the moves to the states the
  5534. /// pass needs; the twin is left in the unordered access state. Only
  5535. /// for a list that records nothing of the title's afterwards
  5536. /// (`record_plane_pass`).
  5537. fn pass_plane(
  5538. &self,
  5539. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5540. twin: &crate::resource::Twin,
  5541. ) {
  5542. const UNORDERED_ACCESS: u32 = 0x8;
  5543. const DEPTH_WRITE: u32 = 0x10;
  5544. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5545. let Some(plane) = &twin.plane else { return };
  5546. self.settle(depth, DEPTH_WRITE);
  5547. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5548. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5549. self.settle(plane, UNORDERED_ACCESS);
  5550. }
  5551. /// Records the copy of a depth texture into its colour twin (`colour`)
  5552. /// or of the twin into the depth texture, with the moves to the copy
  5553. /// states. The twin is left in the unordered access state.
  5554. fn twin_copy(
  5555. &self,
  5556. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5557. twin: &crate::resource::Twin,
  5558. colour: bool,
  5559. ) {
  5560. const UNORDERED_ACCESS: u32 = 0x8;
  5561. const COPY_DEST: u32 = 0x400;
  5562. const COPY_SOURCE: u32 = 0x800;
  5563. let (from, to) = if colour {
  5564. (depth, &twin.colour)
  5565. } else {
  5566. (&twin.colour, depth)
  5567. };
  5568. self.settle(from, COPY_SOURCE);
  5569. self.settle(to, COPY_DEST);
  5570. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5571. self.settle(&twin.colour, UNORDERED_ACCESS);
  5572. }
  5573. /// Before the list closes: the depth textures whose twins it wrote last
  5574. /// are given what was written, and left readable by shaders. Shaders
  5575. /// that pick a view from the heap by a computed index are not seen by
  5576. /// `twin_use` and read the depth texture in lists that never name it
  5577. /// (in a captured frame of the title no table names a shadow
  5578. /// map for reading but the pass that fills the next one).
  5579. fn twins_to_depth(&self) {
  5580. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5581. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5582. let written: Vec<_> = twins
  5583. .values_mut()
  5584. .filter(|u| u.behind[0] == Some(true) || u.late)
  5585. .map(|u| {
  5586. // Not copied again if the list copied since the last write
  5587. // and only the depth plane's pass is left.
  5588. let copy = u.behind[0] == Some(true);
  5589. u.behind[0] = Some(false);
  5590. u.late = false;
  5591. (u.depth.clone(), u.twin.clone(), copy)
  5592. })
  5593. .collect();
  5594. drop(twins);
  5595. for (depth, twin, copy) in &written {
  5596. if *copy {
  5597. self.twin_copy(depth, twin, false);
  5598. }
  5599. // Nothing of the title's is recorded after this: the pass may
  5600. // leave its own pipeline and target set.
  5601. self.pass_plane(depth, twin);
  5602. self.settle(depth, SHADER_RESOURCE);
  5603. }
  5604. }
  5605. /// The draw or dispatch just prepared is recorded: the twins it writes
  5606. /// now hold what their depth textures lack.
  5607. pub(crate) fn twins_written(&self) {
  5608. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5609. for u in twins.values_mut().filter(|u| u.writing) {
  5610. u.writing = false;
  5611. u.behind[0] = Some(true);
  5612. }
  5613. }
  5614. /// At submission: the list that moves each texture this list uses from
  5615. /// its real state to the one the list starts with; the textures' real
  5616. /// states become those the list ends with. For depth textures with a
  5617. /// colour twin it first copies the side the list uses as it finds it
  5618. /// from the other, if a list submitted earlier left it behind.
  5619. fn prelude(&self) -> Option<ID3D12CommandList> {
  5620. const COPY_DEST: u32 = 0x400;
  5621. const COPY_SOURCE: u32 = 0x800;
  5622. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5623. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5624. // The copies (depth texture, twin, whether into the twin); the
  5625. // sides are then as this list leaves them.
  5626. let mut syncs = Vec::new();
  5627. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5628. for u in twins.values() {
  5629. let real = u.twin.behind.load(Ordering::Relaxed);
  5630. let mut behind = [real & 1 != 0, real & 2 != 0];
  5631. for side in [0, 1] {
  5632. if u.needs[side] && behind[side] {
  5633. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5634. behind = [false; 2];
  5635. }
  5636. }
  5637. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5638. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5639. u.twin.behind.store(left, Ordering::Relaxed);
  5640. }
  5641. drop(twins);
  5642. // A copy runs with its textures in the copy states: each moves
  5643. // there from its real state, and from there to the state the list
  5644. // starts with (back to its real state if the list does not use it).
  5645. let mut to_copy = Vec::new();
  5646. let mut barriers = Vec::new();
  5647. let mut copying = std::collections::HashMap::new();
  5648. for (depth, twin, colour) in &syncs {
  5649. let (from, to) = if *colour {
  5650. (depth, &twin.colour)
  5651. } else {
  5652. (&twin.colour, depth)
  5653. };
  5654. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  5655. let key = std::sync::Arc::as_ptr(texture) as usize;
  5656. let real = texture.state.load(Ordering::Relaxed);
  5657. copying.insert(key, state);
  5658. if real != state {
  5659. to_copy.push(transition(
  5660. &texture.texture,
  5661. host_state(real),
  5662. host_state(state),
  5663. ));
  5664. if !states.contains_key(&key) {
  5665. barriers.push(transition(
  5666. &texture.texture,
  5667. host_state(state),
  5668. host_state(real),
  5669. ));
  5670. }
  5671. }
  5672. }
  5673. }
  5674. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5675. let real = copy.state.swap(*last, Ordering::Relaxed);
  5676. let real = copying.get(key).copied().unwrap_or(real);
  5677. (real != *first)
  5678. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5679. }));
  5680. if barriers.is_empty() && syncs.is_empty() {
  5681. return None;
  5682. }
  5683. let Some((allocator, list)) = self
  5684. .prelude
  5685. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5686. .as_ref()
  5687. else {
  5688. fail(format_args!("no host list for a state prelude"));
  5689. };
  5690. // SAFETY: the prelude is not executing (every submission is waited
  5691. // for); the textures are live.
  5692. let recorded = unsafe {
  5693. allocator.Reset().and_then(|()| {
  5694. list.Reset(allocator, None)?;
  5695. if !to_copy.is_empty() {
  5696. list.ResourceBarrier(&to_copy);
  5697. }
  5698. for (depth, twin, colour) in &syncs {
  5699. record_twin_copy(list, &depth.texture, twin, *colour);
  5700. }
  5701. if !barriers.is_empty() {
  5702. list.ResourceBarrier(&barriers);
  5703. }
  5704. list.Close()
  5705. })
  5706. };
  5707. if let Err(e) = recorded {
  5708. fail(format_args!("a host state prelude did not record ({e})"));
  5709. }
  5710. list.cast().ok()
  5711. }
  5712. /// Notes what the command about to be recorded does, as a marker
  5713. /// command whose text the list keeps (diagnostics, with device-removed
  5714. /// data on): the report pairs the breadcrumbs' marker commands with the
  5715. /// texts in order and names the commands a fault stopped among.
  5716. #[cfg(feature = "diagnostics")]
  5717. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5718. self.note(what, None);
  5719. }
  5720. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5721. /// `(address, bytes)`: the report places the faulting address in it.
  5722. #[cfg(feature = "diagnostics")]
  5723. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5724. self.note(what, Some(range));
  5725. }
  5726. #[cfg(feature = "diagnostics")]
  5727. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5728. if !dred_on() {
  5729. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5730. return;
  5731. }
  5732. {
  5733. let started = std::time::Instant::now();
  5734. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5735. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5736. // SAFETY: an open list and our query heap.
  5737. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5738. }
  5739. let what = what();
  5740. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5741. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5742. const UNICODE: u32 = 0;
  5743. // SAFETY: an open list; the marker is copied when recorded.
  5744. unsafe {
  5745. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5746. };
  5747. self.notes
  5748. .lock()
  5749. .unwrap_or_else(|e| e.into_inner())
  5750. .push((what, range));
  5751. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5752. }
  5753. }
  5754. /// Whether nothing recorded since the list was opened does any work:
  5755. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5756. /// upload or resolve (they defer a step or move a texture's state), no
  5757. /// bottom-of-pipe write. State set on the list does not count.
  5758. pub(crate) fn untouched(&self) -> bool {
  5759. {
  5760. let deferred = self.deferred();
  5761. if !(deferred.copies.is_empty()
  5762. && deferred.uploads.is_empty()
  5763. && deferred.kept.is_empty()
  5764. && deferred.textures.is_empty()
  5765. && deferred.writes.is_empty()
  5766. && deferred.backs.is_empty())
  5767. {
  5768. return false;
  5769. }
  5770. }
  5771. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5772. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5773. }
  5774. /// Notes an indirect execution, while device-removed data is kept
  5775. /// ([`indirects`]).
  5776. #[cfg(feature = "diagnostics")]
  5777. pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) {
  5778. if dred_on() || dred_light() {
  5779. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user);
  5780. }
  5781. }
  5782. /// Notes a pipeline the list binds.
  5783. pub(crate) fn used_pipeline(&self, name: &str) {
  5784. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5785. if !pipelines.contains(name) {
  5786. pipelines.insert(name.to_owned());
  5787. }
  5788. }
  5789. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5790. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5791. }
  5792. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5793. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5794. let mut deferred = self.deferred();
  5795. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5796. // A copy that goes on where the one recorded just before it ended,
  5797. // source and destination both: with `join_copies` the two are one
  5798. // step.
  5799. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5800. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5801. {
  5802. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5803. if join_copies() {
  5804. *n += len;
  5805. return;
  5806. }
  5807. }
  5808. deferred
  5809. .copies
  5810. .push(Step::Copy(dst as usize, src as usize, len));
  5811. deferred.refreshed.clear();
  5812. }
  5813. /// Copies `len` bytes of title memory at `src` into the list's upload
  5814. /// memory at `dst` when the list is submitted.
  5815. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5816. self.deferred()
  5817. .copies
  5818. .push(Step::Fill(dst as usize, src as usize, len, None));
  5819. }
  5820. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5821. /// title heap's address, and the slot) shows.
  5822. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5823. self.deferred()
  5824. .copies
  5825. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  5826. }
  5827. /// As [`HostList::defer_fill`], for the beginning of a buffer
  5828. /// [`HostList::upload`] made.
  5829. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  5830. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  5831. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  5832. }
  5833. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5834. /// when the list is submitted (once per range until a title copy
  5835. /// intervenes), keeping the copy alive until the list is reset.
  5836. pub(crate) fn defer_refresh(
  5837. &self,
  5838. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5839. address: usize,
  5840. len: usize,
  5841. ) {
  5842. let mut deferred = self.deferred();
  5843. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5844. if deferred.refreshed.insert(key) {
  5845. deferred
  5846. .copies
  5847. .push(Step::Refresh(shadow.clone(), address, len));
  5848. }
  5849. }
  5850. /// Shaders of the list write `[address, address + len)` of a buffer's
  5851. /// host copy: copied back into title memory once the list has run.
  5852. pub(crate) fn defer_gpu_write(
  5853. &self,
  5854. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5855. address: usize,
  5856. len: usize,
  5857. ) {
  5858. self.deferred()
  5859. .copies
  5860. .push(Step::GpuWrite(shadow.clone(), address, len));
  5861. }
  5862. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5863. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5864. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5865. /// the list is reset.
  5866. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5867. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5868. }
  5869. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5870. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5871. self.deferred().writes.push((dst as usize, what, bytes));
  5872. }
  5873. /// A mapped upload buffer of `size` bytes, alive until the list is
  5874. /// reset.
  5875. ///
  5876. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5877. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5878. // With [`card_steps`] the card may be the one that fills it.
  5879. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  5880. name(&buffer, || format!("list upload {size:#x}"));
  5881. self.deferred().hold_upload(buffer.clone(), size);
  5882. Some((buffer, data))
  5883. }
  5884. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5885. /// reset: the host GPU address and the CPU pointer.
  5886. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5887. let (buffer, at, data) = self.scratch_at(len)?;
  5888. // SAFETY: a live buffer.
  5889. Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data))
  5890. }
  5891. /// [`HostList::scratch`] and the buffer it lies in, for a descriptor
  5892. /// slot to hold: the slot outlives the list's use of it.
  5893. pub(crate) fn scratch_held(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  5894. let (buffer, at, data) = self.scratch_at(len)?;
  5895. // SAFETY: a live buffer.
  5896. let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at;
  5897. Some((buffer, gpu, data))
  5898. }
  5899. /// [`HostList::scratch`]: the buffer, the offset in it and the CPU
  5900. /// pointer.
  5901. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  5902. let host = host()?;
  5903. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5904. let len = len.max(1).next_multiple_of(256);
  5905. if len > SCRATCH_CHUNK {
  5906. let (buffer, data) = host.upload_buffer(len)?;
  5907. name(&buffer, || format!("list scratch {len:#x}"));
  5908. self.deferred().hold_upload(buffer.clone(), len);
  5909. return Some((buffer, 0, data));
  5910. }
  5911. // The chunk in use while `len` fits in what is left of it, else the
  5912. // next one (a list's first chunk may be a small one).
  5913. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5914. (s.current, s.used) = (s.current + 1, 0);
  5915. }
  5916. if s.current == s.chunks.len() {
  5917. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  5918. SCRATCH_FIRST
  5919. } else {
  5920. SCRATCH_CHUNK
  5921. };
  5922. let chunk = take_chunk(host, size)?;
  5923. s.chunks.push((chunk, size));
  5924. s.used = 0;
  5925. }
  5926. let (data, buffer) = (s.chunks[s.current].0.data, s.chunks[s.current].0.buffer.clone());
  5927. let at = s.used;
  5928. s.used += len;
  5929. Some((buffer, at, (data + at as usize) as *mut u8))
  5930. }
  5931. /// The bytes of scratch chunks the list holds now (after a reset:
  5932. /// none while lists share their chunks).
  5933. pub(crate) fn scratch_kept(&self) -> u64 {
  5934. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5935. scratch.chunks.iter().map(|c| c.1).sum()
  5936. }
  5937. /// The host address of the list's indirect-work budget, zeroed at each
  5938. /// submission of the list from the first use after a reset on.
  5939. pub(crate) fn budget(&self) -> Option<u64> {
  5940. let (buffer, data) = self
  5941. .budget
  5942. .get_or_init(|| {
  5943. let (b, d) = host()?.shared_buffer(256)?;
  5944. Some((b, d as usize))
  5945. })
  5946. .as_ref()?;
  5947. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5948. let mut deferred = self.deferred();
  5949. if !deferred.budget_zeroed {
  5950. deferred.budget_zeroed = true;
  5951. let at = *data;
  5952. // SAFETY: the list's own mapped words, written before it runs.
  5953. // The words after the budget hold what the clamp noted about the
  5954. // list's last run (mesh dispatches: the largest group count
  5955. // asked for, the groups asked in all; with the card's copy, as
  5956. // the list's end copied them here): taken, then zeroed.
  5957. let notes = Box::new(move || unsafe {
  5958. let words = at as *mut u32;
  5959. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  5960. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  5961. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  5962. for k in 0..3 {
  5963. words.add(k).write_volatile(0);
  5964. }
  5965. });
  5966. deferred.copies.push(Step::Host(notes, (0, 0)));
  5967. drop(deferred);
  5968. if let Some(card) = card {
  5969. self.zero_card_budget(card);
  5970. }
  5971. }
  5972. // SAFETY: a live buffer.
  5973. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  5974. }
  5975. /// The budget's words in the card's own memory ([`card_budget`]), if
  5976. /// the list can zero them itself (`WriteBufferImmediate`).
  5977. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  5978. if !card_budget() {
  5979. return None;
  5980. }
  5981. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  5982. let buffer = host()?.uav_buffer(256)?;
  5983. name(&buffer, || "indirect budget".to_owned());
  5984. Some(buffer)
  5985. }
  5986. /// Records, before the list's first clamp, the zeroing of the card's
  5987. /// copy of the budget: common, written as a copy, then left for
  5988. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  5989. fn zero_card_budget(&self, card: &ID3D12Resource) {
  5990. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  5991. return;
  5992. };
  5993. // SAFETY: a live buffer.
  5994. let at = unsafe { card.GetGPUVirtualAddress() };
  5995. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  5996. Dest: at + offset,
  5997. Value: 0,
  5998. });
  5999. // SAFETY: an open list; the buffer is the list's own and in the
  6000. // common state at the start of every recording.
  6001. unsafe {
  6002. self.list.ResourceBarrier(&[transition(
  6003. card,
  6004. D3D12_RESOURCE_STATE_COMMON,
  6005. D3D12_RESOURCE_STATE_COPY_DEST,
  6006. )]);
  6007. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  6008. self.list.ResourceBarrier(&[transition(
  6009. card,
  6010. D3D12_RESOURCE_STATE_COPY_DEST,
  6011. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  6012. )]);
  6013. }
  6014. }
  6015. /// Before the list closes, if this recording charged the card's copy
  6016. /// of the budget: its notes on mesh records go to the mapped words
  6017. /// (read at the next submission), and it goes back to common.
  6018. fn card_budget_out(&self) {
  6019. if !self.deferred().budget_zeroed {
  6020. return;
  6021. }
  6022. let (Some(Some(card)), Some(Some((mapped, _)))) =
  6023. (self.card_budget.get(), self.budget.get())
  6024. else {
  6025. return;
  6026. };
  6027. // SAFETY: an open list; both buffers are the list's own. The
  6028. // mapped one is promoted from common to the copy destination.
  6029. unsafe {
  6030. self.list.ResourceBarrier(&[transition(
  6031. card,
  6032. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  6033. D3D12_RESOURCE_STATE_COPY_SOURCE,
  6034. )]);
  6035. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  6036. self.list.ResourceBarrier(&[transition(
  6037. card,
  6038. D3D12_RESOURCE_STATE_COPY_SOURCE,
  6039. D3D12_RESOURCE_STATE_COMMON,
  6040. )]);
  6041. }
  6042. }
  6043. /// A device-local unordered-access buffer of at least `size` bytes for
  6044. /// clamped indirect arguments, reused across executions and resets of the
  6045. /// list. Smaller buffers replaced mid-list stay alive until
  6046. /// [`HostList::reset`].
  6047. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  6048. let needed = size.max(64 << 10);
  6049. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  6050. if let Some((buffer, cap)) = &*slot
  6051. && *cap >= needed
  6052. {
  6053. return Some(buffer.clone());
  6054. }
  6055. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  6056. let alloc = prev
  6057. .saturating_mul(2)
  6058. .max(needed)
  6059. .next_multiple_of(64 << 10);
  6060. let buffer = host()?.uav_buffer(alloc)?;
  6061. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  6062. let old = slot.replace((buffer.clone(), alloc));
  6063. drop(slot);
  6064. if let Some((old_buf, _)) = old {
  6065. // It ends the list common, as every scratch buffer does.
  6066. self.indirect_common(&old_buf);
  6067. self.keep(&old_buf);
  6068. }
  6069. Some(buffer)
  6070. }
  6071. /// Where the next batch of clamped records goes: a device-local buffer
  6072. /// the list keeps from recording to recording, the batch's place in it
  6073. /// and the state the buffer is in. Every batch of a recording has a place
  6074. /// of its own: the executions before it may still read theirs.
  6075. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  6076. use crate::indirect::batch::{JOBS, SLOT};
  6077. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6078. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  6079. if buffer == args.0.len() {
  6080. let size = u64::from(BATCHES * JOBS * SLOT);
  6081. let made = host()?.uav_buffer(size)?;
  6082. name(&made, || format!("indirect batches {size:#x}"));
  6083. args.0.push(made);
  6084. }
  6085. args.1 += 1;
  6086. // (Its first batch finds it as the recording before left it:
  6087. // `batches_common`.)
  6088. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  6089. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  6090. }
  6091. /// Before the list closes: the scratch buffers of the batched clamps go
  6092. /// back to the common state, where the next recording expects them.
  6093. fn batches_common(&self) {
  6094. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6095. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  6096. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  6097. .iter()
  6098. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  6099. .collect();
  6100. if !barriers.is_empty() {
  6101. // SAFETY: an open list and live buffers this recording left in
  6102. // `INDIRECT_ARGUMENT`.
  6103. unsafe { self.list.ResourceBarrier(&barriers) };
  6104. }
  6105. }
  6106. /// Moves `scratch` back to the common state if a clamp left it readable
  6107. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  6108. /// list's first clamp expects it. Done before the list closes and before
  6109. /// a bigger scratch buffer replaces it: one barrier per list (where
  6110. /// there was one per indirect execution), and the list ends as it
  6111. /// begins however it is submitted.
  6112. fn indirect_common(&self, scratch: &ID3D12Resource) {
  6113. {
  6114. let mut deferred = self.deferred();
  6115. if deferred.indirect_readable != scratch.as_raw() as usize {
  6116. return;
  6117. }
  6118. deferred.indirect_readable = 0;
  6119. }
  6120. let barrier = transition(
  6121. scratch,
  6122. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  6123. D3D12_RESOURCE_STATE_COMMON,
  6124. );
  6125. // SAFETY: an open list and a live buffer this recording left in
  6126. // `INDIRECT_ARGUMENT`.
  6127. unsafe { self.list.ResourceBarrier(&[barrier]) };
  6128. }
  6129. /// The state the list's indirect scratch buffer `scratch` is in at this
  6130. /// point of the recording: indirect arguments if a clamp in this
  6131. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  6132. /// common: the state a buffer is made in, and the one a recording
  6133. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  6134. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  6135. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  6136. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  6137. } else {
  6138. D3D12_RESOURCE_STATE_COMMON
  6139. }
  6140. }
  6141. /// A clamp recorded in this list left `scratch` readable as indirect
  6142. /// arguments. It stays so for every execution that reads it, until the
  6143. /// next clamp moves it back to unordered access.
  6144. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  6145. self.deferred().indirect_readable = scratch.as_raw() as usize;
  6146. }
  6147. /// Keeps `object` alive until the list is reset.
  6148. pub(crate) fn keep(&self, object: &impl Interface) {
  6149. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  6150. self.deferred().kept.push(object);
  6151. }
  6152. }
  6153. /// Whether this is the first time since the reset that the list asks
  6154. /// about `key` (a texture to bring up to date).
  6155. pub(crate) fn first_use(&self, key: usize) -> bool {
  6156. self.deferred().textures.insert(key)
  6157. }
  6158. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  6159. /// reset.
  6160. pub(crate) fn used(&self, key: usize) -> bool {
  6161. self.deferred().textures.contains(&key)
  6162. }
  6163. /// Runs `work` when the list is submitted, in order with its copies.
  6164. /// `work` may write title memory (refreshes after it copy again).
  6165. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  6166. self.deferred().copies.push(Step::Run(Box::new(work)));
  6167. self.deferred().refreshed.clear();
  6168. }
  6169. /// As [`HostList::defer`], for work that writes only host memory.
  6170. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  6171. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  6172. }
  6173. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  6174. /// memory at `from`.
  6175. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  6176. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  6177. }
  6178. /// Brings a texture's staging buffer up to date when the list is
  6179. /// submitted, keeping it alive until the list is reset.
  6180. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  6181. self.deferred().copies.push(Step::Texture(staging));
  6182. }
  6183. /// Runs the list's submission-time steps; refreshes go into `batch`
  6184. /// (the title's big buffers, a 174 MB one among them, are read by most
  6185. /// lists of a submission, through many ranges). Copies and fills that
  6186. /// `taken` names (by their place) are left out: they are done on the
  6187. /// card ([`card_steps`]).
  6188. fn run_deferred(&self, batch: &mut Batch, air: &[(usize, usize)], taken: impl Fn(usize) -> bool) {
  6189. #[cfg(feature = "diagnostics")]
  6190. use crate::copystat::{C, add};
  6191. // The time and the bytes of the copies and fills, some 13,000 a
  6192. // frame between 20,000 refreshes: summed here and added once.
  6193. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  6194. #[cfg(feature = "diagnostics")]
  6195. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  6196. for (i, step) in self.deferred().copies.iter().enumerate() {
  6197. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  6198. continue;
  6199. }
  6200. let (started, copied) = match step {
  6201. &Step::Copy(dst, src, len) => {
  6202. let started = std::time::Instant::now();
  6203. #[cfg(feature = "diagnostics")]
  6204. {
  6205. copies += 1;
  6206. }
  6207. batch.title_written();
  6208. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  6209. // With the submission's one asking: the journal learns it.
  6210. crate::watch::wrote(dst, len);
  6211. // What the card holds there may be another value although
  6212. // ours did not change.
  6213. if send::own() {
  6214. crate::shadow::send_copied(dst, len);
  6215. }
  6216. (started, len)
  6217. }
  6218. &Step::Fill(dst, src, len, _) => {
  6219. let started = std::time::Instant::now();
  6220. #[cfg(feature = "diagnostics")]
  6221. {
  6222. copies += 1;
  6223. }
  6224. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6225. (started, len)
  6226. }
  6227. Step::Placed(p) => {
  6228. let started = std::time::Instant::now();
  6229. let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len);
  6230. if free {
  6231. batch.title_written();
  6232. }
  6233. if let Some(bytes) = p.prepare(free) {
  6234. batch.placed.push((p.shadow.clone(), p.dst, bytes));
  6235. }
  6236. (started, p.len)
  6237. }
  6238. Step::Refresh(shadow, address, len) => {
  6239. #[cfg(feature = "diagnostics")]
  6240. {
  6241. refreshes += 1;
  6242. refreshed += *len as u64;
  6243. }
  6244. batch.add(shadow, *address, *len);
  6245. continue;
  6246. }
  6247. Step::Run(work) | Step::Host(work, _) => {
  6248. #[cfg(feature = "diagnostics")]
  6249. let started = std::time::Instant::now();
  6250. if matches!(step, Step::Run(_)) {
  6251. batch.title_written();
  6252. }
  6253. work();
  6254. // It wrote title memory, where is not known here: the
  6255. // submission's one asking ends, later refreshes ask anew.
  6256. if matches!(step, Step::Run(_)) {
  6257. crate::watch::ask_once_end();
  6258. }
  6259. #[cfg(feature = "diagnostics")]
  6260. {
  6261. add(C::Runs, 1);
  6262. add(C::RunUs, started.elapsed().as_micros() as u64);
  6263. }
  6264. continue;
  6265. }
  6266. Step::GpuWrite(shadow, address, len) => {
  6267. // The shaders start from the title's data: this copy's
  6268. // pending refresh first. The other copies' wait for
  6269. // the next flush of all (flushing all of them at every
  6270. // range a dispatch writes made thousands of write-watch
  6271. // askings a frame).
  6272. batch.flush_one(shadow);
  6273. #[cfg(feature = "diagnostics")]
  6274. let snapshot = std::time::Instant::now();
  6275. shadow.writing(*address, *len);
  6276. #[cfg(feature = "diagnostics")]
  6277. {
  6278. add(C::GpuWrites, 1);
  6279. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  6280. }
  6281. continue;
  6282. }
  6283. Step::Texture(staging) => {
  6284. if batch.texture_due(staging) {
  6285. batch.due.push(staging.clone());
  6286. if !wide_textures() {
  6287. batch.refresh_textures();
  6288. }
  6289. }
  6290. continue;
  6291. }
  6292. };
  6293. us += started.elapsed();
  6294. bytes += copied as u64;
  6295. }
  6296. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  6297. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  6298. #[cfg(feature = "diagnostics")]
  6299. {
  6300. add(C::Copies, copies);
  6301. add(C::CopyBytes, bytes);
  6302. add(C::Refreshes, refreshes);
  6303. add(C::RefreshBytes, refreshed);
  6304. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  6305. }
  6306. }
  6307. }
  6308. /// A table by a copy's address.
  6309. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  6310. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  6311. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  6312. /// but our own.
  6313. #[derive(Default)]
  6314. pub(crate) struct AddressHash(u64);
  6315. impl std::hash::Hasher for AddressHash {
  6316. fn finish(&self) -> u64 {
  6317. self.0
  6318. }
  6319. fn write(&mut self, bytes: &[u8]) {
  6320. for &b in bytes {
  6321. self.write_usize(usize::from(b));
  6322. }
  6323. }
  6324. fn write_usize(&mut self, n: usize) {
  6325. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  6326. self.0 = h ^ (h >> 32);
  6327. }
  6328. }
  6329. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  6330. /// preparing: the write-watch asking for a submission; the title's bytes put
  6331. /// in under flights' writes; the lists' steps, the refreshes among them; the
  6332. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  6333. /// of the steps: the refreshes, and the copies and fills (those with the
  6334. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  6335. /// is of. Of the refreshes, those before ranges are given to shaders, one
  6336. /// copy at a time: nanoseconds, and how many.
  6337. #[cfg(feature = "diagnostics")]
  6338. static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  6339. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  6340. /// those known to copy nothing, and those done on several threads.
  6341. #[cfg(feature = "diagnostics")]
  6342. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  6343. /// Counts into [`SPLIT`].
  6344. #[cfg(feature = "diagnostics")]
  6345. struct Split(std::cell::Cell<std::time::Instant>);
  6346. #[cfg(feature = "diagnostics")]
  6347. impl Split {
  6348. fn begin() -> Split {
  6349. Split(std::cell::Cell::new(std::time::Instant::now()))
  6350. }
  6351. /// Nanoseconds since the last part.
  6352. fn so_far(&self) -> u64 {
  6353. self.0.get().elapsed().as_nanos() as u64
  6354. }
  6355. /// What came since the last part was part `i`.
  6356. fn part(&self, i: usize) {
  6357. let now = std::time::Instant::now();
  6358. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  6359. }
  6360. }
  6361. /// The split of the preparing, per frame, for the frame-rate line.
  6362. #[cfg(feature = "diagnostics")]
  6363. fn split_line(frames: f64) {
  6364. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6365. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  6366. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  6367. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6368. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
  6369. tracing::info!(
  6370. "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' \
  6371. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  6372. 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 \
  6373. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
  6374. ms[0],
  6375. ms[8],
  6376. ms[1],
  6377. ms[2],
  6378. ms[6],
  6379. f[0],
  6380. f[1],
  6381. f[2],
  6382. f[3],
  6383. ms[9],
  6384. ms[10] * 1e6,
  6385. ms[7],
  6386. ms[3],
  6387. ms[4],
  6388. ms[5],
  6389. if crate::watch::light() { "on" } else { "off" },
  6390. );
  6391. tracing::info!(
  6392. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6393. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6394. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6395. waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
  6396. as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
  6397. a[0],
  6398. a[1] / 1024.0,
  6399. a[11] / 1e6,
  6400. a[12],
  6401. a[10],
  6402. a[9],
  6403. a[2],
  6404. a[3],
  6405. a[4],
  6406. a[5],
  6407. a[6],
  6408. a[7] / 1e6,
  6409. a[8] / 1e6,
  6410. s[0] / 1048576.0,
  6411. s[1] / 1048576.0,
  6412. s[2] / 1048576.0,
  6413. s[3],
  6414. );
  6415. tracing::info!(
  6416. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures",
  6417. h[0],
  6418. h[1],
  6419. h[2],
  6420. );
  6421. }
  6422. /// Whether a submission's refreshes of host copies run on several threads,
  6423. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6424. ///
  6425. /// A submission brings some sixty copies up to date, one after the other
  6426. /// on the submitting thread: for each, the pages the title wrote are asked
  6427. /// for and read through the kernel into the copy. That is the frame line's
  6428. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6429. /// another: each refresh writes its own copy and its own notes, and reads
  6430. /// title memory. With the switch the copies of a flush (four or more) are
  6431. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6432. /// The write-watch journal and the guards are behind their own locks, as
  6433. /// they are for the title's threads.
  6434. fn wide_refresh() -> bool {
  6435. static ON: OnceLock<bool> = OnceLock::new();
  6436. *ON.get_or_init(|| {
  6437. wide_refresh_enabled(
  6438. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6439. std::thread::available_parallelism().ok().map(|n| n.get()),
  6440. )
  6441. })
  6442. }
  6443. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6444. match setting {
  6445. Some("1") => true,
  6446. Some("0") => false,
  6447. _ => logical_cpus.is_some_and(|n| n >= 4),
  6448. }
  6449. }
  6450. #[cfg(test)]
  6451. mod wide_refresh_tests {
  6452. use super::wide_refresh_enabled;
  6453. #[test]
  6454. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6455. assert!(wide_refresh_enabled(None, Some(4)));
  6456. assert!(wide_refresh_enabled(None, Some(16)));
  6457. assert!(!wide_refresh_enabled(None, Some(2)));
  6458. assert!(!wide_refresh_enabled(None, None));
  6459. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6460. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6461. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6462. }
  6463. }
  6464. /// A submission's refreshes not done yet, merged per buffer copy into the
  6465. /// range that covers them: done before a step that writes title memory or
  6466. /// gives a range to shaders, and before the lists run.
  6467. ///
  6468. /// Also the textures brought up to date in the submission so far: most
  6469. /// lists of a world submission sample the same textures, and a texture in
  6470. /// physical-page memory is hashed whole each time it is checked. Checked
  6471. /// once, it is checked again only after a step that writes title memory.
  6472. #[derive(Default)]
  6473. struct Batch {
  6474. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6475. /// Where each copy (by address) is in `refreshes`: the list that makes
  6476. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6477. /// for every refresh of a submission was tens of millions of
  6478. /// comparisons a frame.
  6479. index: ByCopy<usize>,
  6480. /// Staging buffers (by address) refreshed since the last title write,
  6481. /// or due to be.
  6482. textures: std::collections::HashSet<usize>,
  6483. /// Those due ([`Batch::refresh_textures`]).
  6484. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6485. /// What copies at their place in the submission's lists put into title
  6486. /// memory ([`place`]): the host copy, the title address, the bytes.
  6487. placed: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, Vec<u8>)>,
  6488. }
  6489. /// Whether a submission's textures are brought up to date on several
  6490. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6491. /// name them, as before).
  6492. ///
  6493. /// They are read, hashed and, if they changed, detiled into their staging
  6494. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6495. /// its own buffer, notes and lock, and is refreshed by the title's own
  6496. /// threads as it is. They are done before the next step that writes title
  6497. /// memory, as the copies' refreshes are, and before the lists go to the
  6498. /// card. What is new: the note of a list that its upload takes what the
  6499. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6500. /// an earlier list of the submission asked for, not behind it. The texture
  6501. /// is then uploaded by a later list too, once more than needed.
  6502. fn wide_textures() -> bool {
  6503. static ON: OnceLock<bool> = OnceLock::new();
  6504. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6505. }
  6506. impl Batch {
  6507. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6508. let end = address + len;
  6509. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6510. match self.index.get(&key) {
  6511. Some(&at) => {
  6512. let r = &mut self.refreshes[at];
  6513. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6514. }
  6515. None => {
  6516. self.index.insert(key, self.refreshes.len());
  6517. self.refreshes.push((shadow.clone(), address, end));
  6518. }
  6519. }
  6520. }
  6521. /// Before shaders are given a range of `shadow`'s copy: its pending
  6522. /// refresh is done, the others stay pending.
  6523. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  6524. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  6525. return;
  6526. };
  6527. let (shadow, from, to) = self.refreshes.swap_remove(at);
  6528. // The last entry took its place.
  6529. if let Some(moved) = self.refreshes.get(at) {
  6530. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  6531. }
  6532. #[cfg(feature = "diagnostics")]
  6533. let started = std::time::Instant::now();
  6534. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  6535. Self::update(&shadow, from, to);
  6536. }
  6537. #[cfg(feature = "diagnostics")]
  6538. {
  6539. let ns = started.elapsed().as_nanos() as u64;
  6540. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6541. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6542. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  6543. }
  6544. }
  6545. /// Brings `[from, to)` of a copy up to date, timed.
  6546. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  6547. let started = std::time::Instant::now();
  6548. let copied = shadow.update(from, to - from);
  6549. let us = started.elapsed().as_micros() as u64;
  6550. #[cfg(feature = "diagnostics")]
  6551. crate::copystat::range(from, to - from, us, 0);
  6552. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  6553. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  6554. }
  6555. /// Whether `staging` is still to be refreshed in this submission (and
  6556. /// notes it refreshed).
  6557. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  6558. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  6559. }
  6560. /// Before a step that writes title memory: pending refreshes are done
  6561. /// first, and textures are checked again after it.
  6562. fn title_written(&mut self) {
  6563. self.flush();
  6564. self.textures.clear();
  6565. }
  6566. /// The textures due are brought up to date.
  6567. fn refresh_textures(&mut self) {
  6568. if self.due.len() < 2 || !wide_textures() {
  6569. self.due.drain(..).for_each(|staging| staging.refresh());
  6570. return;
  6571. }
  6572. // The time counted is the time it took, not the threads' sum.
  6573. let started = std::time::Instant::now();
  6574. let before = PREPARING[2].load(Ordering::Relaxed);
  6575. let due = std::mem::take(&mut self.due);
  6576. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  6577. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  6578. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6579. }
  6580. fn flush(&mut self) {
  6581. self.refresh_textures();
  6582. self.index.clear();
  6583. if self.refreshes.is_empty() {
  6584. return;
  6585. }
  6586. #[cfg(feature = "diagnostics")]
  6587. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  6588. self.flush_all();
  6589. #[cfg(feature = "diagnostics")]
  6590. {
  6591. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6592. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  6593. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  6594. }
  6595. }
  6596. fn flush_all(&mut self) {
  6597. // Most of a flush's copies are as they were: they are told so here,
  6598. // from what the submission's asking found, before anything is asked
  6599. // and any thread woken. (Thousands of them, the heap's buffer views
  6600. // once a frame: on the threads, below.)
  6601. const FEW: usize = 256;
  6602. let light = crate::watch::light();
  6603. if light && self.refreshes.len() <= FEW {
  6604. let started = std::time::Instant::now();
  6605. #[cfg(feature = "diagnostics")]
  6606. let all = self.refreshes.len();
  6607. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  6608. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6609. #[cfg(feature = "diagnostics")]
  6610. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  6611. }
  6612. // One write-watch asking for the copies that lie close together,
  6613. // not one per copy.
  6614. let ahead = self.refreshes.len() > 1;
  6615. if ahead {
  6616. let started = std::time::Instant::now();
  6617. let ranges: Vec<(usize, usize)> = self
  6618. .refreshes
  6619. .iter()
  6620. .filter(|r| r.0.asked_ahead())
  6621. .map(|r| (r.1, r.2))
  6622. .collect();
  6623. crate::watch::ask_ahead(&ranges);
  6624. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6625. }
  6626. if wide_refresh() && self.refreshes.len() >= 4 {
  6627. // Each copy on its own, several at a time: a copy's refresh
  6628. // writes that copy and reads title memory, nothing of another's.
  6629. // The time counted is the time it took, not the threads' sum.
  6630. let started = std::time::Instant::now();
  6631. let before = PREPARING[0].load(Ordering::Relaxed);
  6632. #[cfg(feature = "diagnostics")]
  6633. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  6634. if light {
  6635. // A number to a free thread, not a job to each copy.
  6636. let refreshes = std::mem::take(&mut self.refreshes);
  6637. crate::shadow::wide_each(refreshes.len(), move |i| {
  6638. let (shadow, from, to) = &refreshes[i];
  6639. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  6640. #[cfg(feature = "diagnostics")]
  6641. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  6642. return;
  6643. }
  6644. Self::update(shadow, *from, *to);
  6645. });
  6646. } else {
  6647. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  6648. .refreshes
  6649. .drain(..)
  6650. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  6651. .collect();
  6652. crate::shadow::wide_run(jobs);
  6653. }
  6654. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6655. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6656. } else {
  6657. for (shadow, from, to) in self.refreshes.drain(..) {
  6658. Self::update(&shadow, from, to);
  6659. }
  6660. }
  6661. if ahead {
  6662. crate::watch::ask_ahead_done();
  6663. }
  6664. }
  6665. }
  6666. /// Copies title memory at submission. The ranges were checked against their
  6667. /// resources when recorded, but the title may since have unmapped pages of
  6668. /// them (tiled memory, page mappings), which read as zeros here; a title
  6669. /// destination (`title_dst`) that is not all mapped is left alone.
  6670. ///
  6671. /// The source is read through the kernel (`ReadProcessMemory`), which
  6672. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  6673. /// cost about 2 ms per copy in the title's big pools (it walks the page
  6674. /// tables to the region's end), which made copies run at 100-200 MB/s.
  6675. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  6676. #[cfg(feature = "diagnostics")]
  6677. match crate::copystat::mode() {
  6678. 1 => {
  6679. // SAFETY: timing only: the caller vouches for the source.
  6680. unsafe { std::ptr::copy(src, dst, len) };
  6681. return;
  6682. }
  6683. 2 => return,
  6684. _ => {}
  6685. }
  6686. if len == 0 {
  6687. return;
  6688. }
  6689. // A title destination that is not all mapped is left alone. Asking
  6690. // Windows first (`VirtualQuery`) walks the page tables to the end of
  6691. // the destination's region: in the title's big blocks that is
  6692. // milliseconds a copy, and it was a seventh of the submitting thread's
  6693. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  6694. // says the same when it fails, so the question is only asked then.
  6695. // `VICTORY_COPY_ASK=1` asks first, as before.
  6696. static ASK: OnceLock<bool> = OnceLock::new();
  6697. let ask_first = title_dst
  6698. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  6699. if ask_first && !crate::texture::committed(dst, len) {
  6700. return;
  6701. }
  6702. if title_dst {
  6703. // The kernel writes the destination: it must not be guarded.
  6704. crate::watch::writing(dst as usize, len);
  6705. }
  6706. #[cfg(feature = "diagnostics")]
  6707. let moved = std::time::Instant::now();
  6708. let since = crate::watch::changes();
  6709. // (A title destination that is away only while the runtime changes a
  6710. // mapping beside it is written when that is done.)
  6711. let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
  6712. #[cfg(feature = "diagnostics")]
  6713. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  6714. if whole {
  6715. return;
  6716. }
  6717. // The copy failed: a source page is not there, or the destination is
  6718. // not all mapped. Then the destination stays as it is (the kernel may
  6719. // have written its first pages).
  6720. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  6721. crate::watch::lost("a copy of the title's", dst as usize, len);
  6722. return;
  6723. }
  6724. #[cfg(feature = "diagnostics")]
  6725. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  6726. #[cfg(feature = "diagnostics")]
  6727. let sparse = std::time::Instant::now();
  6728. if !title_dst && len >= 64 << 10 {
  6729. read_sparse(src, dst, len);
  6730. } else {
  6731. read_pieces(src, dst, len);
  6732. }
  6733. #[cfg(feature = "diagnostics")]
  6734. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  6735. }
  6736. /// After a failed bulk read into host memory, skip contiguous holes. Never
  6737. /// cache the query across copies: the title may remap the same address.
  6738. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  6739. use windows_sys::Win32::System::Memory::{
  6740. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  6741. };
  6742. let mut offset = 0;
  6743. while offset < len {
  6744. let at = src.wrapping_add(offset);
  6745. let to = dst.wrapping_add(offset);
  6746. let remaining = len - offset;
  6747. // SAFETY: the query inspects an address and fills a local structure.
  6748. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  6749. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  6750. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  6751. .saturating_sub(at as usize).min(remaining);
  6752. if size != size_of_val(&info) || n == 0 {
  6753. read_pieces(at, to, remaining);
  6754. break;
  6755. }
  6756. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  6757. #[cfg(feature = "diagnostics")]
  6758. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6759. // SAFETY: this path is only used with a writable host destination.
  6760. unsafe { to.write_bytes(0, n) };
  6761. } else if !read(at, to, n) {
  6762. // A mapping may change between query and read.
  6763. read_pieces(at, to, n);
  6764. }
  6765. offset += n;
  6766. }
  6767. }
  6768. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  6769. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  6770. // that fails), zeros for what cannot be read.
  6771. for_pieces(src as usize, len, 64 << 10, |at, n| {
  6772. let to = dst.wrapping_add(at - src as usize);
  6773. if !read(at as *const u8, to, n) {
  6774. for_pieces(at, n, 4 << 10, |at, n| {
  6775. let to = dst.wrapping_add(at - src as usize);
  6776. if !read(at as *const u8, to, n) {
  6777. #[cfg(feature = "diagnostics")]
  6778. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6779. zero(to, n);
  6780. }
  6781. });
  6782. }
  6783. });
  6784. }
  6785. /// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
  6786. /// destination of a title's copy), which can go between the question whether
  6787. /// it is there and this.
  6788. fn zero(to: *mut u8, n: usize) {
  6789. static ZEROS: [u8; 4096] = [0; 4096];
  6790. if n <= ZEROS.len() && crate::safecopy::on() {
  6791. // SAFETY: a destination that is not there fails the copy.
  6792. if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
  6793. crate::watch::lost("zeros", to as usize, n);
  6794. }
  6795. return;
  6796. }
  6797. // SAFETY: inside the destination, which is mapped.
  6798. unsafe { to.write_bytes(0, n) };
  6799. }
  6800. /// Reads title memory at `src` into `dst`; false if a page of it is not
  6801. /// readable.
  6802. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  6803. read(src, dst.as_mut_ptr(), dst.len())
  6804. }
  6805. /// Reads what is there of the `dst.len()` bytes of title memory at `src`,
  6806. /// zeros for the rest; returns how many bytes were there. Safe while the
  6807. /// runtime remaps title memory (the kernel, or a copy that takes the fault,
  6808. /// reads). What the runtime's record says is mapped is read in one go each,
  6809. /// and by pieces where that fails; memory it has no record of by pieces.
  6810. pub(crate) fn read_there(src: *const u8, dst: &mut [u8]) -> usize {
  6811. dst.fill(0);
  6812. let (start, len) = (src as usize, dst.len());
  6813. let mut got = 0;
  6814. let mut runs = crate::inplace::shown_runs(start, len);
  6815. if runs.is_empty() {
  6816. runs.push((start, len));
  6817. }
  6818. for (at, n) in runs {
  6819. let piece = &mut dst[at - start..at - start + n];
  6820. if read_into(at as *const u8, piece) {
  6821. got += n;
  6822. continue;
  6823. }
  6824. // (What failed may have written its first pages.)
  6825. piece.fill(0);
  6826. for_pieces(at, n, 64 << 10, |from, n| {
  6827. let piece = &mut dst[from - start..from - start + n];
  6828. if read_into(from as *const u8, piece) {
  6829. got += n;
  6830. return;
  6831. }
  6832. piece.fill(0);
  6833. for_pieces(from, n, 4 << 10, |from, n| {
  6834. let piece = &mut dst[from - start..from - start + n];
  6835. if read_into(from as *const u8, piece) {
  6836. got += n;
  6837. } else {
  6838. piece.fill(0);
  6839. }
  6840. });
  6841. });
  6842. }
  6843. got
  6844. }
  6845. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  6846. /// readable.
  6847. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  6848. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  6849. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6850. if crate::safecopy::on() {
  6851. // SAFETY: the destination is mapped writable memory of `len` bytes;
  6852. // a source page that is not there fails the copy.
  6853. return unsafe { crate::safecopy::copy(dst, src, len) };
  6854. }
  6855. let mut done = 0;
  6856. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  6857. // kernel checks the source.
  6858. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  6859. }
  6860. #[link(name = "ntdll", kind = "raw-dylib")]
  6861. unsafe extern "system" {
  6862. /// The kernel's write into a process's memory, `(process, address,
  6863. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  6864. /// the range is not there or not writable. It changes no protection.
  6865. fn NtWriteVirtualMemory(
  6866. process: *mut std::ffi::c_void,
  6867. base: *mut std::ffi::c_void,
  6868. buffer: *const std::ffi::c_void,
  6869. size: usize,
  6870. written: *mut usize,
  6871. ) -> i32;
  6872. }
  6873. /// Whether title memory is written with the kernel's own call
  6874. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  6875. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  6876. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  6877. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  6878. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  6879. fn direct_writes() -> bool {
  6880. static ON: OnceLock<bool> = OnceLock::new();
  6881. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  6882. }
  6883. /// Copies host memory into title memory after a submission (what shaders
  6884. /// wrote), leaving pages that are not mapped alone.
  6885. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  6886. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  6887. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6888. let direct = direct_writes();
  6889. let since = crate::watch::changes();
  6890. let write = |at: usize, n: usize| {
  6891. let from = src.wrapping_add(at - dst as usize);
  6892. if crate::safecopy::on() {
  6893. // SAFETY: the source is ours; a destination page that is not
  6894. // there, or not writable, fails the copy.
  6895. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  6896. }
  6897. let mut done = 0;
  6898. if direct {
  6899. // SAFETY: as below; the kernel checks the destination and
  6900. // writes nothing it cannot (the caller opened its guards:
  6901. // `crate::watch::writing`).
  6902. return unsafe {
  6903. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  6904. };
  6905. }
  6906. // SAFETY: the source is our mapped host copy; the kernel checks the
  6907. // destination.
  6908. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  6909. };
  6910. if len == 0 || write(dst as usize, len) {
  6911. return;
  6912. }
  6913. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  6914. if !write(at, n) {
  6915. for_pieces(at, n, 4 << 10, |at, n| {
  6916. if write(at, n) {
  6917. return;
  6918. }
  6919. // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
  6920. // refresh guarded the block again since the caller opened
  6921. // it; and any where the runtime was changing a mapping.
  6922. crate::watch::writing(at, n);
  6923. if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
  6924. crate::watch::lost("a host copy's bytes", at, n);
  6925. }
  6926. });
  6927. }
  6928. });
  6929. }
  6930. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  6931. /// `step`.
  6932. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  6933. let end = start + len;
  6934. let mut at = start;
  6935. while at < end {
  6936. let next = ((at / step + 1) * step).min(end);
  6937. f(at, next - at);
  6938. at = next;
  6939. }
  6940. }
  6941. impl Host {
  6942. /// The queue everything of ours runs on, for a call that must go to it
  6943. /// in order with the lists (`crate::tiles`: a texture's levels are
  6944. /// given memory ahead of the list that uploads them).
  6945. pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
  6946. &self.queue
  6947. }
  6948. /// A buffer in the upload heap, mapped for writing.
  6949. /// A buffer of `size` bytes the card writes and we read (a read back),
  6950. /// in the state copies into it need.
  6951. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  6952. let heap = D3D12_HEAP_PROPERTIES {
  6953. Type: D3D12_HEAP_TYPE_READBACK,
  6954. ..Default::default()
  6955. };
  6956. let desc = D3D12_RESOURCE_DESC {
  6957. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6958. Width: size.max(1),
  6959. Height: 1,
  6960. DepthOrArraySize: 1,
  6961. MipLevels: 1,
  6962. SampleDesc: DXGI_SAMPLE_DESC {
  6963. Count: 1,
  6964. Quality: 0,
  6965. },
  6966. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6967. ..Default::default()
  6968. };
  6969. let mut buffer: Option<ID3D12Resource> = None;
  6970. // SAFETY: plain creation of a read-back buffer.
  6971. let made = unsafe {
  6972. self.device.CreateCommittedResource(
  6973. &heap,
  6974. D3D12_HEAP_FLAG_NONE,
  6975. &desc,
  6976. D3D12_RESOURCE_STATE_COPY_DEST,
  6977. None,
  6978. &mut buffer,
  6979. )
  6980. };
  6981. match made {
  6982. Ok(()) => buffer,
  6983. Err(e) => {
  6984. tracing::warn!(error = %e, size, "no read-back buffer");
  6985. None
  6986. }
  6987. }
  6988. }
  6989. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6990. MADE[0].fetch_add(1, Ordering::Relaxed);
  6991. MADE[1].fetch_add(size, Ordering::Relaxed);
  6992. let heap = D3D12_HEAP_PROPERTIES {
  6993. Type: D3D12_HEAP_TYPE_UPLOAD,
  6994. ..Default::default()
  6995. };
  6996. let desc = D3D12_RESOURCE_DESC {
  6997. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6998. Width: size.max(1),
  6999. Height: 1,
  7000. DepthOrArraySize: 1,
  7001. MipLevels: 1,
  7002. SampleDesc: DXGI_SAMPLE_DESC {
  7003. Count: 1,
  7004. Quality: 0,
  7005. },
  7006. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7007. ..Default::default()
  7008. };
  7009. let mut buffer: Option<ID3D12Resource> = None;
  7010. let mut data = std::ptr::null_mut();
  7011. // SAFETY: plain creation and mapping of an upload buffer.
  7012. let made = unsafe {
  7013. self.device
  7014. .CreateCommittedResource(
  7015. &heap,
  7016. D3D12_HEAP_FLAG_NONE,
  7017. &desc,
  7018. D3D12_RESOURCE_STATE_GENERIC_READ,
  7019. None,
  7020. &mut buffer,
  7021. )
  7022. .and_then(|()| {
  7023. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7024. b.Map(0, None, Some(&mut data))
  7025. })
  7026. };
  7027. match made {
  7028. Ok(()) => Some((buffer?, data.cast())),
  7029. Err(e) => {
  7030. tracing::warn!(error = %e, size, "no upload buffer");
  7031. None
  7032. }
  7033. }
  7034. }
  7035. }
  7036. /// The swap chain formats a presented texture can be copied into: its own
  7037. /// family's.
  7038. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  7039. Some(match format.0 {
  7040. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  7041. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  7042. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  7043. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  7044. _ => return None,
  7045. })
  7046. }
  7047. const BUFFERS: u32 = 2;
  7048. struct Presenter {
  7049. swap_chain: IDXGISwapChain3,
  7050. width: u32,
  7051. height: u32,
  7052. format: DXGI_FORMAT,
  7053. copy: HostList,
  7054. /// With presents sent ahead ([`late_free_present`]): a list for each
  7055. /// present in the air, and the submission it last flew as (it is used
  7056. /// again once that one has finished).
  7057. ahead: Vec<(HostList, u64)>,
  7058. hwnd: HWND,
  7059. meter: Meter,
  7060. }
  7061. /// The frame rate, shown in the window's caption every second and logged
  7062. /// every few seconds.
  7063. struct Meter {
  7064. since: std::time::Instant,
  7065. frames: u32,
  7066. #[cfg(feature = "diagnostics")]
  7067. copy_stats_frames: u64,
  7068. drawn: u64,
  7069. logged: std::time::Instant,
  7070. /// The caption the window had, once read.
  7071. caption: Option<Vec<u16>>,
  7072. }
  7073. impl Meter {
  7074. fn new() -> Self {
  7075. let now = std::time::Instant::now();
  7076. Meter {
  7077. since: now,
  7078. frames: 0,
  7079. #[cfg(feature = "diagnostics")]
  7080. copy_stats_frames: 0,
  7081. drawn: crate::draw::drawn(),
  7082. logged: now,
  7083. caption: None,
  7084. }
  7085. }
  7086. /// Counts a presented frame.
  7087. fn frame(&mut self, hwnd: HWND) {
  7088. #[cfg(feature = "diagnostics")]
  7089. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  7090. #[cfg(feature = "diagnostics")]
  7091. crate::copystat::presented();
  7092. self.frames += 1;
  7093. #[cfg(feature = "diagnostics")]
  7094. {
  7095. self.copy_stats_frames += 1;
  7096. }
  7097. let elapsed = self.since.elapsed();
  7098. if elapsed < std::time::Duration::from_secs(1) {
  7099. return;
  7100. }
  7101. let drawn = crate::draw::drawn();
  7102. let frames = f64::from(self.frames);
  7103. let fps = frames / elapsed.as_secs_f64();
  7104. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  7105. let draws = (drawn - self.drawn) as f64 / frames;
  7106. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  7107. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  7108. let [cpu, gpu] = [0, 1].map(|i| {
  7109. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  7110. });
  7111. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  7112. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  7113. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  7114. });
  7115. let [back_ms, back_mb] = [0, 1].map(|i| {
  7116. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  7117. });
  7118. let dropped = crate::draw::take_dropped() as f64 / frames;
  7119. let indirect = crate::list::take_indirect() as f64 / frames;
  7120. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  7121. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  7122. tracing::info!(
  7123. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  7124. );
  7125. crate::shadow::exact_line(frames);
  7126. crate::descriptor::sync_line(frames);
  7127. late_line(frames);
  7128. card_clock_line(frames, ms);
  7129. #[cfg(feature = "diagnostics")]
  7130. spans::line(frames);
  7131. crate::shadow::back_line(frames);
  7132. #[cfg(feature = "diagnostics")]
  7133. split_line(frames);
  7134. {
  7135. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7136. if passes + compares > 0.0 {
  7137. tracing::info!(
  7138. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  7139. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  7140. if rehash_runs() { "on" } else { "off" }
  7141. );
  7142. }
  7143. }
  7144. {
  7145. let [own, asking, still, all] =
  7146. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  7147. if all >= 1.0 {
  7148. tracing::info!(
  7149. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  7150. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  7151. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  7152. );
  7153. }
  7154. let [through, left, filled, short] =
  7155. [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7156. if through + left + filled > 0.0 {
  7157. tracing::info!(
  7158. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  7159. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \
  7160. {filled:.1} first fillings from the pages there (VICTORY_TEXTURE_FILL=0: left empty), {short:.1} of them \
  7161. with less than was mapped (looked at again)"
  7162. );
  7163. }
  7164. }
  7165. {
  7166. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7167. if copies > 0.0 {
  7168. tracing::info!(
  7169. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  7170. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  7171. if join_copies() { "on" } else { "off" }
  7172. );
  7173. }
  7174. }
  7175. // Passes over the heap's buffer views for shaders that pick them by index.
  7176. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  7177. let picked_ms =
  7178. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  7179. // Copies between depth textures and their colour twins, each way.
  7180. let [twin_to_depth, twin_to_colour] =
  7181. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7182. // Depth planes drawn from their twins.
  7183. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  7184. // Copies in the card's memory (`crate::shadow::cards`).
  7185. let card = crate::shadow::card_stats();
  7186. #[cfg(feature = "diagnostics")]
  7187. let slow = crate::watch::slow_asks();
  7188. // Over the same frames as the counts above.
  7189. #[cfg(feature = "diagnostics")]
  7190. let drops = crate::pipeline::take_drops();
  7191. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  7192. self.logged = std::time::Instant::now();
  7193. tracing::info!(
  7194. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  7195. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  7196. );
  7197. crate::tiles::status();
  7198. {
  7199. let [queued, due, away, partly, oldest] =
  7200. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  7201. let [same, parts, tails] =
  7202. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  7203. tracing::info!(
  7204. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  7205. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  7206. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  7207. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  7208. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  7209. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  7210. {} made slots found unmapped and made null",
  7211. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  7212. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  7213. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  7214. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  7215. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  7216. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  7217. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  7218. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  7219. );
  7220. }
  7221. if crate::resource::held_only() {
  7222. let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed));
  7223. let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed));
  7224. tracing::info!(
  7225. "textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \
  7226. levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \
  7227. {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \
  7228. out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free",
  7229. bytes >> 20,
  7230. whole >> 20,
  7231. crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed),
  7232. crate::pool::texture_room() >> 20
  7233. );
  7234. }
  7235. {
  7236. let mode = crate::watch::page_writes();
  7237. let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
  7238. let [kept, dropped, slots, uploaded] =
  7239. [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
  7240. tracing::info!(
  7241. "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)",
  7242. bytes >> 20,
  7243. if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
  7244. if mode & 4 != 0 { "told as well" } else { "counted only" },
  7245. if mode & 2 != 0 { "made due again" } else { "left as they were" }
  7246. );
  7247. }
  7248. #[cfg(feature = "diagnostics")]
  7249. tracing::info!(
  7250. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  7251. slow[0] as f64 / frames,
  7252. slow[1] as f64 / 1e3 / frames,
  7253. slow[2] as f64 / 1e3
  7254. );
  7255. if crate::shadow::cards() {
  7256. let per_frame = |i: usize| card[i] as f64 / frames;
  7257. tracing::info!(
  7258. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  7259. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  7260. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  7261. card[7],
  7262. card[8] >> 20,
  7263. card[9] >> 20,
  7264. per_frame(0) / 1e6,
  7265. per_frame(1),
  7266. per_frame(2),
  7267. per_frame(3),
  7268. per_frame(4) / 1e6,
  7269. per_frame(5),
  7270. per_frame(6) / 1e3
  7271. );
  7272. }
  7273. tracing::info!(
  7274. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  7275. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  7276. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  7277. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  7278. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  7279. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  7280. {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}",
  7281. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  7282. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  7283. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  7284. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  7285. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  7286. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  7287. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  7288. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  7289. refused = format!(
  7290. "{} ({} 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",
  7291. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  7292. crate::shadow::OWN_MADE.load(Ordering::Relaxed),
  7293. crate::resource::TWINS[0].load(Ordering::Relaxed),
  7294. crate::resource::TWINS[1].load(Ordering::Relaxed),
  7295. crate::resource::PLANES[1].load(Ordering::Relaxed),
  7296. crate::resource::PLANES[2].load(Ordering::Relaxed)
  7297. ),
  7298. making = crate::pipeline::making(),
  7299. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  7300. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  7301. );
  7302. #[cfg(feature = "diagnostics")]
  7303. {
  7304. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7305. tracing::info!(
  7306. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  7307. put[0],
  7308. put[1],
  7309. put[2] / 1e6,
  7310. put[3]
  7311. );
  7312. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  7313. for (why, n) in drops.iter().take(40) {
  7314. tracing::info!(
  7315. "dropped {:.1}/frame without a host pipeline: {why}",
  7316. *n as f64 / frames
  7317. );
  7318. }
  7319. }
  7320. }
  7321. if self.caption.is_none() {
  7322. // The window's own text, read without a message.
  7323. let mut buffer = vec![0u16; 512];
  7324. // SAFETY: a window handle and a buffer of that length.
  7325. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  7326. buffer.truncate(n.max(0) as usize);
  7327. self.caption = Some(buffer);
  7328. }
  7329. let Some(caption) = &self.caption else { return };
  7330. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  7331. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  7332. text.push(0);
  7333. // Setting the text waits for the window's thread (a title thread,
  7334. // which may not pump for a while), so a thread of ours does it and
  7335. // presenting never waits; it takes the newest text when free.
  7336. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  7337. static SETTER: std::sync::Once = std::sync::Once::new();
  7338. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  7339. SETTER.call_once(|| {
  7340. let _ = std::thread::Builder::new()
  7341. .name("victory-caption".into())
  7342. .spawn(|| {
  7343. loop {
  7344. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  7345. match next {
  7346. // SAFETY: a window handle and a NUL-terminated text.
  7347. Some((hwnd, text)) => unsafe {
  7348. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  7349. },
  7350. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  7351. }
  7352. }
  7353. });
  7354. });
  7355. }
  7356. }
  7357. impl Host {
  7358. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  7359. /// as frame `frame` (saved if captures are on). `None` if nothing was
  7360. /// shown; else, in diagnostics builds, whether the frame was black.
  7361. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  7362. // SAFETY: a live resource.
  7363. let desc = unsafe { texture.GetDesc() };
  7364. let Some(format) = swap_format(desc.Format) else {
  7365. tracing::warn!(format = desc.Format.0, "cannot present this format");
  7366. return None;
  7367. };
  7368. let (width, height) = (desc.Width as u32, desc.Height);
  7369. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  7370. if presenter.is_none() {
  7371. *presenter = match self.presenter(width, height, format) {
  7372. Ok(p) => Some(p),
  7373. Err(e) => {
  7374. tracing::warn!(error = %e, "no swap chain");
  7375. return None;
  7376. }
  7377. };
  7378. }
  7379. let p = presenter.as_mut()?;
  7380. if (p.width, p.height, p.format) != (width, height, format) {
  7381. // Presents sent ahead hold back buffers until they have run.
  7382. settle_now(WHY_SYNC);
  7383. // SAFETY: no back buffer is held; every submission was waited for.
  7384. let resized = unsafe {
  7385. p.swap_chain
  7386. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  7387. };
  7388. match resized {
  7389. Ok(()) => {
  7390. (p.width, p.height, p.format) = (width, height, format);
  7391. tracing::info!(
  7392. width,
  7393. height,
  7394. format = format.0,
  7395. frame,
  7396. "the swap chain's buffers were made again for another size or format"
  7397. );
  7398. self.log_video_memory("right after the swap chain's buffers were made again");
  7399. }
  7400. Err(e) => {
  7401. tracing::warn!(error = %e, width, height, "swap chain not resized");
  7402. return None;
  7403. }
  7404. }
  7405. }
  7406. let state = D3D12_RESOURCE_STATES(state as i32);
  7407. // SAFETY: our swap chain, list and a live source texture.
  7408. unsafe {
  7409. let index = p.swap_chain.GetCurrentBackBufferIndex();
  7410. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  7411. return None;
  7412. };
  7413. // Sent ahead ([`late_free_present`]) unless the frame is to be
  7414. // read back at once (a saved or listed frame): then a list of
  7415. // its own, one whose last flight has finished or a new one.
  7416. #[cfg(feature = "diagnostics")]
  7417. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  7418. #[cfg(not(feature = "diagnostics"))]
  7419. let read_now = false;
  7420. let slot = if late_free_present() && !read_now {
  7421. let finished = FINISHED.load(Ordering::Acquire);
  7422. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  7423. let list = self.new_list().ok()?;
  7424. list.close();
  7425. p.ahead.push((list, 0));
  7426. Some(p.ahead.len() - 1)
  7427. })
  7428. } else {
  7429. None
  7430. };
  7431. let copy = match slot {
  7432. Some(i) => &p.ahead[i].0,
  7433. None => &p.copy,
  7434. };
  7435. copy.reset();
  7436. let list = &copy.list;
  7437. list.ResourceBarrier(&[
  7438. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  7439. transition(
  7440. &back,
  7441. D3D12_RESOURCE_STATE_PRESENT,
  7442. D3D12_RESOURCE_STATE_COPY_DEST,
  7443. ),
  7444. ]);
  7445. list.CopyResource(&back, texture);
  7446. #[cfg(feature = "diagnostics")]
  7447. let capture = crate::capture::wanted(frame)
  7448. .then(|| crate::capture::read_back(&self.device, list, texture))
  7449. .flatten();
  7450. #[cfg(feature = "diagnostics")]
  7451. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  7452. #[cfg(not(feature = "diagnostics"))]
  7453. let _ = frame;
  7454. list.ResourceBarrier(&[
  7455. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  7456. transition(
  7457. &back,
  7458. D3D12_RESOURCE_STATE_COPY_DEST,
  7459. D3D12_RESOURCE_STATE_PRESENT,
  7460. ),
  7461. ]);
  7462. copy.close();
  7463. match slot {
  7464. Some(i) => {
  7465. let flown = self.execute_own(copy);
  7466. p.ahead[i].1 = flown;
  7467. }
  7468. None => self.execute(&[copy]),
  7469. }
  7470. #[cfg(feature = "diagnostics")]
  7471. if let Some((buffer, footprint)) = capture {
  7472. crate::capture::save_read_back(frame, &buffer, &footprint);
  7473. }
  7474. #[cfg(feature = "diagnostics")]
  7475. crate::replay::record::present(texture, state);
  7476. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  7477. p.meter.frame(p.hwnd);
  7478. #[cfg(feature = "diagnostics")]
  7479. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  7480. #[cfg(not(feature = "diagnostics"))]
  7481. Some(false)
  7482. }
  7483. }
  7484. fn presenter(
  7485. &self,
  7486. width: u32,
  7487. height: u32,
  7488. format: DXGI_FORMAT,
  7489. ) -> windows::core::Result<Presenter> {
  7490. let hwnd = match title_window() {
  7491. Some(hwnd) => hwnd,
  7492. None => window(width, height)?,
  7493. };
  7494. self.log_video_memory("right before the swap chain is made");
  7495. // SAFETY: plain object creation for our window.
  7496. unsafe {
  7497. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  7498. let desc = DXGI_SWAP_CHAIN_DESC1 {
  7499. Width: width,
  7500. Height: height,
  7501. Format: format,
  7502. SampleDesc: DXGI_SAMPLE_DESC {
  7503. Count: 1,
  7504. Quality: 0,
  7505. },
  7506. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  7507. BufferCount: BUFFERS,
  7508. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  7509. ..Default::default()
  7510. };
  7511. let swap_chain = factory
  7512. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  7513. .cast::<IDXGISwapChain3>()?;
  7514. let copy = self.new_list()?;
  7515. copy.close();
  7516. tracing::info!(width, height, format = format.0, "presenting to a window");
  7517. self.log_video_memory("right after the swap chain is made");
  7518. Ok(Presenter {
  7519. swap_chain,
  7520. width,
  7521. height,
  7522. format,
  7523. copy,
  7524. ahead: Vec::new(),
  7525. hwnd,
  7526. meter: Meter::new(),
  7527. })
  7528. }
  7529. }
  7530. }
  7531. /// A visible top-level window of this process: the one the title made, if
  7532. /// it made one.
  7533. fn title_window() -> Option<HWND> {
  7534. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  7535. let mut process = 0;
  7536. // SAFETY: a window handle from the enumeration; `found` is ours.
  7537. unsafe {
  7538. GetWindowThreadProcessId(hwnd, Some(&mut process));
  7539. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  7540. && IsWindowVisible(hwnd).as_bool()
  7541. {
  7542. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  7543. return false.into();
  7544. }
  7545. }
  7546. true.into()
  7547. }
  7548. let mut found: Option<HWND> = None;
  7549. // SAFETY: the callback only writes `found`, which outlives the call.
  7550. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  7551. found
  7552. }
  7553. /// `state` without the bits the host texture's flags forbid: the console
  7554. /// lets the title name states its own resources allow (unordered access on
  7555. /// a depth target, whose host copy cannot have both).
  7556. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  7557. // SAFETY: a plain query.
  7558. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  7559. }
  7560. /// [`legal_state`] for a texture with resource flags `flags`.
  7561. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  7562. // (flag, set or clear forbids, state bits): render target, unordered
  7563. // access, depth, denied shader resource.
  7564. const FORBIDDEN: [(u32, bool, u32); 4] = [
  7565. (0x1, false, 0x4),
  7566. (0x4, false, 0x8),
  7567. (0x2, false, 0x10 | 0x20),
  7568. (0x8, true, 0x40 | 0x80),
  7569. ];
  7570. FORBIDDEN
  7571. .iter()
  7572. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  7573. .fold(state, |s, &(_, _, bits)| s & !bits)
  7574. }
  7575. impl Host {
  7576. /// The card's memory as the system accounts it to this process, in
  7577. /// bytes: the budget and the use of the card's own memory, then of the
  7578. /// PC's memory shared with the card (where the system moves what does
  7579. /// not fit on the card).
  7580. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  7581. let adapter = self.adapter.as_ref()?;
  7582. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7583. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7584. // SAFETY: plain queries that fill our structures.
  7585. unsafe {
  7586. adapter
  7587. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7588. .ok()?;
  7589. adapter
  7590. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7591. .ok()?;
  7592. }
  7593. // The card's budget moved by 256 MB or more since the last look:
  7594. // said at once, with what was in use at the last look, so the log
  7595. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  7596. // the first world frame in runs 179 to 185, and the memory line,
  7597. // seconds later, was the first to show it. We reserve nothing
  7598. // and make the swap chain once, at the start.)
  7599. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  7600. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  7601. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  7602. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  7603. tracing::info!(
  7604. "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",
  7605. last[0] >> 20,
  7606. own.Budget >> 20,
  7607. crate::frame::current(),
  7608. last[1] >> 20,
  7609. last[2] >> 20
  7610. );
  7611. self.log_video_memory("right after that change");
  7612. }
  7613. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  7614. }
  7615. /// Both of the system's memory groups for this process, in bytes: for
  7616. /// the card's own memory and then for the PC's memory shared with the
  7617. /// card, the budget, the use, what could still be reserved and what
  7618. /// is reserved (the layer reserves none).
  7619. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  7620. let adapter = self.adapter.as_ref()?;
  7621. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7622. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7623. // SAFETY: plain queries that fill our structures.
  7624. unsafe {
  7625. adapter
  7626. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7627. .ok()?;
  7628. adapter
  7629. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7630. .ok()?;
  7631. }
  7632. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  7633. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  7634. };
  7635. Some([all(&own), all(&shared)])
  7636. }
  7637. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  7638. pub(crate) fn log_video_memory(&self, when: &str) {
  7639. let Some([own, shared]) = self.video_memory_groups() else {
  7640. return;
  7641. };
  7642. tracing::info!(
  7643. "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)",
  7644. when,
  7645. own[0] >> 20,
  7646. own[1] >> 20,
  7647. own[2] >> 20,
  7648. own[3] >> 20,
  7649. shared[0] >> 20,
  7650. shared[1] >> 20,
  7651. shared[2] >> 20,
  7652. shared[3] >> 20
  7653. );
  7654. }
  7655. /// A buffer in system memory that the CPU maps (write-back, so reading
  7656. /// it is fast too) and shaders read and write: for host copies of title
  7657. /// memory that shaders write, which upload memory cannot be. Starts in
  7658. /// the common state (buffers move out of it implicitly).
  7659. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7660. MADE[2].fetch_add(1, Ordering::Relaxed);
  7661. MADE[3].fetch_add(size, Ordering::Relaxed);
  7662. let heap = D3D12_HEAP_PROPERTIES {
  7663. Type: D3D12_HEAP_TYPE_CUSTOM,
  7664. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  7665. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  7666. ..Default::default()
  7667. };
  7668. let desc = D3D12_RESOURCE_DESC {
  7669. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7670. Width: size.max(1),
  7671. Height: 1,
  7672. DepthOrArraySize: 1,
  7673. MipLevels: 1,
  7674. SampleDesc: DXGI_SAMPLE_DESC {
  7675. Count: 1,
  7676. Quality: 0,
  7677. },
  7678. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7679. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7680. ..Default::default()
  7681. };
  7682. let mut buffer: Option<ID3D12Resource> = None;
  7683. let mut data = std::ptr::null_mut();
  7684. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7685. let made = unsafe {
  7686. self.device
  7687. .CreateCommittedResource(
  7688. &heap,
  7689. D3D12_HEAP_FLAG_NONE,
  7690. &desc,
  7691. D3D12_RESOURCE_STATE_COMMON,
  7692. None,
  7693. &mut buffer,
  7694. )
  7695. .and_then(|()| {
  7696. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7697. b.Map(0, None, Some(&mut data))
  7698. })
  7699. };
  7700. match made {
  7701. Ok(()) => Some((buffer?, data.cast())),
  7702. Err(e) => {
  7703. tracing::warn!(error = %e, size, "no shared buffer");
  7704. None
  7705. }
  7706. }
  7707. }
  7708. /// Whether buffers can lie in the card's memory and be mapped by the CPU
  7709. /// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver
  7710. /// that offer it); logged once.
  7711. pub(crate) fn mapped_card_memory(&self) -> bool {
  7712. static THERE: OnceLock<bool> = OnceLock::new();
  7713. *THERE.get_or_init(|| {
  7714. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default();
  7715. // SAFETY: writes `options` of the given size.
  7716. let ok = unsafe {
  7717. self.device
  7718. .CheckFeatureSupport(
  7719. D3D12_FEATURE_D3D12_OPTIONS16,
  7720. (&raw mut options).cast(),
  7721. size_of_val(&options) as u32,
  7722. )
  7723. .is_ok()
  7724. };
  7725. let supported = ok && options.GPUUploadHeapSupported.as_bool();
  7726. tracing::info!(supported, "card memory the CPU maps");
  7727. supported
  7728. })
  7729. }
  7730. /// A buffer in the card's own memory that the CPU maps, shaders read and
  7731. /// (with `written`) may write. The CPU should only write it: a read of the
  7732. /// mapping crosses the bus a few bytes at a time.
  7733. pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> {
  7734. if !self.mapped_card_memory() {
  7735. return None;
  7736. }
  7737. MADE[4].fetch_add(1, Ordering::Relaxed);
  7738. MADE[5].fetch_add(size, Ordering::Relaxed);
  7739. let heap = D3D12_HEAP_PROPERTIES {
  7740. Type: D3D12_HEAP_TYPE_GPU_UPLOAD,
  7741. ..Default::default()
  7742. };
  7743. let desc = D3D12_RESOURCE_DESC {
  7744. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7745. Width: size.max(1),
  7746. Height: 1,
  7747. DepthOrArraySize: 1,
  7748. MipLevels: 1,
  7749. SampleDesc: DXGI_SAMPLE_DESC {
  7750. Count: 1,
  7751. Quality: 0,
  7752. },
  7753. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7754. Flags: if written {
  7755. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
  7756. } else {
  7757. D3D12_RESOURCE_FLAG_NONE
  7758. },
  7759. ..Default::default()
  7760. };
  7761. let mut buffer: Option<ID3D12Resource> = None;
  7762. let mut data = std::ptr::null_mut();
  7763. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7764. let made = unsafe {
  7765. self.device
  7766. .CreateCommittedResource(
  7767. &heap,
  7768. D3D12_HEAP_FLAG_NONE,
  7769. &desc,
  7770. D3D12_RESOURCE_STATE_COMMON,
  7771. None,
  7772. &mut buffer,
  7773. )
  7774. .and_then(|()| {
  7775. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7776. b.Map(0, None, Some(&mut data))
  7777. })
  7778. };
  7779. match made {
  7780. Ok(()) => Some((buffer?, data.cast())),
  7781. Err(e) => {
  7782. tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps");
  7783. None
  7784. }
  7785. }
  7786. }
  7787. /// A device-local buffer shaders may write (unordered access) and indirect
  7788. /// execution may read, starting in the common state.
  7789. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7790. MADE[4].fetch_add(1, Ordering::Relaxed);
  7791. MADE[5].fetch_add(size, Ordering::Relaxed);
  7792. let heap = D3D12_HEAP_PROPERTIES {
  7793. Type: D3D12_HEAP_TYPE_DEFAULT,
  7794. ..Default::default()
  7795. };
  7796. let desc = D3D12_RESOURCE_DESC {
  7797. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7798. Width: size.max(1),
  7799. Height: 1,
  7800. DepthOrArraySize: 1,
  7801. MipLevels: 1,
  7802. SampleDesc: DXGI_SAMPLE_DESC {
  7803. Count: 1,
  7804. Quality: 0,
  7805. },
  7806. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7807. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7808. ..Default::default()
  7809. };
  7810. let mut buffer: Option<ID3D12Resource> = None;
  7811. // SAFETY: plain creation of a device-local buffer.
  7812. let made = unsafe {
  7813. self.device.CreateCommittedResource(
  7814. &heap,
  7815. D3D12_HEAP_FLAG_NONE,
  7816. &desc,
  7817. D3D12_RESOURCE_STATE_COMMON,
  7818. None,
  7819. &mut buffer,
  7820. )
  7821. };
  7822. match made {
  7823. Ok(()) => buffer,
  7824. Err(e) => {
  7825. tracing::warn!(error = %e, size, "no unordered-access buffer");
  7826. None
  7827. }
  7828. }
  7829. }
  7830. }
  7831. /// For adapters without device-removed data (the software one): the last
  7832. /// commands each list of the failed submission noted (diagnostics, with
  7833. /// `VICTORY_D3D12_DRED`).
  7834. fn last_notes(runs: &[&HostList]) -> String {
  7835. #[cfg(feature = "diagnostics")]
  7836. {
  7837. let mut text = String::new();
  7838. for (i, r) in runs.iter().enumerate() {
  7839. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  7840. for (n, _) in notes.iter().rev().take(6).rev() {
  7841. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  7842. }
  7843. }
  7844. text
  7845. }
  7846. #[cfg(not(feature = "diagnostics"))]
  7847. {
  7848. let _ = runs;
  7849. String::new()
  7850. }
  7851. }
  7852. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  7853. /// command reads (diagnostics).
  7854. #[cfg(feature = "diagnostics")]
  7855. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  7856. let end = start + bytes;
  7857. if va < start {
  7858. format!(" (fault {:#x} below its source)", start - va)
  7859. } else if va < end {
  7860. format!(" (fault at source +{:#x})", va - start)
  7861. } else {
  7862. format!(" (fault {:#x} past its source's end)", va - end)
  7863. }
  7864. }
  7865. /// The commands that may have been running where a list stopped at
  7866. /// command `done`: those between the barriers around it (work between
  7867. /// barriers overlaps on the GPU), by kind, and what the markers just
  7868. /// before them say (`HostList::note_op`: diagnostics builds with
  7869. /// device-removed data on).
  7870. /// For a list that stopped at command `done`: what the indirect executions
  7871. /// there ran, from the one before it to the next barrier (four at most), and
  7872. /// what the heap slots their user data names hold now.
  7873. #[cfg(feature = "diagnostics")]
  7874. fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &indirects::Shared) -> String {
  7875. let indirect = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT;
  7876. let all = all.lock().unwrap_or_else(|e| e.into_inner());
  7877. let mut text = String::new();
  7878. let mut shown = 0;
  7879. for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) {
  7880. if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) {
  7881. break;
  7882. }
  7883. if !indirect(op) {
  7884. continue;
  7885. }
  7886. shown += 1;
  7887. let Some((what, words)) = all.nth(indirects::before(history, at, indirect)) else {
  7888. continue;
  7889. };
  7890. text.push_str(&format!("; command {at} ran {what}"));
  7891. for (word, slot, what) in crate::descriptor::host::describe_slots(words) {
  7892. text.push_str(&format!(", word {word} slot {slot}: {what}"));
  7893. }
  7894. }
  7895. text
  7896. }
  7897. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  7898. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  7899. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  7900. let to = history[done..]
  7901. .iter()
  7902. .position(barrier)
  7903. .map_or(history.len(), |b| (done + b).max(done + 1));
  7904. let mut text = format!(", commands {from}..{to} between its barriers:");
  7905. let mut shown = 0;
  7906. // From just before the command the GPU had not finished: the first
  7907. // twelve after the barrier named draws long done when a list of 79
  7908. // mesh draws stopped at its 45th (run 41).
  7909. for i in from.max(done.saturating_sub(4))..to {
  7910. let op = history[i];
  7911. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  7912. continue;
  7913. }
  7914. shown += 1;
  7915. let marker = i
  7916. .checked_sub(1)
  7917. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  7918. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  7919. .map_or("no marker", |(_, s)| s.as_str());
  7920. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  7921. }
  7922. text
  7923. }
  7924. pub(crate) fn transition(
  7925. resource: &ID3D12Resource,
  7926. before: D3D12_RESOURCE_STATES,
  7927. after: D3D12_RESOURCE_STATES,
  7928. ) -> D3D12_RESOURCE_BARRIER {
  7929. D3D12_RESOURCE_BARRIER {
  7930. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  7931. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  7932. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  7933. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  7934. // SAFETY: a borrowed pointer; the barrier never releases it.
  7935. pResource: unsafe { std::mem::transmute_copy(resource) },
  7936. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  7937. StateBefore: before,
  7938. StateAfter: after,
  7939. }),
  7940. },
  7941. }
  7942. }
  7943. /// A window of the given client size, owned by its own message thread.
  7944. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7945. let (sender, receiver) = std::sync::mpsc::channel();
  7946. std::thread::Builder::new()
  7947. .name("victory-window".into())
  7948. .spawn(move || {
  7949. let made = make_window(width, height);
  7950. let ok = made.is_ok();
  7951. let _ = sender.send(made.map(|h| h.0 as usize));
  7952. if ok {
  7953. pump();
  7954. }
  7955. })
  7956. .map_err(|_| windows::core::Error::empty())?;
  7957. let hwnd = receiver
  7958. .recv()
  7959. .map_err(|_| windows::core::Error::empty())??;
  7960. Ok(HWND(hwnd as *mut _))
  7961. }
  7962. extern "system" fn window_proc(
  7963. hwnd: HWND,
  7964. message: u32,
  7965. wparam: WPARAM,
  7966. lparam: LPARAM,
  7967. ) -> LRESULT {
  7968. // SAFETY: the default handling for our window.
  7969. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  7970. }
  7971. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7972. const CLASS: PCWSTR = w!("VIctory");
  7973. // SAFETY: registers our class once and creates a window of it.
  7974. unsafe {
  7975. let instance = GetModuleHandleW(None)?;
  7976. let class = WNDCLASSEXW {
  7977. cbSize: size_of::<WNDCLASSEXW>() as u32,
  7978. lpfnWndProc: Some(window_proc),
  7979. hInstance: instance.into(),
  7980. lpszClassName: CLASS,
  7981. hCursor: LoadCursorW(None, IDC_ARROW)?,
  7982. ..Default::default()
  7983. };
  7984. RegisterClassExW(&class);
  7985. let mut rect = RECT {
  7986. left: 0,
  7987. top: 0,
  7988. right: width as i32,
  7989. bottom: height as i32,
  7990. };
  7991. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  7992. CreateWindowExW(
  7993. WINDOW_EX_STYLE(0),
  7994. CLASS,
  7995. w!("VIctory"),
  7996. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  7997. CW_USEDEFAULT,
  7998. CW_USEDEFAULT,
  7999. rect.right - rect.left,
  8000. rect.bottom - rect.top,
  8001. None,
  8002. None,
  8003. Some(instance.into()),
  8004. None,
  8005. )
  8006. }
  8007. }
  8008. fn pump() {
  8009. let mut message = MSG::default();
  8010. // SAFETY: the standard message loop of this thread's window.
  8011. unsafe {
  8012. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  8013. let _ = TranslateMessage(&message);
  8014. DispatchMessageW(&message);
  8015. }
  8016. }
  8017. }
  8018. #[cfg(test)]
  8019. mod trail {
  8020. /// The trail keeps the newest things, and the report made when the
  8021. /// host device is removed says them and the pipeline library's state
  8022. /// (no card is asked for any of it).
  8023. #[test]
  8024. fn the_removal_report_says_the_newest_things_done() {
  8025. for n in 0..super::TRAIL_MOST + 5 {
  8026. super::trail(|| format!("thing {n} done"));
  8027. }
  8028. let text = super::removal_context();
  8029. assert!(text.contains("the submitting thread was"));
  8030. assert!(text.contains("pipeline library: no call running"));
  8031. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  8032. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  8033. }
  8034. }
  8035. #[cfg(test)]
  8036. mod spare {
  8037. use super::Spare;
  8038. /// Kept things come back by size, the last given first, and nothing is
  8039. /// kept past the limit.
  8040. #[test]
  8041. fn kept_things_come_back_by_size_within_the_limit() {
  8042. let mut spare: Spare<u32> = Spare::new();
  8043. assert_eq!(spare.take(4), None);
  8044. assert_eq!(spare.give(1, 4, 10), None);
  8045. assert_eq!(spare.give(2, 1, 10), None);
  8046. assert_eq!(spare.give(3, 4, 10), None);
  8047. assert_eq!(spare.bytes, 9);
  8048. // Past the limit: handed back, nothing changes.
  8049. assert_eq!(spare.give(4, 4, 10), Some(4));
  8050. assert_eq!(spare.bytes, 9);
  8051. assert_eq!(spare.take(2), None, "no thing of that size");
  8052. assert_eq!(spare.take(4), Some(3));
  8053. assert_eq!(spare.take(4), Some(1));
  8054. assert_eq!(spare.take(4), None);
  8055. assert_eq!(spare.take(1), Some(2));
  8056. assert_eq!(spare.bytes, 0);
  8057. assert!(spare.kept.is_empty());
  8058. }
  8059. }
  8060. #[cfg(test)]
  8061. mod refresh_tests {
  8062. use super::Batch;
  8063. use crate::shadow::Shadow;
  8064. use std::sync::Arc;
  8065. use windows_sys::Win32::System::Memory::{
  8066. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  8067. VirtualAlloc,
  8068. };
  8069. const PAGE: usize = 64 << 10;
  8070. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  8071. /// Title memory for the tests (never given back: copies of it stay in
  8072. /// the guards): write-watched, or a view of a section.
  8073. fn title(len: usize, view: bool) -> usize {
  8074. // SAFETY: plain allocations.
  8075. let at = unsafe {
  8076. if view {
  8077. let section =
  8078. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  8079. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  8080. // As the runtime tells of it.
  8081. crate::title_memory_section(section as usize, len as u64, true);
  8082. crate::title_memory_remapped(at, len);
  8083. crate::title_memory_view(at, len, section as usize, 0);
  8084. at
  8085. } else {
  8086. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  8087. }
  8088. };
  8089. assert_ne!(at, 0);
  8090. at
  8091. }
  8092. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  8093. /// and every fourth page not there: as a title that streams has it.
  8094. fn with_holes(blocks: usize) -> usize {
  8095. use windows_sys::Win32::System::Memory::{
  8096. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  8097. VirtualAlloc2, VirtualFree,
  8098. };
  8099. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  8100. // SAFETY: a placeholder and a section of our own.
  8101. unsafe {
  8102. let at = VirtualAlloc2(
  8103. GetCurrentProcess(),
  8104. std::ptr::null(),
  8105. blocks * PAGE,
  8106. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  8107. PAGE_NOACCESS,
  8108. std::ptr::null_mut(),
  8109. 0,
  8110. ) as usize;
  8111. assert_ne!(at, 0);
  8112. let len = blocks * PAGE;
  8113. let section =
  8114. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  8115. for block in (0..blocks).filter(|b| b % 4 != 3) {
  8116. let to = at + block * PAGE;
  8117. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  8118. let view = MapViewOfFile3(
  8119. section,
  8120. GetCurrentProcess(),
  8121. to as *const _,
  8122. (block * PAGE) as u64,
  8123. PAGE,
  8124. MEM_REPLACE_PLACEHOLDER,
  8125. PAGE_READWRITE,
  8126. std::ptr::null_mut(),
  8127. 0,
  8128. );
  8129. assert_eq!(view.Value as usize, to);
  8130. crate::title_memory_remapped(to, PAGE);
  8131. }
  8132. at
  8133. }
  8134. }
  8135. fn memory(len: usize) -> *mut u8 {
  8136. // SAFETY: a plain allocation.
  8137. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  8138. }
  8139. struct Random(u64);
  8140. impl Random {
  8141. fn below(&mut self, n: usize) -> usize {
  8142. self.0 ^= self.0 << 13;
  8143. self.0 ^= self.0 >> 7;
  8144. self.0 ^= self.0 << 17;
  8145. (self.0 >> 11) as usize % n
  8146. }
  8147. }
  8148. /// Prepares as a submission does: one asking for all the ranges, the
  8149. /// refreshes in several flushes, the asking's end.
  8150. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  8151. // One at a time, as submissions are.
  8152. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  8153. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  8154. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  8155. crate::watch::ask_once(&asked);
  8156. let mut batch = Batch::default();
  8157. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  8158. for (shadow, at, len) in part {
  8159. batch.add(shadow, *at, *len);
  8160. }
  8161. batch.flush();
  8162. }
  8163. crate::watch::ask_once_end();
  8164. }
  8165. /// Whatever is written where, by the title or by us, and whichever
  8166. /// copies (of both kinds of memory, over one another, none on a page
  8167. /// line) are refreshed in which ranges: a refreshed range holds what
  8168. /// title memory holds.
  8169. #[test]
  8170. fn refreshed_ranges_hold_title_memory() {
  8171. // SAFETY (all blocks): title memory and copies of the test's own,
  8172. // written by this thread and, in `Batch::flush`, by the threads that
  8173. // refresh, which are done when it returns.
  8174. let mut random = Random(0x1234_5678_9ABC_DEF1);
  8175. const LEN: usize = 24 * PAGE;
  8176. let regions = [title(LEN, false), title(LEN, true)];
  8177. let mut copies = Vec::new();
  8178. for &region in &regions {
  8179. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  8180. let data = memory(to - from);
  8181. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  8182. }
  8183. }
  8184. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  8185. for round in 0..600 {
  8186. for _ in 0..random.below(4) {
  8187. let at = regions[random.below(2)] + random.below(LEN - 64);
  8188. let n = 1 + random.below(60);
  8189. if random.below(3) == 0 {
  8190. // What shaders wrote.
  8191. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  8192. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  8193. Shadow::put(at, &was, &now);
  8194. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  8195. continue;
  8196. }
  8197. for i in 0..n {
  8198. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  8199. }
  8200. }
  8201. let mut ranges = Vec::new();
  8202. for (shadow, _) in &copies {
  8203. if random.below(3) == 0 {
  8204. continue;
  8205. }
  8206. let (start, len) = shadow.span();
  8207. let (start, len) = (start as usize, len as usize);
  8208. // Often the range of the time before, as a list's is.
  8209. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  8210. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  8211. ranges.push((shadow.clone(), start + from, n));
  8212. }
  8213. if ranges.is_empty() {
  8214. continue;
  8215. }
  8216. let flushes = 1 + random.below(3);
  8217. submission(&ranges, flushes);
  8218. for (shadow, at, n) in &ranges {
  8219. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  8220. let start = shadow.span().0 as usize;
  8221. let same = unsafe {
  8222. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  8223. };
  8224. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  8225. }
  8226. }
  8227. }
  8228. /// A copy in the card's memory, with the card's side and the sends to it
  8229. /// played by the test.
  8230. struct Carded {
  8231. shadow: Arc<Shadow>,
  8232. data: usize,
  8233. start: usize,
  8234. len: usize,
  8235. /// The last send, the last send every fetch to come is behind, and
  8236. /// the card's bytes: the queue's order is the order it is locked in.
  8237. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  8238. /// Whether a flight that writes it has not landed.
  8239. flying: std::sync::atomic::AtomicBool,
  8240. /// The dword of each eight its shaders write.
  8241. class: usize,
  8242. }
  8243. impl Carded {
  8244. fn new(start: usize, len: usize, class: usize) -> Carded {
  8245. let data = memory(len);
  8246. Carded {
  8247. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  8248. data: data as usize,
  8249. start,
  8250. len,
  8251. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  8252. flying: std::sync::atomic::AtomicBool::new(false),
  8253. class,
  8254. }
  8255. }
  8256. /// What changed on the CPU's side goes up.
  8257. fn send(&self) {
  8258. let mut card = self.card.lock().unwrap();
  8259. card.0 += 1;
  8260. let (number, merged) = (card.0, card.1);
  8261. for (a, b) in self.shadow.send_up(number, merged) {
  8262. // SAFETY: the copy's bytes; nothing writes those that are to
  8263. // go up.
  8264. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  8265. }
  8266. }
  8267. }
  8268. /// Everything at once: the title writes its memory on two threads, the
  8269. /// submitting thread puts its bytes in under shader writes
  8270. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  8271. /// the card's memory, one not), sends up what changed and declares what
  8272. /// the next flight's shaders write, and what flights wrote is landed
  8273. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  8274. /// still and the copies are refreshed once more, each of them, and the
  8275. /// card's side of those that have one, hold what title memory holds, and
  8276. /// title memory what was written last.
  8277. ///
  8278. /// Into the first copy shaders write besides through a view nobody
  8279. /// declared, words the title does not write: nothing that goes up ever
  8280. /// puts an older value over those.
  8281. ///
  8282. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  8283. /// only takes the block out of the guards' clean ones and leaves its bit,
  8284. /// or if a fault leaves the bit; in some thousand rounds,
  8285. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  8286. #[test]
  8287. fn landings_title_writes_and_light_refreshes_at_once() {
  8288. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  8289. assert!(crate::safecopy::on());
  8290. const LEN: usize = 24 * PAGE;
  8291. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  8292. let region = title(LEN, true);
  8293. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  8294. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  8295. let plain = {
  8296. let (start, len) = (region + 700, LEN - 9000);
  8297. let data = memory(len);
  8298. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  8299. };
  8300. // What was last written so, by offset.
  8301. let mut undeclared = std::collections::HashMap::new();
  8302. let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0");
  8303. let stop = AtomicBool::new(false);
  8304. // Also when an assertion fails on one of the threads.
  8305. struct Stop<'a>(&'a AtomicBool);
  8306. impl Drop for Stop<'_> {
  8307. fn drop(&mut self) {
  8308. self.0.store(true, Ordering::Relaxed);
  8309. }
  8310. }
  8311. // Held shared by who writes title memory, alone while it is looked at.
  8312. let still = std::sync::RwLock::new(());
  8313. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  8314. std::thread::scope(|s| {
  8315. for t in 0..2usize {
  8316. let (stop, still) = (&stop, &still);
  8317. s.spawn(move || {
  8318. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  8319. let mut value = 0u32;
  8320. while !stop.load(Ordering::Relaxed) {
  8321. {
  8322. let _moving = still.read().unwrap();
  8323. for _ in 0..3 {
  8324. value += 1;
  8325. // Of each eight dwords, one a thread.
  8326. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  8327. dword(at).store(value, Ordering::Relaxed);
  8328. }
  8329. }
  8330. std::thread::sleep(std::time::Duration::from_micros(20));
  8331. }
  8332. });
  8333. }
  8334. // Lands flights.
  8335. {
  8336. let (carded, stop) = (&carded, &stop);
  8337. s.spawn(move || {
  8338. let _stop = Stop(stop);
  8339. while let Ok((which, ranges, value)) = flights.recv() {
  8340. let c = &carded[which];
  8341. // Fetched: the card's bytes, behind every send so far.
  8342. let (after, now) = {
  8343. let card = c.card.lock().unwrap();
  8344. (card.0, card.2.clone())
  8345. };
  8346. // By piece: 64 KiB of title memory.
  8347. let mut pieces = Vec::new();
  8348. for &(from, to) in &ranges {
  8349. let mut at = from;
  8350. while at < to {
  8351. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  8352. pieces.push((at, next, now.as_ptr() as usize + at));
  8353. at = next;
  8354. }
  8355. }
  8356. let parts: Vec<_> = pieces.chunks(3).collect();
  8357. crate::land::each(parts.len(), &|i| {
  8358. let mut notes = crate::land::Notes::default();
  8359. // SAFETY: the bytes of `now`; each piece once.
  8360. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  8361. notes.flush();
  8362. });
  8363. for &(from, to) in &ranges {
  8364. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8365. // (The next fetch may have brought more.)
  8366. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  8367. }
  8368. }
  8369. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  8370. c.shadow.copy_back_done(&done);
  8371. c.card.lock().unwrap().1 = after;
  8372. c.flying.store(false, Ordering::Release);
  8373. }
  8374. });
  8375. }
  8376. let _stop = Stop(&stop);
  8377. let mut random = Random(0xABCD_EF01_2345_6789);
  8378. let check = |round: usize, random: &mut Random, quiet: bool| {
  8379. for c in &carded {
  8380. if c.shadow.writes_pending() {
  8381. let mut runs = usize::MAX;
  8382. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  8383. }
  8384. }
  8385. let mut ranges = Vec::new();
  8386. for (shadow, start, len) in
  8387. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  8388. {
  8389. // All of it, or a part; often the same part.
  8390. let (from, n) = match random.below(3) {
  8391. _ if quiet => (0, len),
  8392. 0 => (0, len),
  8393. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  8394. _ => {
  8395. let from = random.below(len / 4) * 4;
  8396. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  8397. }
  8398. };
  8399. ranges.push((shadow.clone(), start + from, n));
  8400. }
  8401. submission(&ranges, 1 + random.below(3));
  8402. carded.iter().for_each(Carded::send);
  8403. };
  8404. let mut value = 1u32;
  8405. for round in 0..rounds {
  8406. check(round, &mut random, false);
  8407. if exact {
  8408. let c = &carded[0];
  8409. let mut card = c.card.lock().unwrap();
  8410. for _ in 0..40 {
  8411. value += 1;
  8412. let at = random.below(LEN / 32) * 32 + 4 * 6;
  8413. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8414. undeclared.insert(at, value);
  8415. }
  8416. }
  8417. // The flight of this submission: its shaders' writes.
  8418. for (which, c) in carded.iter().enumerate() {
  8419. if c.flying.swap(true, Ordering::Acquire) {
  8420. continue;
  8421. }
  8422. value += 1;
  8423. let mut ranges: Vec<(usize, usize)> = Vec::new();
  8424. let first = random.below(6) * PAGE / 2;
  8425. for k in 0..2 {
  8426. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  8427. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  8428. if from < to {
  8429. ranges.push((from, to));
  8430. }
  8431. }
  8432. for &(from, to) in &ranges {
  8433. c.shadow.writing(c.start + from, to - from);
  8434. }
  8435. {
  8436. let mut card = c.card.lock().unwrap();
  8437. for &(from, to) in &ranges {
  8438. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8439. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8440. }
  8441. }
  8442. }
  8443. fly.send((which, ranges, value)).unwrap();
  8444. }
  8445. if round % 20 != 19 {
  8446. continue;
  8447. }
  8448. // Still: no flight in the air, no title write.
  8449. let _still = still.write().unwrap();
  8450. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  8451. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  8452. std::thread::yield_now();
  8453. }
  8454. check(round, &mut random, true);
  8455. // SAFETY: the test's own memory, written by nobody now.
  8456. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  8457. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  8458. for c in &carded {
  8459. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  8460. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  8461. let card = c.card.lock().unwrap();
  8462. let mut side = card.2.clone();
  8463. if c.class == carded[0].class {
  8464. // (They may have been landed meanwhile, by a flight
  8465. // that declared their range, and may not.)
  8466. for (&at, &value) in &undeclared {
  8467. let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
  8468. assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
  8469. side[at..at + 4].copy_from_slice(&there[at..at + 4]);
  8470. }
  8471. }
  8472. assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
  8473. }
  8474. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  8475. }
  8476. drop(fly);
  8477. });
  8478. }
  8479. /// The title's bytes put in under shader writes, for a copy of 174 MB
  8480. /// whose shader writes were declared as 40 ranges that overlap, with 12
  8481. /// pages written since. Run with `--ignored --nocapture`, and with
  8482. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8483. #[test]
  8484. #[ignore]
  8485. fn bytes_under_overlapping_ranges() {
  8486. const BIG: usize = 174 << 20;
  8487. let big = title(BIG, true);
  8488. // SAFETY (both): the test's own memory.
  8489. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  8490. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8491. copy.update(big, BIG);
  8492. copy.take_dirty();
  8493. for i in 0..40 {
  8494. copy.writing(big + i * 5920, BIG - i * 5920);
  8495. }
  8496. let mut best = f64::MAX;
  8497. for round in 0..30 {
  8498. for i in 0..12 {
  8499. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  8500. }
  8501. let started = std::time::Instant::now();
  8502. let mut runs = usize::MAX;
  8503. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  8504. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  8505. copy.take_dirty();
  8506. }
  8507. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  8508. }
  8509. /// A range nothing wrote is known to be as it was, at its ends too, and
  8510. /// is so no more once something wrote it.
  8511. #[test]
  8512. fn unchanged_ranges_are_known() {
  8513. for view in [false, true] {
  8514. let region = title(8 * PAGE, view);
  8515. // (A page read for the first time counts as written.)
  8516. // SAFETY: the test's own memory.
  8517. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  8518. let data = memory(8 * PAGE);
  8519. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  8520. // Ends in the middle of pages.
  8521. let (at, len) = (region + 500, 5 * PAGE);
  8522. let look = |expected: bool, what: &str| {
  8523. // The submission's one asking, which takes two ranges. (Again
  8524. // if a submission of another test ended it.)
  8525. let mut known = false;
  8526. for _ in 0..100 {
  8527. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  8528. known = copy.nothing_new(at, len);
  8529. if known || !expected {
  8530. break;
  8531. }
  8532. }
  8533. assert_eq!(known, expected, "view {view}: {what}");
  8534. let copied = copy.update(at, len);
  8535. crate::watch::ask_once_end();
  8536. copied
  8537. };
  8538. assert_eq!(look(false, "never taken"), len);
  8539. assert_eq!(look(true, "taken"), 0);
  8540. assert_eq!(look(true, "taken"), 0);
  8541. // SAFETY: the test's own memory.
  8542. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  8543. assert_eq!(look(false, "written at its end"), PAGE - 500);
  8544. assert_eq!(look(true, "taken again"), 0);
  8545. // Outside the range, on its last page.
  8546. // SAFETY: as above.
  8547. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  8548. assert_eq!(look(false, "written on its last page"), 500);
  8549. // A longer range was never taken whole.
  8550. assert!(!copy.nothing_new(region, 6 * PAGE));
  8551. }
  8552. }
  8553. /// Of a copy in the card's memory only the dwords title memory changed go
  8554. /// up, and none beside them, not even between two in 64 bytes; a page
  8555. /// never taken goes up whole.
  8556. #[test]
  8557. fn only_what_differs_goes_up() {
  8558. let region = title(4 * PAGE, true);
  8559. let data = memory(4 * PAGE);
  8560. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  8561. copy.update(region, 4 * PAGE);
  8562. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  8563. // What the relay does: shader writes into title memory, and into the
  8564. // CPU's side.
  8565. crate::watch::landing(region + PAGE + 640, 64);
  8566. // SAFETY: the test's own memory.
  8567. unsafe {
  8568. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  8569. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  8570. }
  8571. copy.update(region, 4 * PAGE);
  8572. let again = copy.take_dirty();
  8573. // SAFETY: as above.
  8574. unsafe {
  8575. ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
  8576. ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
  8577. ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
  8578. // The value that was there.
  8579. ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
  8580. }
  8581. copy.update(region, 4 * PAGE);
  8582. let written = copy.take_dirty();
  8583. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") {
  8584. assert_eq!(again, []);
  8585. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
  8586. } else {
  8587. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  8588. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  8589. }
  8590. // SAFETY: as above.
  8591. assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
  8592. }
  8593. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  8594. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  8595. /// big copy that 55 landed pieces and 9 title writes opened, while a
  8596. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  8597. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8598. #[test]
  8599. #[ignore]
  8600. fn frame_of_refreshes() {
  8601. let mut random = Random(0x9876_5432_1234_5671);
  8602. const EACH: usize = 224 << 10;
  8603. const BIG: usize = 174 << 20;
  8604. let watched = title(3000 * EACH, false);
  8605. // `VICTORY_BENCH_HOLES=0`: views without holes.
  8606. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  8607. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  8608. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  8609. let big = title(BIG, true);
  8610. // SAFETY: the test's own memory.
  8611. unsafe {
  8612. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  8613. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  8614. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  8615. }
  8616. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  8617. }
  8618. let mut small = Vec::new();
  8619. for i in 0..4400 {
  8620. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  8621. let data = memory(EACH);
  8622. // The range views read, not all of the copy.
  8623. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  8624. }
  8625. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  8626. // The same memory, as another copy: what is landed is landed through
  8627. // it, and the refreshes are of the first.
  8628. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8629. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  8630. let (mut sum, mut landing) = (0.0, 0.0);
  8631. const FRAMES: usize = 12;
  8632. for frame in 0..FRAMES {
  8633. let mut took = [0f64; 2];
  8634. for i in 0..30 {
  8635. // The title's writes, and the relay's beside the submission.
  8636. for _ in 0..9 {
  8637. let at = views + random.below(1400 * EACH / 8) * 8;
  8638. if there(at) {
  8639. // SAFETY: the test's own memory.
  8640. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8641. }
  8642. }
  8643. for _ in 0..60 {
  8644. let at = watched + random.below(3000 * EACH / 8) * 8;
  8645. // SAFETY: the test's own memory.
  8646. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8647. }
  8648. let first = random.below(BIG / PAGE - 60);
  8649. let lands = lands.clone();
  8650. let land = std::thread::spawn(move || {
  8651. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  8652. let started = std::time::Instant::now();
  8653. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  8654. let pieces: Vec<_> =
  8655. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  8656. let mut notes = crate::land::Notes::default();
  8657. // SAFETY: the bytes of `now`; nothing else lands here.
  8658. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  8659. notes.flush();
  8660. }
  8661. started.elapsed().as_secs_f64() * 1e3
  8662. });
  8663. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  8664. small.iter().cloned().chain([heap.clone()]).collect()
  8665. } else {
  8666. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  8667. };
  8668. let started = std::time::Instant::now();
  8669. submission(&ranges, 3);
  8670. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  8671. let put = land.join().unwrap();
  8672. if frame >= 2 {
  8673. landing += put;
  8674. }
  8675. heap.0.take_dirty();
  8676. }
  8677. if frame >= 2 {
  8678. sum += took[0] + took[1];
  8679. for k in 0..2 {
  8680. best[k] = best[k].min(took[k]);
  8681. asking[k] += took[k];
  8682. }
  8683. }
  8684. }
  8685. println!(
  8686. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  8687. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  8688. crate::watch::light(),
  8689. sum / (FRAMES - 2) as f64,
  8690. asking[0] / (FRAMES - 2) as f64,
  8691. best[0],
  8692. asking[1] / (FRAMES - 2) as f64,
  8693. best[1],
  8694. landing / (FRAMES - 2) as f64,
  8695. );
  8696. #[cfg(feature = "diagnostics")]
  8697. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  8698. }
  8699. }
  8700. #[cfg(test)]
  8701. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  8702. use super::Batch;
  8703. use std::sync::Arc;
  8704. #[test]
  8705. fn a_texture_is_checked_once_per_submission() {
  8706. let mut batch = Batch::default();
  8707. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  8708. // The first list sampling each texture checks it ...
  8709. assert!(batch.texture_due(&a));
  8710. assert!(batch.texture_due(&b));
  8711. // ... later lists of the same submission do not.
  8712. assert!(!batch.texture_due(&a));
  8713. assert!(!batch.texture_due(&a.clone()));
  8714. assert!(!batch.texture_due(&b));
  8715. }
  8716. #[test]
  8717. fn title_writes_make_textures_due_again() {
  8718. let mut batch = Batch::default();
  8719. let a = Arc::new(1u32);
  8720. assert!(batch.texture_due(&a));
  8721. assert!(!batch.texture_due(&a));
  8722. // A copy into title memory or work that may write it may have
  8723. // changed the texture's memory.
  8724. batch.title_written();
  8725. assert!(batch.texture_due(&a));
  8726. assert!(!batch.texture_due(&a));
  8727. // A fresh submission starts over.
  8728. let mut next = Batch::default();
  8729. assert!(next.texture_due(&a));
  8730. }
  8731. /// The hashing a submission does for textures in physical-page memory,
  8732. /// with every list checking the textures it samples (before) and with
  8733. /// each checked once (after). Run with
  8734. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  8735. #[test]
  8736. #[ignore = "benchmark"]
  8737. fn texture_checks_per_submission() {
  8738. const TEXTURES: usize = 48;
  8739. const SIZE: usize = 4 << 20;
  8740. const LISTS: usize = 12;
  8741. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  8742. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  8743. .collect();
  8744. let submit = |dedupe: bool| {
  8745. let mut batch = Batch::default();
  8746. let mut hashed = 0usize;
  8747. let started = std::time::Instant::now();
  8748. for _ in 0..LISTS {
  8749. for t in &textures {
  8750. if !dedupe || batch.texture_due(t) {
  8751. std::hint::black_box(blake3::hash(t));
  8752. hashed += 1;
  8753. }
  8754. }
  8755. }
  8756. (started.elapsed(), hashed)
  8757. };
  8758. submit(false); // warm up
  8759. let (before, n_before) = submit(false);
  8760. let (after, n_after) = submit(true);
  8761. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  8762. println!(
  8763. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  8764. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  8765. SIZE >> 20,
  8766. before.as_secs_f64() / after.as_secs_f64()
  8767. );
  8768. }
  8769. #[test]
  8770. fn vram_idle_ms_scales_with_pressure() {
  8771. let vram_idle_ms = |memory| super::vram_idle_for(memory, false);
  8772. let keeps = |memory| super::vram_idle_for(memory, true);
  8773. let gib = 1024 * 1024 * 1024;
  8774. assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000);
  8775. assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000);
  8776. assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500);
  8777. assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000);
  8778. assert_eq!(keeps(None), 5_000);
  8779. // Normal (< 75%)
  8780. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  8781. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  8782. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  8783. // Moderate (75%..85%)
  8784. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  8785. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  8786. // High (>= 85%, including over-budget)
  8787. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  8788. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  8789. // Missing or zero budget falls back to normal
  8790. assert_eq!(vram_idle_ms(None), 5_000);
  8791. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  8792. }
  8793. #[test]
  8794. fn textures_are_kept_while_the_card_has_room() {
  8795. use super::vram_keep;
  8796. let gib = 1 << 30;
  8797. assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000);
  8798. // Past it: the longest idle ones, enough to come down to 85 %.
  8799. let (ms, bytes) = vram_keep(100 * gib, 90 * gib);
  8800. assert_eq!((ms, bytes), (5_000, 5 * gib));
  8801. assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib));
  8802. assert_eq!(vram_keep(0, 7).0, 5_000);
  8803. }
  8804. #[test]
  8805. fn ram_idle_ms_scales_with_pressure() {
  8806. let ram_idle_ms = |avail| super::ram_idle_for(avail, false);
  8807. assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000);
  8808. assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000);
  8809. assert_eq!(super::ram_idle_for(None, true), 10_000);
  8810. let gib = 1024 * 1024 * 1024;
  8811. // Normal (>= 4 GiB)
  8812. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  8813. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  8814. // Moderate (2 GiB..4 GiB)
  8815. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  8816. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  8817. // High (< 2 GiB)
  8818. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  8819. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  8820. // Missing falls back to normal
  8821. assert_eq!(ram_idle_ms(None), 10_000);
  8822. }
  8823. }