host.rs 397 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035
  1. //! The host GPU: one D3D12 device and direct queue (decision 0007), and a
  2. //! window to present on.
  3. //!
  4. //! shortcut: every submission is waited for, so CPU and GPU never overlap
  5. //! (unless `VICTORY_LATE_WAIT=1`, see [`late`]);
  6. //! overlap them with per-submission fences once more than clears run.
  7. use std::sync::atomic::{AtomicU32, Ordering};
  8. use std::sync::{Mutex, OnceLock};
  9. use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
  10. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  11. use windows::Win32::Graphics::Direct3D12::*;
  12. use windows::Win32::Graphics::Dxgi::Common::*;
  13. use windows::Win32::Graphics::Dxgi::*;
  14. use windows::Win32::System::LibraryLoader::GetModuleHandleW;
  15. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  16. use windows::Win32::UI::WindowsAndMessaging::*;
  17. use windows::core::{Interface, PCWSTR, w};
  18. /// Resource states without the console's own bits (compression hints from
  19. /// bit 25 up), which the host rejects.
  20. pub(crate) fn pc_state(state: u32) -> u32 {
  21. state & 0x01ff_ffff
  22. }
  23. /// A console state as a host texture state: PC bits only, and none of the
  24. /// buffer-only ones the console allows on textures (vertex, constant and
  25. /// index buffer, stream out, indirect arguments, as in "generic read").
  26. pub(crate) fn texture_state(state: u32) -> u32 {
  27. const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
  28. pc_state(state) & !BUFFER_ONLY
  29. }
  30. /// Render target views live only until their command is recorded, so a
  31. /// ring of host descriptors is enough.
  32. const RTV_RING: u32 = 1024;
  33. pub(crate) struct Host {
  34. pub(crate) device: ID3D12Device,
  35. queue: ID3D12CommandQueue,
  36. fence: ID3D12Fence,
  37. /// The last value signalled on `fence`, behind the submission lock.
  38. submitted: Mutex<u64>,
  39. event: HANDLE,
  40. rtvs: ID3D12DescriptorHeap,
  41. rtv_size: u32,
  42. /// A ring of depth views, used as `rtvs`.
  43. dsvs: ID3D12DescriptorHeap,
  44. dsv_size: u32,
  45. next_dsv: AtomicU32,
  46. /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug
  47. /// layer's messages.
  48. messages: Option<ID3D12InfoQueue>,
  49. next_rtv: AtomicU32,
  50. presenter: Mutex<Option<Presenter>>,
  51. /// The adapter the device is on, for its memory budget
  52. /// ([`Host::video_memory`]); `None` if the system does not name it.
  53. adapter: Option<IDXGIAdapter3>,
  54. }
  55. // SAFETY: D3D12 devices, queues, fences and descriptor heaps are
  56. // free-threaded; the event handle is only waited on under `submitted`.
  57. unsafe impl Send for Host {}
  58. // SAFETY: as above.
  59. unsafe impl Sync for Host {}
  60. /// Host objects the title let go of while a submission may still use them
  61. /// (a texture its descriptors name, a descriptor slot's old resource), by
  62. /// the submission count they wait for. The title's descriptor writes and
  63. /// releases reach the host at once, from its own threads, while the host
  64. /// runs a submission: freeing there is a GPU page fault on the freed
  65. /// texture (a device hang).
  66. static RETIRED: Mutex<Vec<(u64, Retired)>> = Mutex::new(Vec::new());
  67. /// Submissions started and finished (waited for).
  68. static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  69. static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  70. /// A retired object, dropped on whatever thread finishes the submission.
  71. struct Retired(#[allow(dead_code)] Box<dyn std::any::Any>);
  72. // SAFETY: what is retired is D3D12 objects (free-threaded) and the
  73. // reference-counted wrappers holding them, dropped once.
  74. unsafe impl Send for Retired {}
  75. /// Milliseconds since the first call.
  76. pub(crate) fn now_ms() -> u64 {
  77. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  78. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  79. }
  80. /// This moment, for telling later how long ago it was ([`long_ago`]): the
  81. /// frames begun so far (high half, `crate::frame::current`) and tenths of a
  82. /// second since the start. Host copies of title memory, staging buffers and
  83. /// host textures note when they were last used with it.
  84. pub(crate) fn moment() -> u64 {
  85. (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff)
  86. }
  87. /// Whether `moment` lies at least `ms` milliseconds and `frames` frames
  88. /// back. Both: at seconds per frame, what every frame uses is not touched
  89. /// for seconds, and at many frames per second not for many frames. (A title
  90. /// that never waits for frames has no frame count: nothing is then idle.)
  91. pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
  92. let now = self::moment();
  93. let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
  94. (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
  95. }
  96. /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
  97. pub(crate) fn available_physical_ram() -> Option<u64> {
  98. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  99. // SAFETY: plain data the call fills in.
  100. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  101. m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
  102. // SAFETY: a sized structure.
  103. let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
  104. ok.then_some(m.ullAvailPhys)
  105. }
  106. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  107. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  108. /// handles not yet recorded into a list or slot remain protected.
  109. ///
  110. /// With room on the card nothing has to go: in session play-1125-0127 88,000
  111. /// of them (31 GB) went after 5 s with 7 GB of the card free, and 24,700
  112. /// (12 GB) had to be made and uploaded again.
  113. /// `VICTORY_TEXTURE_KEEP=0`: 5 s there too, as before.
  114. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  115. static KEEP: OnceLock<bool> = OnceLock::new();
  116. let keep = *KEEP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_KEEP").is_none_or(|v| v != "0"));
  117. vram_idle_for(video_memory, keep)
  118. }
  119. fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 {
  120. const KEPT_MS: u64 = 600_000;
  121. const LONG_MS: u64 = 30_000;
  122. const NORMAL_MS: u64 = 5_000;
  123. const MODERATE_MS: u64 = 2_500;
  124. const HIGH_MS: u64 = 1_000;
  125. let Some([budget, used, ..]) = video_memory else {
  126. return NORMAL_MS;
  127. };
  128. if budget == 0 {
  129. return NORMAL_MS;
  130. }
  131. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  132. if used_pct >= 85 {
  133. HIGH_MS
  134. } else if used_pct >= 75 {
  135. MODERATE_MS
  136. } else if !keep {
  137. NORMAL_MS
  138. } else if used_pct >= 68 {
  139. LONG_MS
  140. } else {
  141. KEPT_MS
  142. }
  143. }
  144. /// Whether memory the card was given stays with it while there is room (on
  145. /// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader
  146. /// that reads past a view (a raw load through a typed, structured or
  147. /// constant buffer view has no end on AMD: `indirect::tests::raw_loads_past_views`)
  148. /// or through a slot that shows wrong data reads whatever lies there, and
  149. /// nothing happens; where memory was given back it is a page fault, and the
  150. /// device is lost. Both losses of 2026-11-25 were reads in memory given back
  151. /// seconds before (a block of textures; a list's scratch and a window of
  152. /// title memory). Kept are: empty blocks of textures ([`crate::pool`]) below
  153. /// 85 % of the card's budget, windows of title memory and staging buffers
  154. /// for five minutes with 12 GiB of the PC's memory free, and 1 GiB of
  155. /// scratch chunks.
  156. pub(crate) fn keep_freed() -> bool {
  157. static ON: OnceLock<bool> = OnceLock::new();
  158. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_FREED").is_none_or(|v| v != "0"))
  159. }
  160. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  161. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  162. /// when free physical RAM is low. Never returns less than 2,000 ms.
  163. /// With plenty of it five minutes ([`keep_freed`]).
  164. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  165. ram_idle_for(avail_phys, keep_freed())
  166. }
  167. fn ram_idle_for(avail_phys: Option<u64>, keep: bool) -> u64 {
  168. const GIB: u64 = 1024 * 1024 * 1024;
  169. const KEPT_MS: u64 = 300_000;
  170. if keep && avail_phys.is_some_and(|avail| avail >= 12 * GIB) {
  171. return KEPT_MS;
  172. }
  173. const NORMAL_MS: u64 = 10_000;
  174. const MODERATE_MS: u64 = 5_000;
  175. const HIGH_MS: u64 = 2_000;
  176. let Some(avail) = avail_phys else {
  177. return NORMAL_MS;
  178. };
  179. if avail < 2 * GIB {
  180. HIGH_MS
  181. } else if avail < 4 * GIB {
  182. MODERATE_MS
  183. } else {
  184. NORMAL_MS
  185. }
  186. }
  187. /// How many references are held on a host object (its COM count): ours
  188. /// all, since the host's views and commands hold none. A buffer or texture
  189. /// with one is held by its owner alone: no descriptor slot keeps it
  190. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  191. pub(crate) fn references(object: &impl Interface) -> u32 {
  192. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  193. let raw = object.as_raw();
  194. // SAFETY: a live COM object, whose first three methods are those of
  195. // `IUnknown` (query, add a reference, release one); the pair leaves the
  196. // count as it was, and the release returns it. The first is not called.
  197. unsafe {
  198. let methods = *raw.cast::<*const [Method; 3]>();
  199. ((*methods)[1])(raw);
  200. ((*methods)[2])(raw)
  201. }
  202. }
  203. /// Once a second, before a submission starts: lets go of what nothing
  204. /// names any more (copies of windows of title memory, staging buffers,
  205. /// host copies of textures the title fills).
  206. /// `VICTORY_SWEEP=0` keeps everything, as before.
  207. fn sweep() {
  208. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  209. crate::inplace::tick();
  210. static ON: OnceLock<bool> = OnceLock::new();
  211. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  212. return;
  213. }
  214. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  215. let now = now_ms();
  216. let last = LAST.load(Ordering::Relaxed);
  217. if now < last + 1000
  218. || LAST
  219. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  220. .is_err()
  221. {
  222. return;
  223. }
  224. crate::pool::room(host().and_then(|h| h.video_memory()));
  225. crate::pipeline::trim_library();
  226. crate::shadow::let_go_idle();
  227. crate::texture::let_go_idle();
  228. crate::resource::let_go_idle();
  229. }
  230. /// Drops `object` once every submission running now has finished: at once
  231. /// if none is.
  232. pub(crate) fn retire<T: 'static>(object: T) {
  233. let started = STARTED.load(Ordering::Acquire);
  234. if started <= FINISHED.load(Ordering::Acquire) {
  235. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  236. drop(object);
  237. return;
  238. }
  239. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  240. RETIRED
  241. .lock()
  242. .unwrap_or_else(|e| e.into_inner())
  243. .push((started, Retired(Box::new(object))));
  244. }
  245. /// Drops what waited for submissions up to `finished`.
  246. fn bury(finished: u64) {
  247. let done: Vec<(u64, Retired)> = {
  248. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  249. if retired.is_empty() {
  250. return;
  251. }
  252. let (done, keep) = std::mem::take(&mut *retired)
  253. .into_iter()
  254. .partition(|(at, _)| *at <= finished);
  255. *retired = keep;
  256. done
  257. };
  258. drop(done);
  259. }
  260. /// Objects [`retire`] dropped at once (no submission was running) and
  261. /// kept until a running submission finished, since the start.
  262. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  263. /// What the layer did to the host's objects lately, newest last (sweeps
  264. /// that let host copies go, pipeline library calls, saves and trims): said
  265. /// once when the host device is removed ([`log_removal_context`]), with
  266. /// what the submitting thread and the pipeline workers were doing at that
  267. /// moment. A device the driver removes "internally" names no command, and
  268. /// the pass that happens to notice first names only the view it was at:
  269. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  270. /// pipeline library call that no line of the log tied to them.
  271. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  272. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  273. /// The entries kept.
  274. const TRAIL_MOST: usize = 96;
  275. fn trail_on() -> bool {
  276. static ON: OnceLock<bool> = OnceLock::new();
  277. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  278. }
  279. /// Microseconds since the first call.
  280. pub(crate) fn now_us() -> u64 {
  281. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  282. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  283. }
  284. /// The calling thread, as the log's other lines name threads.
  285. pub(crate) fn thread_id() -> u32 {
  286. // SAFETY: a plain query.
  287. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  288. }
  289. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  290. /// run when the trail is kept.
  291. pub(crate) fn trail(what: impl FnOnce() -> String) {
  292. if !trail_on() {
  293. return;
  294. }
  295. let entry = (now_us(), thread_id(), what());
  296. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  297. if trail.len() >= TRAIL_MOST {
  298. trail.pop_front();
  299. }
  300. trail.push_back(entry);
  301. }
  302. /// What the submitting thread is doing (0 nothing: between submissions,
  303. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  304. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  305. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  306. fn submitting(phase: u64, lists: usize) {
  307. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  308. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  309. SUBMITTING[0].store(phase, Ordering::Relaxed);
  310. }
  311. /// What was going on when the host device went: whether a submission was
  312. /// on the card, the pipeline library's state and the calls running in it,
  313. /// and the trail.
  314. pub(crate) fn removal_context() -> String {
  315. use std::fmt::Write;
  316. let now = now_us();
  317. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  318. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  319. 0 => "between submissions (nothing of ours was running on the card)",
  320. 1 => "preparing a submission (nothing of ours was running on the card)",
  321. 2 => "waiting for the card to run a submission",
  322. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  323. };
  324. let mut text = format!(
  325. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  326. SUBMITTING[1].load(Ordering::Relaxed),
  327. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  328. crate::pipeline::library_removal_note(),
  329. RETIREMENTS[0].load(Ordering::Relaxed),
  330. RETIREMENTS[1].load(Ordering::Relaxed),
  331. STARTED.load(Ordering::Relaxed),
  332. FINISHED.load(Ordering::Relaxed),
  333. );
  334. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  335. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  336. for (at, thread, what) in trail.iter() {
  337. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  338. }
  339. text
  340. }
  341. /// Says [`removal_context`] in the log, once: called by whoever finds the
  342. /// host device removed.
  343. pub(crate) fn log_removal_context() {
  344. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  345. if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) {
  346. return;
  347. }
  348. tracing::error!("when the host device went: {}", removal_context());
  349. if dred_any() {
  350. let data = host().map(|h| h.removal_data(&[])).unwrap_or_default();
  351. tracing::error!("device-removed data{}", if data.is_empty() { "; none" } else { &data });
  352. }
  353. }
  354. /// Time spent in submissions since the last frame-rate line, in
  355. /// microseconds: preparing them on the CPU (title memory copies, texture
  356. /// detiling), then waiting for the GPU.
  357. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  358. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  359. /// After submissions: shader-written ranges compared and copied back into
  360. /// title memory (microseconds, bytes that differed), since the last
  361. /// frame-rate line.
  362. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  363. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  364. /// The card's clock, for the frame line of every run, in microseconds since
  365. /// the last one: how long the card had nothing of ours queued; how much of
  366. /// that while the thread that holds the submission lock was working (the
  367. /// card idle behind us: preparing and copying back are done with the card
  368. /// standing); and how long that thread stood waiting for the card.
  369. ///
  370. /// Every send of lists to the queue is followed by a signal on a fence of
  371. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  372. /// the newest signal and notes the moment the card reached it with nothing
  373. /// newer sent; the next send ends that idle stretch.
  374. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  375. /// Of the thread that holds the submission lock: the microseconds it has
  376. /// worked so far (preparing, copying back; not its waits for the card), and
  377. /// since when it works now ([`now_us`] plus one; 0: it does not).
  378. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  379. /// The thread that holds the submission lock starts (`on`) or stops
  380. /// working; whether it worked until now.
  381. fn working(on: bool) -> bool {
  382. let now = now_us() + 1;
  383. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  384. if since != 0 {
  385. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  386. }
  387. since != 0
  388. }
  389. /// [`WORKING`] as of now: microseconds worked so far.
  390. fn worked() -> u64 {
  391. let since = WORKING[1].load(Ordering::Relaxed);
  392. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  393. WORKING[0].load(Ordering::Relaxed) + now
  394. }
  395. /// The thread that holds the submission lock stood waiting for the card
  396. /// from `since` until now ([`CARD_CLOCK_US`]).
  397. fn stood(since: std::time::Instant) {
  398. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  399. }
  400. /// What [`CARD_CLOCK_US`] is measured with.
  401. struct CardClock {
  402. fence: ID3D12Fence,
  403. /// Signals sent so far; and, while the card has reached the last of
  404. /// them, since when and what [`worked`] said then.
  405. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  406. sent: std::sync::Condvar,
  407. }
  408. // SAFETY: a fence (free-threaded) behind a lock.
  409. unsafe impl Send for CardClock {}
  410. // SAFETY: as above.
  411. unsafe impl Sync for CardClock {}
  412. /// The clock's thread: waits for the newest signal sent and notes when the
  413. /// card got there with nothing newer behind it.
  414. fn card_clock_watch(clock: &'static CardClock) {
  415. // SAFETY: a plain event of our own.
  416. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  417. return;
  418. };
  419. let mut seen = 0;
  420. loop {
  421. let target = {
  422. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  423. while state.0 == seen {
  424. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  425. }
  426. state.0
  427. };
  428. // SAFETY: the clock's fence and this thread's event.
  429. unsafe {
  430. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  431. WaitForSingleObject(event, INFINITE);
  432. }
  433. }
  434. seen = target;
  435. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  436. if state.0 == target && state.1.is_none() {
  437. state.1 = Some((std::time::Instant::now(), worked()));
  438. }
  439. }
  440. }
  441. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  442. /// frame's time.
  443. fn card_clock_line(frames: f64, ms: f64) {
  444. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  445. tracing::info!(
  446. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  447. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  448. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  449. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  450. );
  451. }
  452. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  453. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  454. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  455. std::sync::atomic::AtomicU64::new(0),
  456. std::sync::atomic::AtomicU64::new(0),
  457. std::sync::atomic::AtomicU64::new(0),
  458. std::sync::atomic::AtomicU64::new(0),
  459. ];
  460. /// Host buffers made since the start, as (count, bytes): in the upload heap
  461. /// (staging, list scratch), shared with the processor (host copies of title
  462. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  463. /// For the memory line: against what is alive, they show what was let go.
  464. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  465. /// What of that is alive now, for the memory line (`MADE` counts what was
  466. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  467. /// and nothing said how many were alive): host lists; the lists' scratch
  468. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  469. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  470. /// instead of made, since the start; and the lists' other upload buffers
  471. /// (texture data copied from buffers, scratch too big for a chunk) and
  472. /// their bytes.
  473. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  474. /// About host lists, for the memory line: lists made by the host since the
  475. /// start; preludes made (a list's second allocator and list, made when it
  476. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  477. /// bytes the process's private memory grew by while lists were being made
  478. /// (what a list costs: host objects with the driver's command memory; 631
  479. /// lists were alive in run 65, each with a prelude it may never use).
  480. /// Then the lists alive that were never reset since they were made: the
  481. /// host sides of title lists the title made and has not used (a host list
  482. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  483. /// makes at its start).
  484. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  485. /// The process's private bytes (diagnostics: around the making of lists).
  486. #[cfg(feature = "diagnostics")]
  487. fn private_bytes() -> u64 {
  488. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  489. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  490. let mut c = PROCESS_MEMORY_COUNTERS {
  491. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  492. ..Default::default()
  493. };
  494. // SAFETY: our own process and a sized structure.
  495. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  496. c.PagefileUsage as u64
  497. }
  498. /// What the runtime does when the host GPU fails for good: report it like a
  499. /// crash and end the run. The console has no such state, and carrying on
  500. /// draws nothing at seconds per frame.
  501. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  502. /// Sets what a host GPU failure does (the runtime's crash report).
  503. pub fn on_failure(report: fn(&str) -> !) {
  504. let _ = ON_FAILURE.set(report);
  505. }
  506. /// Ends the run on a host GPU failure: what failed, the removal reason and
  507. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  508. /// diagnostics build names the command).
  509. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  510. let mut text = what.to_string();
  511. if let Some(host) = host() {
  512. // SAFETY: a plain query.
  513. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  514. text.push_str(&format!("; device removed: {e}"));
  515. log_removal_context();
  516. }
  517. match host.log_messages() {
  518. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  519. None if host.messages.is_none() => text.push_str(
  520. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  521. ),
  522. None => {}
  523. }
  524. }
  525. tracing::error!("{text}");
  526. // Tests have no log: the reason goes to their output.
  527. #[cfg(test)]
  528. eprintln!("host GPU failure: {text}");
  529. match ON_FAILURE.get() {
  530. Some(report) => report(&text),
  531. None => std::process::abort(),
  532. }
  533. }
  534. /// The host GPU, created on first use; `None` without one (a run then
  535. /// behaves as before: nothing executes).
  536. pub(crate) fn host() -> Option<&'static Host> {
  537. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  538. HOST.get_or_init(|| match create() {
  539. Ok(host) => Some(host),
  540. Err(e) => {
  541. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  542. None
  543. }
  544. })
  545. .as_ref()
  546. }
  547. fn create() -> windows::core::Result<Host> {
  548. // SAFETY: plain D3D12 object creation with valid descriptions.
  549. unsafe {
  550. // The debug layer only in builds with diagnostics.
  551. let debug = cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DEBUG");
  552. if debug {
  553. let mut layer: Option<ID3D12Debug> = None;
  554. match D3D12GetDebugInterface(&mut layer) {
  555. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  556. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  557. }
  558. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  559. // descriptor heap indices and the like become messages naming
  560. // the command instead of page faults. Without state tracking
  561. // (directly indexed textures are not transitioned).
  562. if crate::switch::on("VICTORY_D3D12_GBV")
  563. && let Some(l) = &layer
  564. {
  565. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  566. d1.SetEnableGPUBasedValidation(true);
  567. }
  568. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  569. d2.SetGPUBasedValidationFlags(
  570. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  571. );
  572. }
  573. tracing::info!("GPU-based validation on");
  574. }
  575. }
  576. // Diagnostics: device-removed data (the command that faulted, the
  577. // faulting address), read when the device is removed.
  578. if dred_any() {
  579. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  580. if D3D12GetDebugInterface(&mut dred).is_ok()
  581. && let Some(dred) = dred
  582. {
  583. if dred_on() || dred_light() {
  584. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  585. }
  586. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  587. tracing::info!(
  588. breadcrumbs = dred_on() || dred_light(),
  589. markers = dred_on(),
  590. "crash tracing on (device-removed data)"
  591. );
  592. } else {
  593. tracing::warn!("crash tracing asked for and not there: no device-removed data settings");
  594. }
  595. }
  596. let mut device: Option<ID3D12Device> = None;
  597. // Diagnostics: the software adapter, on which a shader's wild access
  598. // is an access violation in this process (a crash report with the
  599. // address and instruction) instead of a GPU fault and driver reset.
  600. if cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_WARP") {
  601. let adapter = warp_adapter()?;
  602. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  603. tracing::info!("host device on the software adapter (WARP)");
  604. } else {
  605. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  606. // Whether a GPU hang ends the run or freezes the PC (#1054).
  607. crate::tdr::log();
  608. }
  609. let device = device.ok_or_else(windows::core::Error::empty)?;
  610. // Before anything is made with it (`VICTORY_RECORD`).
  611. #[cfg(feature = "diagnostics")]
  612. crate::replay::record::from_env(&device);
  613. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  614. // driver compiling shaders again on the "D3D Background Thread"s,
  615. // for minutes after pipelines were made or loaded) is switched off.
  616. // An experiment: while those threads ran, the same shot took
  617. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  618. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  619. // whether the card is slower with the shaders it then keeps is not
  620. // known.
  621. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  622. && let Ok(device6) = device.cast::<ID3D12Device6>()
  623. {
  624. let set = device6.SetBackgroundProcessingMode(
  625. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  626. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  627. None,
  628. None,
  629. );
  630. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  631. }
  632. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  633. // cross-lane code stays in 32-lane halves translated for waves of 32
  634. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  635. if device
  636. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  637. .is_ok()
  638. {
  639. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  640. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  641. }
  642. let messages = debug
  643. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  644. .flatten();
  645. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  646. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  647. ..Default::default()
  648. })?;
  649. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  650. let event = CreateEventW(None, false, false, None)?;
  651. let rtvs: ID3D12DescriptorHeap =
  652. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  653. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  654. NumDescriptors: RTV_RING,
  655. ..Default::default()
  656. })?;
  657. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  658. let dsvs: ID3D12DescriptorHeap =
  659. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  660. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  661. NumDescriptors: RTV_RING,
  662. ..Default::default()
  663. })?;
  664. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  665. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  666. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  667. .ok();
  668. tracing::info!("host D3D12 device ready");
  669. Ok(Host {
  670. device,
  671. queue,
  672. fence,
  673. submitted: Mutex::new(0),
  674. event,
  675. rtvs,
  676. rtv_size,
  677. dsvs,
  678. dsv_size,
  679. next_dsv: AtomicU32::new(0),
  680. messages,
  681. next_rtv: AtomicU32::new(0),
  682. presenter: Mutex::new(None),
  683. adapter,
  684. })
  685. }
  686. }
  687. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  688. /// Reject it before creating a device in diagnostics' software-only mode.
  689. pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  690. // SAFETY: plain DXGI adapter queries.
  691. unsafe {
  692. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  693. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  694. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  695. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  696. tracing::warn!(
  697. vendor = format_args!("{:#x}", desc.VendorId),
  698. flags = format_args!("{:#x}", desc.Flags),
  699. "DXGI did not identify the WARP adapter as software; refusing device"
  700. );
  701. return Err(windows::core::Error::from_hresult(
  702. windows::Win32::Foundation::E_FAIL,
  703. ));
  704. }
  705. Ok(adapter)
  706. }
  707. }
  708. #[cfg(test)]
  709. mod tests {
  710. /// A list of ours is found by its name, with the debug layer's note or not.
  711. #[cfg(feature = "diagnostics")]
  712. #[test]
  713. fn a_list_is_found_by_the_number_in_its_name() {
  714. assert_eq!(super::list_number("victory host list 7"), Some(7));
  715. assert_eq!(super::list_number("victory host list 158 (debug layer indirect)"), Some(158));
  716. assert_eq!(super::list_number("victory host list 7x"), None);
  717. assert_eq!(super::list_number("victory host list 7 x"), None);
  718. assert_eq!(super::list_number("another list 7"), None);
  719. assert_eq!(super::list_number(""), None);
  720. }
  721. /// What is there of a range some of whose pages are not: those bytes,
  722. /// counted, and zeros for the rest, whatever the buffer held.
  723. #[test]
  724. fn what_is_there_is_read_and_the_rest_is_zeros() {
  725. use windows_sys::Win32::System::Memory::*;
  726. const SIZE: usize = 0x8_0000;
  727. // SAFETY: a reservation of ours; only committed pages are written.
  728. unsafe {
  729. let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  730. assert!(!at.is_null());
  731. // 0-0x1_1000 and 0x3_0000-0x4_0000 are there.
  732. for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] {
  733. assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null());
  734. at.add(from).write_bytes(0x5a, len);
  735. }
  736. // From an address inside a page, as textures are packed.
  737. let mut out = vec![0x77u8; SIZE - 0x300];
  738. assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000);
  739. for (i, &b) in out.iter().enumerate() {
  740. let from = i + 0x300;
  741. let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from);
  742. assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}");
  743. }
  744. // All there: one read.
  745. let mut out = vec![0x77u8; 0x1_0000];
  746. assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000);
  747. assert!(out.iter().all(|&b| b == 0x5a));
  748. // Nothing there.
  749. let mut out = vec![0x77u8; 0x1_0000];
  750. assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0);
  751. assert!(out.iter().all(|&b| b == 0));
  752. assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0);
  753. }
  754. }
  755. /// Zeros for a title destination that went meanwhile are no fault.
  756. #[test]
  757. fn zeros_where_nothing_is_are_lost() {
  758. use windows_sys::Win32::System::Memory::*;
  759. // SAFETY: a reservation of ours, its first page committed.
  760. unsafe {
  761. let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  762. assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
  763. at.write_bytes(7, 4096);
  764. super::zero(at, 4096);
  765. assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
  766. super::zero(at.add(4096), 4096);
  767. VirtualFree(at.cast(), 0, MEM_RELEASE);
  768. }
  769. }
  770. #[test]
  771. fn sparse_copies_preserve_islands_and_observe_remaps() {
  772. use windows_sys::Win32::System::Memory::*;
  773. const N: usize = 5 << 16;
  774. // SAFETY: we reserve a private region, commit selected pages inside it,
  775. // and only directly access the pages while they are writable.
  776. unsafe {
  777. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  778. assert!(!base.is_null());
  779. let mut expected = vec![0; N];
  780. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  781. let at = base.add(offset);
  782. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  783. at.write_bytes(value, 4096);
  784. expected[offset..offset + 4096].fill(value);
  785. }
  786. for remap in [false, true] {
  787. if remap {
  788. let mut old = 0;
  789. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  790. expected[..4096].fill(0);
  791. let at = base.add(1 << 16);
  792. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  793. at.write_bytes(0xc7, 4096);
  794. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  795. }
  796. let mut out = vec![0xee; N];
  797. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  798. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  799. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  800. }
  801. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  802. }
  803. }
  804. use super::*;
  805. #[test]
  806. fn warp_adapter_accepts_only_software() {
  807. // This probes DXGI without creating a D3D12 device or running a title.
  808. // SAFETY: plain DXGI adapter queries.
  809. let raw = unsafe {
  810. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  811. else {
  812. return;
  813. };
  814. factory.EnumWarpAdapter::<IDXGIAdapter>()
  815. };
  816. let Ok(raw) = raw else { return };
  817. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  818. // IDXGIAdapter1; `raw` owns that interface.
  819. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  820. eprintln!(
  821. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  822. desc.VendorId, desc.Flags
  823. );
  824. assert_eq!(
  825. warp_adapter().is_ok(),
  826. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  827. );
  828. }
  829. }
  830. /// The batches of clamped records in one scratch buffer
  831. /// ([`HostList::batch_place`]).
  832. const BATCHES: u32 = 8;
  833. /// A host command list and its allocator, always used together.
  834. pub(crate) struct HostList {
  835. allocator: ID3D12CommandAllocator,
  836. pub(crate) list: ID3D12GraphicsCommandList,
  837. /// Work for submission time, in recorded order.
  838. deferred: Mutex<Deferred>,
  839. /// Upload memory for data the list's draws make (expanded vertices),
  840. /// reused after a reset.
  841. scratch: Mutex<Scratch>,
  842. /// Host texture states the list assumes, by host copy: at its start and
  843. /// at its end. Lists are recorded on many threads and run in submission
  844. /// order, so the transitions from a texture's real state are made at
  845. /// submission, in `prelude`. Holding the copies keeps every texture the
  846. /// list names alive until it is reset, even if the title releases the
  847. /// resource first.
  848. states: Mutex<States>,
  849. /// What the list does with depth textures that have a colour twin, by
  850. /// twin ([`TwinUse`]).
  851. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  852. /// The list that runs those transitions just before this one, made
  853. /// when the list first has such transitions ([`lazy_prelude`]).
  854. prelude: OnceLock<Option<Prelude>>,
  855. /// The pipelines the list binds, for reports of slow submissions.
  856. pipelines: std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>,
  857. /// What its indirect executions ran, for the report of a removed device.
  858. #[cfg(feature = "diagnostics")]
  859. indirects: indirects::Shared,
  860. /// The work its indirect executions may still do (`indirect`): a
  861. /// shader-writable word, zeroed when the list is submitted, and after
  862. /// it what the clamp notes about mesh records. In memory the CPU maps.
  863. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  864. /// The same words in the card's own memory ([`card_budget`]), which the
  865. /// clamp uses instead when there is one: zeroed in the list before its
  866. /// first clamp, its notes copied to `budget` when the list closes.
  867. card_budget: OnceLock<Option<ID3D12Resource>>,
  868. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  869. /// grown to the largest indirect execution recorded on the list.
  870. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  871. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  872. /// how many batches of this recording have a place in them.
  873. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  874. /// Counts the list in [`ALIVE`] while it lives.
  875. _alive: Counted,
  876. /// The texts of the markers `note_op` set, in order (for device-removed
  877. /// data without marker texts), with the host GPU range a copy reads.
  878. #[cfg(feature = "diagnostics")]
  879. notes: std::sync::Arc<Mutex<Vec<Note>>>,
  880. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  881. /// and at the end, and where they are read back.
  882. #[cfg(feature = "diagnostics")]
  883. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  884. }
  885. /// A list's prelude: an allocator and a closed list.
  886. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  887. /// Whether a host list's prelude is made when the list first needs one. A
  888. /// prelude runs the texture transitions and twin copies a list needs before
  889. /// it; lists that name no texture never have one, and every host list was
  890. /// made with one all the same: twice the host objects per list, for the
  891. /// title's 630 lists and for every list made anew.
  892. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  893. fn lazy_prelude() -> bool {
  894. static ON: OnceLock<bool> = OnceLock::new();
  895. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  896. }
  897. /// Timestamps per list (diagnostics); commands past them are not timed.
  898. #[cfg(feature = "diagnostics")]
  899. const STAMPS: u32 = 4096;
  900. /// A marker's text and the host range its command reads (diagnostics).
  901. #[cfg(feature = "diagnostics")]
  902. type Note = (String, Option<(u64, u64)>);
  903. type States = std::collections::HashMap<
  904. usize,
  905. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  906. >;
  907. /// What a list does with a depth texture that has a colour twin
  908. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  909. /// in submission order, so a list cannot know which side an earlier list
  910. /// leaves behind: it notes which sides it uses as it finds them, and its
  911. /// prelude copies one side into the other at submission if that side is
  912. /// behind then. From its first use of a side on, the list knows.
  913. struct TwinUse {
  914. /// The depth texture (the title resource's host copy) and its twin.
  915. depth: std::sync::Arc<crate::resource::HostTexture>,
  916. twin: std::sync::Arc<crate::resource::Twin>,
  917. /// The sides (depth texture, twin) the list uses as it finds them.
  918. needs: [bool; 2],
  919. /// Whether each side lacks what the other was written last, where the
  920. /// list is now; `None`: as the list found it.
  921. behind: [Option<bool>; 2],
  922. /// The draw or dispatch being prepared writes the twin.
  923. writing: bool,
  924. /// The depth plane's twin holds what the plane lacks although the list
  925. /// copied the twins since: the plane's pass waits for the list's close.
  926. late: bool,
  927. }
  928. /// The pass that draws the twin of a depth plane into the plane: one
  929. /// triangle over each mip of each slice, its pixel shader writing the
  930. /// twin's texel as the depth, with the depth test "always" and no stencil
  931. /// (the stencil plane is copied through a buffer and not touched here).
  932. ///
  933. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  934. /// the step times the float nearest 1/65535 (0x37800080). That is how
  935. /// The title's tiled lighting computes the depth of the
  936. /// rectangles it then draws with the test "equal", one class of materials
  937. /// a draw (all six of its vertex shaders multiply the class number by that
  938. /// constant), so the pass and the draw give the host the same float, and
  939. /// the host turns the same float into the same 24 bits. The step divided
  940. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  941. /// and lands in another 24-bit step for 127 of them (none under 385).
  942. const PLANE_CORNERS: &str = r#"
  943. float4 corner(uint i : SV_VertexID) : SV_Position {
  944. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  945. }
  946. "#;
  947. const PLANE_STEPS: &str = r#"
  948. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  949. Texture2DArray<uint> twin : register(t0);
  950. [RootSignature(RS)]
  951. float plane(float4 p : SV_Position) : SV_Depth {
  952. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  953. }
  954. "#;
  955. const PLANE_FLOATS: &str = r#"
  956. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  957. Texture2DArray<float> twin : register(t0);
  958. [RootSignature(RS)]
  959. float plane(float4 p : SV_Position) : SV_Depth {
  960. return twin.Load(int4(int2(p.xy), 0, 0));
  961. }
  962. "#;
  963. /// Views of twins the pass reads, in a heap of ours used as a ring.
  964. /// shortcut: a view must last until its list has run; with one or two
  965. /// passes a frame the ring is far from coming round.
  966. const PLANE_VIEWS: u32 = 256;
  967. /// What the pass draws with: the heap of its views of twins, and per kind
  968. /// of twin (16-bit steps or floats) and depth format the root signature
  969. /// and pipeline, made when first needed (`None`: the host refused).
  970. struct PlanePass {
  971. views: ID3D12DescriptorHeap,
  972. cpu: usize,
  973. gpu: u64,
  974. step: u32,
  975. next: AtomicU32,
  976. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  977. }
  978. /// The pass's root signature and pipeline for one kind of twin and one
  979. /// depth format.
  980. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  981. // SAFETY: D3D12 objects are free-threaded.
  982. unsafe impl Send for PlanePass {}
  983. // SAFETY: as above.
  984. unsafe impl Sync for PlanePass {}
  985. fn plane_pass() -> Option<&'static PlanePass> {
  986. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  987. PASS.get_or_init(|| {
  988. let host = host()?;
  989. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  990. // SAFETY: plain heap creation and queries.
  991. unsafe {
  992. let views: ID3D12DescriptorHeap = host
  993. .device
  994. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  995. Type: kind,
  996. NumDescriptors: PLANE_VIEWS,
  997. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  998. NodeMask: 0,
  999. })
  1000. .ok()?;
  1001. Some(PlanePass {
  1002. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  1003. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  1004. step: host.device.GetDescriptorHandleIncrementSize(kind),
  1005. views,
  1006. next: AtomicU32::new(0),
  1007. made: Mutex::default(),
  1008. })
  1009. }
  1010. })
  1011. .as_ref()
  1012. }
  1013. /// Compiles function `entry` of `source` for `target` with the system's
  1014. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  1015. pub(crate) fn compile(
  1016. source: &str,
  1017. entry: windows::core::PCSTR,
  1018. target: windows::core::PCSTR,
  1019. ) -> windows::core::Result<Vec<u8>> {
  1020. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  1021. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  1022. let mut code: Option<ID3DBlob> = None;
  1023. let mut errors: Option<ID3DBlob> = None;
  1024. // SAFETY: the source and names live through the call; out pointers ours.
  1025. let compiled = unsafe {
  1026. D3DCompile(
  1027. source.as_ptr().cast(),
  1028. source.len(),
  1029. windows::core::s!("victory"),
  1030. None,
  1031. None,
  1032. entry,
  1033. target,
  1034. 0,
  1035. 0,
  1036. &mut code,
  1037. Some(&mut errors),
  1038. )
  1039. };
  1040. if let Err(e) = compiled {
  1041. if let Some(errors) = errors {
  1042. // SAFETY: the blob's own bytes.
  1043. let text = unsafe {
  1044. std::slice::from_raw_parts(
  1045. errors.GetBufferPointer().cast::<u8>(),
  1046. errors.GetBufferSize(),
  1047. )
  1048. };
  1049. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  1050. }
  1051. return Err(e);
  1052. }
  1053. let code = code.ok_or_else(windows::core::Error::empty)?;
  1054. // SAFETY: the blob's own bytes.
  1055. let bytes = unsafe {
  1056. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  1057. };
  1058. Ok(bytes.to_vec())
  1059. }
  1060. impl PlanePass {
  1061. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  1062. /// or of floats and the depth format `format`.
  1063. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  1064. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1065. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  1066. return pipeline.clone();
  1067. }
  1068. let pipeline = match Self::make(steps, format) {
  1069. Ok(pipeline) => Some(pipeline),
  1070. Err(e) => {
  1071. tracing::warn!(
  1072. error = %e,
  1073. steps,
  1074. format = format.0,
  1075. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  1076. );
  1077. None
  1078. }
  1079. };
  1080. made.push((steps, format.0, pipeline.clone()));
  1081. pipeline
  1082. }
  1083. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  1084. use windows::core::s;
  1085. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  1086. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  1087. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  1088. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  1089. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  1090. pShaderBytecode: bytes.as_ptr().cast(),
  1091. BytecodeLength: bytes.len(),
  1092. };
  1093. // SAFETY: the root signature is inside the pixel shader; the
  1094. // description points at live data and never releases its pointer.
  1095. unsafe {
  1096. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  1097. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1098. pRootSignature: std::mem::transmute_copy(&root),
  1099. VS: code(&vs[..]),
  1100. PS: code(&ps[..]),
  1101. SampleMask: u32::MAX,
  1102. RasterizerState: D3D12_RASTERIZER_DESC {
  1103. FillMode: D3D12_FILL_MODE_SOLID,
  1104. CullMode: D3D12_CULL_MODE_NONE,
  1105. DepthClipEnable: true.into(),
  1106. ..Default::default()
  1107. },
  1108. // Every texel is written; stencil stays off.
  1109. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1110. DepthEnable: true.into(),
  1111. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  1112. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1113. ..Default::default()
  1114. },
  1115. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1116. DSVFormat: format,
  1117. SampleDesc: DXGI_SAMPLE_DESC {
  1118. Count: 1,
  1119. Quality: 0,
  1120. },
  1121. ..Default::default()
  1122. };
  1123. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1124. Ok((root, pipeline))
  1125. }
  1126. }
  1127. }
  1128. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1129. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1130. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1131. /// heap, graphics root signature, pipeline, depth target, viewport,
  1132. /// scissor and topology and puts none of them back: it is for a list that
  1133. /// records nothing of the title's after it.
  1134. fn record_plane_pass(
  1135. list: &ID3D12GraphicsCommandList,
  1136. depth: &ID3D12Resource,
  1137. plane: &ID3D12Resource,
  1138. ) {
  1139. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1140. return;
  1141. };
  1142. // SAFETY: live resources.
  1143. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1144. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1145. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1146. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1147. let steps = twin.Format.0 == 53;
  1148. let format = DXGI_FORMAT(match of.Format.0 {
  1149. 44 => 45,
  1150. 19 => 20,
  1151. typed => typed,
  1152. });
  1153. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1154. return;
  1155. };
  1156. for slice in 0..u32::from(of.DepthOrArraySize) {
  1157. for mip in 0..u32::from(of.MipLevels) {
  1158. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1159. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1160. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1161. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1162. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1163. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1164. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1165. MostDetailedMip: mip,
  1166. MipLevels: 1,
  1167. FirstArraySlice: slice,
  1168. ArraySize: 1,
  1169. ..Default::default()
  1170. },
  1171. },
  1172. };
  1173. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1174. Format: format,
  1175. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1176. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1177. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1178. MipSlice: mip,
  1179. FirstArraySlice: slice,
  1180. ArraySize: 1,
  1181. },
  1182. },
  1183. ..Default::default()
  1184. };
  1185. let target = host.dsv(depth, Some(&target));
  1186. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1187. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1188. ptr: pass.cpu + (slot * pass.step) as usize,
  1189. };
  1190. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1191. ptr: pass.gpu + u64::from(slot * pass.step),
  1192. };
  1193. // SAFETY: an open list; a slot of our heap; live resources and
  1194. // objects (the pass's own live as long as the process).
  1195. unsafe {
  1196. host.device
  1197. .CreateShaderResourceView(plane, Some(&view), cpu);
  1198. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1199. list.SetGraphicsRootSignature(&root);
  1200. list.SetPipelineState(&pipeline);
  1201. list.SetGraphicsRootDescriptorTable(0, gpu);
  1202. list.OMSetRenderTargets(0, None, false, Some(&target));
  1203. list.RSSetViewports(&[D3D12_VIEWPORT {
  1204. TopLeftX: 0.0,
  1205. TopLeftY: 0.0,
  1206. Width: width as f32,
  1207. Height: height as f32,
  1208. MinDepth: 0.0,
  1209. MaxDepth: 1.0,
  1210. }]);
  1211. list.RSSetScissorRects(&[RECT {
  1212. left: 0,
  1213. top: 0,
  1214. right: width as i32,
  1215. bottom: height as i32,
  1216. }]);
  1217. list.IASetPrimitiveTopology(
  1218. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1219. );
  1220. list.DrawInstanced(3, 1, 0, 0);
  1221. }
  1222. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1223. }
  1224. }
  1225. }
  1226. /// Records into `list` the copy of a depth texture into its colour twin
  1227. /// (`colour`) or of the twin into the depth texture, both already in their
  1228. /// copy states: whole textures of one size in one format family, which the
  1229. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1230. /// alone, through the twin's buffer.
  1231. fn record_twin_copy(
  1232. list: &ID3D12GraphicsCommandList,
  1233. depth: &ID3D12Resource,
  1234. twin: &crate::resource::Twin,
  1235. colour: bool,
  1236. ) {
  1237. let (from, to) = if colour {
  1238. (depth, &twin.colour.texture)
  1239. } else {
  1240. (&twin.colour.texture, depth)
  1241. };
  1242. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1243. // shortcut: the depth plane's twin is not given the plane (that is a
  1244. // pass the other way: the plane read by a shader, the twin as its
  1245. // target). The twin then lacks what draws and clears wrote to the
  1246. // plane since shaders last wrote the twin. In the title
  1247. // nothing writes that plane but the twin's pass (its 192 draws against
  1248. // it only test, run 29), so the twin lacks nothing. Counted.
  1249. if colour && twin.plane.is_some() {
  1250. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1251. }
  1252. let Some(through) = &twin.through else {
  1253. // SAFETY: an open list and two live textures.
  1254. unsafe { list.CopyResource(to, from) };
  1255. return;
  1256. };
  1257. // A stencil plane and its twin: each mip and slice of the plane goes
  1258. // into the buffer, laid out as the host lays the plane out for copies,
  1259. // and from the buffer into the other texture, whole subresources both
  1260. // times. In the depth texture the stencil plane's subresources follow
  1261. // the depth plane's; the twin has the one plane.
  1262. let Some(host) = host() else { return };
  1263. // SAFETY: a live texture.
  1264. let of = unsafe { depth.GetDesc() };
  1265. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1266. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1267. // SAFETY: a plain query writing `planes` footprints.
  1268. unsafe {
  1269. host.device.GetCopyableFootprints(
  1270. &of,
  1271. planes,
  1272. planes,
  1273. 0,
  1274. Some(rows.as_mut_ptr()),
  1275. None,
  1276. None,
  1277. None,
  1278. );
  1279. }
  1280. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1281. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1282. // SAFETY: a borrowed pointer the location never releases.
  1283. pResource: unsafe { std::mem::transmute_copy(texture) },
  1284. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1285. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1286. SubresourceIndex: index,
  1287. },
  1288. };
  1289. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1290. // SAFETY: as above.
  1291. pResource: unsafe { std::mem::transmute_copy(through) },
  1292. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1293. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1294. PlacedFootprint: *row,
  1295. },
  1296. };
  1297. let (common, source, dest) = (
  1298. D3D12_RESOURCE_STATE_COMMON,
  1299. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1300. D3D12_RESOURCE_STATE_COPY_DEST,
  1301. );
  1302. // SAFETY: an open list and live resources; the buffer was made as big
  1303. // as these footprints, and rests in the common state between copies.
  1304. unsafe {
  1305. list.ResourceBarrier(&[transition(through, common, dest)]);
  1306. for (i, row) in rows.iter().enumerate() {
  1307. let index = first_from + i as u32;
  1308. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1309. }
  1310. list.ResourceBarrier(&[transition(through, dest, source)]);
  1311. for (i, row) in rows.iter().enumerate() {
  1312. let index = first_to + i as u32;
  1313. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1314. }
  1315. list.ResourceBarrier(&[transition(through, source, common)]);
  1316. }
  1317. }
  1318. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1319. /// builds).
  1320. pub(crate) fn dred_on() -> bool {
  1321. static ON: OnceLock<bool> = OnceLock::new();
  1322. *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED") && !dred_faults() && !dred_light())
  1323. }
  1324. /// Breadcrumbs and the faulting address, but no markers and no texts
  1325. /// (`VICTORY_D3D12_DRED=light`): which list a removed device stopped in, at
  1326. /// which of its commands, and the pipelines the list binds; formatting a text
  1327. /// for every command is what makes the whole of it slow.
  1328. pub(crate) fn dred_light() -> bool {
  1329. static ON: OnceLock<bool> = OnceLock::new();
  1330. *ON.get_or_init(|| {
  1331. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "light")
  1332. })
  1333. }
  1334. /// Any of the three.
  1335. pub(crate) fn dred_any() -> bool {
  1336. dred_on() || dred_light() || dred_faults()
  1337. }
  1338. /// Whether only the faulting address of a removed device is kept
  1339. /// (`VICTORY_D3D12_DRED=faults`): no breadcrumbs, no markers and no texts, so
  1340. /// it costs next to nothing and can stay on while the title is played.
  1341. pub(crate) fn dred_faults() -> bool {
  1342. static ON: OnceLock<bool> = OnceLock::new();
  1343. *ON.get_or_init(|| {
  1344. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "faults")
  1345. })
  1346. }
  1347. /// The lists alive while device-removed data is on, by the number their name
  1348. /// ends in, with their marker texts and the pipelines they bind: a report made
  1349. /// on another thread than the one that submits has no lists of its own.
  1350. #[cfg(feature = "diagnostics")]
  1351. #[allow(clippy::type_complexity)]
  1352. static LIST_NOTES: Mutex<
  1353. std::collections::BTreeMap<
  1354. u32,
  1355. (
  1356. std::sync::Weak<Mutex<Vec<Note>>>,
  1357. std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>,
  1358. std::sync::Weak<Mutex<indirects::Indirects>>,
  1359. ),
  1360. >,
  1361. > = Mutex::new(std::collections::BTreeMap::new());
  1362. /// The number in the name of a list of ours ("victory host list 7", which the
  1363. /// debug layer ends with a note of its own in brackets).
  1364. #[cfg(feature = "diagnostics")]
  1365. fn list_number(name: &str) -> Option<u32> {
  1366. let rest = name.strip_prefix("victory host list ")?;
  1367. let digits = rest.split(' ').next()?;
  1368. (rest.len() == digits.len() || rest[digits.len()..].starts_with(" (")).then(|| digits.parse().ok()).flatten()
  1369. }
  1370. /// Indirect mesh dispatches since the last frame line: the largest group
  1371. /// count a record asked for, and the groups asked in all (from the lists'
  1372. /// budget buffers, a run late).
  1373. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1374. /// Whether a list's indirect-work budget lives in the card's own memory
  1375. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1376. /// before). The clamp charges it with atomics, at least two in a row for
  1377. /// every clamp; in mapped memory on a card of its own each of them
  1378. /// crosses the bus.
  1379. fn card_budget() -> bool {
  1380. static ON: OnceLock<bool> = OnceLock::new();
  1381. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1382. }
  1383. /// Whether each list of a submission runs and is timed on its own, slow
  1384. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1385. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1386. #[cfg(feature = "diagnostics")]
  1387. fn timing() -> bool {
  1388. static ON: OnceLock<bool> = OnceLock::new();
  1389. *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING"))
  1390. }
  1391. /// Names a host object for the device-removed report, which names the
  1392. /// allocations a page fault hit (only with device-removed data on), or for
  1393. /// the frame recorder (`VICTORY_RECORD`).
  1394. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1395. #[cfg(feature = "diagnostics")]
  1396. if crate::replay::record::on() {
  1397. let text = text();
  1398. crate::replay::record::name(object, &text);
  1399. if dred_any()
  1400. && let Ok(object) = object.cast::<ID3D12Object>()
  1401. {
  1402. // SAFETY: a plain call on a live object.
  1403. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1404. }
  1405. return;
  1406. }
  1407. if dred_any()
  1408. && let Ok(object) = object.cast::<ID3D12Object>()
  1409. {
  1410. // SAFETY: a plain call on a live object.
  1411. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1412. }
  1413. }
  1414. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1415. /// [`LISTS`]`[3]` until it is first reset.
  1416. struct Counted {
  1417. /// Not reset since it was made.
  1418. fresh: std::sync::atomic::AtomicBool,
  1419. }
  1420. impl Counted {
  1421. fn new() -> Counted {
  1422. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1423. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1424. Counted {
  1425. fresh: std::sync::atomic::AtomicBool::new(true),
  1426. }
  1427. }
  1428. /// The list is reset: it is in use.
  1429. fn used(&self) {
  1430. if self.fresh.swap(false, Ordering::Relaxed) {
  1431. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1432. }
  1433. }
  1434. }
  1435. impl Drop for Counted {
  1436. fn drop(&mut self) {
  1437. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1438. self.used();
  1439. }
  1440. }
  1441. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1442. /// mapping.
  1443. struct Chunk {
  1444. buffer: ID3D12Resource,
  1445. data: usize,
  1446. }
  1447. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1448. // written only by the list that holds the chunk.
  1449. unsafe impl Send for Chunk {}
  1450. /// Upload chunks handed out front to back: the chunks (each with its
  1451. /// bytes), the one in use and the bytes used in it.
  1452. #[derive(Default)]
  1453. struct Scratch {
  1454. chunks: Vec<(Chunk, u64)>,
  1455. current: usize,
  1456. used: u64,
  1457. }
  1458. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1459. unsafe impl Send for Scratch {}
  1460. impl Drop for Scratch {
  1461. fn drop(&mut self) {
  1462. give_chunks(std::mem::take(&mut self.chunks));
  1463. }
  1464. }
  1465. const SCRATCH_CHUNK: u64 = 4 << 20;
  1466. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1467. /// lists put a few constants or a rectangle's corners there, and every
  1468. /// list that did took 4 MiB of the PC's memory for it.
  1469. const SCRATCH_FIRST: u64 = 256 << 10;
  1470. /// The most bytes of chunks kept while no list holds them.
  1471. const SPARE_MOST: u64 = 128 << 20;
  1472. /// The same with [`keep_freed`].
  1473. const SPARE_KEPT: u64 = 1 << 30;
  1474. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1475. /// first needs one, a small one first, and gives all of them back when it
  1476. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1477. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1478. /// host lists of held submissions, which live for one submission, each
  1479. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1480. /// freed per frame of gameplay (run 60).
  1481. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1482. fn scratch_pool() -> bool {
  1483. static ON: OnceLock<bool> = OnceLock::new();
  1484. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1485. }
  1486. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1487. /// for one of the same size.
  1488. struct Spare<T> {
  1489. kept: Vec<(T, u64)>,
  1490. bytes: u64,
  1491. }
  1492. impl<T> Spare<T> {
  1493. const fn new() -> Self {
  1494. Spare { kept: Vec::new(), bytes: 0 }
  1495. }
  1496. /// A kept thing of `size` bytes, the one given last.
  1497. fn take(&mut self, size: u64) -> Option<T> {
  1498. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1499. self.bytes -= size;
  1500. Some(self.kept.remove(at).0)
  1501. }
  1502. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1503. /// `most`: then it comes back.
  1504. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1505. if self.bytes + size > most {
  1506. return Some(thing);
  1507. }
  1508. self.bytes += size;
  1509. self.kept.push((thing, size));
  1510. None
  1511. }
  1512. }
  1513. /// Scratch chunks no list holds.
  1514. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1515. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1516. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1517. if scratch_pool()
  1518. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1519. {
  1520. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1521. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1522. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1523. return Some(chunk);
  1524. }
  1525. let (buffer, data) = host.upload_buffer(size)?;
  1526. name(&buffer, || "list scratch".into());
  1527. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1528. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1529. Some(Chunk {
  1530. buffer,
  1531. data: data as usize,
  1532. })
  1533. }
  1534. /// A list is done with `chunks` (it was reset after its submissions ran,
  1535. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1536. /// without the pool.
  1537. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1538. if chunks.is_empty() {
  1539. return;
  1540. }
  1541. let mut freed = Vec::new();
  1542. {
  1543. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1544. for (chunk, size) in chunks {
  1545. let back = if scratch_pool() {
  1546. spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST })
  1547. } else {
  1548. Some(chunk)
  1549. };
  1550. match back {
  1551. None => {
  1552. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1553. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1554. }
  1555. Some(chunk) => {
  1556. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1557. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1558. freed.push(chunk);
  1559. }
  1560. }
  1561. }
  1562. }
  1563. // Freed outside the lock.
  1564. drop(freed);
  1565. }
  1566. /// What the host keeps for copies in the card's own memory
  1567. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1568. struct CardWork {
  1569. /// Before a submission's lists: what changed on the copies' CPU side
  1570. /// goes to their card side. Those not in use: a plan takes one and
  1571. /// gives it back when its submission has run (`Host::card_done`), so
  1572. /// that submissions sent ahead ([`late`]) each have their own.
  1573. sync: Vec<Prelude>,
  1574. /// After them, in the same submission: the compare of the declared
  1575. /// ranges with their bytes from before. As `sync`.
  1576. check: Vec<Prelude>,
  1577. /// After it ran: the pieces that differ come down.
  1578. fetch: Prelude,
  1579. root: ID3D12RootSignature,
  1580. pso: ID3D12PipelineState,
  1581. /// One dword per piece compared, odd where the piece differs: PC
  1582. /// memory, mapped (buffer, mapping, bytes).
  1583. differs: (ID3D12Resource, usize, u64),
  1584. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1585. fetched: Option<(ID3D12Resource, usize, u64)>,
  1586. /// The dwords of `differs` taken by plans whose results were not read
  1587. /// yet.
  1588. taken: u32,
  1589. /// Plans made and not done with (`Host::card_done`).
  1590. out: u32,
  1591. }
  1592. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1593. // under the submission lock.
  1594. unsafe impl Send for CardWork {}
  1595. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1596. /// The compare of a declared range of a copy in the card's memory with
  1597. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1598. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1599. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1600. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1601. /// byte just outside the range costs a fetch that finds nothing.
  1602. ///
  1603. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1604. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1605. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1606. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1607. /// those steps.
  1608. pub(crate) const CARD_COMPARE: &str = r#"
  1609. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1610. cbuffer Span : register(b0) {
  1611. uint first; // the first piece
  1612. uint skew; // where the copy starts in its piece 0
  1613. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1614. uint pieces;
  1615. uint out_at; // the first piece's dword in `differs`, in bytes
  1616. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1617. };
  1618. ByteAddressBuffer now : register(t0);
  1619. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1620. // last sent up (or hashed whole, the first time).
  1621. RWByteAddressBuffer hashes : register(u0);
  1622. RWByteAddressBuffer differs : register(u1);
  1623. groupshared uint4 parts[64];
  1624. [RootSignature(RS)]
  1625. [numthreads(64, 1, 1)]
  1626. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1627. uint piece = first + id.x;
  1628. uint lo = piece * 65536u;
  1629. lo = lo > skew ? lo - skew : 0u;
  1630. uint hi = min((piece + 1u) * 65536u - skew, size);
  1631. lo = lo & ~15u;
  1632. hi = (hi + 15u) & ~15u;
  1633. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1634. [loop]
  1635. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1636. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1637. h = h.yzwx ^ (h >> 15);
  1638. }
  1639. parts[thread] = h;
  1640. GroupMemoryBarrierWithGroupSync();
  1641. if (thread != 0u) return;
  1642. h = parts[0];
  1643. [loop]
  1644. for (uint i = 1u; i < 64u; ++i) {
  1645. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1646. h = h.yzwx ^ (h >> 15);
  1647. }
  1648. if (compare != 0u) {
  1649. // The flag, and above it 31 bits of the hash (`torn`).
  1650. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1651. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1652. // With the copy-back on its own thread: the next compare of the
  1653. // piece finds what is written from here on.
  1654. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1655. } else {
  1656. hashes.Store4(piece * 16u, h);
  1657. }
  1658. }
  1659. "#;
  1660. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1661. #[cfg(test)]
  1662. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1663. torn::hash(bytes)
  1664. }
  1665. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1666. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1667. /// parts a dispatch can hold.
  1668. ///
  1669. /// # Safety
  1670. /// The list is open with the compare's root signature, pipeline and buffers
  1671. /// set, and the pieces lie in the buffer.
  1672. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1673. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1674. let mut done = 0;
  1675. while done < span.pieces {
  1676. let n = (span.pieces - done).min(MOST);
  1677. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1678. // SAFETY: the caller's.
  1679. unsafe {
  1680. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1681. list.Dispatch(n, 1, 1);
  1682. }
  1683. done += n;
  1684. }
  1685. }
  1686. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1687. /// the card's memory are hashed in runs of pieces that touch, each piece
  1688. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1689. /// per range sent up.
  1690. ///
  1691. /// These passes are ours, they run on the card before every submission's
  1692. /// lists: a pass takes the time of one piece however few its pieces are.
  1693. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1694. /// a piece hashed when it need not be, or not hashed when it should, costs
  1695. /// a fetch that finds nothing and loses no shader write.
  1696. fn rehash_runs() -> bool {
  1697. static ON: OnceLock<bool> = OnceLock::new();
  1698. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1699. }
  1700. /// Since the last frame-rate line, of our own passes over copies in the
  1701. /// card's memory: hash passes after ranges were sent up, the pieces they
  1702. /// hashed, and compare passes after the lists.
  1703. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1704. /// Whether what shaders wrote to copies in the card's memory is merged
  1705. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1706. /// default). The pieces the card's compare found differing come down in
  1707. /// one fetch and were then merged one after the other on the thread that
  1708. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1709. /// with the copy's CPU side byte by byte and put into title memory through
  1710. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1711. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1712. /// landings do not come here: `crate::land` has threads of its own.)
  1713. fn wide_merge() -> bool {
  1714. static ON: OnceLock<bool> = OnceLock::new();
  1715. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1716. }
  1717. /// One declared range of a copy in the card's memory, in a submission.
  1718. struct CardRange {
  1719. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1720. /// As declared (title addresses), for the statistics.
  1721. declared: (usize, usize),
  1722. span: crate::shadow::CardSpan,
  1723. /// Its first piece's dword in the compare's results.
  1724. at: u32,
  1725. /// Whether the card compares it; else every piece is fetched.
  1726. compared: bool,
  1727. /// Looked at by `crate::picked`, and not declared: what is found changed
  1728. /// there was written through a view nobody declared. Not landed.
  1729. picked: bool,
  1730. }
  1731. impl CardPlan {
  1732. /// `crate::picked` is told where what it looked at changed, by the
  1733. /// compare's results.
  1734. fn picked_found(&self, differs: &[u32]) {
  1735. for r in self.ranges.iter().filter(|r| r.picked) {
  1736. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1737. if let Some(p) = changed {
  1738. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1739. }
  1740. }
  1741. }
  1742. }
  1743. /// What a submission does for copies in the card's memory.
  1744. struct CardPlan {
  1745. ranges: Vec<CardRange>,
  1746. /// The compare, run after the submission's lists.
  1747. check: Option<ID3D12CommandList>,
  1748. /// The copies whose card side was brought up to date, alive until the
  1749. /// submission has run.
  1750. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1751. /// The lists of ours the plan recorded (whether the compare, the
  1752. /// list), given back by `Host::card_done`.
  1753. lists: Vec<(bool, Prelude)>,
  1754. /// With [`relay`]: the number of the send to copies in the card's memory
  1755. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1756. sent_as: u64,
  1757. /// With [`upcheck`]: the look at what it sent up.
  1758. looks: Option<upcheck::Looks>,
  1759. /// With [`send`]: the memory its sends come from.
  1760. sends: Option<send::Memory>,
  1761. }
  1762. /// One piece of submission-time work, in recorded order.
  1763. enum Step {
  1764. /// A copy into title memory (destination, source, bytes): the title's
  1765. /// buffer copies, which later refreshes must see.
  1766. Copy(usize, usize, usize),
  1767. /// A copy of title memory into the list's own upload memory, and how
  1768. /// the card could bring the bytes instead.
  1769. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  1770. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1771. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1772. /// intervenes.
  1773. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1774. /// Work that may write title memory.
  1775. Run(Box<dyn Fn() + Send>),
  1776. /// Work that writes host memory only, and the title memory it reads
  1777. /// (from, to; empty for none).
  1778. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1779. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1780. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1781. /// Brings a texture's staging buffer up to date: once per submission,
  1782. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1783. Texture(std::sync::Arc<crate::texture::Staging>),
  1784. /// A title buffer copy that the list does on the card ([`place`]): what
  1785. /// is done on the CPU for it.
  1786. Placed(place::Placed),
  1787. }
  1788. /// What a list does on the CPU when it is submitted: copies between host
  1789. /// memory regions (title buffers, upload buffers and buffer copies), and
  1790. /// the upload buffers its GPU commands read, kept until the list is reset.
  1791. #[derive(Default)]
  1792. struct Deferred {
  1793. /// Destination, source, bytes.
  1794. copies: Vec<Step>,
  1795. uploads: Vec<ID3D12Resource>,
  1796. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1797. upload_bytes: u64,
  1798. /// Host objects the list's commands name (pipelines, root signatures,
  1799. /// descriptor heaps): the title may release its objects before it
  1800. /// submits the list.
  1801. kept: Vec<windows::core::IUnknown>,
  1802. /// Buffer ranges refreshed since the last title copy (host copy,
  1803. /// address, bytes): refreshing them again would find the same bytes.
  1804. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1805. /// Textures whose contents the list brings up to date.
  1806. textures: std::collections::HashSet<usize>,
  1807. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1808. /// bytes.
  1809. writes: Vec<(usize, crate::queue::Written, usize)>,
  1810. /// Textures read back (texture to buffer copies), done once the list
  1811. /// has run: the host buffer the list copies the texels into, the title
  1812. /// memory they go to, the bytes of a row, the rows, the title's row
  1813. /// pitch.
  1814. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1815. /// Whether the indirect-work budget is zeroed for this recording (a
  1816. /// step on the CPU, or in the list for the card's copy).
  1817. budget_zeroed: bool,
  1818. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1819. /// interface pointer) that a clamp in this recording left readable as
  1820. /// indirect arguments; 0 if none. It stays readable until the next
  1821. /// clamp into it ([`HostList::indirect_state`]).
  1822. indirect_readable: usize,
  1823. }
  1824. impl Deferred {
  1825. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1826. /// reset.
  1827. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1828. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1829. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1830. self.upload_bytes += size;
  1831. self.uploads.push(buffer);
  1832. }
  1833. }
  1834. impl Drop for Deferred {
  1835. fn drop(&mut self) {
  1836. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1837. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1838. }
  1839. }
  1840. /// Whether a queue's submissions go to the card without a wait for each
  1841. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1842. /// waits for every list on its own).
  1843. ///
  1844. /// Every submission was prepared, sent, waited for and copied back before
  1845. /// the next one was looked at, so the card stood idle while we prepared
  1846. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1847. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1848. /// other, on the one thread that submits.
  1849. ///
  1850. /// With the switch a queue's submission is sent and joins a line of
  1851. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1852. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1853. /// for the card, what their shaders wrote copied back once per byte, then
  1854. /// their bottom-of-pipe writes and the fence signals behind them, in
  1855. /// order) at the next point where the title, or our own preparing, can
  1856. /// observe what they do. Those points, exactly:
  1857. ///
  1858. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1859. /// read-back or map of a texture, a clear or upload run at once;
  1860. /// 2. the next submission reads title memory that a flight's shaders may
  1861. /// write: a title buffer copy, a fill of upload memory, a texture's
  1862. /// memory, any step that runs code of ours on title memory
  1863. /// ([`late_blocked`]);
  1864. /// 3. the next submission refreshes a range of a host copy that a flight's
  1865. /// shaders may write, and the title wrote a page of it since it was last
  1866. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1867. /// alone until the flight's writes are back, as it always did within a
  1868. /// submission;
  1869. /// 4. a queue stands at a wait for a memory value that no flight's
  1870. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1871. /// write ([`late_met`]);
  1872. /// 5. the title blocks on a fence without an event;
  1873. /// 6. the card has run every flight (a thread of ours waits for that:
  1874. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1875. ///
  1876. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1877. /// when the card has really run the work, later than before and never
  1878. /// earlier; a fence signalled on a queue while flights are in the air is
  1879. /// set behind them. A wait for a memory value that a flight's
  1880. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1881. /// the card behind that flight, which is the order the wait asks for.
  1882. ///
  1883. /// What it assumes beyond today: memory the title rewrites between two of
  1884. /// its submissions, without waiting for the first, may be seen by the
  1885. /// first's shaders (as on the console, where the card reads title memory
  1886. /// when it runs, not when the list is submitted).
  1887. pub(crate) fn late() -> bool {
  1888. late_stage() > 0
  1889. }
  1890. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1891. fn late_stage() -> u8 {
  1892. static STAGE: OnceLock<u8> = OnceLock::new();
  1893. *STAGE.get_or_init(|| {
  1894. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1895. return 0;
  1896. }
  1897. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1898. Ok("1") => 1,
  1899. Ok("2") => 2,
  1900. Ok("3") => 3,
  1901. // The relay alone: on top of stage 3.
  1902. Err(_) if crate::shadow::relay() => 3,
  1903. _ => 0,
  1904. }
  1905. })
  1906. }
  1907. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1908. /// longer a point. Where the title wrote a page that lies in a range a
  1909. /// flight's shaders may write, the bytes the title changed are found (the
  1910. /// page as it is now against what the copy held when the flight was
  1911. /// prepared) and put into the copy, and only those: what the flight's
  1912. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1913. /// flights are settled for it only where that cannot be done: memory that
  1914. /// is not write-watched, or a copy in the card's memory with more changed
  1915. /// runs than a submission should send up one by one.
  1916. ///
  1917. /// In run 92 (stage 1) this point settled the flights five times a frame
  1918. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1919. /// frame of waiting were left of 200.
  1920. ///
  1921. /// What differs from settling first: a byte both the title and a flight's
  1922. /// shader wrote is the title's if the shader wrote it first, the shader's
  1923. /// if it wrote it afterwards; settled first it was always the shader's.
  1924. /// The title writing a byte a shader of its own is writing is a race on
  1925. /// the console too.
  1926. fn late_exact() -> bool {
  1927. late_stage() > 1
  1928. }
  1929. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1930. /// no longer a point where flights are settled). The copy to the back
  1931. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1932. /// its own for each present in the air) and the swap chain is told to
  1933. /// present behind it; the queue's call returns, and the card finishes the
  1934. /// frame while the title records the next one. What the title is told
  1935. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1936. /// has run it, by the settling thread.
  1937. ///
  1938. /// What is left out with it: the look whether the presented frame is black
  1939. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1940. /// or listed is presented the old way. Once every second and a half a
  1941. /// submission settles the flights all the same, for the sweep that lets
  1942. /// idle host objects go (it needs nothing in the air).
  1943. pub(crate) fn late_free_present() -> bool {
  1944. late_stage() > 2
  1945. }
  1946. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1947. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1948. /// and is off with it, in the timing run and with kept snapshots).
  1949. ///
  1950. /// With [`late`] alone every settle does three things on the thread that
  1951. /// holds the submission lock: it waits for everything in the air, copies
  1952. /// back with the card standing, and only then goes on preparing. The frame
  1953. /// stays a relay: the card works about 242 ms of it and one thread
  1954. /// prepares, waits and copies back for about 220.
  1955. ///
  1956. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1957. /// soon as the card has run them, in the order they were sent and without
  1958. /// the submission lock: it fetches and merges what their shaders wrote to
  1959. /// copies in the card's memory, compares and merges the other copies,
  1960. /// frees the flights' ranges, and then does their read-backs, their
  1961. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1962. /// order. The submitting thread meanwhile prepares and sends the next
  1963. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  1964. /// that thread has landed everything in the air, at the same points as
  1965. /// before (the list in [`late`]), so whoever can observe title memory, a
  1966. /// fence or a present still does so only after the flights before it are
  1967. /// merged.
  1968. ///
  1969. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  1970. /// flight; a merge that never stores into memory the card may be writing;
  1971. /// sends to card copies numbered) and here: flights land in the order of
  1972. /// [`LINE`] by one thread, so a later flight's results never reach title
  1973. /// memory before an earlier flight's; the compare on the card stores the
  1974. /// hash it made, so each flight's compare flags exactly what changed since
  1975. /// the compare before it, however late the pieces are fetched; the fetch
  1976. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  1977. /// title bytes the card had received when it ran.
  1978. pub(crate) fn relay() -> bool {
  1979. static ON: OnceLock<bool> = OnceLock::new();
  1980. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  1981. }
  1982. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  1983. /// title memory a flight's shaders may write (a title buffer copy, a fill
  1984. /// of upload memory, a texture) waits only until the flights that declared
  1985. /// that memory have landed, not for everything in the air; and at
  1986. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  1987. /// both wait for everything.
  1988. fn relay_exact() -> bool {
  1989. static ON: OnceLock<bool> = OnceLock::new();
  1990. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  1991. // since the walls of the first room were found drawn in every run with
  1992. // this set and in fewer than half without it).
  1993. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  1994. }
  1995. /// Whether the pieces the relay fetches from the card's memory come over the
  1996. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  1997. /// draws.
  1998. ///
  1999. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  2000. /// and with the relay that is most of a frame: the thread that lands flights
  2001. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  2002. /// a few milliseconds of copying, and everything that waits for a landing
  2003. /// (the title's fences, reads of memory flights may write) waited with it.
  2004. ///
  2005. /// What changes: the fetch runs when its flights are done and beside later
  2006. /// submissions, so of the sends of title bytes it is only known to have run
  2007. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  2008. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  2009. /// the title's, newer than what the flights wrote. A later flight's bytes
  2010. /// may be in what is fetched, as before.
  2011. fn relay_copy() -> bool {
  2012. static ON: OnceLock<bool> = OnceLock::new();
  2013. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  2014. }
  2015. /// Told when something joins [`LINE`], for the thread that lands flights
  2016. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  2017. /// what queues hold.
  2018. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2019. /// Told when flights have landed ([`relay`]): who waits for that looks
  2020. /// again.
  2021. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  2022. /// With [`relay`], the order of what we put on the queue: the number of
  2023. /// sends of changed ranges to copies in the card's memory so far
  2024. /// (`Host::card_before`). Held from the taking of the ranges until their
  2025. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  2026. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  2027. /// later one.
  2028. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  2029. /// Since the last frame-rate line, of the thread that lands flights
  2030. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  2031. /// card with nothing to land, microseconds it waited for fetches of card
  2032. /// copies' pieces, microseconds of landing in all.
  2033. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  2034. /// Of the line's things in order (a flight: the value signalled on the
  2035. /// host's fence behind it; a write or a signal behind a flight: `None`):
  2036. /// how many, from the front, can be landed when the card has reached
  2037. /// `completed`: everything ahead of the first flight it has not run. A
  2038. /// later flight never lands before an earlier one, and what follows a
  2039. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  2040. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  2041. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  2042. }
  2043. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  2044. /// holds, for every piece of every range of the plan, the copy, the
  2045. /// piece's number in the copy and whether the compare flagged it there (or
  2046. /// did not run). The pieces to fetch, under whichever range, in order: all
  2047. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  2048. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  2049. /// the hash, so the second of them may find it stored already and not
  2050. /// flag it.
  2051. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  2052. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  2053. pieces.sort_unstable();
  2054. pieces.dedup();
  2055. pieces
  2056. }
  2057. #[cfg(test)]
  2058. mod relay_tests {
  2059. use super::{flagged_pieces, landable};
  2060. /// Two flights and what follows each: nothing of the second lands
  2061. /// before the card has run it, and nothing behind a flight lands
  2062. /// before the flight.
  2063. #[test]
  2064. fn flights_land_in_the_order_they_were_sent() {
  2065. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  2066. let line = [Some(5), None, None, Some(6), None];
  2067. assert_eq!(landable(&line, 4), 0);
  2068. assert_eq!(landable(&line, 5), 3);
  2069. assert_eq!(landable(&line, 6), 5);
  2070. assert_eq!(landable(&line, u64::MAX), 5);
  2071. // Signals with no flight ahead land at once; behind one they wait.
  2072. assert_eq!(landable(&[None, None], 0), 2);
  2073. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  2074. assert_eq!(landable(&[], 3), 0);
  2075. // After the first three landed, the rest when its turn comes.
  2076. assert_eq!(landable(&line[3..], 5), 0);
  2077. assert_eq!(landable(&line[3..], 6), 2);
  2078. }
  2079. /// A piece flagged under one range of a plan is fetched under every
  2080. /// range that holds a part of it; pieces of other copies are not.
  2081. #[test]
  2082. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  2083. let (a, b) = (0x1000usize, 0x2000usize);
  2084. // Copy a: piece 3 under two ranges, flagged under the first only;
  2085. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  2086. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  2087. let fetch = flagged_pieces(&flags);
  2088. assert!(fetch.contains(&(a, 3)));
  2089. assert!(!fetch.contains(&(a, 4)));
  2090. assert!(!fetch.contains(&(b, 3)));
  2091. assert!(fetch.contains(&(b, 9)));
  2092. assert_eq!(fetch.len(), 2);
  2093. }
  2094. }
  2095. /// The most host lists in the air before the flights are settled
  2096. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  2097. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  2098. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  2099. /// 32 settled the flights three times a
  2100. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  2101. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  2102. /// descriptor slots, upload
  2103. /// memory and scratch chunks are held until then, and a frame's lists held
  2104. /// all at once ran the slots out before (run 45).
  2105. fn late_most() -> usize {
  2106. static MOST: OnceLock<usize> = OnceLock::new();
  2107. *MOST.get_or_init(|| {
  2108. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  2109. })
  2110. }
  2111. /// Whether a submission with bottom-of-pipe writes may fly
  2112. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  2113. /// the title is told at once, as before; for telling a title that polls
  2114. /// such a value from one that does not).
  2115. fn late_writes() -> bool {
  2116. static ON: OnceLock<bool> = OnceLock::new();
  2117. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  2118. }
  2119. /// Per host copy, the ranges a submission's shaders may write, as declared
  2120. /// (address, end).
  2121. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  2122. /// What [`Host::submit`] hands back for a submission it sent and did not
  2123. /// wait for.
  2124. struct Sent {
  2125. /// Its number among the submissions started.
  2126. number: u64,
  2127. card: Option<CardPlan>,
  2128. back: Vec<Declared>,
  2129. /// What was taken off it to be done on the card.
  2130. own: Option<card_steps::Taken>,
  2131. /// Its bottom-of-pipe writes.
  2132. writes: Vec<(usize, crate::queue::Written, usize)>,
  2133. }
  2134. /// A submission on the card that has not been waited for ([`late`]): its
  2135. /// host lists, taken from the title's (which it may reset meanwhile), and
  2136. /// what is to be done once it has run.
  2137. struct Flight {
  2138. number: u64,
  2139. /// The value signalled on the host's fence behind it.
  2140. fence: u64,
  2141. lists: Vec<crate::list::Detached>,
  2142. order: Vec<usize>,
  2143. card: Option<CardPlan>,
  2144. back: Vec<Declared>,
  2145. /// The list of ours that ran ahead of them ([`card_steps`]).
  2146. own: Option<card_steps::Taken>,
  2147. }
  2148. /// One thing in the line of what waits for the card, in order.
  2149. enum Late {
  2150. Run(Flight),
  2151. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  2152. Write(usize, crate::queue::Written, usize),
  2153. /// A fence (its address) signalled behind the flights before it.
  2154. Signal(usize, u64),
  2155. }
  2156. struct Line {
  2157. line: Vec<Late>,
  2158. /// The title memory the flights' shaders may write (address, end), in
  2159. /// order and joined.
  2160. written: Vec<(usize, usize)>,
  2161. /// Host lists in the flights.
  2162. lists: usize,
  2163. /// The value signalled on the host's fence behind the last flight.
  2164. target: u64,
  2165. /// A settle has taken the line and is not done: a signal still goes
  2166. /// behind it.
  2167. settling: bool,
  2168. /// Something was settled away from a queue's own calls: the helper
  2169. /// thread looks at what queues hold.
  2170. poke: bool,
  2171. /// Host lists of settled flights, reset and given back outside the
  2172. /// submission lock ([`land`]: a settle may run under a caller's own
  2173. /// locks).
  2174. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2175. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2176. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2177. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2178. /// With [`card_steps`]: what the flights being landed write.
  2179. landing: Vec<card_steps::Writer>,
  2180. }
  2181. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2182. // into; touched under the lock.
  2183. unsafe impl Send for Line {}
  2184. static LINE: Mutex<Line> = Mutex::new(Line {
  2185. line: Vec::new(),
  2186. written: Vec::new(),
  2187. lists: 0,
  2188. target: 0,
  2189. settling: false,
  2190. poke: false,
  2191. landed: Vec::new(),
  2192. in_hand: Vec::new(),
  2193. landing: Vec::new(),
  2194. });
  2195. /// Told when a flight joins [`LINE`] or it is poked.
  2196. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2197. fn line() -> std::sync::MutexGuard<'static, Line> {
  2198. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2199. }
  2200. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2201. const WHY_SYNC: usize = 2;
  2202. const WHY_CARD_DONE: usize = 3;
  2203. const WHY_VALUE: usize = 4;
  2204. const WHY_STALE: usize = 5;
  2205. const WHY_READ: usize = 6;
  2206. const WHY_RUN: usize = 7;
  2207. const WHY_MOST: usize = 8;
  2208. const WHY_WRITES: usize = 9;
  2209. const WHY_FENCE: usize = 10;
  2210. /// Since the last frame-rate line: submissions sent without a wait;
  2211. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2212. /// microseconds settles waited for the card; value waits met by a flight's
  2213. /// bottom-of-pipe write; fence signals set behind flights.
  2214. /// Then: the settles for title memory read, by what read it (a buffer
  2215. /// copy, a fill of upload memory, a texture).
  2216. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2217. /// Since the last frame-rate line: the microseconds settles waited for the
  2218. /// card, by why they settled (the `WHY_` places).
  2219. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2220. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2221. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2222. if from >= to {
  2223. return false;
  2224. }
  2225. let at = ranges.partition_point(|r| r.1 <= from);
  2226. ranges.get(at).is_some_and(|r| r.0 < to)
  2227. }
  2228. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2229. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2230. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2231. ranges.sort_unstable();
  2232. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2233. for &(from, to) in ranges.iter() {
  2234. match out.last_mut() {
  2235. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2236. _ => out.push((from, to)),
  2237. }
  2238. }
  2239. *ranges = out;
  2240. }
  2241. /// Whether anything is in the air.
  2242. fn flying() -> bool {
  2243. if !late() {
  2244. return false;
  2245. }
  2246. let line = line();
  2247. // (With the relay: also while flights are being landed.)
  2248. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2249. }
  2250. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2251. /// before they are settled, if so. Preparing reads title memory on the
  2252. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2253. /// runs steps of ours that may read or write it anywhere; what the
  2254. /// flights' shaders write is not there yet.
  2255. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2256. let (written, copies) = {
  2257. let line = line();
  2258. if line.written.is_empty() {
  2259. return None;
  2260. }
  2261. (line.written.clone(), card_steps::copies(&line))
  2262. };
  2263. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2264. }
  2265. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2266. /// flights when the title itself wrote the memory since they were given it
  2267. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2268. ///
  2269. /// The title's 174 MB heap is declared written as a whole (a root view has
  2270. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2271. /// bytes a frame, at a new place each time, waited for every flight's
  2272. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2273. /// named). The title writes those bytes just before the draw that reads
  2274. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2275. ///
  2276. /// Or no shader's write went into that page in the last 600 frames
  2277. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2278. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2279. /// before the page was taken.
  2280. ///
  2281. /// What can go wrong: a constant a flight's shader really writes, in a
  2282. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2283. /// for the first time, is read as it was before that flight.
  2284. fn fill_is_titles(src: usize, len: usize) -> bool {
  2285. const SMALL: usize = 64 << 10;
  2286. static ON: OnceLock<bool> = OnceLock::new();
  2287. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2288. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2289. }
  2290. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2291. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2292. /// in (start, bytes).
  2293. #[cfg(feature = "diagnostics")]
  2294. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2295. /// How often and how long, and the address the last one read.
  2296. #[cfg(feature = "diagnostics")]
  2297. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2298. /// What the wait that comes next is for, and why not on the card.
  2299. #[cfg(feature = "diagnostics")]
  2300. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2301. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2302. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2303. /// shaders.
  2304. #[cfg(feature = "diagnostics")]
  2305. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2306. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2307. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2308. /// raw address (1).
  2309. #[cfg(feature = "diagnostics")]
  2310. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2311. if len < 1 << 20 {
  2312. return;
  2313. }
  2314. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2315. let e = all
  2316. .get_or_insert_with(Default::default)
  2317. .entry((address as usize, (address + len) as usize, pipeline))
  2318. .or_insert_with(|| {
  2319. let shaders = match pipeline {
  2320. 0 => "a view in a table".into(),
  2321. 1 => "a raw address".into(),
  2322. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2323. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2324. }),
  2325. };
  2326. (0, shaders)
  2327. });
  2328. e.0 += 1;
  2329. }
  2330. #[cfg(feature = "diagnostics")]
  2331. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2332. let i = written.partition_point(|r| r.1 <= at);
  2333. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2334. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2335. let why = blamed.1;
  2336. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2337. }
  2338. /// Why [`card_steps`] left the submission to the wait that comes next.
  2339. #[cfg(feature = "diagnostics")]
  2340. fn refused(why: &'static str) {
  2341. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2342. }
  2343. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2344. #[cfg(feature = "diagnostics")]
  2345. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2346. if let Some((shadow, from, _)) = stale.first() {
  2347. let (start, len) = shadow.span();
  2348. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2349. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2350. }
  2351. }
  2352. /// The wait for what [`blame`] last named, or a wait of another reason than
  2353. /// title memory read, took `us`.
  2354. #[cfg(feature = "diagnostics")]
  2355. fn blamed(why: usize, us: u64) {
  2356. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2357. let (key, at) = match (why, named) {
  2358. (WHY_READ | WHY_STALE, Some(named)) => named,
  2359. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2360. _ => {
  2361. let kind = match why {
  2362. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2363. WHY_VALUE => "a memory value",
  2364. WHY_STALE => "title memory changed under shader writes",
  2365. WHY_RUN => "a step of ours",
  2366. WHY_MOST => "lists in the air",
  2367. WHY_FENCE => "a blocking fence wait",
  2368. _ => "another reason",
  2369. };
  2370. ((kind, "", 0, 0, 0), 0)
  2371. }
  2372. };
  2373. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2374. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2375. *e = (e.0 + 1, e.1 + us, at);
  2376. }
  2377. /// For the frame-rate line: the five that waited longest.
  2378. #[cfg(feature = "diagnostics")]
  2379. fn log_blame(frames: f64) {
  2380. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2381. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2382. let mut all: Vec<_> = all.into_iter().collect();
  2383. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2384. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2385. // The passes that declare it written, the ones that do so most.
  2386. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2387. for ((a, b, _), (n, shaders)) in &wide {
  2388. if *a < at + len && at < *b {
  2389. *passes.entry(shaders).or_default() += n;
  2390. }
  2391. }
  2392. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2393. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2394. let passes: Vec<String> =
  2395. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2396. tracing::info!(
  2397. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2398. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2399. us as f64 / 1e3 / frames,
  2400. n as f64 / frames,
  2401. passes.join(", "),
  2402. match (why.is_empty(), kind) {
  2403. (true, _) => "",
  2404. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2405. _ => "; not done on the card: ",
  2406. },
  2407. );
  2408. }
  2409. }
  2410. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2411. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2412. touches(written, src, src + len) && !fill_is_titles(src, len)
  2413. }
  2414. /// Whether they stop a title buffer copy, and if so whether by its source.
  2415. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2416. let read = read_blocked(written, src, len);
  2417. (read || touches(written, dst, dst + len)).then_some(read)
  2418. }
  2419. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2420. /// may write (in order, joined); `count` whether the kind of read is
  2421. /// counted for the frame line.
  2422. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2423. if written.is_empty() {
  2424. return None;
  2425. }
  2426. // Destinations of copies at their place, if a step reads them.
  2427. let mut placed: Vec<(usize, usize)> = Vec::new();
  2428. for list in runs {
  2429. for step in &list.deferred().copies {
  2430. match step {
  2431. &Step::Copy(dst, src, len) => {
  2432. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2433. if count {
  2434. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2435. #[cfg(feature = "diagnostics")]
  2436. if _read {
  2437. blame("a buffer copy's source", written, src, len);
  2438. } else {
  2439. blame("a buffer copy's destination", written, dst, len);
  2440. }
  2441. }
  2442. return Some(WHY_READ);
  2443. }
  2444. }
  2445. &Step::Fill(_, src, len, _) => {
  2446. if read_blocked(written, src, len) {
  2447. if count {
  2448. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2449. #[cfg(feature = "diagnostics")]
  2450. blame("a fill of upload memory", written, src, len);
  2451. }
  2452. return Some(WHY_READ);
  2453. }
  2454. }
  2455. Step::Texture(staging) => {
  2456. let (at, len) = staging.memory();
  2457. if touches(written, at, at + len) {
  2458. if count {
  2459. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2460. #[cfg(feature = "diagnostics")]
  2461. blame("a texture", written, at, len);
  2462. }
  2463. return Some(WHY_READ);
  2464. }
  2465. }
  2466. Step::Run(_) => return Some(WHY_RUN),
  2467. Step::Placed(p) => match p.waits(written) {
  2468. place::Waits::No => {}
  2469. place::Waits::ForReaders => placed.push((p.dst, p.dst + p.len)),
  2470. place::Waits::Yes => {
  2471. if count {
  2472. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2473. #[cfg(feature = "diagnostics")]
  2474. blame("a buffer copy at its place", written, p.src, p.len);
  2475. }
  2476. return Some(WHY_READ);
  2477. }
  2478. },
  2479. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2480. }
  2481. }
  2482. }
  2483. (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ)
  2484. }
  2485. /// With flights in the air, after the submission's write-watch asking:
  2486. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2487. /// may write and that the title wrote since it was last copied. The
  2488. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2489. /// the title's bytes there would reach the card a submission late.
  2490. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2491. use std::sync::Arc;
  2492. // Per copy, the span of what is refreshed (a flush brings that much
  2493. // up to date at most).
  2494. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2495. // Where each copy is in it, if shaders may be writing it (none begins to
  2496. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2497. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2498. for list in runs {
  2499. for step in &list.deferred().copies {
  2500. if let Step::Refresh(shadow, address, len) = step {
  2501. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2502. shadow.writes_pending().then(|| {
  2503. spans.push((shadow.clone(), *address, *address + *len));
  2504. spans.len() - 1
  2505. })
  2506. });
  2507. if let Some(i) = *place {
  2508. let s = &mut spans[i];
  2509. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2510. }
  2511. }
  2512. }
  2513. }
  2514. if late_exact() {
  2515. // The title's bytes are put in beside the flights' writes; a
  2516. // settle is still due where that could not be done. At most this
  2517. // many changed runs go up to copies in the card's memory, each a
  2518. // copy of its own there. With [`card_steps`] the pages of the
  2519. // title's ring of constants come here too, which were waited for
  2520. // before: hundreds of short runs each, at about 1.5 us a run.
  2521. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2522. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2523. return spans;
  2524. }
  2525. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2526. spans
  2527. }
  2528. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2529. /// air, if there are any, and is set when they are settled. Whether it
  2530. /// did; if not the caller sets the fence now.
  2531. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2532. if !late() {
  2533. return false;
  2534. }
  2535. let mut line = line();
  2536. if line.line.is_empty() && !line.settling {
  2537. return false;
  2538. }
  2539. line.line.push(Late::Signal(fence, value));
  2540. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2541. drop(line);
  2542. // A signal alone (behind a settle under way) has no flight to wake
  2543. // the helper thread for it.
  2544. LINE_MOVED.notify_one();
  2545. RELAY_MOVED.notify_one();
  2546. true
  2547. }
  2548. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2549. /// whether it is met once the flights in the air have run. A flight's
  2550. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2551. /// for the card: the part behind the wait goes to the card behind that
  2552. /// flight, which is the order the wait asks for. If the flights may write
  2553. /// the value in a way not known here (shaders, a timestamp, another
  2554. /// width), they are settled and memory is asked again.
  2555. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2556. let (address, bytes) = wait.place();
  2557. {
  2558. let line = line();
  2559. if line.line.is_empty() && line.in_hand.is_empty() {
  2560. return false;
  2561. }
  2562. let mut unsure = touches(&line.written, address, address + bytes);
  2563. // (With the relay: first the writes of flights being landed.)
  2564. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2565. Late::Write(at, what, n) => Some((at, what, n)),
  2566. _ => None,
  2567. }));
  2568. for (at, what, n) in writes {
  2569. if *at >= address + bytes || address >= *at + *n {
  2570. continue;
  2571. }
  2572. match what {
  2573. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2574. if wait.holds_for(*v) {
  2575. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2576. return true;
  2577. }
  2578. }
  2579. _ => unsure = true,
  2580. }
  2581. }
  2582. if !unsure {
  2583. return false;
  2584. }
  2585. }
  2586. settle_now(WHY_VALUE);
  2587. wait.met()
  2588. }
  2589. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2590. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2591. pub(crate) fn settle_now(why: usize) {
  2592. if !late() {
  2593. return;
  2594. }
  2595. let Some(host) = host() else {
  2596. return;
  2597. };
  2598. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2599. host.settle(&mut submitted, why);
  2600. }
  2601. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2602. pub(crate) fn settle_for_present() {
  2603. settle_now(WHY_SYNC);
  2604. }
  2605. pub(crate) fn settle_for_fence() {
  2606. settle_now(WHY_FENCE);
  2607. }
  2608. /// Resets the host lists of settled flights and keeps them for reuse, as
  2609. /// a queue does for the lists it ran (`crate::list::recycle`).
  2610. fn land() {
  2611. let landed = std::mem::take(&mut line().landed);
  2612. for (lists, order) in landed {
  2613. crate::list::recycle(lists, &order);
  2614. }
  2615. }
  2616. /// The thread that settles the flights once the card has run them all
  2617. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2618. /// at the next call that settles, and a title thread that polls such a
  2619. /// value while the submitting thread waits for that thread would never
  2620. /// see it.
  2621. fn late_helper() {
  2622. let Some(host) = host() else {
  2623. return;
  2624. };
  2625. // SAFETY: a plain event of our own.
  2626. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2627. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2628. return;
  2629. };
  2630. loop {
  2631. let target = {
  2632. let mut line = line();
  2633. loop {
  2634. if line.poke {
  2635. line.poke = false;
  2636. break None;
  2637. }
  2638. // (With the relay the flights are another thread's.)
  2639. if !relay() && !line.line.is_empty() && !line.settling {
  2640. break Some(line.target);
  2641. }
  2642. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2643. }
  2644. };
  2645. let Some(target) = target else {
  2646. land();
  2647. crate::queue::release_held(false);
  2648. continue;
  2649. };
  2650. // The card first, without the submission lock: the submitting
  2651. // thread prepares and sends meanwhile.
  2652. // SAFETY: our fence and event.
  2653. unsafe {
  2654. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2655. WaitForSingleObject(event, INFINITE);
  2656. }
  2657. }
  2658. {
  2659. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2660. // Something newer went up meanwhile: the card is waited for
  2661. // again, the submitting thread is not held up for it.
  2662. if line().target != target {
  2663. continue;
  2664. }
  2665. host.settle(&mut submitted, WHY_CARD_DONE);
  2666. }
  2667. land();
  2668. crate::queue::release_held(false);
  2669. }
  2670. }
  2671. /// Starts the threads of [`late`], once: the one that settles flights when
  2672. /// the card has run them and looks at what queues hold, and with [`relay`]
  2673. /// the one that lands flights.
  2674. fn late_threads() {
  2675. static HELPER: std::sync::Once = std::sync::Once::new();
  2676. HELPER.call_once(|| {
  2677. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2678. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2679. }
  2680. tracing::info!(
  2681. most = late_most(),
  2682. writes = late_writes(),
  2683. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2684. );
  2685. if relay() {
  2686. // Without it nothing would ever land.
  2687. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2688. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2689. }
  2690. tracing::info!(
  2691. exact = relay_exact(),
  2692. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2693. );
  2694. }
  2695. });
  2696. }
  2697. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2698. /// time flights have landed. Counted as a settle for `why`, and its time
  2699. /// as waiting for the card. The caller may hold the submission lock: the
  2700. /// thread that lands flights never takes it.
  2701. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2702. let mut line = line();
  2703. if done(&line) {
  2704. return;
  2705. }
  2706. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2707. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2708. let was_working = working(false);
  2709. let waiting = std::time::Instant::now();
  2710. while !done(&line) {
  2711. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2712. }
  2713. drop(line);
  2714. stood(waiting);
  2715. working(was_working);
  2716. let us = waiting.elapsed().as_micros() as u64;
  2717. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2718. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2719. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2720. #[cfg(feature = "diagnostics")]
  2721. blamed(why, us);
  2722. }
  2723. /// What the thread that lands flights fetches card copies' pieces with
  2724. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2725. /// behind the submission lock), and the memory the pieces come down to.
  2726. struct RelayFetch {
  2727. list: Prelude,
  2728. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2729. queue: Option<ID3D12CommandQueue>,
  2730. fence: ID3D12Fence,
  2731. event: HANDLE,
  2732. /// The last value signalled on `fence`.
  2733. sent: u64,
  2734. /// Buffer, mapping, bytes.
  2735. buffer: Option<(ID3D12Resource, usize, u64)>,
  2736. /// Pieces caught while a later flight was writing them.
  2737. suspects: torn::Suspects,
  2738. /// What earlier fetches brought of flights not landed yet.
  2739. had: crate::land::Had,
  2740. }
  2741. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2742. /// the first flights of the line it takes them, with what follows them,
  2743. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2744. /// the card, or for a flight. It takes neither the submission lock nor
  2745. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2746. /// lists and looking at what queues hold are left to [`late_helper`].
  2747. fn relay_worker() {
  2748. let Some(host) = host() else {
  2749. return;
  2750. };
  2751. // SAFETY: a plain event of our own.
  2752. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2753. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2754. };
  2755. let mut fetch: Option<RelayFetch> = None;
  2756. loop {
  2757. let next = {
  2758. let mut line = line();
  2759. loop {
  2760. if line.line.is_empty() {
  2761. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2762. continue;
  2763. }
  2764. let fences: Vec<Option<u64>> = line
  2765. .line
  2766. .iter()
  2767. .map(|l| match l {
  2768. Late::Run(flight) => Some(flight.fence),
  2769. _ => None,
  2770. })
  2771. .collect();
  2772. // SAFETY: a plain query.
  2773. let completed = unsafe { host.fence.GetCompletedValue() };
  2774. let n = landable(&fences, completed);
  2775. if n == 0 {
  2776. // The first thing is a flight the card has not run.
  2777. break Err(fences[0].unwrap_or(0));
  2778. }
  2779. line.settling = true;
  2780. let items: Vec<Late> = line.line.drain(..n).collect();
  2781. line.in_hand = items
  2782. .iter()
  2783. .filter_map(|l| match l {
  2784. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2785. _ => None,
  2786. })
  2787. .collect();
  2788. if card_steps::stage() > 0 {
  2789. line.landing = card_steps::writers(&items);
  2790. }
  2791. break Ok(items);
  2792. }
  2793. };
  2794. match next {
  2795. Ok(items) => host.relay_land(items, &mut fetch),
  2796. Err(target) => {
  2797. let waiting = std::time::Instant::now();
  2798. // SAFETY: the host's fence and this thread's event.
  2799. let waited = unsafe {
  2800. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2801. WaitForSingleObject(event, INFINITE);
  2802. })
  2803. };
  2804. if waited.is_err() {
  2805. std::thread::sleep(std::time::Duration::from_millis(1));
  2806. }
  2807. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2808. }
  2809. }
  2810. }
  2811. }
  2812. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2813. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2814. /// once, the pieces that differ found on several threads; but the merge is
  2815. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2816. /// are not done with here (each flight's are, afterwards). In two steps:
  2817. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  2818. /// which needs nothing that the fetch from the card's memory brings), and
  2819. /// the merge.
  2820. struct RelayBack {
  2821. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  2822. found: Option<Vec<Vec<(usize, usize)>>>,
  2823. }
  2824. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  2825. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2826. for (shadow, declared) in back {
  2827. if shadow.carded() {
  2828. continue;
  2829. }
  2830. let mut spans: Vec<(usize, usize)> = Vec::new();
  2831. join_ranges(&mut spans, declared.iter().copied());
  2832. for &(from, to) in &spans {
  2833. shadow.relay_compared(from, to - from);
  2834. }
  2835. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2836. }
  2837. RelayBack { work, found: None }
  2838. }
  2839. impl RelayBack {
  2840. /// Looks the ranges through, once; its time counts as `stat`.
  2841. fn look(&mut self, stat: usize) {
  2842. if self.work.is_empty() || self.found.is_some() {
  2843. return;
  2844. }
  2845. let scanning = std::time::Instant::now();
  2846. // Looked through without a lock: a piece that changes meanwhile (a
  2847. // later flight writing, the title's bytes going in) is found now or
  2848. // by that flight's landing, and the merge looks again under the
  2849. // lock.
  2850. self.found = Some(crate::shadow::find_all(&self.work));
  2851. crate::land::spent(stat, scanning);
  2852. #[cfg(feature = "diagnostics")]
  2853. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2854. }
  2855. /// What differs goes into title memory.
  2856. fn merge(mut self) {
  2857. use crate::land;
  2858. self.look(land::stat::SCAN);
  2859. let Some(found) = self.found else {
  2860. return;
  2861. };
  2862. let merging = std::time::Instant::now();
  2863. let mut written: Vec<u64> = Vec::new();
  2864. if land::on() {
  2865. // Pieces in the same block of title memory in one job, in order.
  2866. let pieces: Vec<(usize, usize, usize)> =
  2867. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  2868. let start = |i: usize| self.work[i].0.span().0 as usize;
  2869. let mut order: Vec<usize> = (0..pieces.len()).collect();
  2870. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  2871. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  2872. let jobs = land::jobs(&cut);
  2873. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  2874. land::each(jobs.len(), &|j| {
  2875. let working = std::time::Instant::now();
  2876. let mut notes = land::Notes::default();
  2877. for &p in &order[jobs[j].clone()] {
  2878. let (i, at, n) = pieces[p];
  2879. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  2880. }
  2881. notes.flush();
  2882. land::spent(land::stat::BACK_ALL, working);
  2883. });
  2884. land::count(land::stat::JOBS, jobs.len() as u64);
  2885. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  2886. } else {
  2887. let (mut now, mut title) = (Vec::new(), Vec::new());
  2888. for ((shadow, ..), found) in self.work.iter().zip(found) {
  2889. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  2890. written.push(found.into_iter().map(merge).sum());
  2891. }
  2892. }
  2893. land::spent(land::stat::BACK, merging);
  2894. for ((_, from, to), written) in self.work.iter().zip(written) {
  2895. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  2896. #[cfg(feature = "diagnostics")]
  2897. crate::copystat::compared(*from, to - from, written as usize);
  2898. let _ = (from, to);
  2899. }
  2900. }
  2901. }
  2902. /// For the frame-rate line, with [`late`]: what the line of flights did
  2903. /// per frame since the last one.
  2904. fn late_line(frames: f64) {
  2905. if !late() {
  2906. return;
  2907. }
  2908. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2909. tracing::info!(
  2910. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2911. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2912. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2913. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2914. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2915. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2916. s[0],
  2917. s[1],
  2918. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2919. s[12] / 1000.0,
  2920. s[WHY_SYNC],
  2921. s[WHY_CARD_DONE],
  2922. s[WHY_VALUE],
  2923. s[WHY_STALE],
  2924. s[WHY_READ],
  2925. s[15],
  2926. s[16],
  2927. s[17],
  2928. s[WHY_RUN],
  2929. late_most(),
  2930. s[WHY_MOST],
  2931. s[WHY_WRITES],
  2932. s[WHY_FENCE],
  2933. s[13],
  2934. s[14],
  2935. );
  2936. {
  2937. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2938. tracing::info!(
  2939. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2940. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2941. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2942. w[WHY_SYNC],
  2943. w[WHY_CARD_DONE],
  2944. w[WHY_VALUE],
  2945. w[WHY_STALE],
  2946. w[WHY_READ],
  2947. w[WHY_RUN],
  2948. w[WHY_MOST],
  2949. w[WHY_WRITES],
  2950. w[WHY_FENCE],
  2951. );
  2952. }
  2953. if relay() {
  2954. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2955. tracing::info!(
  2956. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2957. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2958. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2959. \"settles\" above are waits of other threads for it)",
  2960. r[1],
  2961. r[0],
  2962. r[2] / 1000.0,
  2963. r[3] / 1000.0,
  2964. r[4] / 1000.0,
  2965. );
  2966. if send::own() {
  2967. let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2968. tracing::info!(
  2969. "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
  2970. taking them out of the CPU sides",
  2971. t[0] / (1 << 20) as f64,
  2972. t[1],
  2973. t[2],
  2974. t[3] / 1000.0,
  2975. );
  2976. }
  2977. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2978. if t[0] > 0.0 {
  2979. tracing::info!(
  2980. "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",
  2981. t[0],
  2982. t[1],
  2983. t[2],
  2984. );
  2985. }
  2986. }
  2987. crate::land::log(frames);
  2988. if place::on() {
  2989. let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2990. tracing::info!(
  2991. "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",
  2992. t[0],
  2993. t[1] / 1024.0,
  2994. t[2],
  2995. t[3],
  2996. );
  2997. }
  2998. card_steps::log(frames);
  2999. crate::picked::log(frames);
  3000. #[cfg(feature = "diagnostics")]
  3001. log_blame(frames);
  3002. if late_exact() {
  3003. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  3004. tracing::info!(
  3005. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  3006. {runs:.0} changed runs, {:.2} MB",
  3007. bytes / (1 << 20) as f64
  3008. );
  3009. }
  3010. }
  3011. mod card_steps;
  3012. pub(crate) mod indirects;
  3013. mod place;
  3014. mod send;
  3015. mod torn;
  3016. pub(crate) mod upcheck;
  3017. #[cfg(test)]
  3018. mod late_tests {
  3019. use super::{continues, join_ranges, touches};
  3020. /// Copies join only when both ends continue and the whole does not
  3021. /// overlap itself.
  3022. #[test]
  3023. fn copies_join_only_end_to_end_and_apart() {
  3024. // (destination, source, bytes)
  3025. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  3026. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  3027. // A gap, or only one side continues.
  3028. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  3029. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  3030. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  3031. // Together they would overlap: the second reads what the first wrote.
  3032. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  3033. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  3034. // They touch without overlapping.
  3035. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  3036. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  3037. }
  3038. /// Ranges are found by what they hold, not by where they start, and a
  3039. /// range that only touches another's end does not touch it.
  3040. #[test]
  3041. fn ranges_touch_where_they_overlap() {
  3042. let mut ranges = Vec::new();
  3043. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  3044. assert_eq!(ranges, [(10, 25), (40, 60)]);
  3045. join_ranges(&mut ranges, [(25, 40)]);
  3046. assert_eq!(ranges, [(10, 60)]);
  3047. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  3048. for (from, to, hit) in [
  3049. (0, 10, false),
  3050. (0, 11, true),
  3051. (24, 25, true),
  3052. (25, 40, false),
  3053. (25, 41, true),
  3054. (59, 200, true),
  3055. (60, 100, false),
  3056. (100, 101, true),
  3057. (101, 500, false),
  3058. (30, 30, false),
  3059. (50, 50, false),
  3060. ] {
  3061. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  3062. }
  3063. assert!(!touches(&[], 0, usize::MAX));
  3064. }
  3065. }
  3066. /// Whether a title buffer copy that continues the one recorded before it
  3067. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  3068. /// default).
  3069. ///
  3070. /// Each copy is done at submission through the kernel, which reports a
  3071. /// page that is not there instead of faulting (`copy_mapped`), tells the
  3072. /// write watch and the guards, and ends the refreshes gathered so far: a
  3073. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  3074. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  3075. /// continue the one before is counted either way and said on its own line
  3076. /// with the frame rate; the switch is worth that many kernel calls.
  3077. ///
  3078. /// Joined, the same bytes move: [`continues`] joins only copies whose
  3079. /// ranges, taken together, do not overlap, and nothing is recorded between
  3080. /// two steps that follow each other. What differs: a page that is not
  3081. /// mapped now fails the joined copy as a whole (it then goes page by page,
  3082. /// zeros for what cannot be read, as a single copy does), where before
  3083. /// only the copy that held it did.
  3084. fn join_copies() -> bool {
  3085. static ON: OnceLock<bool> = OnceLock::new();
  3086. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  3087. }
  3088. /// Since the last frame-rate line: title buffer copies recorded, and those
  3089. /// that continue the one before ([`join_copies`]).
  3090. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  3091. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  3092. /// where `last` ended, source and destination both, and the two as one do
  3093. /// not overlap (source over destination): then one copy of both moves the
  3094. /// bytes the two would move in turn.
  3095. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  3096. let ((d, s, n), (dst, src, len)) = (last, next);
  3097. let Some(all) = n.checked_add(len) else {
  3098. return false;
  3099. };
  3100. d.checked_add(n) == Some(dst)
  3101. && s.checked_add(n) == Some(src)
  3102. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  3103. }
  3104. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  3105. /// One list's lock at a time: a submission may name a list twice.
  3106. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  3107. let mut back: Vec<Declared> = Vec::new();
  3108. // Where each copy is in it, and the ranges seen: dispatches declare the
  3109. // same ranges thousands of times a frame.
  3110. let mut places: ByCopy<usize> = ByCopy::default();
  3111. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  3112. for list in runs {
  3113. for step in &list.deferred().copies {
  3114. if let Step::GpuWrite(shadow, address, len) = step {
  3115. let key = std::sync::Arc::as_ptr(shadow) as usize;
  3116. if !seen.insert((key, *address, *len)) {
  3117. continue;
  3118. }
  3119. let i = *places.entry(key).or_insert_with(|| {
  3120. back.push((shadow.clone(), Vec::new()));
  3121. back.len() - 1
  3122. });
  3123. back[i].1.push((*address, *address + *len));
  3124. }
  3125. }
  3126. }
  3127. back
  3128. }
  3129. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  3130. /// lines that say what the title's CPU was given while it decided whether
  3131. /// the camera is in a room. The values of the small read-backs
  3132. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  3133. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  3134. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  3135. /// copies found stale after their refresh (`shadow.rs`; only with
  3136. /// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
  3137. /// runtime, the read requests that fail (with 2: every request).
  3138. pub(crate) fn walls_trace() -> bool {
  3139. static ON: OnceLock<bool> = OnceLock::new();
  3140. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  3141. }
  3142. /// After `list` has run: the texels its read-backs copied into host
  3143. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  3144. ///
  3145. /// A submission that is waited for did this itself. One sent ahead
  3146. /// ([`late`]) did not, at any stage: the flights' lists were settled
  3147. /// without it, so the title read a buffer nobody wrote, as before read-backs
  3148. /// were made (the exposure metering's two small float targets, every frame).
  3149. fn read_backs(list: &HostList) {
  3150. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  3151. let mut data = std::ptr::null_mut();
  3152. // SAFETY: a read-back buffer of ours, written by the list that has
  3153. // run; the title's destination holds every row (checked when the
  3154. // copy was recorded).
  3155. unsafe {
  3156. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  3157. let from = data.cast::<u8>().cast_const();
  3158. for line in 0..*rows {
  3159. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  3160. }
  3161. // The walls trace: what the title is handed (one row of at
  3162. // most 24 values: its 5x1 and 1x1 float targets).
  3163. if walls_trace() && *rows == 1 && *row <= 96 {
  3164. let mut values = [0f32; 24];
  3165. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  3166. tracing::info!(
  3167. frame = crate::frame::current(),
  3168. to = format_args!("{:#x}", *at),
  3169. bytes = *row,
  3170. values = ?&values[..*row / 4],
  3171. "walls trace: a read-back lands in title memory"
  3172. );
  3173. }
  3174. buffer.Unmap(0, None);
  3175. }
  3176. }
  3177. }
  3178. }
  3179. /// After the card ran what declared `back`: what shaders wrote there goes
  3180. /// into title memory, and the ranges are done with.
  3181. fn hand_back(back: &[Declared]) {
  3182. if crate::shadow::wide_back() {
  3183. // Every range first (the pieces that differ, found on several
  3184. // threads), then the merges, in order, as below.
  3185. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3186. for (shadow, declared) in back {
  3187. if shadow.carded() {
  3188. continue;
  3189. }
  3190. let mut sorted = declared.clone();
  3191. sorted.sort_unstable();
  3192. let mut spans: Vec<(usize, usize)> = Vec::new();
  3193. for (from, to) in sorted {
  3194. match spans.last_mut() {
  3195. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3196. _ => spans.push((from, to)),
  3197. }
  3198. }
  3199. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3200. }
  3201. #[cfg(feature = "diagnostics")]
  3202. let scanning = std::time::Instant::now();
  3203. let found = crate::shadow::find_all(&work);
  3204. #[cfg(feature = "diagnostics")]
  3205. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3206. for ((shadow, from, to), found) in work.iter().zip(found) {
  3207. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3208. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3209. #[cfg(feature = "diagnostics")]
  3210. crate::copystat::compared(*from, to - from, written);
  3211. }
  3212. for (shadow, declared) in back {
  3213. shadow.copy_back_done(declared);
  3214. }
  3215. return;
  3216. }
  3217. for (shadow, declared) in back {
  3218. if shadow.carded() {
  3219. // Done before (`Host::card_back`).
  3220. shadow.copy_back_done(declared);
  3221. continue;
  3222. }
  3223. // Each byte compared once: the world declares dozens of views
  3224. // of its 174 MB heap that overlap almost entirely, and comparing
  3225. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3226. // MB shaders wrote. Only ranges that overlap or touch are
  3227. // joined: what lies between two was not given to shaders (the
  3228. // snapshot does not hold it).
  3229. let mut sorted = declared.clone();
  3230. sorted.sort_unstable();
  3231. let mut spans: Vec<(usize, usize)> = Vec::new();
  3232. for (from, to) in sorted {
  3233. match spans.last_mut() {
  3234. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3235. _ => spans.push((from, to)),
  3236. }
  3237. }
  3238. for (from, to) in spans {
  3239. let written = shadow.copy_back(from, to - from);
  3240. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3241. #[cfg(feature = "diagnostics")]
  3242. crate::copystat::compared(from, to - from, written);
  3243. }
  3244. shadow.copy_back_done(declared);
  3245. }
  3246. }
  3247. impl Host {
  3248. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3249. /// mesh shaders need both); logged once.
  3250. pub(crate) fn mesh_shaders(&self) -> bool {
  3251. static MESH: OnceLock<bool> = OnceLock::new();
  3252. *MESH.get_or_init(|| {
  3253. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3254. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3255. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3256. };
  3257. // SAFETY: each query writes its own structure of the given size.
  3258. let ok = unsafe {
  3259. self.device
  3260. .CheckFeatureSupport(
  3261. D3D12_FEATURE_D3D12_OPTIONS7,
  3262. (&raw mut options).cast(),
  3263. size_of_val(&options) as u32,
  3264. )
  3265. .is_ok()
  3266. && self
  3267. .device
  3268. .CheckFeatureSupport(
  3269. D3D12_FEATURE_SHADER_MODEL,
  3270. (&raw mut model).cast(),
  3271. size_of_val(&model) as u32,
  3272. )
  3273. .is_ok()
  3274. };
  3275. let mesh = ok
  3276. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3277. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3278. tracing::info!(mesh, "host mesh shader support");
  3279. mesh
  3280. })
  3281. }
  3282. /// Whether the host GPU supports the depth bounds test; logged once.
  3283. pub(crate) fn depth_bounds(&self) -> bool {
  3284. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3285. *BOUNDS.get_or_init(|| {
  3286. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3287. // SAFETY: writes `options` of the given size.
  3288. let ok = unsafe {
  3289. self.device
  3290. .CheckFeatureSupport(
  3291. D3D12_FEATURE_D3D12_OPTIONS2,
  3292. (&raw mut options).cast(),
  3293. size_of_val(&options) as u32,
  3294. )
  3295. .is_ok()
  3296. };
  3297. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3298. tracing::info!(supported, "host depth bounds support");
  3299. supported
  3300. })
  3301. }
  3302. /// A new list, open for recording.
  3303. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3304. #[cfg(feature = "diagnostics")]
  3305. let started = std::time::Instant::now();
  3306. #[cfg(feature = "diagnostics")]
  3307. let before = private_bytes();
  3308. let list = self.make_list();
  3309. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3310. // (May shrink while a list is made, on another thread's account:
  3311. // added as it is, the sum is what counts.)
  3312. #[cfg(feature = "diagnostics")]
  3313. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3314. #[cfg(feature = "diagnostics")]
  3315. {
  3316. use crate::copystat::{C, add};
  3317. add(C::HostLists, 1);
  3318. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3319. }
  3320. list
  3321. }
  3322. /// An allocator and a closed list for a prelude.
  3323. fn make_prelude(&self) -> Option<Prelude> {
  3324. // SAFETY: plain object creation.
  3325. let made: windows::core::Result<Prelude> = unsafe {
  3326. (|| {
  3327. let allocator: ID3D12CommandAllocator =
  3328. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3329. let list: ID3D12GraphicsCommandList =
  3330. self.device
  3331. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3332. list.Close()?;
  3333. Ok((allocator, list))
  3334. })()
  3335. };
  3336. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3337. match made {
  3338. Ok(prelude) => Some(prelude),
  3339. Err(e) => {
  3340. tracing::warn!(error = %e, "no host list for a prelude");
  3341. None
  3342. }
  3343. }
  3344. }
  3345. fn make_list(&self) -> windows::core::Result<HostList> {
  3346. // SAFETY: plain object creation.
  3347. unsafe {
  3348. let allocator: ID3D12CommandAllocator = self
  3349. .device
  3350. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3351. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3352. 0,
  3353. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3354. &allocator,
  3355. None,
  3356. )?;
  3357. let prelude = OnceLock::new();
  3358. if !lazy_prelude() {
  3359. let _ = prelude.set(self.make_prelude());
  3360. }
  3361. #[cfg(feature = "diagnostics")]
  3362. let notes = std::sync::Arc::<Mutex<Vec<Note>>>::default();
  3363. let pipelines = std::sync::Arc::<Mutex<std::collections::BTreeSet<String>>>::default();
  3364. #[cfg(feature = "diagnostics")]
  3365. let indirects = indirects::Shared::default();
  3366. #[cfg(feature = "diagnostics")]
  3367. if dred_on() || dred_light() {
  3368. static NUMBER: AtomicU32 = AtomicU32::new(0);
  3369. let number = NUMBER.fetch_add(1, Ordering::Relaxed);
  3370. name(&list, || format!("victory host list {number}"));
  3371. let mut all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  3372. if number.is_multiple_of(256) {
  3373. all.retain(|_, l| l.0.strong_count() > 0);
  3374. }
  3375. all.insert(
  3376. number,
  3377. (
  3378. std::sync::Arc::downgrade(&notes),
  3379. std::sync::Arc::downgrade(&pipelines),
  3380. std::sync::Arc::downgrade(&indirects),
  3381. ),
  3382. );
  3383. }
  3384. Ok(HostList {
  3385. allocator,
  3386. list,
  3387. deferred: Mutex::default(),
  3388. scratch: Mutex::default(),
  3389. states: Mutex::default(),
  3390. twins: Mutex::default(),
  3391. prelude,
  3392. pipelines,
  3393. #[cfg(feature = "diagnostics")]
  3394. indirects,
  3395. budget: OnceLock::new(),
  3396. card_budget: OnceLock::new(),
  3397. indirect_args: Mutex::default(),
  3398. batch_args: Mutex::default(),
  3399. _alive: Counted::new(),
  3400. #[cfg(feature = "diagnostics")]
  3401. notes,
  3402. #[cfg(feature = "diagnostics")]
  3403. stamps: OnceLock::new(),
  3404. })
  3405. }
  3406. }
  3407. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3408. fn card_clock(&self) -> Option<&'static CardClock> {
  3409. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3410. static WATCH: std::sync::Once = std::sync::Once::new();
  3411. let clock = CLOCK
  3412. .get_or_init(|| {
  3413. // SAFETY: a plain fence on our device.
  3414. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3415. Some(CardClock {
  3416. fence,
  3417. state: Mutex::new((0, None)),
  3418. sent: std::sync::Condvar::new(),
  3419. })
  3420. })
  3421. .as_ref()?;
  3422. WATCH.call_once(|| {
  3423. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3424. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3425. }
  3426. });
  3427. Some(clock)
  3428. }
  3429. /// Lists of ours just went to the queue: the clock's signal goes
  3430. /// behind them, and an idle stretch of the card, if one was under way,
  3431. /// ends here ([`CARD_CLOCK_US`]).
  3432. fn card_sent(&self) {
  3433. let Some(clock) = self.card_clock() else {
  3434. return;
  3435. };
  3436. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3437. state.0 += 1;
  3438. // SAFETY: our queue and the clock's fence.
  3439. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3440. if let Some((since, worked_then)) = state.1.take() {
  3441. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3442. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3443. }
  3444. drop(state);
  3445. clock.sent.notify_one();
  3446. }
  3447. /// Whether the host has what copies in the card's memory need (three
  3448. /// lists and the compare); made at the first ask. A copy goes to the
  3449. /// card's memory only if it has.
  3450. pub(crate) fn card_ready(&self) -> bool {
  3451. static READY: OnceLock<bool> = OnceLock::new();
  3452. *READY.get_or_init(|| match self.make_card_work() {
  3453. Ok(work) => {
  3454. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3455. true
  3456. }
  3457. Err(e) => {
  3458. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3459. false
  3460. }
  3461. })
  3462. }
  3463. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3464. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3465. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3466. let mut code: Option<ID3DBlob> = None;
  3467. // SAFETY: the source and names live through the call; the out
  3468. // pointer is ours.
  3469. unsafe {
  3470. D3DCompile(
  3471. CARD_COMPARE.as_ptr().cast(),
  3472. CARD_COMPARE.len(),
  3473. windows::core::s!("card compare"),
  3474. None,
  3475. None,
  3476. windows::core::s!("main"),
  3477. windows::core::s!("cs_5_1"),
  3478. 0,
  3479. 0,
  3480. &mut code,
  3481. None,
  3482. )?;
  3483. }
  3484. let code = code.ok_or_else(windows::core::Error::empty)?;
  3485. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3486. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3487. // in one submission.
  3488. const RESULTS: u64 = 1 << 20;
  3489. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3490. name(&differs, || "card compare results".into());
  3491. // SAFETY: the blob's own bytes; the root signature is inside the
  3492. // shader.
  3493. unsafe {
  3494. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3495. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3496. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3497. pRootSignature: std::mem::transmute_copy(&root),
  3498. CS: D3D12_SHADER_BYTECODE {
  3499. pShaderBytecode: bytes.as_ptr().cast(),
  3500. BytecodeLength: bytes.len(),
  3501. },
  3502. ..Default::default()
  3503. })?;
  3504. #[cfg(feature = "diagnostics")]
  3505. name(&pso, || crate::replay::play::COMPARE.into());
  3506. Ok(CardWork {
  3507. sync: vec![list()?],
  3508. check: vec![list()?],
  3509. fetch: list()?,
  3510. root,
  3511. pso,
  3512. differs: (differs, data as usize, RESULTS),
  3513. fetched: None,
  3514. taken: 0,
  3515. out: 0,
  3516. })
  3517. }
  3518. }
  3519. /// Before a submission's lists run, for copies in the card's memory
  3520. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3521. /// the last submission goes to their card side (a list of ours, run
  3522. /// now; the submission's lists follow it on the queue), and the ranges
  3523. /// this submission's shaders may write get a compare to run after its
  3524. /// lists. `None` if there is nothing to do.
  3525. ///
  3526. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3527. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3528. /// `relay`).
  3529. /// `picked`: ranges that may be written too, and ranges to look at
  3530. /// (`crate::picked`).
  3531. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3532. use std::sync::Arc;
  3533. if !crate::shadow::cards() {
  3534. return None;
  3535. }
  3536. // The ranges this submission's shaders may write, per copy.
  3537. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3538. for list in runs {
  3539. for step in &list.deferred().copies {
  3540. if let Step::GpuWrite(shadow, address, len) = step
  3541. && shadow.carded()
  3542. {
  3543. let range = (*address, *address + *len);
  3544. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3545. Some((_, ranges)) => {
  3546. if !ranges.contains(&range) {
  3547. ranges.push(range);
  3548. }
  3549. }
  3550. None => declared.push((shadow.clone(), vec![range])),
  3551. }
  3552. }
  3553. }
  3554. }
  3555. let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
  3556. // (Of a copy with a declared range here, that says it.)
  3557. let looked: Vec<&crate::picked::Range> =
  3558. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3559. // With the relay: the order of the queue is held from here until
  3560. // what is taken is on the queue, and the taking is numbered.
  3561. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3562. let sent_as = match order.as_mut() {
  3563. Some(order) => {
  3564. **order += 1;
  3565. **order
  3566. }
  3567. None => 0,
  3568. };
  3569. let mut dirty = crate::shadow::card_dirty(sent_as);
  3570. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3571. return None;
  3572. }
  3573. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3574. let work = work.as_mut()?;
  3575. // A copy whose shader writes are declared for the first time gets
  3576. // its bytes from before, whole.
  3577. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3578. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3579. if shadow.card_make_before(|size| {
  3580. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3581. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3582. Some(before)
  3583. }) {
  3584. whole.push(shadow.clone());
  3585. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3586. dirty.push((shadow.clone(), Vec::new()));
  3587. }
  3588. }
  3589. }
  3590. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3591. let mut looks = None;
  3592. // The bytes as they are now, whatever later submissions put there.
  3593. let own = if send::own() { send::take(self, &dirty) } else { None };
  3594. if !dirty.is_empty() {
  3595. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3596. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3597. };
  3598. let (allocator, list) = &sync;
  3599. // SAFETY: the list's last run finished (it ran ahead of a
  3600. // submission that was waited for, and came back after that);
  3601. // live buffers, and the ranges lie in them.
  3602. let recorded = unsafe {
  3603. (|| -> windows::core::Result<()> {
  3604. allocator.Reset()?;
  3605. list.Reset(allocator, None)?;
  3606. if upcheck::on() {
  3607. looks = upcheck::record(self, list, &dirty);
  3608. }
  3609. // Every copy first, then one barrier call, then every
  3610. // pass: a wait between each copy and its pass had the
  3611. // card do them one after the other.
  3612. let mut sent = Vec::new();
  3613. if let Some(own) = &own {
  3614. own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
  3615. }
  3616. for (shadow, ranges) in &dirty {
  3617. let Some((staging, before, _)) = shadow.card_sides() else {
  3618. continue;
  3619. };
  3620. for &(a, b) in ranges {
  3621. if own.is_none() {
  3622. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3623. }
  3624. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3625. }
  3626. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3627. if own.is_none() && before.is_some() && !ranges.is_empty() {
  3628. sent.push(transition(
  3629. &shadow.buffer,
  3630. D3D12_RESOURCE_STATE_COPY_DEST,
  3631. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3632. ));
  3633. }
  3634. }
  3635. if !sent.is_empty() {
  3636. list.ResourceBarrier(&sent);
  3637. }
  3638. list.SetComputeRootSignature(&work.root);
  3639. list.SetPipelineState(&work.pso);
  3640. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3641. for (shadow, ranges) in &dirty {
  3642. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3643. continue;
  3644. };
  3645. // No twin (it cost the card the copy's size again,
  3646. // 399 MB in run 75): `before` holds a 128-bit hash
  3647. // of each 64 KiB piece. The pieces just sent up are
  3648. // hashed again, all of them the first time; the
  3649. // compare after the lists hashes the declared
  3650. // pieces and flags those whose hash is another.
  3651. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3652. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3653. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3654. vec![shadow.card_run(0, usize::MAX)]
  3655. } else {
  3656. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3657. };
  3658. // The same pieces in fewer passes (`rehash_runs`).
  3659. let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3660. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3661. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3662. for run in runs {
  3663. card_pass(list, &run, size as u32, 0, 0);
  3664. }
  3665. }
  3666. list.Close()?;
  3667. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3668. Ok(())
  3669. })()
  3670. };
  3671. if let Err(e) = recorded {
  3672. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3673. }
  3674. used.push((false, sync));
  3675. }
  3676. drop(order);
  3677. let mut plan = CardPlan {
  3678. ranges: Vec::new(),
  3679. check: None,
  3680. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3681. lists: used,
  3682. sent_as,
  3683. looks,
  3684. sends: own.map(send::Own::memory),
  3685. };
  3686. // Each byte once, as the copy-back joins the declared ranges. The
  3687. // results go behind those of plans still in the air.
  3688. let mut at = work.taken;
  3689. for (shadow, ranges) in &declared {
  3690. let mut sorted = ranges.clone();
  3691. sorted.sort_unstable();
  3692. let mut spans: Vec<(usize, usize)> = Vec::new();
  3693. for (from, to) in sorted {
  3694. match spans.last_mut() {
  3695. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3696. _ => spans.push((from, to)),
  3697. }
  3698. }
  3699. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3700. for (from, to) in spans {
  3701. let Some(span) = shadow.card_span(from, to) else {
  3702. continue;
  3703. };
  3704. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3705. plan.ranges.push(CardRange {
  3706. shadow: shadow.clone(),
  3707. declared: (from, to),
  3708. span,
  3709. at,
  3710. compared,
  3711. picked: false,
  3712. });
  3713. if compared {
  3714. at += span.pieces;
  3715. }
  3716. }
  3717. }
  3718. for (shadow, from, len) in looked {
  3719. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3720. if let Some(span) = shadow.card_span(*from, from + len)
  3721. && twin
  3722. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3723. {
  3724. plan.ranges.push(CardRange {
  3725. shadow: shadow.clone(),
  3726. declared: (*from, from + len),
  3727. span,
  3728. at,
  3729. compared: true,
  3730. picked: true,
  3731. });
  3732. at += span.pieces;
  3733. }
  3734. }
  3735. work.taken = at;
  3736. if plan.ranges.iter().any(|r| r.compared) {
  3737. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3738. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3739. };
  3740. let (allocator, list) = &check;
  3741. // SAFETY: the list's last run finished (its submission was
  3742. // waited for, and it came back after that); live buffers; the
  3743. // compare's own root signature.
  3744. let recorded = unsafe {
  3745. (|| -> windows::core::Result<ID3D12CommandList> {
  3746. allocator.Reset()?;
  3747. list.Reset(allocator, None)?;
  3748. // What the submission's shaders wrote, first.
  3749. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3750. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3751. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3752. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3753. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3754. pResource: std::mem::ManuallyDrop::new(None),
  3755. }),
  3756. },
  3757. }]);
  3758. list.SetComputeRootSignature(&work.root);
  3759. list.SetPipelineState(&work.pso);
  3760. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3761. for r in plan.ranges.iter().filter(|r| r.compared) {
  3762. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3763. continue;
  3764. };
  3765. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3766. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3767. // (What is only looked at keeps its hashes: what
  3768. // changed there is the next declared range's to land.)
  3769. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  3770. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3771. }
  3772. list.Close()?;
  3773. list.cast()
  3774. })()
  3775. };
  3776. match recorded {
  3777. Ok(list) => plan.check = Some(list),
  3778. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3779. }
  3780. plan.lists.push((true, check));
  3781. }
  3782. work.out += 1;
  3783. Some(plan)
  3784. }
  3785. /// With [`relay`]: whether the compare's result area is half taken by
  3786. /// plans in the air. It starts from the beginning only when no plan is
  3787. /// out, so the caller lets the flights land first.
  3788. fn card_results_low(&self) -> bool {
  3789. CARD_WORK
  3790. .lock()
  3791. .unwrap_or_else(|e| e.into_inner())
  3792. .as_ref()
  3793. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3794. }
  3795. /// The plan's submission has run and its results were read
  3796. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3797. /// when nothing of ours is on the card, so the compare's results start
  3798. /// from the beginning again.
  3799. fn card_done(&self, plan: CardPlan) {
  3800. if let Some(looks) = plan.looks {
  3801. looks.read();
  3802. }
  3803. if let Some(memory) = plan.sends {
  3804. send::give_back(memory);
  3805. }
  3806. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3807. let Some(work) = work.as_mut() else {
  3808. return;
  3809. };
  3810. for (check, list) in plan.lists {
  3811. if check { work.check.push(list) } else { work.sync.push(list) }
  3812. }
  3813. work.out = work.out.saturating_sub(1);
  3814. // With the relay other plans may be on the card, their results
  3815. // not read yet: the area starts again only when none is out.
  3816. if !relay() || work.out == 0 {
  3817. work.taken = 0;
  3818. }
  3819. }
  3820. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3821. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3822. // SAFETY: plain object creation.
  3823. let copying = relay_copy().then(|| unsafe {
  3824. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3825. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3826. let list: ID3D12GraphicsCommandList =
  3827. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3828. list.Close()?;
  3829. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3830. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3831. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3832. ..Default::default()
  3833. })?;
  3834. Ok(((allocator, list), queue))
  3835. })()
  3836. });
  3837. let (list, queue) = match copying {
  3838. Some(Ok((list, queue))) => (list, Some(queue)),
  3839. Some(Err(e)) => {
  3840. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3841. (self.make_prelude()?, None)
  3842. }
  3843. None => (self.make_prelude()?, None),
  3844. };
  3845. // SAFETY: plain objects of our own.
  3846. unsafe {
  3847. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3848. let event = CreateEventW(None, false, false, None).ok()?;
  3849. Some(RelayFetch {
  3850. list,
  3851. queue,
  3852. fence,
  3853. event,
  3854. sent: 0,
  3855. buffer: None,
  3856. suspects: torn::Suspects::default(),
  3857. had: crate::land::Had::default(),
  3858. })
  3859. }
  3860. }
  3861. /// [`relay`], on the thread that lands flights: for the plans of the
  3862. /// flights being landed (the card has run them), the pieces their
  3863. /// compares flagged are fetched, once each, with a list and a wait of
  3864. /// this thread's own, and what shaders wrote in them goes into title
  3865. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3866. /// no submission lock; a piece flagged under one range of a plan is
  3867. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3868. /// whatever was sent meanwhile, so it may bring a later flight's
  3869. /// bytes, which that flight's landing then finds merged already; and
  3870. /// nothing is sent back up. `plans` come with the value signalled behind
  3871. /// their flight. `meanwhile` is called while the fetch is on its way, if
  3872. /// there is one.
  3873. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  3874. use crate::land;
  3875. let gathering = std::time::Instant::now();
  3876. let differs = {
  3877. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3878. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3879. };
  3880. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3881. let mut total = 0u64;
  3882. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  3883. fetch.had.landing(first);
  3884. }
  3885. // SAFETY: the mapping of the results. The compares of these plans
  3886. // have run, and their dwords are given to no other plan before these
  3887. // are done with (`card_done`).
  3888. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  3889. if let Some(differs) = differs {
  3890. // Pieces caught while a later flight was at them (`torn`).
  3891. let suspects = fetch.as_ref().map(|f| &f.suspects);
  3892. let mut seen = std::collections::HashSet::new();
  3893. for &(plan, behind) in plans {
  3894. plan.picked_found(differs);
  3895. let flags: Vec<(usize, u32, bool)> = plan
  3896. .ranges
  3897. .iter()
  3898. .filter(|r| !r.picked)
  3899. .flat_map(|r| {
  3900. (0..r.span.pieces).map(move |p| {
  3901. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  3902. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  3903. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  3904. })
  3905. })
  3906. .collect();
  3907. let fetched = flagged_pieces(&flags);
  3908. for r in plan.ranges.iter().filter(|r| !r.picked) {
  3909. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3910. if upcheck::on() {
  3911. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  3912. }
  3913. for p in 0..r.span.pieces {
  3914. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  3915. continue;
  3916. }
  3917. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3918. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  3919. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  3920. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  3921. land::count(land::stat::HAD, 1);
  3922. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  3923. if land::skip_on() {
  3924. continue;
  3925. }
  3926. }
  3927. if upcheck::on() {
  3928. upcheck::fetched(r.shadow.id(), lo);
  3929. }
  3930. seen.insert((copy, lo, hi));
  3931. pieces.push((r.shadow.clone(), lo, hi, total));
  3932. total += (hi - lo) as u64;
  3933. }
  3934. }
  3935. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3936. }
  3937. }
  3938. }
  3939. if land::on() {
  3940. // In the order they are landed, each byte of a copy once.
  3941. let keys: Vec<land::Piece> =
  3942. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  3943. total = 0;
  3944. pieces = land::ordered(&keys)
  3945. .into_iter()
  3946. .map(|(i, title, len)| {
  3947. let shadow = &pieces[i].0;
  3948. let lo = title - shadow.span().0 as usize;
  3949. let at = total;
  3950. total += len as u64;
  3951. (shadow.clone(), lo, lo + len, at)
  3952. })
  3953. .collect();
  3954. }
  3955. land::spent(land::stat::GATHER, gathering);
  3956. if fetch.is_none() {
  3957. *fetch = self.make_relay_fetch();
  3958. }
  3959. // On the copy queue a later flight may be at a piece while it is
  3960. // fetched: the pieces come down whole, to be hashed.
  3961. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  3962. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  3963. if let Some(check) = &check {
  3964. total = check.total;
  3965. }
  3966. // The sends these flights ran behind, all a fetch on the copy queue
  3967. // is known to have run behind.
  3968. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  3969. if pieces.is_empty() {
  3970. // Nothing to fetch: every send so far is older than the next
  3971. // fetch, if that goes to the queue the sends went to.
  3972. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  3973. true => behind,
  3974. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  3975. };
  3976. crate::shadow::relay_fetched(after);
  3977. return;
  3978. }
  3979. let Some(f) = fetch.as_mut() else {
  3980. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  3981. };
  3982. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  3983. let size = total.next_multiple_of(16 << 20);
  3984. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3985. }
  3986. let Some((buffer, data, _)) = f.buffer.clone() else {
  3987. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  3988. };
  3989. f.sent += 1;
  3990. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  3991. let copy_queue = f.queue.clone();
  3992. let waiting = std::time::Instant::now();
  3993. // The flights the fetch runs behind: those in the line by now have
  3994. // been given to the queue. On the copy queue, those landed here.
  3995. let ahead = match copy_queue {
  3996. Some(_) => 0,
  3997. None => line().target,
  3998. };
  3999. // SAFETY: the list's last run was waited for by this thread; live
  4000. // buffers (the copies are held by the plans); the fence and the
  4001. // event are this thread's.
  4002. let ran = unsafe {
  4003. (|| -> windows::core::Result<u64> {
  4004. allocator.Reset()?;
  4005. list.Reset(&allocator, None)?;
  4006. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  4007. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  4008. }
  4009. list.Close()?;
  4010. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  4011. if let Some(queue) = &copy_queue {
  4012. queue.ExecuteCommandLists(&lists);
  4013. queue.Signal(&fence, sent)?;
  4014. meanwhile();
  4015. fence.SetEventOnCompletion(sent, event)?;
  4016. WaitForSingleObject(event, INFINITE);
  4017. return Ok(behind);
  4018. }
  4019. // In the order of the queue: the sends of title bytes so
  4020. // far are ahead of this fetch, every later one behind it.
  4021. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  4022. self.queue.ExecuteCommandLists(&lists);
  4023. let after = *order;
  4024. drop(order);
  4025. self.card_sent();
  4026. self.queue.Signal(&fence, sent)?;
  4027. meanwhile();
  4028. fence.SetEventOnCompletion(sent, event)?;
  4029. WaitForSingleObject(event, INFINITE);
  4030. Ok(after)
  4031. })()
  4032. };
  4033. let after = match ran {
  4034. Ok(after) => after,
  4035. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  4036. };
  4037. let us = waiting.elapsed().as_micros() as u64;
  4038. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  4039. {
  4040. use crate::shadow::CARD_STATS;
  4041. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4042. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4043. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4044. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  4045. }
  4046. let merging = std::time::Instant::now();
  4047. let mut written = 0;
  4048. if land::on() {
  4049. let titles: Vec<(usize, usize)> =
  4050. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  4051. let jobs = land::jobs(&titles);
  4052. let put = std::sync::atomic::AtomicU64::new(0);
  4053. land::each(jobs.len(), &|j| {
  4054. let working = std::time::Instant::now();
  4055. if let Some(check) = &check {
  4056. for i in jobs[j].clone() {
  4057. // SAFETY: as below.
  4058. unsafe { check.look(i, data) };
  4059. }
  4060. }
  4061. let mut notes = land::Notes::default();
  4062. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  4063. let addressed: Vec<(usize, usize, usize)> =
  4064. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  4065. // SAFETY: the mapping of the fetched bytes, `total` of
  4066. // them; the copy into it has run, and the next waits
  4067. // for this call.
  4068. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  4069. }
  4070. notes.flush();
  4071. land::spent(land::stat::CARD_ALL, working);
  4072. });
  4073. land::count(land::stat::JOBS, jobs.len() as u64);
  4074. written = put.into_inner();
  4075. } else {
  4076. let mut title = Vec::new();
  4077. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  4078. if let Some(check) = &check {
  4079. // SAFETY: as below.
  4080. unsafe { check.look(i, data) };
  4081. }
  4082. // SAFETY: the mapping of the fetched bytes, `total` of them;
  4083. // the copy into it has run.
  4084. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  4085. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  4086. shadow.walls_merged(gpu.len(), merged);
  4087. written += merged as u64;
  4088. }
  4089. }
  4090. land::spent(land::stat::CARD, merging);
  4091. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  4092. if let Some(f) = fetch.as_mut() {
  4093. if let Some(check) = &check {
  4094. check.done(&mut f.suspects);
  4095. }
  4096. f.had.fetched(
  4097. ahead,
  4098. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  4099. );
  4100. }
  4101. // Sends up to `after` are of no use to any later merge.
  4102. crate::shadow::relay_fetched(after);
  4103. }
  4104. /// [`relay`], on the thread that lands flights: `items` are the first
  4105. /// things of the line, flights the card has run and what follows them.
  4106. /// What their shaders wrote goes into title memory (copies in the
  4107. /// card's memory first, then the others, each byte once whichever
  4108. /// flights declared it); then every flight's ranges are done with;
  4109. /// then, in the line's order, each flight's read-backs, its
  4110. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  4111. /// is complete before the title is told anything.
  4112. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  4113. let landing = std::time::Instant::now();
  4114. {
  4115. let flights: Vec<&Flight> = items
  4116. .iter()
  4117. .filter_map(|l| match l {
  4118. Late::Run(flight) => Some(flight),
  4119. _ => None,
  4120. })
  4121. .collect();
  4122. if !flights.is_empty() {
  4123. // SAFETY: a plain query.
  4124. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4125. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  4126. fail(format_args!(
  4127. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  4128. flights.len(),
  4129. runs.len(),
  4130. self.removal_data(&runs),
  4131. last_notes(&runs)
  4132. ));
  4133. }
  4134. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  4135. // (Each byte once: the ranges are joined.)
  4136. let mut back: Vec<Declared> = Vec::new();
  4137. for flight in &flights {
  4138. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  4139. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4140. Some((_, all)) => all.extend_from_slice(ranges),
  4141. None => back.push((shadow.clone(), ranges.clone())),
  4142. }
  4143. }
  4144. }
  4145. let mut hand_back = relay_hand_back(&back);
  4146. self.relay_card_back(&plans, fetch, &mut || {
  4147. if crate::land::on() {
  4148. hand_back.look(crate::land::stat::SCAN_BESIDE);
  4149. }
  4150. });
  4151. hand_back.merge();
  4152. let finishing = std::time::Instant::now();
  4153. // Only now, and flight by flight: a range another flight
  4154. // in the air declared too stays closed to refreshes.
  4155. for flight in &flights {
  4156. for (shadow, ranges) in &flight.back {
  4157. shadow.copy_back_done(ranges);
  4158. }
  4159. }
  4160. crate::land::spent(crate::land::stat::DONE, finishing);
  4161. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4162. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  4163. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  4164. }
  4165. }
  4166. // In the order given: what tells the title the card is done.
  4167. let mut last = 0;
  4168. let mut landed = Vec::new();
  4169. let mut telling = std::time::Instant::now();
  4170. for item in items {
  4171. telling = match item {
  4172. Late::Run(flight) => {
  4173. last = flight.number;
  4174. for &i in &flight.order {
  4175. read_backs(flight.lists[i].host());
  4176. }
  4177. if let Some(card) = flight.card {
  4178. self.card_done(card);
  4179. }
  4180. if let Some(own) = flight.own {
  4181. own.landed();
  4182. }
  4183. landed.push((flight.lists, flight.order));
  4184. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  4185. }
  4186. Late::Write(at, what, bytes) => {
  4187. what.write(at as *mut u8, bytes);
  4188. crate::land::spent(crate::land::stat::TOLD, telling)
  4189. }
  4190. Late::Signal(fence, value) => {
  4191. crate::fence::set(fence as crate::object::This, value);
  4192. crate::land::spent(crate::land::stat::TOLD, telling)
  4193. }
  4194. };
  4195. }
  4196. if last > 0 {
  4197. FINISHED.store(last, Ordering::Release);
  4198. bury(last);
  4199. }
  4200. self.log_messages();
  4201. crate::land::spent(crate::land::stat::REST, telling);
  4202. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4203. {
  4204. let mut line = line();
  4205. let Line {
  4206. line: items,
  4207. written,
  4208. lists,
  4209. settling,
  4210. poke,
  4211. landed: kept,
  4212. in_hand,
  4213. landing,
  4214. ..
  4215. } = &mut *line;
  4216. kept.extend(landed);
  4217. in_hand.clear();
  4218. landing.clear();
  4219. // What is still in the air, from the flights that are.
  4220. written.clear();
  4221. *lists = 0;
  4222. let mut ranges = Vec::new();
  4223. for item in items.iter() {
  4224. if let Late::Run(flight) = item {
  4225. *lists += flight.order.len().max(1);
  4226. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  4227. }
  4228. }
  4229. join_ranges(written, ranges);
  4230. *settling = false;
  4231. // The landed lists are reset, and what queues hold looked at,
  4232. // by the helper thread (they take locks a waiter may hold).
  4233. *poke = true;
  4234. }
  4235. LINE_MOVED.notify_all();
  4236. LINE_LANDED.notify_all();
  4237. }
  4238. /// After a submission ran, for copies in the card's memory: the pieces
  4239. /// of the declared ranges that the compare found differing (all of a
  4240. /// range it did not compare) are fetched, with one more wait for the
  4241. /// card, and what shaders wrote in them goes into title memory.
  4242. /// `submitted` is the last value signalled on the fence. `seen` holds
  4243. /// the pieces fetched already since the card was last waited for
  4244. /// (several submissions settled together name the same ones).
  4245. fn card_back(
  4246. &self,
  4247. plan: &CardPlan,
  4248. submitted: &mut u64,
  4249. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4250. ) {
  4251. if plan.ranges.is_empty() {
  4252. return;
  4253. }
  4254. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4255. let Some(work) = work.as_mut() else {
  4256. return;
  4257. };
  4258. // SAFETY: the mapping of the results, which the compare (it has
  4259. // run) wrote.
  4260. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4261. // The pieces to fetch: the range, the offsets in its copy, and
  4262. // where the bytes come down.
  4263. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4264. let mut total = 0u64;
  4265. plan.picked_found(differs);
  4266. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4267. for p in 0..r.span.pieces {
  4268. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4269. continue;
  4270. }
  4271. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4272. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4273. pieces.push((i, lo, hi, total));
  4274. total += (hi - lo) as u64;
  4275. }
  4276. }
  4277. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4278. }
  4279. let mut written = vec![0usize; plan.ranges.len()];
  4280. if !pieces.is_empty() {
  4281. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4282. let size = total.next_multiple_of(16 << 20);
  4283. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4284. }
  4285. let Some((fetched, data, _)) = &work.fetched else {
  4286. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4287. };
  4288. let waiting = std::time::Instant::now();
  4289. let (allocator, list) = &work.fetch;
  4290. // SAFETY: the list's last run was waited for; live buffers; the
  4291. // fence and event are ours, under the submission lock.
  4292. let ran = unsafe {
  4293. (|| -> windows::core::Result<()> {
  4294. allocator.Reset()?;
  4295. list.Reset(allocator, None)?;
  4296. for &(i, lo, hi, at) in &pieces {
  4297. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4298. }
  4299. list.Close()?;
  4300. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4301. self.card_sent();
  4302. *submitted += 1;
  4303. self.queue.Signal(&self.fence, *submitted)?;
  4304. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4305. let was_working = working(false);
  4306. WaitForSingleObject(self.event, INFINITE);
  4307. stood(waiting);
  4308. working(was_working);
  4309. Ok(())
  4310. })()
  4311. };
  4312. if let Err(e) = ran {
  4313. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4314. }
  4315. {
  4316. use crate::shadow::CARD_STATS;
  4317. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4318. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4319. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4320. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4321. }
  4322. if wide_merge() && pieces.len() >= 8 {
  4323. // The pieces are apart from one another (each its own bytes
  4324. // of its copy and of title memory): several at a time.
  4325. let fetched = *data;
  4326. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4327. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4328. let each = pieces.len().div_ceil(8);
  4329. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4330. .chunks(each)
  4331. .map(|chunk| {
  4332. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4333. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4334. let counts = counts.clone();
  4335. Box::new(move || {
  4336. let mut title = Vec::new();
  4337. for (shadow, i, lo, hi, at) in chunk {
  4338. // SAFETY: the mapping of the fetched bytes;
  4339. // the copy into it has run, and the caller
  4340. // waits for this job.
  4341. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4342. let merged = shadow.card_merge(lo, gpu, &mut title);
  4343. shadow.walls_merged(gpu.len(), merged);
  4344. counts[i].fetch_add(merged, Ordering::Relaxed);
  4345. }
  4346. }) as Box<dyn FnOnce() + Send>
  4347. })
  4348. .collect();
  4349. crate::shadow::wide_run(jobs);
  4350. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4351. *written += count.load(Ordering::Relaxed);
  4352. }
  4353. } else {
  4354. let mut title = Vec::new();
  4355. for &(i, lo, hi, at) in &pieces {
  4356. // SAFETY: the mapping of the fetched bytes, `total` of
  4357. // them; the copy into it has run.
  4358. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4359. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4360. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4361. written[i] += merged;
  4362. }
  4363. }
  4364. }
  4365. for (r, written) in plan.ranges.iter().zip(written) {
  4366. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4367. let (from, to) = r.declared;
  4368. #[cfg(feature = "diagnostics")]
  4369. crate::copystat::compared(from, to - from, written);
  4370. let _ = (from, to);
  4371. }
  4372. }
  4373. /// Runs closed lists and waits for them, and with [`late`] for
  4374. /// everything sent to the card before them, which is settled first.
  4375. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4376. let _ = self.submit(runs, false);
  4377. }
  4378. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4379. /// from the title's, go to the card in `order` and are not waited for.
  4380. /// They join the line of flights and are settled, with the others in
  4381. /// the air, at the next point where what they do can be observed
  4382. /// ([`late`] lists those points); their host lists are reset and kept
  4383. /// for reuse then, as a queue does for the lists it ran.
  4384. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4385. if order.is_empty() {
  4386. crate::list::recycle(lists, &order);
  4387. return;
  4388. }
  4389. late_threads();
  4390. let sent = {
  4391. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4392. self.submit(&runs, true)
  4393. };
  4394. let Some((mut submitted, sent)) = sent else {
  4395. // (Not reached: a submission sent ahead always comes back.)
  4396. crate::list::recycle(lists, &order);
  4397. return;
  4398. };
  4399. let told = !sent.writes.is_empty();
  4400. let most = {
  4401. let mut line = line();
  4402. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4403. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4404. *flying += order.len();
  4405. *target = *submitted;
  4406. items.push(Late::Run(Flight {
  4407. number: sent.number,
  4408. fence: *target,
  4409. lists,
  4410. order,
  4411. card: sent.card,
  4412. back: sent.back,
  4413. own: sent.own,
  4414. }));
  4415. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4416. *flying >= late_most()
  4417. };
  4418. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4419. RELAY_MOVED.notify_one();
  4420. if told && !late_writes() {
  4421. self.settle(&mut submitted, WHY_WRITES);
  4422. } else if most && relay_exact() {
  4423. // Until there are fewer, not until there are none.
  4424. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4425. } else if most {
  4426. self.settle(&mut submitted, WHY_MOST);
  4427. } else {
  4428. LINE_MOVED.notify_one();
  4429. }
  4430. drop(submitted);
  4431. land();
  4432. }
  4433. /// Sends `list`, a closed list of ours (the present's copy), as a
  4434. /// flight ([`late_free_present`]): not waited for, settled with the
  4435. /// others. The caller keeps the list and does not reset it before the
  4436. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4437. /// it ran and was waited for after all.
  4438. fn execute_own(&self, list: &HostList) -> u64 {
  4439. late_threads();
  4440. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4441. return 0;
  4442. };
  4443. let number = sent.number;
  4444. {
  4445. let mut line = line();
  4446. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4447. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4448. *flying += 1;
  4449. *target = *submitted;
  4450. items.push(Late::Run(Flight {
  4451. number,
  4452. fence: *target,
  4453. lists: Vec::new(),
  4454. order: Vec::new(),
  4455. card: sent.card,
  4456. back: sent.back,
  4457. own: sent.own,
  4458. }));
  4459. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4460. }
  4461. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4462. LINE_MOVED.notify_one();
  4463. RELAY_MOVED.notify_one();
  4464. drop(submitted);
  4465. number
  4466. }
  4467. /// Waits for the card to run every flight in the air ([`late`]) and
  4468. /// does what they left to do, as [`Host::execute`] does for one
  4469. /// submission after its wait: the pieces their shaders wrote in copies
  4470. /// in the card's memory are fetched and merged (each once), the ranges
  4471. /// they declared in the other copies are compared and copied back
  4472. /// (each byte once, whichever flights declared it), and then, in the
  4473. /// order they were given: their bottom-of-pipe writes and the fence
  4474. /// signals behind them. `submitted` is the submission lock's value;
  4475. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4476. ///
  4477. /// Everything in the air is settled, never the first flights alone:
  4478. /// the merge writes the copies' CPU side, which a flight still on the
  4479. /// card may be writing too.
  4480. fn settle(&self, submitted: &mut u64, why: usize) {
  4481. if !late() {
  4482. return;
  4483. }
  4484. if relay() {
  4485. // Nothing is settled here: the thread that lands flights does
  4486. // it, in order, and this waits until nothing is in the air and
  4487. // nothing is being landed. Every point that settled before
  4488. // comes here, so each still sees title memory, fences and
  4489. // bottom-of-pipe values as after a settle.
  4490. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4491. return;
  4492. }
  4493. let was_working = working(true);
  4494. let mut counted = false;
  4495. loop {
  4496. let items = {
  4497. let mut line = line();
  4498. if line.line.is_empty() {
  4499. line.settling = false;
  4500. break;
  4501. }
  4502. line.settling = true;
  4503. line.written.clear();
  4504. line.lists = 0;
  4505. std::mem::take(&mut line.line)
  4506. };
  4507. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4508. if !counted {
  4509. counted = true;
  4510. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4511. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4512. }
  4513. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4514. if flights > 0 {
  4515. submitting(2, flights);
  4516. let waiting = std::time::Instant::now();
  4517. // SAFETY: the fence and event are ours, under the
  4518. // submission lock; `submitted` is the last value signalled.
  4519. unsafe {
  4520. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4521. Ok(()) => {
  4522. working(false);
  4523. WaitForSingleObject(self.event, INFINITE);
  4524. stood(waiting);
  4525. working(true);
  4526. }
  4527. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4528. }
  4529. }
  4530. let gpu = waiting.elapsed();
  4531. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4532. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4533. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4534. #[cfg(feature = "diagnostics")]
  4535. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4536. format!("{flights} submissions sent ahead, settled together")
  4537. });
  4538. // SAFETY: a plain query.
  4539. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4540. let runs: Vec<&HostList> = items
  4541. .iter()
  4542. .filter_map(|i| match i {
  4543. Late::Run(f) => Some(f),
  4544. _ => None,
  4545. })
  4546. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4547. .collect();
  4548. fail(format_args!(
  4549. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4550. runs.len(),
  4551. self.removal_data(&runs),
  4552. last_notes(&runs)
  4553. ));
  4554. }
  4555. submitting(3, flights);
  4556. let copying = std::time::Instant::now();
  4557. let mut seen = std::collections::HashSet::new();
  4558. let mut back: Vec<Declared> = Vec::new();
  4559. for item in &items {
  4560. let Late::Run(flight) = item else {
  4561. continue;
  4562. };
  4563. if let Some(card) = &flight.card {
  4564. self.card_back(card, submitted, &mut seen);
  4565. }
  4566. for (shadow, ranges) in &flight.back {
  4567. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4568. Some((_, all)) => {
  4569. for range in ranges {
  4570. if !all.contains(range) {
  4571. all.push(*range);
  4572. }
  4573. }
  4574. }
  4575. None => back.push((shadow.clone(), ranges.clone())),
  4576. }
  4577. }
  4578. }
  4579. hand_back(&back);
  4580. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4581. }
  4582. // In the order given: what tells the title the card is done.
  4583. let mut last = 0;
  4584. let mut landed = Vec::new();
  4585. for item in items {
  4586. match item {
  4587. Late::Run(flight) => {
  4588. last = flight.number;
  4589. for &i in &flight.order {
  4590. read_backs(flight.lists[i].host());
  4591. }
  4592. if let Some(card) = flight.card {
  4593. self.card_done(card);
  4594. }
  4595. landed.push((flight.lists, flight.order));
  4596. }
  4597. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4598. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4599. }
  4600. }
  4601. if last > 0 {
  4602. FINISHED.store(last, Ordering::Release);
  4603. bury(last);
  4604. }
  4605. line().landed.extend(landed);
  4606. }
  4607. if counted {
  4608. self.log_messages();
  4609. submitting(0, 0);
  4610. // What was settled may be what a queue stands at, and the
  4611. // caller may not be one that looks (a read-back, a present).
  4612. if why != WHY_CARD_DONE {
  4613. line().poke = true;
  4614. LINE_MOVED.notify_one();
  4615. }
  4616. }
  4617. working(was_working);
  4618. }
  4619. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4620. /// copies, which flights may be writing and the title wrote too
  4621. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4622. /// those of the submission's one asking, which is made again.
  4623. ///
  4624. /// With [`card_steps`] only the flights that declared them: a range of
  4625. /// a copy nobody declared any more is refreshed like any other. What
  4626. /// they landed is title memory written, so everything is asked and
  4627. /// looked at again; what is left after three times waits as before.
  4628. fn settle_stale(
  4629. &self,
  4630. submitted: &mut u64,
  4631. runs: &[&HostList],
  4632. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4633. ranges: &[(usize, usize)],
  4634. ) {
  4635. if relay_exact() && card_steps::stage() > 0 {
  4636. for _ in 0..3 {
  4637. #[cfg(feature = "diagnostics")]
  4638. blame_stale(&stale);
  4639. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4640. crate::watch::ask_once(ranges);
  4641. stale = stale_under_flights(runs);
  4642. if stale.is_empty() {
  4643. return;
  4644. }
  4645. }
  4646. }
  4647. #[cfg(feature = "diagnostics")]
  4648. blame_stale(&stale);
  4649. self.settle(submitted, WHY_STALE);
  4650. crate::watch::ask_once(ranges);
  4651. }
  4652. /// [`Host::execute`], or with `late` the first half of
  4653. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4654. /// to be done once they have run comes back with the submission lock
  4655. /// still held.
  4656. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4657. #[cfg(feature = "diagnostics")]
  4658. let called = std::time::Instant::now();
  4659. #[cfg(feature = "diagnostics")]
  4660. crate::copystat::submission_begins();
  4661. // One submission at a time from preparation to copy-back: snapshots
  4662. // and the ranges shaders write are per host copy, not per submission.
  4663. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4664. let was_working = working(true);
  4665. submitting(1, runs.len());
  4666. // Flights in the air ([`late`]): a submission that is waited for
  4667. // settles them first, one sent ahead only if preparing it reads
  4668. // what they write.
  4669. // Or the reads are done on the card, behind the flights.
  4670. let own = if late { self.card_steps(runs) } else { None };
  4671. if !late {
  4672. self.settle(&mut submitted, WHY_SYNC);
  4673. } else if own.is_none()
  4674. && let Some(why) = late_blocked(runs)
  4675. {
  4676. if relay_exact() && why == WHY_READ {
  4677. // Only until the flights that may write what is read have
  4678. // landed: their copy-back's end, not the card's other work.
  4679. relay_wait(why, |line| {
  4680. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4681. });
  4682. } else {
  4683. self.settle(&mut submitted, why);
  4684. }
  4685. }
  4686. // Descriptors the title copied into placed heaps directly, before
  4687. // command lists that index those slots are submitted.
  4688. crate::descriptor::sync_heaps();
  4689. // That list runs first, and is one of the submission's from here on.
  4690. let with: Vec<&HostList>;
  4691. let runs = match &own {
  4692. Some(own) => {
  4693. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4694. &with[..]
  4695. }
  4696. None => runs,
  4697. };
  4698. let behind = late && flying();
  4699. // Before this submission counts as started: what the sweep lets go
  4700. // of is named by no list, and nothing runs now (behind flights the
  4701. // sweep waits for a submission that finds none in the air: there is
  4702. // one at every present).
  4703. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4704. if !behind {
  4705. if upcheck::on() {
  4706. upcheck::at_rest(self);
  4707. }
  4708. sweep();
  4709. SWEPT.store(now_ms(), Ordering::Relaxed);
  4710. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4711. // With the present sent ahead nothing else brings a moment
  4712. // with nothing in the air: one is made for the sweep.
  4713. self.settle(&mut submitted, WHY_SYNC);
  4714. if upcheck::on() {
  4715. upcheck::at_rest(self);
  4716. }
  4717. sweep();
  4718. SWEPT.store(now_ms(), Ordering::Relaxed);
  4719. }
  4720. let behind = late && flying();
  4721. // The slots that waited for a texture's host copy, before the
  4722. // lists that may read them run.
  4723. crate::descriptor::make_waiting();
  4724. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4725. // The ranges shaders write are counted for it (with the relay).
  4726. crate::shadow::preparing(this_submission);
  4727. let started = std::time::Instant::now();
  4728. #[cfg(feature = "diagnostics")]
  4729. let lock = (started - called).as_micros() as u64;
  4730. #[cfg(feature = "diagnostics")]
  4731. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4732. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4733. // Where each run's lists start in `lists`.
  4734. let mut firsts = Vec::with_capacity(runs.len());
  4735. let mut batch = Batch::default();
  4736. #[cfg(feature = "diagnostics")]
  4737. let split = Split::begin();
  4738. // The time a settle of flights takes inside this preparing: the
  4739. // wait for the card and the copy-back have their own places on the
  4740. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4741. let mut settled = std::time::Duration::ZERO;
  4742. // One write-watch asking for everything the submission refreshes
  4743. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4744. if crate::watch::once() {
  4745. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  4746. for list in runs {
  4747. for step in &list.deferred().copies {
  4748. if let Step::Refresh(shadow, address, len) = step
  4749. && shadow.asked_ahead()
  4750. {
  4751. let span = spans
  4752. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4753. .or_insert((*address, *address + *len));
  4754. *span = (span.0.min(*address), span.1.max(*address + *len));
  4755. }
  4756. }
  4757. }
  4758. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4759. #[cfg(feature = "diagnostics")]
  4760. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  4761. crate::watch::ask_once(&ranges);
  4762. #[cfg(feature = "diagnostics")]
  4763. split.part(0);
  4764. // Behind flights: the title wrote memory that a flight's shaders
  4765. // may write too, and this submission refreshes it. The flights
  4766. // are settled, and the asking made again: the copy-back wrote
  4767. // title memory, which other copies of it must see.
  4768. if upcheck::on() {
  4769. upcheck::order(runs);
  4770. if behind {
  4771. upcheck::reads(runs);
  4772. }
  4773. }
  4774. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  4775. if !stale.is_empty() {
  4776. let settling = std::time::Instant::now();
  4777. self.settle_stale(&mut submitted, runs, stale, &ranges);
  4778. settled += settling.elapsed();
  4779. }
  4780. } else if behind && !stale_under_flights(runs).is_empty() {
  4781. let settling = std::time::Instant::now();
  4782. self.settle(&mut submitted, WHY_STALE);
  4783. settled += settling.elapsed();
  4784. }
  4785. #[cfg(feature = "diagnostics")]
  4786. split.part(1);
  4787. // What flights in the air may write.
  4788. let air = line().written.clone();
  4789. for list in runs {
  4790. list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4791. firsts.push(lists.len());
  4792. if let Some(prelude) = list.prelude() {
  4793. lists.push(Some(prelude));
  4794. }
  4795. lists.push(list.list.cast().ok());
  4796. }
  4797. batch.flush();
  4798. crate::watch::ask_once_end();
  4799. #[cfg(feature = "diagnostics")]
  4800. split.part(2);
  4801. // The snapshots of the ranges shaders may write, if they were left
  4802. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4803. // lists have not gone to the card.
  4804. {
  4805. #[cfg(feature = "diagnostics")]
  4806. let snapshots = std::time::Instant::now();
  4807. crate::shadow::take_snapshots();
  4808. #[cfg(feature = "diagnostics")]
  4809. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4810. }
  4811. #[cfg(feature = "diagnostics")]
  4812. split.part(3);
  4813. // Copies in the card's memory: what changed on their CPU side goes
  4814. // up ahead of the lists, and a compare of what the shaders may
  4815. // write follows them in the same submission.
  4816. let flown = late && relay();
  4817. if flown && self.card_results_low() {
  4818. let settling = std::time::Instant::now();
  4819. self.settle(&mut submitted, WHY_MOST);
  4820. settled += settling.elapsed();
  4821. }
  4822. // What shaders may write through views they pick: last, so that no
  4823. // refresh of this submission leaves it alone.
  4824. let picked = crate::picked::declare(runs);
  4825. for (shadow, at, len) in &picked.written {
  4826. shadow.writing(*at, *len);
  4827. }
  4828. let card = self.card_before(runs, &picked, flown);
  4829. // The sends are taken: from here on the references hold what the
  4830. // copies in the lists put.
  4831. for (shadow, at, bytes) in batch.placed.drain(..) {
  4832. shadow.placed_copy(at, &bytes);
  4833. }
  4834. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4835. lists.push(Some(check));
  4836. }
  4837. #[cfg(feature = "diagnostics")]
  4838. split.part(4);
  4839. let prepared = std::time::Instant::now();
  4840. if late {
  4841. *submitted += 1;
  4842. // SAFETY: closed lists; the fence is ours.
  4843. let signalled = unsafe {
  4844. self.queue.ExecuteCommandLists(&lists);
  4845. self.queue.Signal(&self.fence, *submitted)
  4846. };
  4847. self.card_sent();
  4848. if let Err(e) = signalled {
  4849. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4850. }
  4851. #[cfg(feature = "diagnostics")]
  4852. split.part(5);
  4853. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4854. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4855. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4856. submitting(0, 0);
  4857. #[cfg(feature = "diagnostics")]
  4858. crate::copystat::submission_ends(lock);
  4859. let sent = Sent {
  4860. number: this_submission,
  4861. card,
  4862. back,
  4863. own,
  4864. writes,
  4865. };
  4866. working(was_working);
  4867. return Some((submitted, sent));
  4868. }
  4869. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4870. #[cfg(feature = "diagnostics")]
  4871. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4872. firsts
  4873. .iter()
  4874. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4875. .map(|(&a, &b)| &lists[a..b])
  4876. .collect()
  4877. } else {
  4878. vec![&lists[..]]
  4879. };
  4880. #[cfg(not(feature = "diagnostics"))]
  4881. let groups = [&lists[..]];
  4882. submitting(2, runs.len());
  4883. for (i, group) in groups.iter().enumerate() {
  4884. *submitted += 1;
  4885. let started = std::time::Instant::now();
  4886. // SAFETY: closed lists; the fence and event are ours.
  4887. unsafe {
  4888. self.queue.ExecuteCommandLists(group);
  4889. self.card_sent();
  4890. let waited = self
  4891. .queue
  4892. .Signal(&self.fence, *submitted)
  4893. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4894. match waited {
  4895. Ok(()) => {
  4896. working(false);
  4897. WaitForSingleObject(self.event, INFINITE);
  4898. stood(started);
  4899. working(true);
  4900. }
  4901. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4902. }
  4903. }
  4904. // With timing on each group is one of `runs` (and the compare
  4905. // of copies in the card's memory, with the last): every
  4906. // command's time on the card goes to the sums by pipeline.
  4907. #[cfg(feature = "diagnostics")]
  4908. if timing() {
  4909. // SAFETY: a plain query.
  4910. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4911. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4912. crate::copystat::command_took(&op, ms);
  4913. }
  4914. }
  4915. // A submission of one list was never named here (`groups.len()
  4916. // > 1` was the test): the two 50 ms lists of the gameplay
  4917. // frame, each a submission of its own, printed nothing.
  4918. #[cfg(feature = "diagnostics")]
  4919. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4920. // SAFETY: a plain query.
  4921. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4922. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4923. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4924. for (ms, op) in runs[i].slowest(frequency, 6) {
  4925. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4926. }
  4927. }
  4928. let _ = (i, started);
  4929. }
  4930. let _ = &firsts;
  4931. FINISHED.store(this_submission, Ordering::Release);
  4932. bury(this_submission);
  4933. let gpu = prepared.elapsed();
  4934. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4935. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4936. #[cfg(feature = "diagnostics")]
  4937. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4938. let pipelines: std::collections::BTreeSet<String> = runs
  4939. .iter()
  4940. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4941. .collect();
  4942. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  4943. text.chars().take(1200).collect()
  4944. });
  4945. // The host resets a device whose submission runs for about 2 s.
  4946. if gpu > std::time::Duration::from_millis(250) {
  4947. let pipelines: std::collections::BTreeSet<String> = runs
  4948. .iter()
  4949. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4950. .collect();
  4951. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  4952. }
  4953. // SAFETY: a plain query.
  4954. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4955. fail(format_args!(
  4956. "host GPU device removed after a submission of {} lists{}{}",
  4957. runs.len(),
  4958. self.removal_data(runs),
  4959. last_notes(runs)
  4960. ));
  4961. }
  4962. submitting(3, runs.len());
  4963. // What shaders wrote goes back before the bottom-of-pipe writes,
  4964. // which tell the title the GPU is done; each range once per
  4965. // submission, however many dispatches declared it (the world's
  4966. // passes declare the same big ranges dozens of times).
  4967. let copying = std::time::Instant::now();
  4968. // For copies in the card's memory the compare has run there: the
  4969. // pieces that differ are fetched and merged.
  4970. if let Some(card) = &card {
  4971. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  4972. }
  4973. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4974. hand_back(&back);
  4975. if let Some(card) = card {
  4976. self.card_done(card);
  4977. }
  4978. #[cfg(feature = "diagnostics")]
  4979. if !back.is_empty() {
  4980. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  4981. }
  4982. // Nothing of this submission goes back to the title: no range of
  4983. // shader writes, no value written when it is done. The wait for
  4984. // such a one is only for order and for what the card still holds.
  4985. #[cfg(feature = "diagnostics")]
  4986. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  4987. use crate::copystat::{C, add};
  4988. add(C::NothingBack, 1);
  4989. add(C::NothingBackUs, gpu.as_micros() as u64);
  4990. }
  4991. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4992. for list in runs {
  4993. // Read backs first: a value written at the bottom of the pipe
  4994. // may be what tells the title that they are there.
  4995. read_backs(list);
  4996. for &(at, what, bytes) in &list.deferred().writes {
  4997. what.write(at as *mut u8, bytes);
  4998. }
  4999. }
  5000. self.log_messages();
  5001. submitting(0, 0);
  5002. #[cfg(feature = "diagnostics")]
  5003. crate::copystat::submission_ends(lock);
  5004. // With the relay: nothing is in the air now, so no fetch still to
  5005. // be merged is older than the sends to card copies so far, and
  5006. // their notes can go.
  5007. if relay() {
  5008. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  5009. }
  5010. working(was_working);
  5011. None
  5012. }
  5013. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  5014. /// it lies in (by the names we give them) or the title memory copy just
  5015. /// below it; for each list that did not finish, the command it stopped
  5016. /// at and what the draws and dispatches in flight there run (or, in
  5017. /// lists that never started, the pipelines they bind).
  5018. fn removal_data(&self, runs: &[&HostList]) -> String {
  5019. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  5020. return String::new();
  5021. };
  5022. let mut text = String::new();
  5023. let mut fault_va = None;
  5024. // SAFETY: the outputs are the runtime's, valid while the device
  5025. // lives; nodes are walked as linked, histories have their counts.
  5026. unsafe {
  5027. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  5028. && fault.PageFaultVA != 0
  5029. {
  5030. let va = fault.PageFaultVA;
  5031. fault_va = Some(va);
  5032. text.push_str(&format!("; page fault at {va:#x}"));
  5033. for (what, head) in [
  5034. ("inside", fault.pHeadExistingAllocationNode),
  5035. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  5036. ] {
  5037. let mut names = Vec::new();
  5038. let mut node = head;
  5039. while let Some(n) = node.as_ref()
  5040. && names.len() < 8
  5041. {
  5042. let name = if n.ObjectNameW.is_null() {
  5043. "unnamed".to_owned()
  5044. } else {
  5045. n.ObjectNameW.to_string().unwrap_or_default()
  5046. };
  5047. names.push(format!("{name} (type {})", n.AllocationType.0));
  5048. node = n.pNext;
  5049. }
  5050. if !names.is_empty() {
  5051. text.push_str(&format!("; {what} {names:?}"));
  5052. }
  5053. }
  5054. text.push_str(&crate::shadow::near(va));
  5055. text.push_str(&crate::descriptor::host::near_heaps(va));
  5056. }
  5057. // The plain output: the extended one (with marker texts) came
  5058. // back without stopped lists on this host.
  5059. if dred_faults() {
  5060. return text;
  5061. }
  5062. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  5063. Ok(crumbs) => crumbs,
  5064. Err(e) => {
  5065. text.push_str(&format!("; no breadcrumbs ({e})"));
  5066. return text;
  5067. }
  5068. };
  5069. // Every list's progress (done/count), in the runtime's order.
  5070. let mut progress = Vec::new();
  5071. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  5072. while let Some(p) = node.as_ref() {
  5073. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5074. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  5075. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  5076. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  5077. node = p.pNext;
  5078. }
  5079. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  5080. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  5081. while let Some(p) = plain.as_ref() {
  5082. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5083. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  5084. let history =
  5085. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  5086. text.push_str(&format!(
  5087. "; a list stopped at command {done} of {} (op {})",
  5088. p.BreadcrumbCount, history[done as usize].0
  5089. ));
  5090. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  5091. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  5092. let named = [
  5093. (!p.pCommandListDebugNameW.is_null()).then(|| p.pCommandListDebugNameW.to_string().unwrap_or_default()),
  5094. (!p.pCommandListDebugNameA.is_null()).then(|| {
  5095. std::ffi::CStr::from_ptr(p.pCommandListDebugNameA.cast()).to_string_lossy().into_owned()
  5096. }),
  5097. ]
  5098. .into_iter()
  5099. .flatten()
  5100. .next()
  5101. .unwrap_or_default();
  5102. text.push_str(&format!(" of \"{named}\""));
  5103. // Not one of the caller's: by the name.
  5104. #[cfg(feature = "diagnostics")]
  5105. let by_name = list_number(&named).and_then(|n| {
  5106. let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  5107. all.get(&n).map(|(notes, pipelines, _)| (notes.upgrade(), pipelines.upgrade()))
  5108. });
  5109. #[cfg(feature = "diagnostics")]
  5110. let indirects = run.map(|r| r.indirects.clone()).or_else(|| {
  5111. let n = list_number(&named)?;
  5112. LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()).get(&n)?.2.upgrade()
  5113. });
  5114. #[cfg(not(feature = "diagnostics"))]
  5115. #[allow(clippy::type_complexity)]
  5116. let by_name: Option<(Option<()>, Option<std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>>)> = None;
  5117. #[cfg(feature = "diagnostics")]
  5118. let noted = run.map(|r| r.notes.clone()).or_else(|| by_name.as_ref().and_then(|b| b.0.clone()));
  5119. let bound = run.map(|r| r.pipelines.clone()).or_else(|| by_name.as_ref().and_then(|b| b.1.clone()));
  5120. // The k-th marker command is the k-th note.
  5121. #[cfg(feature = "diagnostics")]
  5122. let markers: Vec<(u32, String)> = noted.map_or_else(Vec::new, |notes| {
  5123. let notes = notes.lock().unwrap_or_else(|e| e.into_inner());
  5124. history
  5125. .iter()
  5126. .enumerate()
  5127. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  5128. .zip(notes.iter())
  5129. .map(|((at, _), (note, range))| {
  5130. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  5131. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  5132. })
  5133. .collect()
  5134. });
  5135. #[cfg(not(feature = "diagnostics"))]
  5136. let markers: Vec<(u32, String)> = Vec::new();
  5137. #[cfg(not(feature = "diagnostics"))]
  5138. let _ = fault_va;
  5139. if done > 0 {
  5140. text.push_str(&in_flight(history, &markers, done as usize));
  5141. }
  5142. #[cfg(feature = "diagnostics")]
  5143. if let Some(indirects) = indirects {
  5144. text.push_str(&indirects_around(history, done as usize, &indirects));
  5145. }
  5146. // (Without markers a list that stopped midway says what
  5147. // it may have been at only by what it binds.)
  5148. if (done == 0 || markers.is_empty())
  5149. && let Some(bound) = bound
  5150. {
  5151. let pipelines = bound.lock().unwrap_or_else(|e| e.into_inner());
  5152. text.push_str(&format!(", its pipelines {pipelines:?}"));
  5153. }
  5154. }
  5155. plain = p.pNext;
  5156. }
  5157. }
  5158. text
  5159. }
  5160. /// Moves the debug layer's messages into our log; returns the first
  5161. /// error among them.
  5162. pub(crate) fn log_messages(&self) -> Option<String> {
  5163. let Some(queue) = &self.messages else {
  5164. return None;
  5165. };
  5166. let mut first_error = None;
  5167. // SAFETY: each message is read into a buffer of the size the queue
  5168. // reports, then the queue is emptied.
  5169. unsafe {
  5170. for i in 0..queue.GetNumStoredMessages() {
  5171. let mut size = 0;
  5172. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  5173. continue;
  5174. }
  5175. let mut buffer = vec![0u64; size.div_ceil(8)];
  5176. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  5177. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  5178. let m = &*message;
  5179. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  5180. let text = String::from_utf8_lossy(text);
  5181. let text = text.trim_end_matches('\0');
  5182. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  5183. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  5184. first_error = Some(text.to_owned());
  5185. }
  5186. }
  5187. }
  5188. queue.ClearStoredMessages();
  5189. }
  5190. first_error
  5191. }
  5192. /// A host render target view of `resource`, valid until it is recorded.
  5193. pub(crate) fn rtv(
  5194. &self,
  5195. resource: Option<&ID3D12Resource>,
  5196. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  5197. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5198. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5199. // SAFETY: a slot of our heap and a live resource, or none with a
  5200. // description (a typed null view).
  5201. unsafe {
  5202. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  5203. handle.ptr += (slot * self.rtv_size) as usize;
  5204. self.device
  5205. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  5206. handle
  5207. }
  5208. }
  5209. /// A host depth view of `resource`, valid until it is recorded.
  5210. pub(crate) fn dsv(
  5211. &self,
  5212. resource: &ID3D12Resource,
  5213. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  5214. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5215. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5216. // SAFETY: a slot of our heap and a live resource.
  5217. unsafe {
  5218. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  5219. handle.ptr += (slot * self.dsv_size) as usize;
  5220. self.device
  5221. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  5222. handle
  5223. }
  5224. }
  5225. }
  5226. impl HostList {
  5227. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  5228. #[cfg(feature = "diagnostics")]
  5229. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  5230. if !timing() {
  5231. return None;
  5232. }
  5233. self.stamps
  5234. .get_or_init(|| {
  5235. let device = &host()?.device;
  5236. let mut heap: Option<ID3D12QueryHeap> = None;
  5237. let mut back: Option<ID3D12Resource> = None;
  5238. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  5239. let desc = D3D12_RESOURCE_DESC {
  5240. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5241. Width: u64::from(STAMPS) * 8,
  5242. Height: 1,
  5243. DepthOrArraySize: 1,
  5244. MipLevels: 1,
  5245. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  5246. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5247. ..Default::default()
  5248. };
  5249. // SAFETY: plain object creation.
  5250. unsafe {
  5251. device
  5252. .CreateQueryHeap(
  5253. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  5254. &mut heap,
  5255. )
  5256. .ok()?;
  5257. device
  5258. .CreateCommittedResource(
  5259. &readback,
  5260. D3D12_HEAP_FLAG_NONE,
  5261. &desc,
  5262. D3D12_RESOURCE_STATE_COPY_DEST,
  5263. None,
  5264. &mut back,
  5265. )
  5266. .ok()?;
  5267. }
  5268. Some((heap?, back?))
  5269. })
  5270. .as_ref()
  5271. }
  5272. /// The noted commands that took longest on the GPU, longest first, as
  5273. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  5274. #[cfg(feature = "diagnostics")]
  5275. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  5276. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  5277. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  5278. return Vec::new();
  5279. };
  5280. let mut data = std::ptr::null_mut();
  5281. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  5282. // SAFETY: a read-back buffer the finished list resolved into.
  5283. let stamps: Vec<u64> = unsafe {
  5284. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  5285. return Vec::new();
  5286. }
  5287. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  5288. back.Unmap(0, None);
  5289. s
  5290. };
  5291. let mut times: Vec<(f64, String)> = (0..count)
  5292. .map(|i| {
  5293. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5294. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5295. })
  5296. .collect();
  5297. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5298. times.truncate(n);
  5299. times
  5300. }
  5301. pub(crate) fn close(&self) {
  5302. self.twins_to_depth();
  5303. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5304. if let Some((scratch, _)) = scratch {
  5305. self.indirect_common(&scratch);
  5306. }
  5307. self.batches_common();
  5308. self.card_budget_out();
  5309. #[cfg(feature = "diagnostics")]
  5310. if let Some((heap, back)) = self.stamps() {
  5311. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5312. // SAFETY: an open list, our heap and read-back buffer.
  5313. unsafe {
  5314. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5315. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5316. }
  5317. }
  5318. // SAFETY: our list.
  5319. if let Err(e) = unsafe { self.list.Close() } {
  5320. fail(format_args!(
  5321. "a host command list did not close ({e}): a command recorded into it was invalid"
  5322. ));
  5323. }
  5324. }
  5325. /// Only after the list's last submission finished (every one is waited
  5326. /// for).
  5327. pub(crate) fn reset(&self) {
  5328. #[cfg(feature = "diagnostics")]
  5329. let started = std::time::Instant::now();
  5330. self._alive.used();
  5331. *self.deferred() = Deferred::default();
  5332. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5333. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5334. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5335. #[cfg(feature = "diagnostics")]
  5336. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5337. #[cfg(feature = "diagnostics")]
  5338. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5339. {
  5340. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5341. (scratch.current, scratch.used) = (0, 0);
  5342. // Every submission of the list has run: nothing reads its
  5343. // scratch memory any more, and the next list to ask takes it.
  5344. if scratch_pool() {
  5345. give_chunks(std::mem::take(&mut scratch.chunks));
  5346. }
  5347. }
  5348. // SAFETY: the list is not executing.
  5349. let reset = unsafe {
  5350. self.allocator
  5351. .Reset()
  5352. .and_then(|()| self.list.Reset(&self.allocator, None))
  5353. };
  5354. if let Err(e) = reset {
  5355. fail(format_args!("a host command list did not reset ({e})"));
  5356. }
  5357. #[cfg(feature = "diagnostics")]
  5358. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5359. }
  5360. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5361. /// list: the host texture and the state it leaves, if that is a change.
  5362. /// The list's first use of a texture records nothing: its prelude brings
  5363. /// the texture there at submission.
  5364. pub(crate) fn transition(
  5365. &self,
  5366. resource: crate::object::This,
  5367. wanted: u32,
  5368. ) -> Option<(&'static ID3D12Resource, u32)> {
  5369. let texture = crate::resource::host_resource(resource)?;
  5370. let copy = crate::resource::host_copy(resource)?;
  5371. let wanted = legal_state(texture, wanted);
  5372. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5373. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5374. std::collections::hash_map::Entry::Vacant(v) => {
  5375. v.insert((wanted, wanted, copy));
  5376. None
  5377. }
  5378. std::collections::hash_map::Entry::Occupied(mut o) => {
  5379. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5380. (before != wanted).then_some((texture, before))
  5381. }
  5382. }
  5383. }
  5384. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5385. /// as [`HostList::transition`] does a title resource's host copy, and
  5386. /// records the barrier: for textures that are not a title resource's
  5387. /// host copy (colour twins) and for the copies between the two.
  5388. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5389. let wanted = legal_state(&copy.texture, wanted);
  5390. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5391. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5392. std::collections::hash_map::Entry::Vacant(v) => {
  5393. v.insert((wanted, wanted, copy.clone()));
  5394. None
  5395. }
  5396. std::collections::hash_map::Entry::Occupied(mut o) => {
  5397. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5398. (before != wanted).then_some(before)
  5399. }
  5400. };
  5401. drop(states);
  5402. if let Some(before) = before {
  5403. let barrier = transition(
  5404. &copy.texture,
  5405. D3D12_RESOURCE_STATES(before as i32),
  5406. D3D12_RESOURCE_STATES(wanted as i32),
  5407. );
  5408. // SAFETY: an open list and a live texture.
  5409. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5410. }
  5411. }
  5412. /// A use of title texture `resource` about to be recorded, if it is a
  5413. /// depth texture with a colour twin (false if it is not): of the twin
  5414. /// (`colour`: unordered access) or of the depth texture (depth target,
  5415. /// clear, shader read, copy, resolve), writing it or only reading. The
  5416. /// side used is first brought up to date: by a copy recorded here if
  5417. /// this list wrote the other side since, by the list's prelude if the
  5418. /// list uses the side as it finds it. The twin is left in the
  5419. /// unordered access state; the caller moves the depth texture to the
  5420. /// state its use needs, as for any texture. A twin still ahead when the
  5421. /// list closes is copied then (`twins_to_depth`).
  5422. /// shortcut: every depth target bound for a draw counts as written
  5423. /// (also when the draw only tests), and every unordered access view a
  5424. /// shader names as written; views a shader picks from the heap by a
  5425. /// computed index are not seen here at all.
  5426. pub(crate) fn twin_use(
  5427. &self,
  5428. resource: crate::object::This,
  5429. colour: bool,
  5430. write: bool,
  5431. ) -> bool {
  5432. const UNORDERED_ACCESS: u32 = 0x8;
  5433. // Asked for every texture a draw reads: most have no twin.
  5434. let Some(twin) = crate::resource::twin(resource) else {
  5435. return false;
  5436. };
  5437. let Some(depth) = crate::resource::host_copy(resource) else {
  5438. return false;
  5439. };
  5440. let side = usize::from(colour);
  5441. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5442. let u = twins
  5443. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5444. .or_insert_with(|| TwinUse {
  5445. depth: depth.clone(),
  5446. twin: twin.clone(),
  5447. needs: [false; 2],
  5448. behind: [None; 2],
  5449. writing: false,
  5450. late: false,
  5451. });
  5452. let copy = match u.behind[side] {
  5453. Some(behind) => behind,
  5454. None => {
  5455. u.needs[side] = true;
  5456. false
  5457. }
  5458. };
  5459. u.behind[side] = Some(false);
  5460. match (write, colour) {
  5461. // Shaders write the twin when the draw or dispatch runs: what
  5462. // the same one reads of the depth texture is prepared before
  5463. // (`twins_written`).
  5464. (true, true) => u.writing = true,
  5465. (true, false) => u.behind[1] = Some(true),
  5466. (false, _) => {}
  5467. }
  5468. // shortcut: the depth plane's twin is not drawn into the plane
  5469. // here: the pass sets a pipeline and a target of ours, which a list
  5470. // still recording the title's commands cannot take. This use sees
  5471. // the plane as it was; the pass runs when the list closes
  5472. // (`twins_to_depth`). Counted.
  5473. if copy && !colour && twin.plane.is_some() {
  5474. u.late = true;
  5475. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5476. }
  5477. drop(twins);
  5478. if copy {
  5479. self.twin_copy(&depth, &twin, colour);
  5480. } else if colour {
  5481. self.settle(&twin.colour, UNORDERED_ACCESS);
  5482. }
  5483. // The depth plane's twin is written through unordered access too.
  5484. if colour && let Some(plane) = &twin.plane {
  5485. self.settle(plane, UNORDERED_ACCESS);
  5486. }
  5487. true
  5488. }
  5489. /// Records the pass that draws the twin of the depth plane of `depth`
  5490. /// into the plane, if `twin` has one, with the moves to the states the
  5491. /// pass needs; the twin is left in the unordered access state. Only
  5492. /// for a list that records nothing of the title's afterwards
  5493. /// (`record_plane_pass`).
  5494. fn pass_plane(
  5495. &self,
  5496. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5497. twin: &crate::resource::Twin,
  5498. ) {
  5499. const UNORDERED_ACCESS: u32 = 0x8;
  5500. const DEPTH_WRITE: u32 = 0x10;
  5501. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5502. let Some(plane) = &twin.plane else { return };
  5503. self.settle(depth, DEPTH_WRITE);
  5504. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5505. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5506. self.settle(plane, UNORDERED_ACCESS);
  5507. }
  5508. /// Records the copy of a depth texture into its colour twin (`colour`)
  5509. /// or of the twin into the depth texture, with the moves to the copy
  5510. /// states. The twin is left in the unordered access state.
  5511. fn twin_copy(
  5512. &self,
  5513. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5514. twin: &crate::resource::Twin,
  5515. colour: bool,
  5516. ) {
  5517. const UNORDERED_ACCESS: u32 = 0x8;
  5518. const COPY_DEST: u32 = 0x400;
  5519. const COPY_SOURCE: u32 = 0x800;
  5520. let (from, to) = if colour {
  5521. (depth, &twin.colour)
  5522. } else {
  5523. (&twin.colour, depth)
  5524. };
  5525. self.settle(from, COPY_SOURCE);
  5526. self.settle(to, COPY_DEST);
  5527. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5528. self.settle(&twin.colour, UNORDERED_ACCESS);
  5529. }
  5530. /// Before the list closes: the depth textures whose twins it wrote last
  5531. /// are given what was written, and left readable by shaders. Shaders
  5532. /// that pick a view from the heap by a computed index are not seen by
  5533. /// `twin_use` and read the depth texture in lists that never name it
  5534. /// (in a captured frame of the title no table names a shadow
  5535. /// map for reading but the pass that fills the next one).
  5536. fn twins_to_depth(&self) {
  5537. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5538. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5539. let written: Vec<_> = twins
  5540. .values_mut()
  5541. .filter(|u| u.behind[0] == Some(true) || u.late)
  5542. .map(|u| {
  5543. // Not copied again if the list copied since the last write
  5544. // and only the depth plane's pass is left.
  5545. let copy = u.behind[0] == Some(true);
  5546. u.behind[0] = Some(false);
  5547. u.late = false;
  5548. (u.depth.clone(), u.twin.clone(), copy)
  5549. })
  5550. .collect();
  5551. drop(twins);
  5552. for (depth, twin, copy) in &written {
  5553. if *copy {
  5554. self.twin_copy(depth, twin, false);
  5555. }
  5556. // Nothing of the title's is recorded after this: the pass may
  5557. // leave its own pipeline and target set.
  5558. self.pass_plane(depth, twin);
  5559. self.settle(depth, SHADER_RESOURCE);
  5560. }
  5561. }
  5562. /// The draw or dispatch just prepared is recorded: the twins it writes
  5563. /// now hold what their depth textures lack.
  5564. pub(crate) fn twins_written(&self) {
  5565. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5566. for u in twins.values_mut().filter(|u| u.writing) {
  5567. u.writing = false;
  5568. u.behind[0] = Some(true);
  5569. }
  5570. }
  5571. /// At submission: the list that moves each texture this list uses from
  5572. /// its real state to the one the list starts with; the textures' real
  5573. /// states become those the list ends with. For depth textures with a
  5574. /// colour twin it first copies the side the list uses as it finds it
  5575. /// from the other, if a list submitted earlier left it behind.
  5576. fn prelude(&self) -> Option<ID3D12CommandList> {
  5577. const COPY_DEST: u32 = 0x400;
  5578. const COPY_SOURCE: u32 = 0x800;
  5579. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5580. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5581. // The copies (depth texture, twin, whether into the twin); the
  5582. // sides are then as this list leaves them.
  5583. let mut syncs = Vec::new();
  5584. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5585. for u in twins.values() {
  5586. let real = u.twin.behind.load(Ordering::Relaxed);
  5587. let mut behind = [real & 1 != 0, real & 2 != 0];
  5588. for side in [0, 1] {
  5589. if u.needs[side] && behind[side] {
  5590. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5591. behind = [false; 2];
  5592. }
  5593. }
  5594. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5595. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5596. u.twin.behind.store(left, Ordering::Relaxed);
  5597. }
  5598. drop(twins);
  5599. // A copy runs with its textures in the copy states: each moves
  5600. // there from its real state, and from there to the state the list
  5601. // starts with (back to its real state if the list does not use it).
  5602. let mut to_copy = Vec::new();
  5603. let mut barriers = Vec::new();
  5604. let mut copying = std::collections::HashMap::new();
  5605. for (depth, twin, colour) in &syncs {
  5606. let (from, to) = if *colour {
  5607. (depth, &twin.colour)
  5608. } else {
  5609. (&twin.colour, depth)
  5610. };
  5611. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  5612. let key = std::sync::Arc::as_ptr(texture) as usize;
  5613. let real = texture.state.load(Ordering::Relaxed);
  5614. copying.insert(key, state);
  5615. if real != state {
  5616. to_copy.push(transition(
  5617. &texture.texture,
  5618. host_state(real),
  5619. host_state(state),
  5620. ));
  5621. if !states.contains_key(&key) {
  5622. barriers.push(transition(
  5623. &texture.texture,
  5624. host_state(state),
  5625. host_state(real),
  5626. ));
  5627. }
  5628. }
  5629. }
  5630. }
  5631. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5632. let real = copy.state.swap(*last, Ordering::Relaxed);
  5633. let real = copying.get(key).copied().unwrap_or(real);
  5634. (real != *first)
  5635. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5636. }));
  5637. if barriers.is_empty() && syncs.is_empty() {
  5638. return None;
  5639. }
  5640. let Some((allocator, list)) = self
  5641. .prelude
  5642. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5643. .as_ref()
  5644. else {
  5645. fail(format_args!("no host list for a state prelude"));
  5646. };
  5647. // SAFETY: the prelude is not executing (every submission is waited
  5648. // for); the textures are live.
  5649. let recorded = unsafe {
  5650. allocator.Reset().and_then(|()| {
  5651. list.Reset(allocator, None)?;
  5652. if !to_copy.is_empty() {
  5653. list.ResourceBarrier(&to_copy);
  5654. }
  5655. for (depth, twin, colour) in &syncs {
  5656. record_twin_copy(list, &depth.texture, twin, *colour);
  5657. }
  5658. if !barriers.is_empty() {
  5659. list.ResourceBarrier(&barriers);
  5660. }
  5661. list.Close()
  5662. })
  5663. };
  5664. if let Err(e) = recorded {
  5665. fail(format_args!("a host state prelude did not record ({e})"));
  5666. }
  5667. list.cast().ok()
  5668. }
  5669. /// Notes what the command about to be recorded does, as a marker
  5670. /// command whose text the list keeps (diagnostics, with device-removed
  5671. /// data on): the report pairs the breadcrumbs' marker commands with the
  5672. /// texts in order and names the commands a fault stopped among.
  5673. #[cfg(feature = "diagnostics")]
  5674. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5675. self.note(what, None);
  5676. }
  5677. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5678. /// `(address, bytes)`: the report places the faulting address in it.
  5679. #[cfg(feature = "diagnostics")]
  5680. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5681. self.note(what, Some(range));
  5682. }
  5683. #[cfg(feature = "diagnostics")]
  5684. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5685. if !dred_on() {
  5686. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5687. return;
  5688. }
  5689. {
  5690. let started = std::time::Instant::now();
  5691. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5692. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5693. // SAFETY: an open list and our query heap.
  5694. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5695. }
  5696. let what = what();
  5697. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5698. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5699. const UNICODE: u32 = 0;
  5700. // SAFETY: an open list; the marker is copied when recorded.
  5701. unsafe {
  5702. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5703. };
  5704. self.notes
  5705. .lock()
  5706. .unwrap_or_else(|e| e.into_inner())
  5707. .push((what, range));
  5708. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5709. }
  5710. }
  5711. /// Whether nothing recorded since the list was opened does any work:
  5712. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5713. /// upload or resolve (they defer a step or move a texture's state), no
  5714. /// bottom-of-pipe write. State set on the list does not count.
  5715. pub(crate) fn untouched(&self) -> bool {
  5716. {
  5717. let deferred = self.deferred();
  5718. if !(deferred.copies.is_empty()
  5719. && deferred.uploads.is_empty()
  5720. && deferred.kept.is_empty()
  5721. && deferred.textures.is_empty()
  5722. && deferred.writes.is_empty()
  5723. && deferred.backs.is_empty())
  5724. {
  5725. return false;
  5726. }
  5727. }
  5728. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5729. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5730. }
  5731. /// Notes an indirect execution, while device-removed data is kept
  5732. /// ([`indirects`]).
  5733. #[cfg(feature = "diagnostics")]
  5734. pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) {
  5735. if dred_on() || dred_light() {
  5736. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user);
  5737. }
  5738. }
  5739. /// Notes a pipeline the list binds.
  5740. pub(crate) fn used_pipeline(&self, name: &str) {
  5741. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5742. if !pipelines.contains(name) {
  5743. pipelines.insert(name.to_owned());
  5744. }
  5745. }
  5746. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5747. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5748. }
  5749. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5750. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5751. let mut deferred = self.deferred();
  5752. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5753. // A copy that goes on where the one recorded just before it ended,
  5754. // source and destination both: with `join_copies` the two are one
  5755. // step.
  5756. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5757. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5758. {
  5759. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5760. if join_copies() {
  5761. *n += len;
  5762. return;
  5763. }
  5764. }
  5765. deferred
  5766. .copies
  5767. .push(Step::Copy(dst as usize, src as usize, len));
  5768. deferred.refreshed.clear();
  5769. }
  5770. /// Copies `len` bytes of title memory at `src` into the list's upload
  5771. /// memory at `dst` when the list is submitted.
  5772. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5773. self.deferred()
  5774. .copies
  5775. .push(Step::Fill(dst as usize, src as usize, len, None));
  5776. }
  5777. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5778. /// title heap's address, and the slot) shows.
  5779. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5780. self.deferred()
  5781. .copies
  5782. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  5783. }
  5784. /// As [`HostList::defer_fill`], for the beginning of a buffer
  5785. /// [`HostList::upload`] made.
  5786. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  5787. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  5788. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  5789. }
  5790. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5791. /// when the list is submitted (once per range until a title copy
  5792. /// intervenes), keeping the copy alive until the list is reset.
  5793. pub(crate) fn defer_refresh(
  5794. &self,
  5795. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5796. address: usize,
  5797. len: usize,
  5798. ) {
  5799. let mut deferred = self.deferred();
  5800. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5801. if deferred.refreshed.insert(key) {
  5802. deferred
  5803. .copies
  5804. .push(Step::Refresh(shadow.clone(), address, len));
  5805. }
  5806. }
  5807. /// Shaders of the list write `[address, address + len)` of a buffer's
  5808. /// host copy: copied back into title memory once the list has run.
  5809. pub(crate) fn defer_gpu_write(
  5810. &self,
  5811. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5812. address: usize,
  5813. len: usize,
  5814. ) {
  5815. self.deferred()
  5816. .copies
  5817. .push(Step::GpuWrite(shadow.clone(), address, len));
  5818. }
  5819. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5820. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5821. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5822. /// the list is reset.
  5823. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5824. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5825. }
  5826. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5827. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5828. self.deferred().writes.push((dst as usize, what, bytes));
  5829. }
  5830. /// A mapped upload buffer of `size` bytes, alive until the list is
  5831. /// reset.
  5832. ///
  5833. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5834. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5835. // With [`card_steps`] the card may be the one that fills it.
  5836. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  5837. name(&buffer, || format!("list upload {size:#x}"));
  5838. self.deferred().hold_upload(buffer.clone(), size);
  5839. Some((buffer, data))
  5840. }
  5841. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5842. /// reset: the host GPU address and the CPU pointer.
  5843. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5844. let (buffer, at, data) = self.scratch_at(len)?;
  5845. // SAFETY: a live buffer.
  5846. Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data))
  5847. }
  5848. /// [`HostList::scratch`] and the buffer it lies in, for a descriptor
  5849. /// slot to hold: the slot outlives the list's use of it.
  5850. pub(crate) fn scratch_held(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  5851. let (buffer, at, data) = self.scratch_at(len)?;
  5852. // SAFETY: a live buffer.
  5853. let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at;
  5854. Some((buffer, gpu, data))
  5855. }
  5856. /// [`HostList::scratch`]: the buffer, the offset in it and the CPU
  5857. /// pointer.
  5858. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  5859. let host = host()?;
  5860. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5861. let len = len.max(1).next_multiple_of(256);
  5862. if len > SCRATCH_CHUNK {
  5863. let (buffer, data) = host.upload_buffer(len)?;
  5864. name(&buffer, || format!("list scratch {len:#x}"));
  5865. self.deferred().hold_upload(buffer.clone(), len);
  5866. return Some((buffer, 0, data));
  5867. }
  5868. // The chunk in use while `len` fits in what is left of it, else the
  5869. // next one (a list's first chunk may be a small one).
  5870. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5871. (s.current, s.used) = (s.current + 1, 0);
  5872. }
  5873. if s.current == s.chunks.len() {
  5874. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  5875. SCRATCH_FIRST
  5876. } else {
  5877. SCRATCH_CHUNK
  5878. };
  5879. let chunk = take_chunk(host, size)?;
  5880. s.chunks.push((chunk, size));
  5881. s.used = 0;
  5882. }
  5883. let (data, buffer) = (s.chunks[s.current].0.data, s.chunks[s.current].0.buffer.clone());
  5884. let at = s.used;
  5885. s.used += len;
  5886. Some((buffer, at, (data + at as usize) as *mut u8))
  5887. }
  5888. /// The bytes of scratch chunks the list holds now (after a reset:
  5889. /// none while lists share their chunks).
  5890. pub(crate) fn scratch_kept(&self) -> u64 {
  5891. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5892. scratch.chunks.iter().map(|c| c.1).sum()
  5893. }
  5894. /// The host address of the list's indirect-work budget, zeroed at each
  5895. /// submission of the list from the first use after a reset on.
  5896. pub(crate) fn budget(&self) -> Option<u64> {
  5897. let (buffer, data) = self
  5898. .budget
  5899. .get_or_init(|| {
  5900. let (b, d) = host()?.shared_buffer(256)?;
  5901. Some((b, d as usize))
  5902. })
  5903. .as_ref()?;
  5904. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5905. let mut deferred = self.deferred();
  5906. if !deferred.budget_zeroed {
  5907. deferred.budget_zeroed = true;
  5908. let at = *data;
  5909. // SAFETY: the list's own mapped words, written before it runs.
  5910. // The words after the budget hold what the clamp noted about the
  5911. // list's last run (mesh dispatches: the largest group count
  5912. // asked for, the groups asked in all; with the card's copy, as
  5913. // the list's end copied them here): taken, then zeroed.
  5914. let notes = Box::new(move || unsafe {
  5915. let words = at as *mut u32;
  5916. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  5917. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  5918. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  5919. for k in 0..3 {
  5920. words.add(k).write_volatile(0);
  5921. }
  5922. });
  5923. deferred.copies.push(Step::Host(notes, (0, 0)));
  5924. drop(deferred);
  5925. if let Some(card) = card {
  5926. self.zero_card_budget(card);
  5927. }
  5928. }
  5929. // SAFETY: a live buffer.
  5930. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  5931. }
  5932. /// The budget's words in the card's own memory ([`card_budget`]), if
  5933. /// the list can zero them itself (`WriteBufferImmediate`).
  5934. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  5935. if !card_budget() {
  5936. return None;
  5937. }
  5938. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  5939. let buffer = host()?.uav_buffer(256)?;
  5940. name(&buffer, || "indirect budget".to_owned());
  5941. Some(buffer)
  5942. }
  5943. /// Records, before the list's first clamp, the zeroing of the card's
  5944. /// copy of the budget: common, written as a copy, then left for
  5945. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  5946. fn zero_card_budget(&self, card: &ID3D12Resource) {
  5947. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  5948. return;
  5949. };
  5950. // SAFETY: a live buffer.
  5951. let at = unsafe { card.GetGPUVirtualAddress() };
  5952. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  5953. Dest: at + offset,
  5954. Value: 0,
  5955. });
  5956. // SAFETY: an open list; the buffer is the list's own and in the
  5957. // common state at the start of every recording.
  5958. unsafe {
  5959. self.list.ResourceBarrier(&[transition(
  5960. card,
  5961. D3D12_RESOURCE_STATE_COMMON,
  5962. D3D12_RESOURCE_STATE_COPY_DEST,
  5963. )]);
  5964. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  5965. self.list.ResourceBarrier(&[transition(
  5966. card,
  5967. D3D12_RESOURCE_STATE_COPY_DEST,
  5968. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5969. )]);
  5970. }
  5971. }
  5972. /// Before the list closes, if this recording charged the card's copy
  5973. /// of the budget: its notes on mesh records go to the mapped words
  5974. /// (read at the next submission), and it goes back to common.
  5975. fn card_budget_out(&self) {
  5976. if !self.deferred().budget_zeroed {
  5977. return;
  5978. }
  5979. let (Some(Some(card)), Some(Some((mapped, _)))) =
  5980. (self.card_budget.get(), self.budget.get())
  5981. else {
  5982. return;
  5983. };
  5984. // SAFETY: an open list; both buffers are the list's own. The
  5985. // mapped one is promoted from common to the copy destination.
  5986. unsafe {
  5987. self.list.ResourceBarrier(&[transition(
  5988. card,
  5989. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5990. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5991. )]);
  5992. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  5993. self.list.ResourceBarrier(&[transition(
  5994. card,
  5995. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5996. D3D12_RESOURCE_STATE_COMMON,
  5997. )]);
  5998. }
  5999. }
  6000. /// A device-local unordered-access buffer of at least `size` bytes for
  6001. /// clamped indirect arguments, reused across executions and resets of the
  6002. /// list. Smaller buffers replaced mid-list stay alive until
  6003. /// [`HostList::reset`].
  6004. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  6005. let needed = size.max(64 << 10);
  6006. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  6007. if let Some((buffer, cap)) = &*slot
  6008. && *cap >= needed
  6009. {
  6010. return Some(buffer.clone());
  6011. }
  6012. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  6013. let alloc = prev
  6014. .saturating_mul(2)
  6015. .max(needed)
  6016. .next_multiple_of(64 << 10);
  6017. let buffer = host()?.uav_buffer(alloc)?;
  6018. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  6019. let old = slot.replace((buffer.clone(), alloc));
  6020. drop(slot);
  6021. if let Some((old_buf, _)) = old {
  6022. // It ends the list common, as every scratch buffer does.
  6023. self.indirect_common(&old_buf);
  6024. self.keep(&old_buf);
  6025. }
  6026. Some(buffer)
  6027. }
  6028. /// Where the next batch of clamped records goes: a device-local buffer
  6029. /// the list keeps from recording to recording, the batch's place in it
  6030. /// and the state the buffer is in. Every batch of a recording has a place
  6031. /// of its own: the executions before it may still read theirs.
  6032. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  6033. use crate::indirect::batch::{JOBS, SLOT};
  6034. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6035. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  6036. if buffer == args.0.len() {
  6037. let size = u64::from(BATCHES * JOBS * SLOT);
  6038. let made = host()?.uav_buffer(size)?;
  6039. name(&made, || format!("indirect batches {size:#x}"));
  6040. args.0.push(made);
  6041. }
  6042. args.1 += 1;
  6043. // (Its first batch finds it as the recording before left it:
  6044. // `batches_common`.)
  6045. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  6046. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  6047. }
  6048. /// Before the list closes: the scratch buffers of the batched clamps go
  6049. /// back to the common state, where the next recording expects them.
  6050. fn batches_common(&self) {
  6051. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6052. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  6053. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  6054. .iter()
  6055. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  6056. .collect();
  6057. if !barriers.is_empty() {
  6058. // SAFETY: an open list and live buffers this recording left in
  6059. // `INDIRECT_ARGUMENT`.
  6060. unsafe { self.list.ResourceBarrier(&barriers) };
  6061. }
  6062. }
  6063. /// Moves `scratch` back to the common state if a clamp left it readable
  6064. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  6065. /// list's first clamp expects it. Done before the list closes and before
  6066. /// a bigger scratch buffer replaces it: one barrier per list (where
  6067. /// there was one per indirect execution), and the list ends as it
  6068. /// begins however it is submitted.
  6069. fn indirect_common(&self, scratch: &ID3D12Resource) {
  6070. {
  6071. let mut deferred = self.deferred();
  6072. if deferred.indirect_readable != scratch.as_raw() as usize {
  6073. return;
  6074. }
  6075. deferred.indirect_readable = 0;
  6076. }
  6077. let barrier = transition(
  6078. scratch,
  6079. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  6080. D3D12_RESOURCE_STATE_COMMON,
  6081. );
  6082. // SAFETY: an open list and a live buffer this recording left in
  6083. // `INDIRECT_ARGUMENT`.
  6084. unsafe { self.list.ResourceBarrier(&[barrier]) };
  6085. }
  6086. /// The state the list's indirect scratch buffer `scratch` is in at this
  6087. /// point of the recording: indirect arguments if a clamp in this
  6088. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  6089. /// common: the state a buffer is made in, and the one a recording
  6090. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  6091. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  6092. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  6093. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  6094. } else {
  6095. D3D12_RESOURCE_STATE_COMMON
  6096. }
  6097. }
  6098. /// A clamp recorded in this list left `scratch` readable as indirect
  6099. /// arguments. It stays so for every execution that reads it, until the
  6100. /// next clamp moves it back to unordered access.
  6101. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  6102. self.deferred().indirect_readable = scratch.as_raw() as usize;
  6103. }
  6104. /// Keeps `object` alive until the list is reset.
  6105. pub(crate) fn keep(&self, object: &impl Interface) {
  6106. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  6107. self.deferred().kept.push(object);
  6108. }
  6109. }
  6110. /// Whether this is the first time since the reset that the list asks
  6111. /// about `key` (a texture to bring up to date).
  6112. pub(crate) fn first_use(&self, key: usize) -> bool {
  6113. self.deferred().textures.insert(key)
  6114. }
  6115. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  6116. /// reset.
  6117. pub(crate) fn used(&self, key: usize) -> bool {
  6118. self.deferred().textures.contains(&key)
  6119. }
  6120. /// Runs `work` when the list is submitted, in order with its copies.
  6121. /// `work` may write title memory (refreshes after it copy again).
  6122. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  6123. self.deferred().copies.push(Step::Run(Box::new(work)));
  6124. self.deferred().refreshed.clear();
  6125. }
  6126. /// As [`HostList::defer`], for work that writes only host memory.
  6127. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  6128. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  6129. }
  6130. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  6131. /// memory at `from`.
  6132. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  6133. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  6134. }
  6135. /// Brings a texture's staging buffer up to date when the list is
  6136. /// submitted, keeping it alive until the list is reset.
  6137. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  6138. self.deferred().copies.push(Step::Texture(staging));
  6139. }
  6140. /// Runs the list's submission-time steps; refreshes go into `batch`
  6141. /// (the title's big buffers, a 174 MB one among them, are read by most
  6142. /// lists of a submission, through many ranges). Copies and fills that
  6143. /// `taken` names (by their place) are left out: they are done on the
  6144. /// card ([`card_steps`]).
  6145. fn run_deferred(&self, batch: &mut Batch, air: &[(usize, usize)], taken: impl Fn(usize) -> bool) {
  6146. #[cfg(feature = "diagnostics")]
  6147. use crate::copystat::{C, add};
  6148. // The time and the bytes of the copies and fills, some 13,000 a
  6149. // frame between 20,000 refreshes: summed here and added once.
  6150. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  6151. #[cfg(feature = "diagnostics")]
  6152. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  6153. for (i, step) in self.deferred().copies.iter().enumerate() {
  6154. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  6155. continue;
  6156. }
  6157. let (started, copied) = match step {
  6158. &Step::Copy(dst, src, len) => {
  6159. let started = std::time::Instant::now();
  6160. #[cfg(feature = "diagnostics")]
  6161. {
  6162. copies += 1;
  6163. }
  6164. batch.title_written();
  6165. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  6166. // With the submission's one asking: the journal learns it.
  6167. crate::watch::wrote(dst, len);
  6168. // What the card holds there may be another value although
  6169. // ours did not change.
  6170. if send::own() {
  6171. crate::shadow::send_copied(dst, len);
  6172. }
  6173. (started, len)
  6174. }
  6175. &Step::Fill(dst, src, len, _) => {
  6176. let started = std::time::Instant::now();
  6177. #[cfg(feature = "diagnostics")]
  6178. {
  6179. copies += 1;
  6180. }
  6181. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6182. (started, len)
  6183. }
  6184. Step::Placed(p) => {
  6185. let started = std::time::Instant::now();
  6186. let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len);
  6187. if free {
  6188. batch.title_written();
  6189. }
  6190. if let Some(bytes) = p.prepare(free) {
  6191. batch.placed.push((p.shadow.clone(), p.dst, bytes));
  6192. }
  6193. (started, p.len)
  6194. }
  6195. Step::Refresh(shadow, address, len) => {
  6196. #[cfg(feature = "diagnostics")]
  6197. {
  6198. refreshes += 1;
  6199. refreshed += *len as u64;
  6200. }
  6201. batch.add(shadow, *address, *len);
  6202. continue;
  6203. }
  6204. Step::Run(work) | Step::Host(work, _) => {
  6205. #[cfg(feature = "diagnostics")]
  6206. let started = std::time::Instant::now();
  6207. if matches!(step, Step::Run(_)) {
  6208. batch.title_written();
  6209. }
  6210. work();
  6211. // It wrote title memory, where is not known here: the
  6212. // submission's one asking ends, later refreshes ask anew.
  6213. if matches!(step, Step::Run(_)) {
  6214. crate::watch::ask_once_end();
  6215. }
  6216. #[cfg(feature = "diagnostics")]
  6217. {
  6218. add(C::Runs, 1);
  6219. add(C::RunUs, started.elapsed().as_micros() as u64);
  6220. }
  6221. continue;
  6222. }
  6223. Step::GpuWrite(shadow, address, len) => {
  6224. // The shaders start from the title's data: this copy's
  6225. // pending refresh first. The other copies' wait for
  6226. // the next flush of all (flushing all of them at every
  6227. // range a dispatch writes made thousands of write-watch
  6228. // askings a frame).
  6229. batch.flush_one(shadow);
  6230. #[cfg(feature = "diagnostics")]
  6231. let snapshot = std::time::Instant::now();
  6232. shadow.writing(*address, *len);
  6233. #[cfg(feature = "diagnostics")]
  6234. {
  6235. add(C::GpuWrites, 1);
  6236. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  6237. }
  6238. continue;
  6239. }
  6240. Step::Texture(staging) => {
  6241. if batch.texture_due(staging) {
  6242. batch.due.push(staging.clone());
  6243. if !wide_textures() {
  6244. batch.refresh_textures();
  6245. }
  6246. }
  6247. continue;
  6248. }
  6249. };
  6250. us += started.elapsed();
  6251. bytes += copied as u64;
  6252. }
  6253. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  6254. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  6255. #[cfg(feature = "diagnostics")]
  6256. {
  6257. add(C::Copies, copies);
  6258. add(C::CopyBytes, bytes);
  6259. add(C::Refreshes, refreshes);
  6260. add(C::RefreshBytes, refreshed);
  6261. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  6262. }
  6263. }
  6264. }
  6265. /// A table by a copy's address.
  6266. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  6267. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  6268. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  6269. /// but our own.
  6270. #[derive(Default)]
  6271. pub(crate) struct AddressHash(u64);
  6272. impl std::hash::Hasher for AddressHash {
  6273. fn finish(&self) -> u64 {
  6274. self.0
  6275. }
  6276. fn write(&mut self, bytes: &[u8]) {
  6277. for &b in bytes {
  6278. self.write_usize(usize::from(b));
  6279. }
  6280. }
  6281. fn write_usize(&mut self, n: usize) {
  6282. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  6283. self.0 = h ^ (h >> 32);
  6284. }
  6285. }
  6286. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  6287. /// preparing: the write-watch asking for a submission; the title's bytes put
  6288. /// in under flights' writes; the lists' steps, the refreshes among them; the
  6289. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  6290. /// of the steps: the refreshes, and the copies and fills (those with the
  6291. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  6292. /// is of. Of the refreshes, those before ranges are given to shaders, one
  6293. /// copy at a time: nanoseconds, and how many.
  6294. #[cfg(feature = "diagnostics")]
  6295. static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  6296. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  6297. /// those known to copy nothing, and those done on several threads.
  6298. #[cfg(feature = "diagnostics")]
  6299. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  6300. /// Counts into [`SPLIT`].
  6301. #[cfg(feature = "diagnostics")]
  6302. struct Split(std::cell::Cell<std::time::Instant>);
  6303. #[cfg(feature = "diagnostics")]
  6304. impl Split {
  6305. fn begin() -> Split {
  6306. Split(std::cell::Cell::new(std::time::Instant::now()))
  6307. }
  6308. /// Nanoseconds since the last part.
  6309. fn so_far(&self) -> u64 {
  6310. self.0.get().elapsed().as_nanos() as u64
  6311. }
  6312. /// What came since the last part was part `i`.
  6313. fn part(&self, i: usize) {
  6314. let now = std::time::Instant::now();
  6315. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  6316. }
  6317. }
  6318. /// The split of the preparing, per frame, for the frame-rate line.
  6319. #[cfg(feature = "diagnostics")]
  6320. fn split_line(frames: f64) {
  6321. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6322. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  6323. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  6324. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6325. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
  6326. tracing::info!(
  6327. "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' \
  6328. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  6329. 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 \
  6330. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
  6331. ms[0],
  6332. ms[8],
  6333. ms[1],
  6334. ms[2],
  6335. ms[6],
  6336. f[0],
  6337. f[1],
  6338. f[2],
  6339. f[3],
  6340. ms[9],
  6341. ms[10] * 1e6,
  6342. ms[7],
  6343. ms[3],
  6344. ms[4],
  6345. ms[5],
  6346. if crate::watch::light() { "on" } else { "off" },
  6347. );
  6348. tracing::info!(
  6349. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6350. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6351. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6352. waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
  6353. as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
  6354. a[0],
  6355. a[1] / 1024.0,
  6356. a[11] / 1e6,
  6357. a[12],
  6358. a[10],
  6359. a[9],
  6360. a[2],
  6361. a[3],
  6362. a[4],
  6363. a[5],
  6364. a[6],
  6365. a[7] / 1e6,
  6366. a[8] / 1e6,
  6367. s[0] / 1048576.0,
  6368. s[1] / 1048576.0,
  6369. s[2] / 1048576.0,
  6370. s[3],
  6371. );
  6372. tracing::info!(
  6373. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures",
  6374. h[0],
  6375. h[1],
  6376. h[2],
  6377. );
  6378. }
  6379. /// Whether a submission's refreshes of host copies run on several threads,
  6380. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6381. ///
  6382. /// A submission brings some sixty copies up to date, one after the other
  6383. /// on the submitting thread: for each, the pages the title wrote are asked
  6384. /// for and read through the kernel into the copy. That is the frame line's
  6385. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6386. /// another: each refresh writes its own copy and its own notes, and reads
  6387. /// title memory. With the switch the copies of a flush (four or more) are
  6388. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6389. /// The write-watch journal and the guards are behind their own locks, as
  6390. /// they are for the title's threads.
  6391. fn wide_refresh() -> bool {
  6392. static ON: OnceLock<bool> = OnceLock::new();
  6393. *ON.get_or_init(|| {
  6394. wide_refresh_enabled(
  6395. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6396. std::thread::available_parallelism().ok().map(|n| n.get()),
  6397. )
  6398. })
  6399. }
  6400. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6401. match setting {
  6402. Some("1") => true,
  6403. Some("0") => false,
  6404. _ => logical_cpus.is_some_and(|n| n >= 4),
  6405. }
  6406. }
  6407. #[cfg(test)]
  6408. mod wide_refresh_tests {
  6409. use super::wide_refresh_enabled;
  6410. #[test]
  6411. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6412. assert!(wide_refresh_enabled(None, Some(4)));
  6413. assert!(wide_refresh_enabled(None, Some(16)));
  6414. assert!(!wide_refresh_enabled(None, Some(2)));
  6415. assert!(!wide_refresh_enabled(None, None));
  6416. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6417. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6418. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6419. }
  6420. }
  6421. /// A submission's refreshes not done yet, merged per buffer copy into the
  6422. /// range that covers them: done before a step that writes title memory or
  6423. /// gives a range to shaders, and before the lists run.
  6424. ///
  6425. /// Also the textures brought up to date in the submission so far: most
  6426. /// lists of a world submission sample the same textures, and a texture in
  6427. /// physical-page memory is hashed whole each time it is checked. Checked
  6428. /// once, it is checked again only after a step that writes title memory.
  6429. #[derive(Default)]
  6430. struct Batch {
  6431. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6432. /// Where each copy (by address) is in `refreshes`: the list that makes
  6433. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6434. /// for every refresh of a submission was tens of millions of
  6435. /// comparisons a frame.
  6436. index: ByCopy<usize>,
  6437. /// Staging buffers (by address) refreshed since the last title write,
  6438. /// or due to be.
  6439. textures: std::collections::HashSet<usize>,
  6440. /// Those due ([`Batch::refresh_textures`]).
  6441. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6442. /// What copies at their place in the submission's lists put into title
  6443. /// memory ([`place`]): the host copy, the title address, the bytes.
  6444. placed: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, Vec<u8>)>,
  6445. }
  6446. /// Whether a submission's textures are brought up to date on several
  6447. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6448. /// name them, as before).
  6449. ///
  6450. /// They are read, hashed and, if they changed, detiled into their staging
  6451. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6452. /// its own buffer, notes and lock, and is refreshed by the title's own
  6453. /// threads as it is. They are done before the next step that writes title
  6454. /// memory, as the copies' refreshes are, and before the lists go to the
  6455. /// card. What is new: the note of a list that its upload takes what the
  6456. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6457. /// an earlier list of the submission asked for, not behind it. The texture
  6458. /// is then uploaded by a later list too, once more than needed.
  6459. fn wide_textures() -> bool {
  6460. static ON: OnceLock<bool> = OnceLock::new();
  6461. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6462. }
  6463. impl Batch {
  6464. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6465. let end = address + len;
  6466. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6467. match self.index.get(&key) {
  6468. Some(&at) => {
  6469. let r = &mut self.refreshes[at];
  6470. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6471. }
  6472. None => {
  6473. self.index.insert(key, self.refreshes.len());
  6474. self.refreshes.push((shadow.clone(), address, end));
  6475. }
  6476. }
  6477. }
  6478. /// Before shaders are given a range of `shadow`'s copy: its pending
  6479. /// refresh is done, the others stay pending.
  6480. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  6481. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  6482. return;
  6483. };
  6484. let (shadow, from, to) = self.refreshes.swap_remove(at);
  6485. // The last entry took its place.
  6486. if let Some(moved) = self.refreshes.get(at) {
  6487. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  6488. }
  6489. #[cfg(feature = "diagnostics")]
  6490. let started = std::time::Instant::now();
  6491. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  6492. Self::update(&shadow, from, to);
  6493. }
  6494. #[cfg(feature = "diagnostics")]
  6495. {
  6496. let ns = started.elapsed().as_nanos() as u64;
  6497. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6498. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6499. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  6500. }
  6501. }
  6502. /// Brings `[from, to)` of a copy up to date, timed.
  6503. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  6504. let started = std::time::Instant::now();
  6505. let copied = shadow.update(from, to - from);
  6506. let us = started.elapsed().as_micros() as u64;
  6507. #[cfg(feature = "diagnostics")]
  6508. crate::copystat::range(from, to - from, us, 0);
  6509. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  6510. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  6511. }
  6512. /// Whether `staging` is still to be refreshed in this submission (and
  6513. /// notes it refreshed).
  6514. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  6515. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  6516. }
  6517. /// Before a step that writes title memory: pending refreshes are done
  6518. /// first, and textures are checked again after it.
  6519. fn title_written(&mut self) {
  6520. self.flush();
  6521. self.textures.clear();
  6522. }
  6523. /// The textures due are brought up to date.
  6524. fn refresh_textures(&mut self) {
  6525. if self.due.len() < 2 || !wide_textures() {
  6526. self.due.drain(..).for_each(|staging| staging.refresh());
  6527. return;
  6528. }
  6529. // The time counted is the time it took, not the threads' sum.
  6530. let started = std::time::Instant::now();
  6531. let before = PREPARING[2].load(Ordering::Relaxed);
  6532. let due = std::mem::take(&mut self.due);
  6533. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  6534. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  6535. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6536. }
  6537. fn flush(&mut self) {
  6538. self.refresh_textures();
  6539. self.index.clear();
  6540. if self.refreshes.is_empty() {
  6541. return;
  6542. }
  6543. #[cfg(feature = "diagnostics")]
  6544. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  6545. self.flush_all();
  6546. #[cfg(feature = "diagnostics")]
  6547. {
  6548. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6549. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  6550. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  6551. }
  6552. }
  6553. fn flush_all(&mut self) {
  6554. // Most of a flush's copies are as they were: they are told so here,
  6555. // from what the submission's asking found, before anything is asked
  6556. // and any thread woken. (Thousands of them, the heap's buffer views
  6557. // once a frame: on the threads, below.)
  6558. const FEW: usize = 256;
  6559. let light = crate::watch::light();
  6560. if light && self.refreshes.len() <= FEW {
  6561. let started = std::time::Instant::now();
  6562. #[cfg(feature = "diagnostics")]
  6563. let all = self.refreshes.len();
  6564. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  6565. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6566. #[cfg(feature = "diagnostics")]
  6567. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  6568. }
  6569. // One write-watch asking for the copies that lie close together,
  6570. // not one per copy.
  6571. let ahead = self.refreshes.len() > 1;
  6572. if ahead {
  6573. let started = std::time::Instant::now();
  6574. let ranges: Vec<(usize, usize)> = self
  6575. .refreshes
  6576. .iter()
  6577. .filter(|r| r.0.asked_ahead())
  6578. .map(|r| (r.1, r.2))
  6579. .collect();
  6580. crate::watch::ask_ahead(&ranges);
  6581. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6582. }
  6583. if wide_refresh() && self.refreshes.len() >= 4 {
  6584. // Each copy on its own, several at a time: a copy's refresh
  6585. // writes that copy and reads title memory, nothing of another's.
  6586. // The time counted is the time it took, not the threads' sum.
  6587. let started = std::time::Instant::now();
  6588. let before = PREPARING[0].load(Ordering::Relaxed);
  6589. #[cfg(feature = "diagnostics")]
  6590. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  6591. if light {
  6592. // A number to a free thread, not a job to each copy.
  6593. let refreshes = std::mem::take(&mut self.refreshes);
  6594. crate::shadow::wide_each(refreshes.len(), move |i| {
  6595. let (shadow, from, to) = &refreshes[i];
  6596. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  6597. #[cfg(feature = "diagnostics")]
  6598. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  6599. return;
  6600. }
  6601. Self::update(shadow, *from, *to);
  6602. });
  6603. } else {
  6604. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  6605. .refreshes
  6606. .drain(..)
  6607. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  6608. .collect();
  6609. crate::shadow::wide_run(jobs);
  6610. }
  6611. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6612. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6613. } else {
  6614. for (shadow, from, to) in self.refreshes.drain(..) {
  6615. Self::update(&shadow, from, to);
  6616. }
  6617. }
  6618. if ahead {
  6619. crate::watch::ask_ahead_done();
  6620. }
  6621. }
  6622. }
  6623. /// Copies title memory at submission. The ranges were checked against their
  6624. /// resources when recorded, but the title may since have unmapped pages of
  6625. /// them (tiled memory, page mappings), which read as zeros here; a title
  6626. /// destination (`title_dst`) that is not all mapped is left alone.
  6627. ///
  6628. /// The source is read through the kernel (`ReadProcessMemory`), which
  6629. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  6630. /// cost about 2 ms per copy in the title's big pools (it walks the page
  6631. /// tables to the region's end), which made copies run at 100-200 MB/s.
  6632. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  6633. #[cfg(feature = "diagnostics")]
  6634. match crate::copystat::mode() {
  6635. 1 => {
  6636. // SAFETY: timing only: the caller vouches for the source.
  6637. unsafe { std::ptr::copy(src, dst, len) };
  6638. return;
  6639. }
  6640. 2 => return,
  6641. _ => {}
  6642. }
  6643. if len == 0 {
  6644. return;
  6645. }
  6646. // A title destination that is not all mapped is left alone. Asking
  6647. // Windows first (`VirtualQuery`) walks the page tables to the end of
  6648. // the destination's region: in the title's big blocks that is
  6649. // milliseconds a copy, and it was a seventh of the submitting thread's
  6650. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  6651. // says the same when it fails, so the question is only asked then.
  6652. // `VICTORY_COPY_ASK=1` asks first, as before.
  6653. static ASK: OnceLock<bool> = OnceLock::new();
  6654. let ask_first = title_dst
  6655. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  6656. if ask_first && !crate::texture::committed(dst, len) {
  6657. return;
  6658. }
  6659. if title_dst {
  6660. // The kernel writes the destination: it must not be guarded.
  6661. crate::watch::writing(dst as usize, len);
  6662. }
  6663. #[cfg(feature = "diagnostics")]
  6664. let moved = std::time::Instant::now();
  6665. let since = crate::watch::changes();
  6666. // (A title destination that is away only while the runtime changes a
  6667. // mapping beside it is written when that is done.)
  6668. let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
  6669. #[cfg(feature = "diagnostics")]
  6670. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  6671. if whole {
  6672. return;
  6673. }
  6674. // The copy failed: a source page is not there, or the destination is
  6675. // not all mapped. Then the destination stays as it is (the kernel may
  6676. // have written its first pages).
  6677. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  6678. crate::watch::lost("a copy of the title's", dst as usize, len);
  6679. return;
  6680. }
  6681. #[cfg(feature = "diagnostics")]
  6682. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  6683. #[cfg(feature = "diagnostics")]
  6684. let sparse = std::time::Instant::now();
  6685. if !title_dst && len >= 64 << 10 {
  6686. read_sparse(src, dst, len);
  6687. } else {
  6688. read_pieces(src, dst, len);
  6689. }
  6690. #[cfg(feature = "diagnostics")]
  6691. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  6692. }
  6693. /// After a failed bulk read into host memory, skip contiguous holes. Never
  6694. /// cache the query across copies: the title may remap the same address.
  6695. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  6696. use windows_sys::Win32::System::Memory::{
  6697. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  6698. };
  6699. let mut offset = 0;
  6700. while offset < len {
  6701. let at = src.wrapping_add(offset);
  6702. let to = dst.wrapping_add(offset);
  6703. let remaining = len - offset;
  6704. // SAFETY: the query inspects an address and fills a local structure.
  6705. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  6706. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  6707. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  6708. .saturating_sub(at as usize).min(remaining);
  6709. if size != size_of_val(&info) || n == 0 {
  6710. read_pieces(at, to, remaining);
  6711. break;
  6712. }
  6713. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  6714. #[cfg(feature = "diagnostics")]
  6715. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6716. // SAFETY: this path is only used with a writable host destination.
  6717. unsafe { to.write_bytes(0, n) };
  6718. } else if !read(at, to, n) {
  6719. // A mapping may change between query and read.
  6720. read_pieces(at, to, n);
  6721. }
  6722. offset += n;
  6723. }
  6724. }
  6725. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  6726. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  6727. // that fails), zeros for what cannot be read.
  6728. for_pieces(src as usize, len, 64 << 10, |at, n| {
  6729. let to = dst.wrapping_add(at - src as usize);
  6730. if !read(at as *const u8, to, n) {
  6731. for_pieces(at, n, 4 << 10, |at, n| {
  6732. let to = dst.wrapping_add(at - src as usize);
  6733. if !read(at as *const u8, to, n) {
  6734. #[cfg(feature = "diagnostics")]
  6735. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6736. zero(to, n);
  6737. }
  6738. });
  6739. }
  6740. });
  6741. }
  6742. /// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
  6743. /// destination of a title's copy), which can go between the question whether
  6744. /// it is there and this.
  6745. fn zero(to: *mut u8, n: usize) {
  6746. static ZEROS: [u8; 4096] = [0; 4096];
  6747. if n <= ZEROS.len() && crate::safecopy::on() {
  6748. // SAFETY: a destination that is not there fails the copy.
  6749. if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
  6750. crate::watch::lost("zeros", to as usize, n);
  6751. }
  6752. return;
  6753. }
  6754. // SAFETY: inside the destination, which is mapped.
  6755. unsafe { to.write_bytes(0, n) };
  6756. }
  6757. /// Reads title memory at `src` into `dst`; false if a page of it is not
  6758. /// readable.
  6759. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  6760. read(src, dst.as_mut_ptr(), dst.len())
  6761. }
  6762. /// Reads what is there of the `dst.len()` bytes of title memory at `src`,
  6763. /// zeros for the rest; returns how many bytes were there. Safe while the
  6764. /// runtime remaps title memory (the kernel, or a copy that takes the fault,
  6765. /// reads). What the runtime's record says is mapped is read in one go each,
  6766. /// and by pieces where that fails; memory it has no record of by pieces.
  6767. pub(crate) fn read_there(src: *const u8, dst: &mut [u8]) -> usize {
  6768. dst.fill(0);
  6769. let (start, len) = (src as usize, dst.len());
  6770. let mut got = 0;
  6771. let mut runs = crate::inplace::shown_runs(start, len);
  6772. if runs.is_empty() {
  6773. runs.push((start, len));
  6774. }
  6775. for (at, n) in runs {
  6776. let piece = &mut dst[at - start..at - start + n];
  6777. if read_into(at as *const u8, piece) {
  6778. got += n;
  6779. continue;
  6780. }
  6781. // (What failed may have written its first pages.)
  6782. piece.fill(0);
  6783. for_pieces(at, n, 64 << 10, |from, n| {
  6784. let piece = &mut dst[from - start..from - start + n];
  6785. if read_into(from as *const u8, piece) {
  6786. got += n;
  6787. return;
  6788. }
  6789. piece.fill(0);
  6790. for_pieces(from, n, 4 << 10, |from, n| {
  6791. let piece = &mut dst[from - start..from - start + n];
  6792. if read_into(from as *const u8, piece) {
  6793. got += n;
  6794. } else {
  6795. piece.fill(0);
  6796. }
  6797. });
  6798. });
  6799. }
  6800. got
  6801. }
  6802. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  6803. /// readable.
  6804. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  6805. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  6806. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6807. if crate::safecopy::on() {
  6808. // SAFETY: the destination is mapped writable memory of `len` bytes;
  6809. // a source page that is not there fails the copy.
  6810. return unsafe { crate::safecopy::copy(dst, src, len) };
  6811. }
  6812. let mut done = 0;
  6813. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  6814. // kernel checks the source.
  6815. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  6816. }
  6817. #[link(name = "ntdll", kind = "raw-dylib")]
  6818. unsafe extern "system" {
  6819. /// The kernel's write into a process's memory, `(process, address,
  6820. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  6821. /// the range is not there or not writable. It changes no protection.
  6822. fn NtWriteVirtualMemory(
  6823. process: *mut std::ffi::c_void,
  6824. base: *mut std::ffi::c_void,
  6825. buffer: *const std::ffi::c_void,
  6826. size: usize,
  6827. written: *mut usize,
  6828. ) -> i32;
  6829. }
  6830. /// Whether title memory is written with the kernel's own call
  6831. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  6832. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  6833. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  6834. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  6835. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  6836. fn direct_writes() -> bool {
  6837. static ON: OnceLock<bool> = OnceLock::new();
  6838. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  6839. }
  6840. /// Copies host memory into title memory after a submission (what shaders
  6841. /// wrote), leaving pages that are not mapped alone.
  6842. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  6843. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  6844. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6845. let direct = direct_writes();
  6846. let since = crate::watch::changes();
  6847. let write = |at: usize, n: usize| {
  6848. let from = src.wrapping_add(at - dst as usize);
  6849. if crate::safecopy::on() {
  6850. // SAFETY: the source is ours; a destination page that is not
  6851. // there, or not writable, fails the copy.
  6852. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  6853. }
  6854. let mut done = 0;
  6855. if direct {
  6856. // SAFETY: as below; the kernel checks the destination and
  6857. // writes nothing it cannot (the caller opened its guards:
  6858. // `crate::watch::writing`).
  6859. return unsafe {
  6860. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  6861. };
  6862. }
  6863. // SAFETY: the source is our mapped host copy; the kernel checks the
  6864. // destination.
  6865. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  6866. };
  6867. if len == 0 || write(dst as usize, len) {
  6868. return;
  6869. }
  6870. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  6871. if !write(at, n) {
  6872. for_pieces(at, n, 4 << 10, |at, n| {
  6873. if write(at, n) {
  6874. return;
  6875. }
  6876. // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
  6877. // refresh guarded the block again since the caller opened
  6878. // it; and any where the runtime was changing a mapping.
  6879. crate::watch::writing(at, n);
  6880. if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
  6881. crate::watch::lost("a host copy's bytes", at, n);
  6882. }
  6883. });
  6884. }
  6885. });
  6886. }
  6887. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  6888. /// `step`.
  6889. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  6890. let end = start + len;
  6891. let mut at = start;
  6892. while at < end {
  6893. let next = ((at / step + 1) * step).min(end);
  6894. f(at, next - at);
  6895. at = next;
  6896. }
  6897. }
  6898. impl Host {
  6899. /// The queue everything of ours runs on, for a call that must go to it
  6900. /// in order with the lists (`crate::tiles`: a texture's levels are
  6901. /// given memory ahead of the list that uploads them).
  6902. pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
  6903. &self.queue
  6904. }
  6905. /// A buffer in the upload heap, mapped for writing.
  6906. /// A buffer of `size` bytes the card writes and we read (a read back),
  6907. /// in the state copies into it need.
  6908. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  6909. let heap = D3D12_HEAP_PROPERTIES {
  6910. Type: D3D12_HEAP_TYPE_READBACK,
  6911. ..Default::default()
  6912. };
  6913. let desc = D3D12_RESOURCE_DESC {
  6914. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6915. Width: size.max(1),
  6916. Height: 1,
  6917. DepthOrArraySize: 1,
  6918. MipLevels: 1,
  6919. SampleDesc: DXGI_SAMPLE_DESC {
  6920. Count: 1,
  6921. Quality: 0,
  6922. },
  6923. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6924. ..Default::default()
  6925. };
  6926. let mut buffer: Option<ID3D12Resource> = None;
  6927. // SAFETY: plain creation of a read-back buffer.
  6928. let made = unsafe {
  6929. self.device.CreateCommittedResource(
  6930. &heap,
  6931. D3D12_HEAP_FLAG_NONE,
  6932. &desc,
  6933. D3D12_RESOURCE_STATE_COPY_DEST,
  6934. None,
  6935. &mut buffer,
  6936. )
  6937. };
  6938. match made {
  6939. Ok(()) => buffer,
  6940. Err(e) => {
  6941. tracing::warn!(error = %e, size, "no read-back buffer");
  6942. None
  6943. }
  6944. }
  6945. }
  6946. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6947. MADE[0].fetch_add(1, Ordering::Relaxed);
  6948. MADE[1].fetch_add(size, Ordering::Relaxed);
  6949. let heap = D3D12_HEAP_PROPERTIES {
  6950. Type: D3D12_HEAP_TYPE_UPLOAD,
  6951. ..Default::default()
  6952. };
  6953. let desc = D3D12_RESOURCE_DESC {
  6954. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6955. Width: size.max(1),
  6956. Height: 1,
  6957. DepthOrArraySize: 1,
  6958. MipLevels: 1,
  6959. SampleDesc: DXGI_SAMPLE_DESC {
  6960. Count: 1,
  6961. Quality: 0,
  6962. },
  6963. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6964. ..Default::default()
  6965. };
  6966. let mut buffer: Option<ID3D12Resource> = None;
  6967. let mut data = std::ptr::null_mut();
  6968. // SAFETY: plain creation and mapping of an upload buffer.
  6969. let made = unsafe {
  6970. self.device
  6971. .CreateCommittedResource(
  6972. &heap,
  6973. D3D12_HEAP_FLAG_NONE,
  6974. &desc,
  6975. D3D12_RESOURCE_STATE_GENERIC_READ,
  6976. None,
  6977. &mut buffer,
  6978. )
  6979. .and_then(|()| {
  6980. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  6981. b.Map(0, None, Some(&mut data))
  6982. })
  6983. };
  6984. match made {
  6985. Ok(()) => Some((buffer?, data.cast())),
  6986. Err(e) => {
  6987. tracing::warn!(error = %e, size, "no upload buffer");
  6988. None
  6989. }
  6990. }
  6991. }
  6992. }
  6993. /// The swap chain formats a presented texture can be copied into: its own
  6994. /// family's.
  6995. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  6996. Some(match format.0 {
  6997. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  6998. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  6999. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  7000. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  7001. _ => return None,
  7002. })
  7003. }
  7004. const BUFFERS: u32 = 2;
  7005. struct Presenter {
  7006. swap_chain: IDXGISwapChain3,
  7007. width: u32,
  7008. height: u32,
  7009. format: DXGI_FORMAT,
  7010. copy: HostList,
  7011. /// With presents sent ahead ([`late_free_present`]): a list for each
  7012. /// present in the air, and the submission it last flew as (it is used
  7013. /// again once that one has finished).
  7014. ahead: Vec<(HostList, u64)>,
  7015. hwnd: HWND,
  7016. meter: Meter,
  7017. }
  7018. /// The frame rate, shown in the window's caption every second and logged
  7019. /// every few seconds.
  7020. struct Meter {
  7021. since: std::time::Instant,
  7022. frames: u32,
  7023. #[cfg(feature = "diagnostics")]
  7024. copy_stats_frames: u64,
  7025. drawn: u64,
  7026. logged: std::time::Instant,
  7027. /// The caption the window had, once read.
  7028. caption: Option<Vec<u16>>,
  7029. }
  7030. impl Meter {
  7031. fn new() -> Self {
  7032. let now = std::time::Instant::now();
  7033. Meter {
  7034. since: now,
  7035. frames: 0,
  7036. #[cfg(feature = "diagnostics")]
  7037. copy_stats_frames: 0,
  7038. drawn: crate::draw::drawn(),
  7039. logged: now,
  7040. caption: None,
  7041. }
  7042. }
  7043. /// Counts a presented frame.
  7044. fn frame(&mut self, hwnd: HWND) {
  7045. #[cfg(feature = "diagnostics")]
  7046. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  7047. #[cfg(feature = "diagnostics")]
  7048. crate::copystat::presented();
  7049. self.frames += 1;
  7050. #[cfg(feature = "diagnostics")]
  7051. {
  7052. self.copy_stats_frames += 1;
  7053. }
  7054. let elapsed = self.since.elapsed();
  7055. if elapsed < std::time::Duration::from_secs(1) {
  7056. return;
  7057. }
  7058. let drawn = crate::draw::drawn();
  7059. let frames = f64::from(self.frames);
  7060. let fps = frames / elapsed.as_secs_f64();
  7061. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  7062. let draws = (drawn - self.drawn) as f64 / frames;
  7063. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  7064. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  7065. let [cpu, gpu] = [0, 1].map(|i| {
  7066. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  7067. });
  7068. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  7069. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  7070. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  7071. });
  7072. let [back_ms, back_mb] = [0, 1].map(|i| {
  7073. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  7074. });
  7075. let dropped = crate::draw::take_dropped() as f64 / frames;
  7076. let indirect = crate::list::take_indirect() as f64 / frames;
  7077. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  7078. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  7079. tracing::info!(
  7080. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  7081. );
  7082. crate::shadow::exact_line(frames);
  7083. crate::descriptor::sync_line(frames);
  7084. late_line(frames);
  7085. card_clock_line(frames, ms);
  7086. crate::shadow::back_line(frames);
  7087. #[cfg(feature = "diagnostics")]
  7088. split_line(frames);
  7089. {
  7090. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7091. if passes + compares > 0.0 {
  7092. tracing::info!(
  7093. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  7094. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  7095. if rehash_runs() { "on" } else { "off" }
  7096. );
  7097. }
  7098. }
  7099. {
  7100. let [own, asking, still, all] =
  7101. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  7102. if all >= 1.0 {
  7103. tracing::info!(
  7104. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  7105. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  7106. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  7107. );
  7108. }
  7109. let [through, left, filled, short] =
  7110. [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7111. if through + left + filled > 0.0 {
  7112. tracing::info!(
  7113. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  7114. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \
  7115. {filled:.1} first fillings from the pages there (VICTORY_TEXTURE_FILL=0: left empty), {short:.1} of them \
  7116. with less than was mapped (looked at again)"
  7117. );
  7118. }
  7119. }
  7120. {
  7121. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7122. if copies > 0.0 {
  7123. tracing::info!(
  7124. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  7125. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  7126. if join_copies() { "on" } else { "off" }
  7127. );
  7128. }
  7129. }
  7130. // Passes over the heap's buffer views for shaders that pick them by index.
  7131. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  7132. let picked_ms =
  7133. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  7134. // Copies between depth textures and their colour twins, each way.
  7135. let [twin_to_depth, twin_to_colour] =
  7136. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7137. // Depth planes drawn from their twins.
  7138. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  7139. // Copies in the card's memory (`crate::shadow::cards`).
  7140. let card = crate::shadow::card_stats();
  7141. #[cfg(feature = "diagnostics")]
  7142. let slow = crate::watch::slow_asks();
  7143. // Over the same frames as the counts above.
  7144. #[cfg(feature = "diagnostics")]
  7145. let drops = crate::pipeline::take_drops();
  7146. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  7147. self.logged = std::time::Instant::now();
  7148. tracing::info!(
  7149. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  7150. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  7151. );
  7152. crate::tiles::status();
  7153. {
  7154. let [queued, due, away, partly, oldest] =
  7155. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  7156. let [same, parts, tails] =
  7157. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  7158. tracing::info!(
  7159. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  7160. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  7161. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  7162. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  7163. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  7164. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  7165. {} made slots found unmapped and made null",
  7166. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  7167. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  7168. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  7169. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  7170. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  7171. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  7172. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  7173. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  7174. );
  7175. }
  7176. {
  7177. let mode = crate::watch::page_writes();
  7178. let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
  7179. let [kept, dropped, slots, uploaded] =
  7180. [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
  7181. tracing::info!(
  7182. "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)",
  7183. bytes >> 20,
  7184. if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
  7185. if mode & 4 != 0 { "told as well" } else { "counted only" },
  7186. if mode & 2 != 0 { "made due again" } else { "left as they were" }
  7187. );
  7188. }
  7189. #[cfg(feature = "diagnostics")]
  7190. tracing::info!(
  7191. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  7192. slow[0] as f64 / frames,
  7193. slow[1] as f64 / 1e3 / frames,
  7194. slow[2] as f64 / 1e3
  7195. );
  7196. if crate::shadow::cards() {
  7197. let per_frame = |i: usize| card[i] as f64 / frames;
  7198. tracing::info!(
  7199. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  7200. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  7201. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  7202. card[7],
  7203. card[8] >> 20,
  7204. card[9] >> 20,
  7205. per_frame(0) / 1e6,
  7206. per_frame(1),
  7207. per_frame(2),
  7208. per_frame(3),
  7209. per_frame(4) / 1e6,
  7210. per_frame(5),
  7211. per_frame(6) / 1e3
  7212. );
  7213. }
  7214. tracing::info!(
  7215. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  7216. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  7217. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  7218. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  7219. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  7220. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  7221. {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}",
  7222. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  7223. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  7224. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  7225. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  7226. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  7227. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  7228. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  7229. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  7230. refused = format!(
  7231. "{} ({} 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",
  7232. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  7233. crate::shadow::OWN_MADE.load(Ordering::Relaxed),
  7234. crate::resource::TWINS[0].load(Ordering::Relaxed),
  7235. crate::resource::TWINS[1].load(Ordering::Relaxed),
  7236. crate::resource::PLANES[1].load(Ordering::Relaxed),
  7237. crate::resource::PLANES[2].load(Ordering::Relaxed)
  7238. ),
  7239. making = crate::pipeline::making(),
  7240. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  7241. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  7242. );
  7243. #[cfg(feature = "diagnostics")]
  7244. {
  7245. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7246. tracing::info!(
  7247. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  7248. put[0],
  7249. put[1],
  7250. put[2] / 1e6,
  7251. put[3]
  7252. );
  7253. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  7254. for (why, n) in drops.iter().take(40) {
  7255. tracing::info!(
  7256. "dropped {:.1}/frame without a host pipeline: {why}",
  7257. *n as f64 / frames
  7258. );
  7259. }
  7260. }
  7261. }
  7262. if self.caption.is_none() {
  7263. // The window's own text, read without a message.
  7264. let mut buffer = vec![0u16; 512];
  7265. // SAFETY: a window handle and a buffer of that length.
  7266. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  7267. buffer.truncate(n.max(0) as usize);
  7268. self.caption = Some(buffer);
  7269. }
  7270. let Some(caption) = &self.caption else { return };
  7271. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  7272. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  7273. text.push(0);
  7274. // Setting the text waits for the window's thread (a title thread,
  7275. // which may not pump for a while), so a thread of ours does it and
  7276. // presenting never waits; it takes the newest text when free.
  7277. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  7278. static SETTER: std::sync::Once = std::sync::Once::new();
  7279. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  7280. SETTER.call_once(|| {
  7281. let _ = std::thread::Builder::new()
  7282. .name("victory-caption".into())
  7283. .spawn(|| {
  7284. loop {
  7285. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  7286. match next {
  7287. // SAFETY: a window handle and a NUL-terminated text.
  7288. Some((hwnd, text)) => unsafe {
  7289. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  7290. },
  7291. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  7292. }
  7293. }
  7294. });
  7295. });
  7296. }
  7297. }
  7298. impl Host {
  7299. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  7300. /// as frame `frame` (saved if captures are on). `None` if nothing was
  7301. /// shown; else, in diagnostics builds, whether the frame was black.
  7302. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  7303. // SAFETY: a live resource.
  7304. let desc = unsafe { texture.GetDesc() };
  7305. let Some(format) = swap_format(desc.Format) else {
  7306. tracing::warn!(format = desc.Format.0, "cannot present this format");
  7307. return None;
  7308. };
  7309. let (width, height) = (desc.Width as u32, desc.Height);
  7310. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  7311. if presenter.is_none() {
  7312. *presenter = match self.presenter(width, height, format) {
  7313. Ok(p) => Some(p),
  7314. Err(e) => {
  7315. tracing::warn!(error = %e, "no swap chain");
  7316. return None;
  7317. }
  7318. };
  7319. }
  7320. let p = presenter.as_mut()?;
  7321. if (p.width, p.height, p.format) != (width, height, format) {
  7322. // Presents sent ahead hold back buffers until they have run.
  7323. settle_now(WHY_SYNC);
  7324. // SAFETY: no back buffer is held; every submission was waited for.
  7325. let resized = unsafe {
  7326. p.swap_chain
  7327. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  7328. };
  7329. match resized {
  7330. Ok(()) => {
  7331. (p.width, p.height, p.format) = (width, height, format);
  7332. tracing::info!(
  7333. width,
  7334. height,
  7335. format = format.0,
  7336. frame,
  7337. "the swap chain's buffers were made again for another size or format"
  7338. );
  7339. self.log_video_memory("right after the swap chain's buffers were made again");
  7340. }
  7341. Err(e) => {
  7342. tracing::warn!(error = %e, width, height, "swap chain not resized");
  7343. return None;
  7344. }
  7345. }
  7346. }
  7347. let state = D3D12_RESOURCE_STATES(state as i32);
  7348. // SAFETY: our swap chain, list and a live source texture.
  7349. unsafe {
  7350. let index = p.swap_chain.GetCurrentBackBufferIndex();
  7351. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  7352. return None;
  7353. };
  7354. // Sent ahead ([`late_free_present`]) unless the frame is to be
  7355. // read back at once (a saved or listed frame): then a list of
  7356. // its own, one whose last flight has finished or a new one.
  7357. #[cfg(feature = "diagnostics")]
  7358. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  7359. #[cfg(not(feature = "diagnostics"))]
  7360. let read_now = false;
  7361. let slot = if late_free_present() && !read_now {
  7362. let finished = FINISHED.load(Ordering::Acquire);
  7363. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  7364. let list = self.new_list().ok()?;
  7365. list.close();
  7366. p.ahead.push((list, 0));
  7367. Some(p.ahead.len() - 1)
  7368. })
  7369. } else {
  7370. None
  7371. };
  7372. let copy = match slot {
  7373. Some(i) => &p.ahead[i].0,
  7374. None => &p.copy,
  7375. };
  7376. copy.reset();
  7377. let list = &copy.list;
  7378. list.ResourceBarrier(&[
  7379. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  7380. transition(
  7381. &back,
  7382. D3D12_RESOURCE_STATE_PRESENT,
  7383. D3D12_RESOURCE_STATE_COPY_DEST,
  7384. ),
  7385. ]);
  7386. list.CopyResource(&back, texture);
  7387. #[cfg(feature = "diagnostics")]
  7388. let capture = crate::capture::wanted(frame)
  7389. .then(|| crate::capture::read_back(&self.device, list, texture))
  7390. .flatten();
  7391. #[cfg(feature = "diagnostics")]
  7392. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  7393. #[cfg(not(feature = "diagnostics"))]
  7394. let _ = frame;
  7395. list.ResourceBarrier(&[
  7396. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  7397. transition(
  7398. &back,
  7399. D3D12_RESOURCE_STATE_COPY_DEST,
  7400. D3D12_RESOURCE_STATE_PRESENT,
  7401. ),
  7402. ]);
  7403. copy.close();
  7404. match slot {
  7405. Some(i) => {
  7406. let flown = self.execute_own(copy);
  7407. p.ahead[i].1 = flown;
  7408. }
  7409. None => self.execute(&[copy]),
  7410. }
  7411. #[cfg(feature = "diagnostics")]
  7412. if let Some((buffer, footprint)) = capture {
  7413. crate::capture::save_read_back(frame, &buffer, &footprint);
  7414. }
  7415. #[cfg(feature = "diagnostics")]
  7416. crate::replay::record::present(texture, state);
  7417. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  7418. p.meter.frame(p.hwnd);
  7419. #[cfg(feature = "diagnostics")]
  7420. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  7421. #[cfg(not(feature = "diagnostics"))]
  7422. Some(false)
  7423. }
  7424. }
  7425. fn presenter(
  7426. &self,
  7427. width: u32,
  7428. height: u32,
  7429. format: DXGI_FORMAT,
  7430. ) -> windows::core::Result<Presenter> {
  7431. let hwnd = match title_window() {
  7432. Some(hwnd) => hwnd,
  7433. None => window(width, height)?,
  7434. };
  7435. self.log_video_memory("right before the swap chain is made");
  7436. // SAFETY: plain object creation for our window.
  7437. unsafe {
  7438. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  7439. let desc = DXGI_SWAP_CHAIN_DESC1 {
  7440. Width: width,
  7441. Height: height,
  7442. Format: format,
  7443. SampleDesc: DXGI_SAMPLE_DESC {
  7444. Count: 1,
  7445. Quality: 0,
  7446. },
  7447. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  7448. BufferCount: BUFFERS,
  7449. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  7450. ..Default::default()
  7451. };
  7452. let swap_chain = factory
  7453. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  7454. .cast::<IDXGISwapChain3>()?;
  7455. let copy = self.new_list()?;
  7456. copy.close();
  7457. tracing::info!(width, height, format = format.0, "presenting to a window");
  7458. self.log_video_memory("right after the swap chain is made");
  7459. Ok(Presenter {
  7460. swap_chain,
  7461. width,
  7462. height,
  7463. format,
  7464. copy,
  7465. ahead: Vec::new(),
  7466. hwnd,
  7467. meter: Meter::new(),
  7468. })
  7469. }
  7470. }
  7471. }
  7472. /// A visible top-level window of this process: the one the title made, if
  7473. /// it made one.
  7474. fn title_window() -> Option<HWND> {
  7475. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  7476. let mut process = 0;
  7477. // SAFETY: a window handle from the enumeration; `found` is ours.
  7478. unsafe {
  7479. GetWindowThreadProcessId(hwnd, Some(&mut process));
  7480. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  7481. && IsWindowVisible(hwnd).as_bool()
  7482. {
  7483. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  7484. return false.into();
  7485. }
  7486. }
  7487. true.into()
  7488. }
  7489. let mut found: Option<HWND> = None;
  7490. // SAFETY: the callback only writes `found`, which outlives the call.
  7491. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  7492. found
  7493. }
  7494. /// `state` without the bits the host texture's flags forbid: the console
  7495. /// lets the title name states its own resources allow (unordered access on
  7496. /// a depth target, whose host copy cannot have both).
  7497. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  7498. // SAFETY: a plain query.
  7499. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  7500. }
  7501. /// [`legal_state`] for a texture with resource flags `flags`.
  7502. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  7503. // (flag, set or clear forbids, state bits): render target, unordered
  7504. // access, depth, denied shader resource.
  7505. const FORBIDDEN: [(u32, bool, u32); 4] = [
  7506. (0x1, false, 0x4),
  7507. (0x4, false, 0x8),
  7508. (0x2, false, 0x10 | 0x20),
  7509. (0x8, true, 0x40 | 0x80),
  7510. ];
  7511. FORBIDDEN
  7512. .iter()
  7513. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  7514. .fold(state, |s, &(_, _, bits)| s & !bits)
  7515. }
  7516. impl Host {
  7517. /// The card's memory as the system accounts it to this process, in
  7518. /// bytes: the budget and the use of the card's own memory, then of the
  7519. /// PC's memory shared with the card (where the system moves what does
  7520. /// not fit on the card).
  7521. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  7522. let adapter = self.adapter.as_ref()?;
  7523. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7524. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7525. // SAFETY: plain queries that fill our structures.
  7526. unsafe {
  7527. adapter
  7528. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7529. .ok()?;
  7530. adapter
  7531. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7532. .ok()?;
  7533. }
  7534. // The card's budget moved by 256 MB or more since the last look:
  7535. // said at once, with what was in use at the last look, so the log
  7536. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  7537. // the first world frame in runs 179 to 185, and the memory line,
  7538. // seconds later, was the first to show it. We reserve nothing
  7539. // and make the swap chain once, at the start.)
  7540. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  7541. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  7542. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  7543. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  7544. tracing::info!(
  7545. "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",
  7546. last[0] >> 20,
  7547. own.Budget >> 20,
  7548. crate::frame::current(),
  7549. last[1] >> 20,
  7550. last[2] >> 20
  7551. );
  7552. self.log_video_memory("right after that change");
  7553. }
  7554. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  7555. }
  7556. /// Both of the system's memory groups for this process, in bytes: for
  7557. /// the card's own memory and then for the PC's memory shared with the
  7558. /// card, the budget, the use, what could still be reserved and what
  7559. /// is reserved (the layer reserves none).
  7560. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  7561. let adapter = self.adapter.as_ref()?;
  7562. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7563. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7564. // SAFETY: plain queries that fill our structures.
  7565. unsafe {
  7566. adapter
  7567. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7568. .ok()?;
  7569. adapter
  7570. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7571. .ok()?;
  7572. }
  7573. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  7574. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  7575. };
  7576. Some([all(&own), all(&shared)])
  7577. }
  7578. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  7579. pub(crate) fn log_video_memory(&self, when: &str) {
  7580. let Some([own, shared]) = self.video_memory_groups() else {
  7581. return;
  7582. };
  7583. tracing::info!(
  7584. "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)",
  7585. when,
  7586. own[0] >> 20,
  7587. own[1] >> 20,
  7588. own[2] >> 20,
  7589. own[3] >> 20,
  7590. shared[0] >> 20,
  7591. shared[1] >> 20,
  7592. shared[2] >> 20,
  7593. shared[3] >> 20
  7594. );
  7595. }
  7596. /// A buffer in system memory that the CPU maps (write-back, so reading
  7597. /// it is fast too) and shaders read and write: for host copies of title
  7598. /// memory that shaders write, which upload memory cannot be. Starts in
  7599. /// the common state (buffers move out of it implicitly).
  7600. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7601. MADE[2].fetch_add(1, Ordering::Relaxed);
  7602. MADE[3].fetch_add(size, Ordering::Relaxed);
  7603. let heap = D3D12_HEAP_PROPERTIES {
  7604. Type: D3D12_HEAP_TYPE_CUSTOM,
  7605. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  7606. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  7607. ..Default::default()
  7608. };
  7609. let desc = D3D12_RESOURCE_DESC {
  7610. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7611. Width: size.max(1),
  7612. Height: 1,
  7613. DepthOrArraySize: 1,
  7614. MipLevels: 1,
  7615. SampleDesc: DXGI_SAMPLE_DESC {
  7616. Count: 1,
  7617. Quality: 0,
  7618. },
  7619. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7620. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7621. ..Default::default()
  7622. };
  7623. let mut buffer: Option<ID3D12Resource> = None;
  7624. let mut data = std::ptr::null_mut();
  7625. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7626. let made = unsafe {
  7627. self.device
  7628. .CreateCommittedResource(
  7629. &heap,
  7630. D3D12_HEAP_FLAG_NONE,
  7631. &desc,
  7632. D3D12_RESOURCE_STATE_COMMON,
  7633. None,
  7634. &mut buffer,
  7635. )
  7636. .and_then(|()| {
  7637. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7638. b.Map(0, None, Some(&mut data))
  7639. })
  7640. };
  7641. match made {
  7642. Ok(()) => Some((buffer?, data.cast())),
  7643. Err(e) => {
  7644. tracing::warn!(error = %e, size, "no shared buffer");
  7645. None
  7646. }
  7647. }
  7648. }
  7649. /// A device-local buffer shaders may write (unordered access) and indirect
  7650. /// execution may read, starting in the common state.
  7651. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7652. MADE[4].fetch_add(1, Ordering::Relaxed);
  7653. MADE[5].fetch_add(size, Ordering::Relaxed);
  7654. let heap = D3D12_HEAP_PROPERTIES {
  7655. Type: D3D12_HEAP_TYPE_DEFAULT,
  7656. ..Default::default()
  7657. };
  7658. let desc = D3D12_RESOURCE_DESC {
  7659. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7660. Width: size.max(1),
  7661. Height: 1,
  7662. DepthOrArraySize: 1,
  7663. MipLevels: 1,
  7664. SampleDesc: DXGI_SAMPLE_DESC {
  7665. Count: 1,
  7666. Quality: 0,
  7667. },
  7668. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7669. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7670. ..Default::default()
  7671. };
  7672. let mut buffer: Option<ID3D12Resource> = None;
  7673. // SAFETY: plain creation of a device-local buffer.
  7674. let made = unsafe {
  7675. self.device.CreateCommittedResource(
  7676. &heap,
  7677. D3D12_HEAP_FLAG_NONE,
  7678. &desc,
  7679. D3D12_RESOURCE_STATE_COMMON,
  7680. None,
  7681. &mut buffer,
  7682. )
  7683. };
  7684. match made {
  7685. Ok(()) => buffer,
  7686. Err(e) => {
  7687. tracing::warn!(error = %e, size, "no unordered-access buffer");
  7688. None
  7689. }
  7690. }
  7691. }
  7692. }
  7693. /// For adapters without device-removed data (the software one): the last
  7694. /// commands each list of the failed submission noted (diagnostics, with
  7695. /// `VICTORY_D3D12_DRED`).
  7696. fn last_notes(runs: &[&HostList]) -> String {
  7697. #[cfg(feature = "diagnostics")]
  7698. {
  7699. let mut text = String::new();
  7700. for (i, r) in runs.iter().enumerate() {
  7701. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  7702. for (n, _) in notes.iter().rev().take(6).rev() {
  7703. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  7704. }
  7705. }
  7706. text
  7707. }
  7708. #[cfg(not(feature = "diagnostics"))]
  7709. {
  7710. let _ = runs;
  7711. String::new()
  7712. }
  7713. }
  7714. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  7715. /// command reads (diagnostics).
  7716. #[cfg(feature = "diagnostics")]
  7717. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  7718. let end = start + bytes;
  7719. if va < start {
  7720. format!(" (fault {:#x} below its source)", start - va)
  7721. } else if va < end {
  7722. format!(" (fault at source +{:#x})", va - start)
  7723. } else {
  7724. format!(" (fault {:#x} past its source's end)", va - end)
  7725. }
  7726. }
  7727. /// The commands that may have been running where a list stopped at
  7728. /// command `done`: those between the barriers around it (work between
  7729. /// barriers overlaps on the GPU), by kind, and what the markers just
  7730. /// before them say (`HostList::note_op`: diagnostics builds with
  7731. /// device-removed data on).
  7732. /// For a list that stopped at command `done`: what the indirect executions
  7733. /// there ran, from the one before it to the next barrier (four at most), and
  7734. /// what the heap slots their user data names hold now.
  7735. #[cfg(feature = "diagnostics")]
  7736. fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &indirects::Shared) -> String {
  7737. let indirect = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT;
  7738. let all = all.lock().unwrap_or_else(|e| e.into_inner());
  7739. let mut text = String::new();
  7740. let mut shown = 0;
  7741. for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) {
  7742. if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) {
  7743. break;
  7744. }
  7745. if !indirect(op) {
  7746. continue;
  7747. }
  7748. shown += 1;
  7749. let Some((what, words)) = all.nth(indirects::before(history, at, indirect)) else {
  7750. continue;
  7751. };
  7752. text.push_str(&format!("; command {at} ran {what}"));
  7753. for (word, slot, what) in crate::descriptor::host::describe_slots(words) {
  7754. text.push_str(&format!(", word {word} slot {slot}: {what}"));
  7755. }
  7756. }
  7757. text
  7758. }
  7759. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  7760. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  7761. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  7762. let to = history[done..]
  7763. .iter()
  7764. .position(barrier)
  7765. .map_or(history.len(), |b| (done + b).max(done + 1));
  7766. let mut text = format!(", commands {from}..{to} between its barriers:");
  7767. let mut shown = 0;
  7768. // From just before the command the GPU had not finished: the first
  7769. // twelve after the barrier named draws long done when a list of 79
  7770. // mesh draws stopped at its 45th (run 41).
  7771. for i in from.max(done.saturating_sub(4))..to {
  7772. let op = history[i];
  7773. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  7774. continue;
  7775. }
  7776. shown += 1;
  7777. let marker = i
  7778. .checked_sub(1)
  7779. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  7780. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  7781. .map_or("no marker", |(_, s)| s.as_str());
  7782. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  7783. }
  7784. text
  7785. }
  7786. pub(crate) fn transition(
  7787. resource: &ID3D12Resource,
  7788. before: D3D12_RESOURCE_STATES,
  7789. after: D3D12_RESOURCE_STATES,
  7790. ) -> D3D12_RESOURCE_BARRIER {
  7791. D3D12_RESOURCE_BARRIER {
  7792. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  7793. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  7794. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  7795. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  7796. // SAFETY: a borrowed pointer; the barrier never releases it.
  7797. pResource: unsafe { std::mem::transmute_copy(resource) },
  7798. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  7799. StateBefore: before,
  7800. StateAfter: after,
  7801. }),
  7802. },
  7803. }
  7804. }
  7805. /// A window of the given client size, owned by its own message thread.
  7806. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7807. let (sender, receiver) = std::sync::mpsc::channel();
  7808. std::thread::Builder::new()
  7809. .name("victory-window".into())
  7810. .spawn(move || {
  7811. let made = make_window(width, height);
  7812. let ok = made.is_ok();
  7813. let _ = sender.send(made.map(|h| h.0 as usize));
  7814. if ok {
  7815. pump();
  7816. }
  7817. })
  7818. .map_err(|_| windows::core::Error::empty())?;
  7819. let hwnd = receiver
  7820. .recv()
  7821. .map_err(|_| windows::core::Error::empty())??;
  7822. Ok(HWND(hwnd as *mut _))
  7823. }
  7824. extern "system" fn window_proc(
  7825. hwnd: HWND,
  7826. message: u32,
  7827. wparam: WPARAM,
  7828. lparam: LPARAM,
  7829. ) -> LRESULT {
  7830. // SAFETY: the default handling for our window.
  7831. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  7832. }
  7833. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7834. const CLASS: PCWSTR = w!("VIctory");
  7835. // SAFETY: registers our class once and creates a window of it.
  7836. unsafe {
  7837. let instance = GetModuleHandleW(None)?;
  7838. let class = WNDCLASSEXW {
  7839. cbSize: size_of::<WNDCLASSEXW>() as u32,
  7840. lpfnWndProc: Some(window_proc),
  7841. hInstance: instance.into(),
  7842. lpszClassName: CLASS,
  7843. hCursor: LoadCursorW(None, IDC_ARROW)?,
  7844. ..Default::default()
  7845. };
  7846. RegisterClassExW(&class);
  7847. let mut rect = RECT {
  7848. left: 0,
  7849. top: 0,
  7850. right: width as i32,
  7851. bottom: height as i32,
  7852. };
  7853. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  7854. CreateWindowExW(
  7855. WINDOW_EX_STYLE(0),
  7856. CLASS,
  7857. w!("VIctory"),
  7858. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  7859. CW_USEDEFAULT,
  7860. CW_USEDEFAULT,
  7861. rect.right - rect.left,
  7862. rect.bottom - rect.top,
  7863. None,
  7864. None,
  7865. Some(instance.into()),
  7866. None,
  7867. )
  7868. }
  7869. }
  7870. fn pump() {
  7871. let mut message = MSG::default();
  7872. // SAFETY: the standard message loop of this thread's window.
  7873. unsafe {
  7874. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  7875. let _ = TranslateMessage(&message);
  7876. DispatchMessageW(&message);
  7877. }
  7878. }
  7879. }
  7880. #[cfg(test)]
  7881. mod trail {
  7882. /// The trail keeps the newest things, and the report made when the
  7883. /// host device is removed says them and the pipeline library's state
  7884. /// (no card is asked for any of it).
  7885. #[test]
  7886. fn the_removal_report_says_the_newest_things_done() {
  7887. for n in 0..super::TRAIL_MOST + 5 {
  7888. super::trail(|| format!("thing {n} done"));
  7889. }
  7890. let text = super::removal_context();
  7891. assert!(text.contains("the submitting thread was"));
  7892. assert!(text.contains("pipeline library: no call running"));
  7893. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  7894. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  7895. }
  7896. }
  7897. #[cfg(test)]
  7898. mod spare {
  7899. use super::Spare;
  7900. /// Kept things come back by size, the last given first, and nothing is
  7901. /// kept past the limit.
  7902. #[test]
  7903. fn kept_things_come_back_by_size_within_the_limit() {
  7904. let mut spare: Spare<u32> = Spare::new();
  7905. assert_eq!(spare.take(4), None);
  7906. assert_eq!(spare.give(1, 4, 10), None);
  7907. assert_eq!(spare.give(2, 1, 10), None);
  7908. assert_eq!(spare.give(3, 4, 10), None);
  7909. assert_eq!(spare.bytes, 9);
  7910. // Past the limit: handed back, nothing changes.
  7911. assert_eq!(spare.give(4, 4, 10), Some(4));
  7912. assert_eq!(spare.bytes, 9);
  7913. assert_eq!(spare.take(2), None, "no thing of that size");
  7914. assert_eq!(spare.take(4), Some(3));
  7915. assert_eq!(spare.take(4), Some(1));
  7916. assert_eq!(spare.take(4), None);
  7917. assert_eq!(spare.take(1), Some(2));
  7918. assert_eq!(spare.bytes, 0);
  7919. assert!(spare.kept.is_empty());
  7920. }
  7921. }
  7922. #[cfg(test)]
  7923. mod refresh_tests {
  7924. use super::Batch;
  7925. use crate::shadow::Shadow;
  7926. use std::sync::Arc;
  7927. use windows_sys::Win32::System::Memory::{
  7928. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  7929. VirtualAlloc,
  7930. };
  7931. const PAGE: usize = 64 << 10;
  7932. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  7933. /// Title memory for the tests (never given back: copies of it stay in
  7934. /// the guards): write-watched, or a view of a section.
  7935. fn title(len: usize, view: bool) -> usize {
  7936. // SAFETY: plain allocations.
  7937. let at = unsafe {
  7938. if view {
  7939. let section =
  7940. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  7941. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  7942. // As the runtime tells of it.
  7943. crate::title_memory_section(section as usize, len as u64, true);
  7944. crate::title_memory_remapped(at, len);
  7945. crate::title_memory_view(at, len, section as usize, 0);
  7946. at
  7947. } else {
  7948. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  7949. }
  7950. };
  7951. assert_ne!(at, 0);
  7952. at
  7953. }
  7954. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  7955. /// and every fourth page not there: as a title that streams has it.
  7956. fn with_holes(blocks: usize) -> usize {
  7957. use windows_sys::Win32::System::Memory::{
  7958. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  7959. VirtualAlloc2, VirtualFree,
  7960. };
  7961. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7962. // SAFETY: a placeholder and a section of our own.
  7963. unsafe {
  7964. let at = VirtualAlloc2(
  7965. GetCurrentProcess(),
  7966. std::ptr::null(),
  7967. blocks * PAGE,
  7968. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  7969. PAGE_NOACCESS,
  7970. std::ptr::null_mut(),
  7971. 0,
  7972. ) as usize;
  7973. assert_ne!(at, 0);
  7974. let len = blocks * PAGE;
  7975. let section =
  7976. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  7977. for block in (0..blocks).filter(|b| b % 4 != 3) {
  7978. let to = at + block * PAGE;
  7979. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  7980. let view = MapViewOfFile3(
  7981. section,
  7982. GetCurrentProcess(),
  7983. to as *const _,
  7984. (block * PAGE) as u64,
  7985. PAGE,
  7986. MEM_REPLACE_PLACEHOLDER,
  7987. PAGE_READWRITE,
  7988. std::ptr::null_mut(),
  7989. 0,
  7990. );
  7991. assert_eq!(view.Value as usize, to);
  7992. crate::title_memory_remapped(to, PAGE);
  7993. }
  7994. at
  7995. }
  7996. }
  7997. fn memory(len: usize) -> *mut u8 {
  7998. // SAFETY: a plain allocation.
  7999. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  8000. }
  8001. struct Random(u64);
  8002. impl Random {
  8003. fn below(&mut self, n: usize) -> usize {
  8004. self.0 ^= self.0 << 13;
  8005. self.0 ^= self.0 >> 7;
  8006. self.0 ^= self.0 << 17;
  8007. (self.0 >> 11) as usize % n
  8008. }
  8009. }
  8010. /// Prepares as a submission does: one asking for all the ranges, the
  8011. /// refreshes in several flushes, the asking's end.
  8012. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  8013. // One at a time, as submissions are.
  8014. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  8015. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  8016. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  8017. crate::watch::ask_once(&asked);
  8018. let mut batch = Batch::default();
  8019. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  8020. for (shadow, at, len) in part {
  8021. batch.add(shadow, *at, *len);
  8022. }
  8023. batch.flush();
  8024. }
  8025. crate::watch::ask_once_end();
  8026. }
  8027. /// Whatever is written where, by the title or by us, and whichever
  8028. /// copies (of both kinds of memory, over one another, none on a page
  8029. /// line) are refreshed in which ranges: a refreshed range holds what
  8030. /// title memory holds.
  8031. #[test]
  8032. fn refreshed_ranges_hold_title_memory() {
  8033. // SAFETY (all blocks): title memory and copies of the test's own,
  8034. // written by this thread and, in `Batch::flush`, by the threads that
  8035. // refresh, which are done when it returns.
  8036. let mut random = Random(0x1234_5678_9ABC_DEF1);
  8037. const LEN: usize = 24 * PAGE;
  8038. let regions = [title(LEN, false), title(LEN, true)];
  8039. let mut copies = Vec::new();
  8040. for &region in &regions {
  8041. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  8042. let data = memory(to - from);
  8043. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  8044. }
  8045. }
  8046. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  8047. for round in 0..600 {
  8048. for _ in 0..random.below(4) {
  8049. let at = regions[random.below(2)] + random.below(LEN - 64);
  8050. let n = 1 + random.below(60);
  8051. if random.below(3) == 0 {
  8052. // What shaders wrote.
  8053. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  8054. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  8055. Shadow::put(at, &was, &now);
  8056. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  8057. continue;
  8058. }
  8059. for i in 0..n {
  8060. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  8061. }
  8062. }
  8063. let mut ranges = Vec::new();
  8064. for (shadow, _) in &copies {
  8065. if random.below(3) == 0 {
  8066. continue;
  8067. }
  8068. let (start, len) = shadow.span();
  8069. let (start, len) = (start as usize, len as usize);
  8070. // Often the range of the time before, as a list's is.
  8071. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  8072. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  8073. ranges.push((shadow.clone(), start + from, n));
  8074. }
  8075. if ranges.is_empty() {
  8076. continue;
  8077. }
  8078. let flushes = 1 + random.below(3);
  8079. submission(&ranges, flushes);
  8080. for (shadow, at, n) in &ranges {
  8081. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  8082. let start = shadow.span().0 as usize;
  8083. let same = unsafe {
  8084. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  8085. };
  8086. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  8087. }
  8088. }
  8089. }
  8090. /// A copy in the card's memory, with the card's side and the sends to it
  8091. /// played by the test.
  8092. struct Carded {
  8093. shadow: Arc<Shadow>,
  8094. data: usize,
  8095. start: usize,
  8096. len: usize,
  8097. /// The last send, the last send every fetch to come is behind, and
  8098. /// the card's bytes: the queue's order is the order it is locked in.
  8099. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  8100. /// Whether a flight that writes it has not landed.
  8101. flying: std::sync::atomic::AtomicBool,
  8102. /// The dword of each eight its shaders write.
  8103. class: usize,
  8104. }
  8105. impl Carded {
  8106. fn new(start: usize, len: usize, class: usize) -> Carded {
  8107. let data = memory(len);
  8108. Carded {
  8109. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  8110. data: data as usize,
  8111. start,
  8112. len,
  8113. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  8114. flying: std::sync::atomic::AtomicBool::new(false),
  8115. class,
  8116. }
  8117. }
  8118. /// What changed on the CPU's side goes up.
  8119. fn send(&self) {
  8120. let mut card = self.card.lock().unwrap();
  8121. card.0 += 1;
  8122. let (number, merged) = (card.0, card.1);
  8123. for (a, b) in self.shadow.send_up(number, merged) {
  8124. // SAFETY: the copy's bytes; nothing writes those that are to
  8125. // go up.
  8126. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  8127. }
  8128. }
  8129. }
  8130. /// Everything at once: the title writes its memory on two threads, the
  8131. /// submitting thread puts its bytes in under shader writes
  8132. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  8133. /// the card's memory, one not), sends up what changed and declares what
  8134. /// the next flight's shaders write, and what flights wrote is landed
  8135. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  8136. /// still and the copies are refreshed once more, each of them, and the
  8137. /// card's side of those that have one, hold what title memory holds, and
  8138. /// title memory what was written last.
  8139. ///
  8140. /// Into the first copy shaders write besides through a view nobody
  8141. /// declared, words the title does not write: nothing that goes up ever
  8142. /// puts an older value over those.
  8143. ///
  8144. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  8145. /// only takes the block out of the guards' clean ones and leaves its bit,
  8146. /// or if a fault leaves the bit; in some thousand rounds,
  8147. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  8148. #[test]
  8149. fn landings_title_writes_and_light_refreshes_at_once() {
  8150. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  8151. assert!(crate::safecopy::on());
  8152. const LEN: usize = 24 * PAGE;
  8153. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  8154. let region = title(LEN, true);
  8155. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  8156. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  8157. let plain = {
  8158. let (start, len) = (region + 700, LEN - 9000);
  8159. let data = memory(len);
  8160. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  8161. };
  8162. // What was last written so, by offset.
  8163. let mut undeclared = std::collections::HashMap::new();
  8164. let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0");
  8165. let stop = AtomicBool::new(false);
  8166. // Also when an assertion fails on one of the threads.
  8167. struct Stop<'a>(&'a AtomicBool);
  8168. impl Drop for Stop<'_> {
  8169. fn drop(&mut self) {
  8170. self.0.store(true, Ordering::Relaxed);
  8171. }
  8172. }
  8173. // Held shared by who writes title memory, alone while it is looked at.
  8174. let still = std::sync::RwLock::new(());
  8175. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  8176. std::thread::scope(|s| {
  8177. for t in 0..2usize {
  8178. let (stop, still) = (&stop, &still);
  8179. s.spawn(move || {
  8180. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  8181. let mut value = 0u32;
  8182. while !stop.load(Ordering::Relaxed) {
  8183. {
  8184. let _moving = still.read().unwrap();
  8185. for _ in 0..3 {
  8186. value += 1;
  8187. // Of each eight dwords, one a thread.
  8188. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  8189. dword(at).store(value, Ordering::Relaxed);
  8190. }
  8191. }
  8192. std::thread::sleep(std::time::Duration::from_micros(20));
  8193. }
  8194. });
  8195. }
  8196. // Lands flights.
  8197. {
  8198. let (carded, stop) = (&carded, &stop);
  8199. s.spawn(move || {
  8200. let _stop = Stop(stop);
  8201. while let Ok((which, ranges, value)) = flights.recv() {
  8202. let c = &carded[which];
  8203. // Fetched: the card's bytes, behind every send so far.
  8204. let (after, now) = {
  8205. let card = c.card.lock().unwrap();
  8206. (card.0, card.2.clone())
  8207. };
  8208. // By piece: 64 KiB of title memory.
  8209. let mut pieces = Vec::new();
  8210. for &(from, to) in &ranges {
  8211. let mut at = from;
  8212. while at < to {
  8213. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  8214. pieces.push((at, next, now.as_ptr() as usize + at));
  8215. at = next;
  8216. }
  8217. }
  8218. let parts: Vec<_> = pieces.chunks(3).collect();
  8219. crate::land::each(parts.len(), &|i| {
  8220. let mut notes = crate::land::Notes::default();
  8221. // SAFETY: the bytes of `now`; each piece once.
  8222. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  8223. notes.flush();
  8224. });
  8225. for &(from, to) in &ranges {
  8226. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8227. // (The next fetch may have brought more.)
  8228. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  8229. }
  8230. }
  8231. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  8232. c.shadow.copy_back_done(&done);
  8233. c.card.lock().unwrap().1 = after;
  8234. c.flying.store(false, Ordering::Release);
  8235. }
  8236. });
  8237. }
  8238. let _stop = Stop(&stop);
  8239. let mut random = Random(0xABCD_EF01_2345_6789);
  8240. let check = |round: usize, random: &mut Random, quiet: bool| {
  8241. for c in &carded {
  8242. if c.shadow.writes_pending() {
  8243. let mut runs = usize::MAX;
  8244. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  8245. }
  8246. }
  8247. let mut ranges = Vec::new();
  8248. for (shadow, start, len) in
  8249. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  8250. {
  8251. // All of it, or a part; often the same part.
  8252. let (from, n) = match random.below(3) {
  8253. _ if quiet => (0, len),
  8254. 0 => (0, len),
  8255. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  8256. _ => {
  8257. let from = random.below(len / 4) * 4;
  8258. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  8259. }
  8260. };
  8261. ranges.push((shadow.clone(), start + from, n));
  8262. }
  8263. submission(&ranges, 1 + random.below(3));
  8264. carded.iter().for_each(Carded::send);
  8265. };
  8266. let mut value = 1u32;
  8267. for round in 0..rounds {
  8268. check(round, &mut random, false);
  8269. if exact {
  8270. let c = &carded[0];
  8271. let mut card = c.card.lock().unwrap();
  8272. for _ in 0..40 {
  8273. value += 1;
  8274. let at = random.below(LEN / 32) * 32 + 4 * 6;
  8275. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8276. undeclared.insert(at, value);
  8277. }
  8278. }
  8279. // The flight of this submission: its shaders' writes.
  8280. for (which, c) in carded.iter().enumerate() {
  8281. if c.flying.swap(true, Ordering::Acquire) {
  8282. continue;
  8283. }
  8284. value += 1;
  8285. let mut ranges: Vec<(usize, usize)> = Vec::new();
  8286. let first = random.below(6) * PAGE / 2;
  8287. for k in 0..2 {
  8288. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  8289. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  8290. if from < to {
  8291. ranges.push((from, to));
  8292. }
  8293. }
  8294. for &(from, to) in &ranges {
  8295. c.shadow.writing(c.start + from, to - from);
  8296. }
  8297. {
  8298. let mut card = c.card.lock().unwrap();
  8299. for &(from, to) in &ranges {
  8300. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8301. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8302. }
  8303. }
  8304. }
  8305. fly.send((which, ranges, value)).unwrap();
  8306. }
  8307. if round % 20 != 19 {
  8308. continue;
  8309. }
  8310. // Still: no flight in the air, no title write.
  8311. let _still = still.write().unwrap();
  8312. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  8313. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  8314. std::thread::yield_now();
  8315. }
  8316. check(round, &mut random, true);
  8317. // SAFETY: the test's own memory, written by nobody now.
  8318. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  8319. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  8320. for c in &carded {
  8321. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  8322. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  8323. let card = c.card.lock().unwrap();
  8324. let mut side = card.2.clone();
  8325. if c.class == carded[0].class {
  8326. // (They may have been landed meanwhile, by a flight
  8327. // that declared their range, and may not.)
  8328. for (&at, &value) in &undeclared {
  8329. let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
  8330. assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
  8331. side[at..at + 4].copy_from_slice(&there[at..at + 4]);
  8332. }
  8333. }
  8334. assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
  8335. }
  8336. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  8337. }
  8338. drop(fly);
  8339. });
  8340. }
  8341. /// The title's bytes put in under shader writes, for a copy of 174 MB
  8342. /// whose shader writes were declared as 40 ranges that overlap, with 12
  8343. /// pages written since. Run with `--ignored --nocapture`, and with
  8344. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8345. #[test]
  8346. #[ignore]
  8347. fn bytes_under_overlapping_ranges() {
  8348. const BIG: usize = 174 << 20;
  8349. let big = title(BIG, true);
  8350. // SAFETY (both): the test's own memory.
  8351. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  8352. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8353. copy.update(big, BIG);
  8354. copy.take_dirty();
  8355. for i in 0..40 {
  8356. copy.writing(big + i * 5920, BIG - i * 5920);
  8357. }
  8358. let mut best = f64::MAX;
  8359. for round in 0..30 {
  8360. for i in 0..12 {
  8361. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  8362. }
  8363. let started = std::time::Instant::now();
  8364. let mut runs = usize::MAX;
  8365. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  8366. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  8367. copy.take_dirty();
  8368. }
  8369. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  8370. }
  8371. /// A range nothing wrote is known to be as it was, at its ends too, and
  8372. /// is so no more once something wrote it.
  8373. #[test]
  8374. fn unchanged_ranges_are_known() {
  8375. for view in [false, true] {
  8376. let region = title(8 * PAGE, view);
  8377. // (A page read for the first time counts as written.)
  8378. // SAFETY: the test's own memory.
  8379. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  8380. let data = memory(8 * PAGE);
  8381. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  8382. // Ends in the middle of pages.
  8383. let (at, len) = (region + 500, 5 * PAGE);
  8384. let look = |expected: bool, what: &str| {
  8385. // The submission's one asking, which takes two ranges. (Again
  8386. // if a submission of another test ended it.)
  8387. let mut known = false;
  8388. for _ in 0..100 {
  8389. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  8390. known = copy.nothing_new(at, len);
  8391. if known || !expected {
  8392. break;
  8393. }
  8394. }
  8395. assert_eq!(known, expected, "view {view}: {what}");
  8396. let copied = copy.update(at, len);
  8397. crate::watch::ask_once_end();
  8398. copied
  8399. };
  8400. assert_eq!(look(false, "never taken"), len);
  8401. assert_eq!(look(true, "taken"), 0);
  8402. assert_eq!(look(true, "taken"), 0);
  8403. // SAFETY: the test's own memory.
  8404. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  8405. assert_eq!(look(false, "written at its end"), PAGE - 500);
  8406. assert_eq!(look(true, "taken again"), 0);
  8407. // Outside the range, on its last page.
  8408. // SAFETY: as above.
  8409. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  8410. assert_eq!(look(false, "written on its last page"), 500);
  8411. // A longer range was never taken whole.
  8412. assert!(!copy.nothing_new(region, 6 * PAGE));
  8413. }
  8414. }
  8415. /// Of a copy in the card's memory only the dwords title memory changed go
  8416. /// up, and none beside them, not even between two in 64 bytes; a page
  8417. /// never taken goes up whole.
  8418. #[test]
  8419. fn only_what_differs_goes_up() {
  8420. let region = title(4 * PAGE, true);
  8421. let data = memory(4 * PAGE);
  8422. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  8423. copy.update(region, 4 * PAGE);
  8424. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  8425. // What the relay does: shader writes into title memory, and into the
  8426. // CPU's side.
  8427. crate::watch::landing(region + PAGE + 640, 64);
  8428. // SAFETY: the test's own memory.
  8429. unsafe {
  8430. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  8431. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  8432. }
  8433. copy.update(region, 4 * PAGE);
  8434. let again = copy.take_dirty();
  8435. // SAFETY: as above.
  8436. unsafe {
  8437. ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
  8438. ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
  8439. ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
  8440. // The value that was there.
  8441. ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
  8442. }
  8443. copy.update(region, 4 * PAGE);
  8444. let written = copy.take_dirty();
  8445. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") {
  8446. assert_eq!(again, []);
  8447. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
  8448. } else {
  8449. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  8450. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  8451. }
  8452. // SAFETY: as above.
  8453. assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
  8454. }
  8455. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  8456. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  8457. /// big copy that 55 landed pieces and 9 title writes opened, while a
  8458. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  8459. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8460. #[test]
  8461. #[ignore]
  8462. fn frame_of_refreshes() {
  8463. let mut random = Random(0x9876_5432_1234_5671);
  8464. const EACH: usize = 224 << 10;
  8465. const BIG: usize = 174 << 20;
  8466. let watched = title(3000 * EACH, false);
  8467. // `VICTORY_BENCH_HOLES=0`: views without holes.
  8468. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  8469. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  8470. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  8471. let big = title(BIG, true);
  8472. // SAFETY: the test's own memory.
  8473. unsafe {
  8474. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  8475. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  8476. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  8477. }
  8478. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  8479. }
  8480. let mut small = Vec::new();
  8481. for i in 0..4400 {
  8482. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  8483. let data = memory(EACH);
  8484. // The range views read, not all of the copy.
  8485. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  8486. }
  8487. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  8488. // The same memory, as another copy: what is landed is landed through
  8489. // it, and the refreshes are of the first.
  8490. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8491. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  8492. let (mut sum, mut landing) = (0.0, 0.0);
  8493. const FRAMES: usize = 12;
  8494. for frame in 0..FRAMES {
  8495. let mut took = [0f64; 2];
  8496. for i in 0..30 {
  8497. // The title's writes, and the relay's beside the submission.
  8498. for _ in 0..9 {
  8499. let at = views + random.below(1400 * EACH / 8) * 8;
  8500. if there(at) {
  8501. // SAFETY: the test's own memory.
  8502. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8503. }
  8504. }
  8505. for _ in 0..60 {
  8506. let at = watched + random.below(3000 * EACH / 8) * 8;
  8507. // SAFETY: the test's own memory.
  8508. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8509. }
  8510. let first = random.below(BIG / PAGE - 60);
  8511. let lands = lands.clone();
  8512. let land = std::thread::spawn(move || {
  8513. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  8514. let started = std::time::Instant::now();
  8515. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  8516. let pieces: Vec<_> =
  8517. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  8518. let mut notes = crate::land::Notes::default();
  8519. // SAFETY: the bytes of `now`; nothing else lands here.
  8520. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  8521. notes.flush();
  8522. }
  8523. started.elapsed().as_secs_f64() * 1e3
  8524. });
  8525. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  8526. small.iter().cloned().chain([heap.clone()]).collect()
  8527. } else {
  8528. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  8529. };
  8530. let started = std::time::Instant::now();
  8531. submission(&ranges, 3);
  8532. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  8533. let put = land.join().unwrap();
  8534. if frame >= 2 {
  8535. landing += put;
  8536. }
  8537. heap.0.take_dirty();
  8538. }
  8539. if frame >= 2 {
  8540. sum += took[0] + took[1];
  8541. for k in 0..2 {
  8542. best[k] = best[k].min(took[k]);
  8543. asking[k] += took[k];
  8544. }
  8545. }
  8546. }
  8547. println!(
  8548. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  8549. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  8550. crate::watch::light(),
  8551. sum / (FRAMES - 2) as f64,
  8552. asking[0] / (FRAMES - 2) as f64,
  8553. best[0],
  8554. asking[1] / (FRAMES - 2) as f64,
  8555. best[1],
  8556. landing / (FRAMES - 2) as f64,
  8557. );
  8558. #[cfg(feature = "diagnostics")]
  8559. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  8560. }
  8561. }
  8562. #[cfg(test)]
  8563. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  8564. use super::Batch;
  8565. use std::sync::Arc;
  8566. #[test]
  8567. fn a_texture_is_checked_once_per_submission() {
  8568. let mut batch = Batch::default();
  8569. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  8570. // The first list sampling each texture checks it ...
  8571. assert!(batch.texture_due(&a));
  8572. assert!(batch.texture_due(&b));
  8573. // ... later lists of the same submission do not.
  8574. assert!(!batch.texture_due(&a));
  8575. assert!(!batch.texture_due(&a.clone()));
  8576. assert!(!batch.texture_due(&b));
  8577. }
  8578. #[test]
  8579. fn title_writes_make_textures_due_again() {
  8580. let mut batch = Batch::default();
  8581. let a = Arc::new(1u32);
  8582. assert!(batch.texture_due(&a));
  8583. assert!(!batch.texture_due(&a));
  8584. // A copy into title memory or work that may write it may have
  8585. // changed the texture's memory.
  8586. batch.title_written();
  8587. assert!(batch.texture_due(&a));
  8588. assert!(!batch.texture_due(&a));
  8589. // A fresh submission starts over.
  8590. let mut next = Batch::default();
  8591. assert!(next.texture_due(&a));
  8592. }
  8593. /// The hashing a submission does for textures in physical-page memory,
  8594. /// with every list checking the textures it samples (before) and with
  8595. /// each checked once (after). Run with
  8596. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  8597. #[test]
  8598. #[ignore = "benchmark"]
  8599. fn texture_checks_per_submission() {
  8600. const TEXTURES: usize = 48;
  8601. const SIZE: usize = 4 << 20;
  8602. const LISTS: usize = 12;
  8603. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  8604. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  8605. .collect();
  8606. let submit = |dedupe: bool| {
  8607. let mut batch = Batch::default();
  8608. let mut hashed = 0usize;
  8609. let started = std::time::Instant::now();
  8610. for _ in 0..LISTS {
  8611. for t in &textures {
  8612. if !dedupe || batch.texture_due(t) {
  8613. std::hint::black_box(blake3::hash(t));
  8614. hashed += 1;
  8615. }
  8616. }
  8617. }
  8618. (started.elapsed(), hashed)
  8619. };
  8620. submit(false); // warm up
  8621. let (before, n_before) = submit(false);
  8622. let (after, n_after) = submit(true);
  8623. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  8624. println!(
  8625. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  8626. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  8627. SIZE >> 20,
  8628. before.as_secs_f64() / after.as_secs_f64()
  8629. );
  8630. }
  8631. #[test]
  8632. fn vram_idle_ms_scales_with_pressure() {
  8633. let vram_idle_ms = |memory| super::vram_idle_for(memory, false);
  8634. let keeps = |memory| super::vram_idle_for(memory, true);
  8635. let gib = 1024 * 1024 * 1024;
  8636. assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000);
  8637. assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000);
  8638. assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500);
  8639. assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000);
  8640. assert_eq!(keeps(None), 5_000);
  8641. // Normal (< 75%)
  8642. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  8643. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  8644. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  8645. // Moderate (75%..85%)
  8646. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  8647. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  8648. // High (>= 85%, including over-budget)
  8649. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  8650. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  8651. // Missing or zero budget falls back to normal
  8652. assert_eq!(vram_idle_ms(None), 5_000);
  8653. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  8654. }
  8655. #[test]
  8656. fn ram_idle_ms_scales_with_pressure() {
  8657. let ram_idle_ms = |avail| super::ram_idle_for(avail, false);
  8658. assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000);
  8659. assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000);
  8660. assert_eq!(super::ram_idle_for(None, true), 10_000);
  8661. let gib = 1024 * 1024 * 1024;
  8662. // Normal (>= 4 GiB)
  8663. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  8664. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  8665. // Moderate (2 GiB..4 GiB)
  8666. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  8667. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  8668. // High (< 2 GiB)
  8669. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  8670. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  8671. // Missing falls back to normal
  8672. assert_eq!(ram_idle_ms(None), 10_000);
  8673. }
  8674. }