host.rs 396 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029
  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. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  145. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  146. /// when free physical RAM is low. Never returns less than 2,000 ms.
  147. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  148. const GIB: u64 = 1024 * 1024 * 1024;
  149. const NORMAL_MS: u64 = 10_000;
  150. const MODERATE_MS: u64 = 5_000;
  151. const HIGH_MS: u64 = 2_000;
  152. let Some(avail) = avail_phys else {
  153. return NORMAL_MS;
  154. };
  155. if avail < 2 * GIB {
  156. HIGH_MS
  157. } else if avail < 4 * GIB {
  158. MODERATE_MS
  159. } else {
  160. NORMAL_MS
  161. }
  162. }
  163. /// How many references are held on a host object (its COM count): ours
  164. /// all, since the host's views and commands hold none. A buffer or texture
  165. /// with one is held by its owner alone: no descriptor slot keeps it
  166. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  167. pub(crate) fn references(object: &impl Interface) -> u32 {
  168. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  169. let raw = object.as_raw();
  170. // SAFETY: a live COM object, whose first three methods are those of
  171. // `IUnknown` (query, add a reference, release one); the pair leaves the
  172. // count as it was, and the release returns it. The first is not called.
  173. unsafe {
  174. let methods = *raw.cast::<*const [Method; 3]>();
  175. ((*methods)[1])(raw);
  176. ((*methods)[2])(raw)
  177. }
  178. }
  179. /// Once a second, before a submission starts: lets go of what nothing
  180. /// names any more (copies of windows of title memory, staging buffers,
  181. /// host copies of textures the title fills).
  182. /// `VICTORY_SWEEP=0` keeps everything, as before.
  183. fn sweep() {
  184. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  185. crate::inplace::tick();
  186. static ON: OnceLock<bool> = OnceLock::new();
  187. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  188. return;
  189. }
  190. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  191. let now = now_ms();
  192. let last = LAST.load(Ordering::Relaxed);
  193. if now < last + 1000
  194. || LAST
  195. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  196. .is_err()
  197. {
  198. return;
  199. }
  200. crate::pipeline::trim_library();
  201. crate::shadow::let_go_idle();
  202. crate::texture::let_go_idle();
  203. crate::resource::let_go_idle();
  204. }
  205. /// Drops `object` once every submission running now has finished: at once
  206. /// if none is.
  207. pub(crate) fn retire<T: 'static>(object: T) {
  208. let started = STARTED.load(Ordering::Acquire);
  209. if started <= FINISHED.load(Ordering::Acquire) {
  210. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  211. drop(object);
  212. return;
  213. }
  214. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  215. RETIRED
  216. .lock()
  217. .unwrap_or_else(|e| e.into_inner())
  218. .push((started, Retired(Box::new(object))));
  219. }
  220. /// Drops what waited for submissions up to `finished`.
  221. fn bury(finished: u64) {
  222. let done: Vec<(u64, Retired)> = {
  223. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  224. if retired.is_empty() {
  225. return;
  226. }
  227. let (done, keep) = std::mem::take(&mut *retired)
  228. .into_iter()
  229. .partition(|(at, _)| *at <= finished);
  230. *retired = keep;
  231. done
  232. };
  233. drop(done);
  234. }
  235. /// Objects [`retire`] dropped at once (no submission was running) and
  236. /// kept until a running submission finished, since the start.
  237. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  238. /// What the layer did to the host's objects lately, newest last (sweeps
  239. /// that let host copies go, pipeline library calls, saves and trims): said
  240. /// once when the host device is removed ([`log_removal_context`]), with
  241. /// what the submitting thread and the pipeline workers were doing at that
  242. /// moment. A device the driver removes "internally" names no command, and
  243. /// the pass that happens to notice first names only the view it was at:
  244. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  245. /// pipeline library call that no line of the log tied to them.
  246. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  247. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  248. /// The entries kept.
  249. const TRAIL_MOST: usize = 96;
  250. fn trail_on() -> bool {
  251. static ON: OnceLock<bool> = OnceLock::new();
  252. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  253. }
  254. /// Microseconds since the first call.
  255. pub(crate) fn now_us() -> u64 {
  256. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  257. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  258. }
  259. /// The calling thread, as the log's other lines name threads.
  260. pub(crate) fn thread_id() -> u32 {
  261. // SAFETY: a plain query.
  262. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  263. }
  264. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  265. /// run when the trail is kept.
  266. pub(crate) fn trail(what: impl FnOnce() -> String) {
  267. if !trail_on() {
  268. return;
  269. }
  270. let entry = (now_us(), thread_id(), what());
  271. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  272. if trail.len() >= TRAIL_MOST {
  273. trail.pop_front();
  274. }
  275. trail.push_back(entry);
  276. }
  277. /// What the submitting thread is doing (0 nothing: between submissions,
  278. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  279. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  280. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  281. fn submitting(phase: u64, lists: usize) {
  282. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  283. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  284. SUBMITTING[0].store(phase, Ordering::Relaxed);
  285. }
  286. /// What was going on when the host device went: whether a submission was
  287. /// on the card, the pipeline library's state and the calls running in it,
  288. /// and the trail.
  289. pub(crate) fn removal_context() -> String {
  290. use std::fmt::Write;
  291. let now = now_us();
  292. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  293. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  294. 0 => "between submissions (nothing of ours was running on the card)",
  295. 1 => "preparing a submission (nothing of ours was running on the card)",
  296. 2 => "waiting for the card to run a submission",
  297. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  298. };
  299. let mut text = format!(
  300. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  301. SUBMITTING[1].load(Ordering::Relaxed),
  302. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  303. crate::pipeline::library_removal_note(),
  304. RETIREMENTS[0].load(Ordering::Relaxed),
  305. RETIREMENTS[1].load(Ordering::Relaxed),
  306. STARTED.load(Ordering::Relaxed),
  307. FINISHED.load(Ordering::Relaxed),
  308. );
  309. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  310. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  311. for (at, thread, what) in trail.iter() {
  312. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  313. }
  314. text
  315. }
  316. /// Says [`removal_context`] in the log, once: called by whoever finds the
  317. /// host device removed.
  318. pub(crate) fn log_removal_context() {
  319. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  320. if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) {
  321. return;
  322. }
  323. tracing::error!("when the host device went: {}", removal_context());
  324. if dred_any() {
  325. let data = host().map(|h| h.removal_data(&[])).unwrap_or_default();
  326. tracing::error!("device-removed data{}", if data.is_empty() { "; none" } else { &data });
  327. }
  328. }
  329. /// Time spent in submissions since the last frame-rate line, in
  330. /// microseconds: preparing them on the CPU (title memory copies, texture
  331. /// detiling), then waiting for the GPU.
  332. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  333. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  334. /// After submissions: shader-written ranges compared and copied back into
  335. /// title memory (microseconds, bytes that differed), since the last
  336. /// frame-rate line.
  337. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  338. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  339. /// The card's clock, for the frame line of every run, in microseconds since
  340. /// the last one: how long the card had nothing of ours queued; how much of
  341. /// that while the thread that holds the submission lock was working (the
  342. /// card idle behind us: preparing and copying back are done with the card
  343. /// standing); and how long that thread stood waiting for the card.
  344. ///
  345. /// Every send of lists to the queue is followed by a signal on a fence of
  346. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  347. /// the newest signal and notes the moment the card reached it with nothing
  348. /// newer sent; the next send ends that idle stretch.
  349. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  350. /// Of the thread that holds the submission lock: the microseconds it has
  351. /// worked so far (preparing, copying back; not its waits for the card), and
  352. /// since when it works now ([`now_us`] plus one; 0: it does not).
  353. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  354. /// The thread that holds the submission lock starts (`on`) or stops
  355. /// working; whether it worked until now.
  356. fn working(on: bool) -> bool {
  357. let now = now_us() + 1;
  358. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  359. if since != 0 {
  360. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  361. }
  362. since != 0
  363. }
  364. /// [`WORKING`] as of now: microseconds worked so far.
  365. fn worked() -> u64 {
  366. let since = WORKING[1].load(Ordering::Relaxed);
  367. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  368. WORKING[0].load(Ordering::Relaxed) + now
  369. }
  370. /// The thread that holds the submission lock stood waiting for the card
  371. /// from `since` until now ([`CARD_CLOCK_US`]).
  372. fn stood(since: std::time::Instant) {
  373. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  374. }
  375. /// What [`CARD_CLOCK_US`] is measured with.
  376. struct CardClock {
  377. fence: ID3D12Fence,
  378. /// Signals sent so far; and, while the card has reached the last of
  379. /// them, since when and what [`worked`] said then.
  380. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  381. sent: std::sync::Condvar,
  382. }
  383. // SAFETY: a fence (free-threaded) behind a lock.
  384. unsafe impl Send for CardClock {}
  385. // SAFETY: as above.
  386. unsafe impl Sync for CardClock {}
  387. /// The clock's thread: waits for the newest signal sent and notes when the
  388. /// card got there with nothing newer behind it.
  389. fn card_clock_watch(clock: &'static CardClock) {
  390. // SAFETY: a plain event of our own.
  391. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  392. return;
  393. };
  394. let mut seen = 0;
  395. loop {
  396. let target = {
  397. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  398. while state.0 == seen {
  399. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  400. }
  401. state.0
  402. };
  403. // SAFETY: the clock's fence and this thread's event.
  404. unsafe {
  405. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  406. WaitForSingleObject(event, INFINITE);
  407. }
  408. }
  409. seen = target;
  410. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  411. if state.0 == target && state.1.is_none() {
  412. state.1 = Some((std::time::Instant::now(), worked()));
  413. }
  414. }
  415. }
  416. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  417. /// frame's time.
  418. fn card_clock_line(frames: f64, ms: f64) {
  419. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  420. tracing::info!(
  421. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  422. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  423. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  424. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  425. );
  426. }
  427. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  428. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  429. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  430. std::sync::atomic::AtomicU64::new(0),
  431. std::sync::atomic::AtomicU64::new(0),
  432. std::sync::atomic::AtomicU64::new(0),
  433. std::sync::atomic::AtomicU64::new(0),
  434. ];
  435. /// Host buffers made since the start, as (count, bytes): in the upload heap
  436. /// (staging, list scratch), shared with the processor (host copies of title
  437. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  438. /// For the memory line: against what is alive, they show what was let go.
  439. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  440. /// What of that is alive now, for the memory line (`MADE` counts what was
  441. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  442. /// and nothing said how many were alive): host lists; the lists' scratch
  443. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  444. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  445. /// instead of made, since the start; and the lists' other upload buffers
  446. /// (texture data copied from buffers, scratch too big for a chunk) and
  447. /// their bytes.
  448. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  449. /// About host lists, for the memory line: lists made by the host since the
  450. /// start; preludes made (a list's second allocator and list, made when it
  451. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  452. /// bytes the process's private memory grew by while lists were being made
  453. /// (what a list costs: host objects with the driver's command memory; 631
  454. /// lists were alive in run 65, each with a prelude it may never use).
  455. /// Then the lists alive that were never reset since they were made: the
  456. /// host sides of title lists the title made and has not used (a host list
  457. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  458. /// makes at its start).
  459. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  460. /// The process's private bytes (diagnostics: around the making of lists).
  461. #[cfg(feature = "diagnostics")]
  462. fn private_bytes() -> u64 {
  463. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  464. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  465. let mut c = PROCESS_MEMORY_COUNTERS {
  466. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  467. ..Default::default()
  468. };
  469. // SAFETY: our own process and a sized structure.
  470. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  471. c.PagefileUsage as u64
  472. }
  473. /// What the runtime does when the host GPU fails for good: report it like a
  474. /// crash and end the run. The console has no such state, and carrying on
  475. /// draws nothing at seconds per frame.
  476. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  477. /// Sets what a host GPU failure does (the runtime's crash report).
  478. pub fn on_failure(report: fn(&str) -> !) {
  479. let _ = ON_FAILURE.set(report);
  480. }
  481. /// Ends the run on a host GPU failure: what failed, the removal reason and
  482. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  483. /// diagnostics build names the command).
  484. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  485. let mut text = what.to_string();
  486. if let Some(host) = host() {
  487. // SAFETY: a plain query.
  488. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  489. text.push_str(&format!("; device removed: {e}"));
  490. log_removal_context();
  491. }
  492. match host.log_messages() {
  493. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  494. None if host.messages.is_none() => text.push_str(
  495. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  496. ),
  497. None => {}
  498. }
  499. }
  500. tracing::error!("{text}");
  501. // Tests have no log: the reason goes to their output.
  502. #[cfg(test)]
  503. eprintln!("host GPU failure: {text}");
  504. match ON_FAILURE.get() {
  505. Some(report) => report(&text),
  506. None => std::process::abort(),
  507. }
  508. }
  509. /// The host GPU, created on first use; `None` without one (a run then
  510. /// behaves as before: nothing executes).
  511. pub(crate) fn host() -> Option<&'static Host> {
  512. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  513. HOST.get_or_init(|| match create() {
  514. Ok(host) => Some(host),
  515. Err(e) => {
  516. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  517. None
  518. }
  519. })
  520. .as_ref()
  521. }
  522. fn create() -> windows::core::Result<Host> {
  523. // SAFETY: plain D3D12 object creation with valid descriptions.
  524. unsafe {
  525. // The debug layer only in builds with diagnostics.
  526. let debug = cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DEBUG");
  527. if debug {
  528. let mut layer: Option<ID3D12Debug> = None;
  529. match D3D12GetDebugInterface(&mut layer) {
  530. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  531. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  532. }
  533. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  534. // descriptor heap indices and the like become messages naming
  535. // the command instead of page faults. Without state tracking
  536. // (directly indexed textures are not transitioned).
  537. if crate::switch::on("VICTORY_D3D12_GBV")
  538. && let Some(l) = &layer
  539. {
  540. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  541. d1.SetEnableGPUBasedValidation(true);
  542. }
  543. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  544. d2.SetGPUBasedValidationFlags(
  545. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  546. );
  547. }
  548. tracing::info!("GPU-based validation on");
  549. }
  550. }
  551. // Diagnostics: device-removed data (the command that faulted, the
  552. // faulting address), read when the device is removed.
  553. if dred_any() {
  554. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  555. if D3D12GetDebugInterface(&mut dred).is_ok()
  556. && let Some(dred) = dred
  557. {
  558. if dred_on() || dred_light() {
  559. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  560. }
  561. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  562. tracing::info!(
  563. breadcrumbs = dred_on() || dred_light(),
  564. markers = dred_on(),
  565. "crash tracing on (device-removed data)"
  566. );
  567. } else {
  568. tracing::warn!("crash tracing asked for and not there: no device-removed data settings");
  569. }
  570. }
  571. let mut device: Option<ID3D12Device> = None;
  572. // Diagnostics: the software adapter, on which a shader's wild access
  573. // is an access violation in this process (a crash report with the
  574. // address and instruction) instead of a GPU fault and driver reset.
  575. if cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_WARP") {
  576. let adapter = warp_adapter()?;
  577. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  578. tracing::info!("host device on the software adapter (WARP)");
  579. } else {
  580. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  581. // Whether a GPU hang ends the run or freezes the PC (#1054).
  582. crate::tdr::log();
  583. }
  584. let device = device.ok_or_else(windows::core::Error::empty)?;
  585. // Before anything is made with it (`VICTORY_RECORD`).
  586. #[cfg(feature = "diagnostics")]
  587. crate::replay::record::from_env(&device);
  588. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  589. // driver compiling shaders again on the "D3D Background Thread"s,
  590. // for minutes after pipelines were made or loaded) is switched off.
  591. // An experiment: while those threads ran, the same shot took
  592. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  593. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  594. // whether the card is slower with the shaders it then keeps is not
  595. // known.
  596. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  597. && let Ok(device6) = device.cast::<ID3D12Device6>()
  598. {
  599. let set = device6.SetBackgroundProcessingMode(
  600. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  601. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  602. None,
  603. None,
  604. );
  605. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  606. }
  607. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  608. // cross-lane code stays in 32-lane halves translated for waves of 32
  609. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  610. if device
  611. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  612. .is_ok()
  613. {
  614. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  615. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  616. }
  617. let messages = debug
  618. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  619. .flatten();
  620. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  621. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  622. ..Default::default()
  623. })?;
  624. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  625. let event = CreateEventW(None, false, false, None)?;
  626. let rtvs: ID3D12DescriptorHeap =
  627. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  628. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  629. NumDescriptors: RTV_RING,
  630. ..Default::default()
  631. })?;
  632. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  633. let dsvs: ID3D12DescriptorHeap =
  634. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  635. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  636. NumDescriptors: RTV_RING,
  637. ..Default::default()
  638. })?;
  639. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  640. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  641. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  642. .ok();
  643. tracing::info!("host D3D12 device ready");
  644. Ok(Host {
  645. device,
  646. queue,
  647. fence,
  648. submitted: Mutex::new(0),
  649. event,
  650. rtvs,
  651. rtv_size,
  652. dsvs,
  653. dsv_size,
  654. next_dsv: AtomicU32::new(0),
  655. messages,
  656. next_rtv: AtomicU32::new(0),
  657. presenter: Mutex::new(None),
  658. adapter,
  659. })
  660. }
  661. }
  662. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  663. /// Reject it before creating a device in diagnostics' software-only mode.
  664. pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  665. // SAFETY: plain DXGI adapter queries.
  666. unsafe {
  667. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  668. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  669. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  670. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  671. tracing::warn!(
  672. vendor = format_args!("{:#x}", desc.VendorId),
  673. flags = format_args!("{:#x}", desc.Flags),
  674. "DXGI did not identify the WARP adapter as software; refusing device"
  675. );
  676. return Err(windows::core::Error::from_hresult(
  677. windows::Win32::Foundation::E_FAIL,
  678. ));
  679. }
  680. Ok(adapter)
  681. }
  682. }
  683. #[cfg(test)]
  684. mod tests {
  685. /// A list of ours is found by its name, with the debug layer's note or not.
  686. #[cfg(feature = "diagnostics")]
  687. #[test]
  688. fn a_list_is_found_by_the_number_in_its_name() {
  689. assert_eq!(super::list_number("victory host list 7"), Some(7));
  690. assert_eq!(super::list_number("victory host list 158 (debug layer indirect)"), Some(158));
  691. assert_eq!(super::list_number("victory host list 7x"), None);
  692. assert_eq!(super::list_number("victory host list 7 x"), None);
  693. assert_eq!(super::list_number("another list 7"), None);
  694. assert_eq!(super::list_number(""), None);
  695. }
  696. /// What is there of a range some of whose pages are not: those bytes,
  697. /// counted, and zeros for the rest, whatever the buffer held.
  698. #[test]
  699. fn what_is_there_is_read_and_the_rest_is_zeros() {
  700. use windows_sys::Win32::System::Memory::*;
  701. const SIZE: usize = 0x8_0000;
  702. // SAFETY: a reservation of ours; only committed pages are written.
  703. unsafe {
  704. let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  705. assert!(!at.is_null());
  706. // 0-0x1_1000 and 0x3_0000-0x4_0000 are there.
  707. for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] {
  708. assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null());
  709. at.add(from).write_bytes(0x5a, len);
  710. }
  711. // From an address inside a page, as textures are packed.
  712. let mut out = vec![0x77u8; SIZE - 0x300];
  713. assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000);
  714. for (i, &b) in out.iter().enumerate() {
  715. let from = i + 0x300;
  716. let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from);
  717. assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}");
  718. }
  719. // All there: one read.
  720. let mut out = vec![0x77u8; 0x1_0000];
  721. assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000);
  722. assert!(out.iter().all(|&b| b == 0x5a));
  723. // Nothing there.
  724. let mut out = vec![0x77u8; 0x1_0000];
  725. assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0);
  726. assert!(out.iter().all(|&b| b == 0));
  727. assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0);
  728. }
  729. }
  730. /// Zeros for a title destination that went meanwhile are no fault.
  731. #[test]
  732. fn zeros_where_nothing_is_are_lost() {
  733. use windows_sys::Win32::System::Memory::*;
  734. // SAFETY: a reservation of ours, its first page committed.
  735. unsafe {
  736. let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  737. assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
  738. at.write_bytes(7, 4096);
  739. super::zero(at, 4096);
  740. assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
  741. super::zero(at.add(4096), 4096);
  742. VirtualFree(at.cast(), 0, MEM_RELEASE);
  743. }
  744. }
  745. #[test]
  746. fn sparse_copies_preserve_islands_and_observe_remaps() {
  747. use windows_sys::Win32::System::Memory::*;
  748. const N: usize = 5 << 16;
  749. // SAFETY: we reserve a private region, commit selected pages inside it,
  750. // and only directly access the pages while they are writable.
  751. unsafe {
  752. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  753. assert!(!base.is_null());
  754. let mut expected = vec![0; N];
  755. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  756. let at = base.add(offset);
  757. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  758. at.write_bytes(value, 4096);
  759. expected[offset..offset + 4096].fill(value);
  760. }
  761. for remap in [false, true] {
  762. if remap {
  763. let mut old = 0;
  764. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  765. expected[..4096].fill(0);
  766. let at = base.add(1 << 16);
  767. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  768. at.write_bytes(0xc7, 4096);
  769. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  770. }
  771. let mut out = vec![0xee; N];
  772. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  773. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  774. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  775. }
  776. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  777. }
  778. }
  779. use super::*;
  780. #[test]
  781. fn warp_adapter_accepts_only_software() {
  782. // This probes DXGI without creating a D3D12 device or running a title.
  783. // SAFETY: plain DXGI adapter queries.
  784. let raw = unsafe {
  785. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  786. else {
  787. return;
  788. };
  789. factory.EnumWarpAdapter::<IDXGIAdapter>()
  790. };
  791. let Ok(raw) = raw else { return };
  792. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  793. // IDXGIAdapter1; `raw` owns that interface.
  794. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  795. eprintln!(
  796. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  797. desc.VendorId, desc.Flags
  798. );
  799. assert_eq!(
  800. warp_adapter().is_ok(),
  801. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  802. );
  803. }
  804. }
  805. /// The batches of clamped records in one scratch buffer
  806. /// ([`HostList::batch_place`]).
  807. const BATCHES: u32 = 8;
  808. /// A host command list and its allocator, always used together.
  809. pub(crate) struct HostList {
  810. allocator: ID3D12CommandAllocator,
  811. pub(crate) list: ID3D12GraphicsCommandList,
  812. /// Work for submission time, in recorded order.
  813. deferred: Mutex<Deferred>,
  814. /// Upload memory for data the list's draws make (expanded vertices),
  815. /// reused after a reset.
  816. scratch: Mutex<Scratch>,
  817. /// Host texture states the list assumes, by host copy: at its start and
  818. /// at its end. Lists are recorded on many threads and run in submission
  819. /// order, so the transitions from a texture's real state are made at
  820. /// submission, in `prelude`. Holding the copies keeps every texture the
  821. /// list names alive until it is reset, even if the title releases the
  822. /// resource first.
  823. states: Mutex<States>,
  824. /// What the list does with depth textures that have a colour twin, by
  825. /// twin ([`TwinUse`]).
  826. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  827. /// The list that runs those transitions just before this one, made
  828. /// when the list first has such transitions ([`lazy_prelude`]).
  829. prelude: OnceLock<Option<Prelude>>,
  830. /// The pipelines the list binds, for reports of slow submissions.
  831. pipelines: std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>,
  832. /// The work its indirect executions may still do (`indirect`): a
  833. /// shader-writable word, zeroed when the list is submitted, and after
  834. /// it what the clamp notes about mesh records. In memory the CPU maps.
  835. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  836. /// The same words in the card's own memory ([`card_budget`]), which the
  837. /// clamp uses instead when there is one: zeroed in the list before its
  838. /// first clamp, its notes copied to `budget` when the list closes.
  839. card_budget: OnceLock<Option<ID3D12Resource>>,
  840. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  841. /// grown to the largest indirect execution recorded on the list.
  842. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  843. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  844. /// how many batches of this recording have a place in them.
  845. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  846. /// Counts the list in [`ALIVE`] while it lives.
  847. _alive: Counted,
  848. /// The texts of the markers `note_op` set, in order (for device-removed
  849. /// data without marker texts), with the host GPU range a copy reads.
  850. #[cfg(feature = "diagnostics")]
  851. notes: std::sync::Arc<Mutex<Vec<Note>>>,
  852. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  853. /// and at the end, and where they are read back.
  854. #[cfg(feature = "diagnostics")]
  855. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  856. }
  857. /// A list's prelude: an allocator and a closed list.
  858. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  859. /// Whether a host list's prelude is made when the list first needs one. A
  860. /// prelude runs the texture transitions and twin copies a list needs before
  861. /// it; lists that name no texture never have one, and every host list was
  862. /// made with one all the same: twice the host objects per list, for the
  863. /// title's 630 lists and for every list made anew.
  864. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  865. fn lazy_prelude() -> bool {
  866. static ON: OnceLock<bool> = OnceLock::new();
  867. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  868. }
  869. /// Timestamps per list (diagnostics); commands past them are not timed.
  870. #[cfg(feature = "diagnostics")]
  871. const STAMPS: u32 = 4096;
  872. /// A marker's text and the host range its command reads (diagnostics).
  873. #[cfg(feature = "diagnostics")]
  874. type Note = (String, Option<(u64, u64)>);
  875. type States = std::collections::HashMap<
  876. usize,
  877. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  878. >;
  879. /// What a list does with a depth texture that has a colour twin
  880. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  881. /// in submission order, so a list cannot know which side an earlier list
  882. /// leaves behind: it notes which sides it uses as it finds them, and its
  883. /// prelude copies one side into the other at submission if that side is
  884. /// behind then. From its first use of a side on, the list knows.
  885. struct TwinUse {
  886. /// The depth texture (the title resource's host copy) and its twin.
  887. depth: std::sync::Arc<crate::resource::HostTexture>,
  888. twin: std::sync::Arc<crate::resource::Twin>,
  889. /// The sides (depth texture, twin) the list uses as it finds them.
  890. needs: [bool; 2],
  891. /// Whether each side lacks what the other was written last, where the
  892. /// list is now; `None`: as the list found it.
  893. behind: [Option<bool>; 2],
  894. /// The draw or dispatch being prepared writes the twin.
  895. writing: bool,
  896. /// The depth plane's twin holds what the plane lacks although the list
  897. /// copied the twins since: the plane's pass waits for the list's close.
  898. late: bool,
  899. }
  900. /// The pass that draws the twin of a depth plane into the plane: one
  901. /// triangle over each mip of each slice, its pixel shader writing the
  902. /// twin's texel as the depth, with the depth test "always" and no stencil
  903. /// (the stencil plane is copied through a buffer and not touched here).
  904. ///
  905. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  906. /// the step times the float nearest 1/65535 (0x37800080). That is how
  907. /// The title's tiled lighting computes the depth of the
  908. /// rectangles it then draws with the test "equal", one class of materials
  909. /// a draw (all six of its vertex shaders multiply the class number by that
  910. /// constant), so the pass and the draw give the host the same float, and
  911. /// the host turns the same float into the same 24 bits. The step divided
  912. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  913. /// and lands in another 24-bit step for 127 of them (none under 385).
  914. const PLANE_CORNERS: &str = r#"
  915. float4 corner(uint i : SV_VertexID) : SV_Position {
  916. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  917. }
  918. "#;
  919. const PLANE_STEPS: &str = r#"
  920. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  921. Texture2DArray<uint> twin : register(t0);
  922. [RootSignature(RS)]
  923. float plane(float4 p : SV_Position) : SV_Depth {
  924. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  925. }
  926. "#;
  927. const PLANE_FLOATS: &str = r#"
  928. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  929. Texture2DArray<float> twin : register(t0);
  930. [RootSignature(RS)]
  931. float plane(float4 p : SV_Position) : SV_Depth {
  932. return twin.Load(int4(int2(p.xy), 0, 0));
  933. }
  934. "#;
  935. /// Views of twins the pass reads, in a heap of ours used as a ring.
  936. /// shortcut: a view must last until its list has run; with one or two
  937. /// passes a frame the ring is far from coming round.
  938. const PLANE_VIEWS: u32 = 256;
  939. /// What the pass draws with: the heap of its views of twins, and per kind
  940. /// of twin (16-bit steps or floats) and depth format the root signature
  941. /// and pipeline, made when first needed (`None`: the host refused).
  942. struct PlanePass {
  943. views: ID3D12DescriptorHeap,
  944. cpu: usize,
  945. gpu: u64,
  946. step: u32,
  947. next: AtomicU32,
  948. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  949. }
  950. /// The pass's root signature and pipeline for one kind of twin and one
  951. /// depth format.
  952. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  953. // SAFETY: D3D12 objects are free-threaded.
  954. unsafe impl Send for PlanePass {}
  955. // SAFETY: as above.
  956. unsafe impl Sync for PlanePass {}
  957. fn plane_pass() -> Option<&'static PlanePass> {
  958. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  959. PASS.get_or_init(|| {
  960. let host = host()?;
  961. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  962. // SAFETY: plain heap creation and queries.
  963. unsafe {
  964. let views: ID3D12DescriptorHeap = host
  965. .device
  966. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  967. Type: kind,
  968. NumDescriptors: PLANE_VIEWS,
  969. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  970. NodeMask: 0,
  971. })
  972. .ok()?;
  973. Some(PlanePass {
  974. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  975. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  976. step: host.device.GetDescriptorHandleIncrementSize(kind),
  977. views,
  978. next: AtomicU32::new(0),
  979. made: Mutex::default(),
  980. })
  981. }
  982. })
  983. .as_ref()
  984. }
  985. /// Compiles function `entry` of `source` for `target` with the system's
  986. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  987. pub(crate) fn compile(
  988. source: &str,
  989. entry: windows::core::PCSTR,
  990. target: windows::core::PCSTR,
  991. ) -> windows::core::Result<Vec<u8>> {
  992. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  993. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  994. let mut code: Option<ID3DBlob> = None;
  995. let mut errors: Option<ID3DBlob> = None;
  996. // SAFETY: the source and names live through the call; out pointers ours.
  997. let compiled = unsafe {
  998. D3DCompile(
  999. source.as_ptr().cast(),
  1000. source.len(),
  1001. windows::core::s!("victory"),
  1002. None,
  1003. None,
  1004. entry,
  1005. target,
  1006. 0,
  1007. 0,
  1008. &mut code,
  1009. Some(&mut errors),
  1010. )
  1011. };
  1012. if let Err(e) = compiled {
  1013. if let Some(errors) = errors {
  1014. // SAFETY: the blob's own bytes.
  1015. let text = unsafe {
  1016. std::slice::from_raw_parts(
  1017. errors.GetBufferPointer().cast::<u8>(),
  1018. errors.GetBufferSize(),
  1019. )
  1020. };
  1021. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  1022. }
  1023. return Err(e);
  1024. }
  1025. let code = code.ok_or_else(windows::core::Error::empty)?;
  1026. // SAFETY: the blob's own bytes.
  1027. let bytes = unsafe {
  1028. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  1029. };
  1030. Ok(bytes.to_vec())
  1031. }
  1032. impl PlanePass {
  1033. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  1034. /// or of floats and the depth format `format`.
  1035. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  1036. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1037. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  1038. return pipeline.clone();
  1039. }
  1040. let pipeline = match Self::make(steps, format) {
  1041. Ok(pipeline) => Some(pipeline),
  1042. Err(e) => {
  1043. tracing::warn!(
  1044. error = %e,
  1045. steps,
  1046. format = format.0,
  1047. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  1048. );
  1049. None
  1050. }
  1051. };
  1052. made.push((steps, format.0, pipeline.clone()));
  1053. pipeline
  1054. }
  1055. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  1056. use windows::core::s;
  1057. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  1058. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  1059. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  1060. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  1061. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  1062. pShaderBytecode: bytes.as_ptr().cast(),
  1063. BytecodeLength: bytes.len(),
  1064. };
  1065. // SAFETY: the root signature is inside the pixel shader; the
  1066. // description points at live data and never releases its pointer.
  1067. unsafe {
  1068. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  1069. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1070. pRootSignature: std::mem::transmute_copy(&root),
  1071. VS: code(&vs[..]),
  1072. PS: code(&ps[..]),
  1073. SampleMask: u32::MAX,
  1074. RasterizerState: D3D12_RASTERIZER_DESC {
  1075. FillMode: D3D12_FILL_MODE_SOLID,
  1076. CullMode: D3D12_CULL_MODE_NONE,
  1077. DepthClipEnable: true.into(),
  1078. ..Default::default()
  1079. },
  1080. // Every texel is written; stencil stays off.
  1081. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1082. DepthEnable: true.into(),
  1083. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  1084. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1085. ..Default::default()
  1086. },
  1087. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1088. DSVFormat: format,
  1089. SampleDesc: DXGI_SAMPLE_DESC {
  1090. Count: 1,
  1091. Quality: 0,
  1092. },
  1093. ..Default::default()
  1094. };
  1095. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1096. Ok((root, pipeline))
  1097. }
  1098. }
  1099. }
  1100. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1101. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1102. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1103. /// heap, graphics root signature, pipeline, depth target, viewport,
  1104. /// scissor and topology and puts none of them back: it is for a list that
  1105. /// records nothing of the title's after it.
  1106. fn record_plane_pass(
  1107. list: &ID3D12GraphicsCommandList,
  1108. depth: &ID3D12Resource,
  1109. plane: &ID3D12Resource,
  1110. ) {
  1111. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1112. return;
  1113. };
  1114. // SAFETY: live resources.
  1115. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1116. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1117. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1118. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1119. let steps = twin.Format.0 == 53;
  1120. let format = DXGI_FORMAT(match of.Format.0 {
  1121. 44 => 45,
  1122. 19 => 20,
  1123. typed => typed,
  1124. });
  1125. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1126. return;
  1127. };
  1128. for slice in 0..u32::from(of.DepthOrArraySize) {
  1129. for mip in 0..u32::from(of.MipLevels) {
  1130. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1131. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1132. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1133. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1134. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1135. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1136. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1137. MostDetailedMip: mip,
  1138. MipLevels: 1,
  1139. FirstArraySlice: slice,
  1140. ArraySize: 1,
  1141. ..Default::default()
  1142. },
  1143. },
  1144. };
  1145. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1146. Format: format,
  1147. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1148. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1149. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1150. MipSlice: mip,
  1151. FirstArraySlice: slice,
  1152. ArraySize: 1,
  1153. },
  1154. },
  1155. ..Default::default()
  1156. };
  1157. let target = host.dsv(depth, Some(&target));
  1158. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1159. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1160. ptr: pass.cpu + (slot * pass.step) as usize,
  1161. };
  1162. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1163. ptr: pass.gpu + u64::from(slot * pass.step),
  1164. };
  1165. // SAFETY: an open list; a slot of our heap; live resources and
  1166. // objects (the pass's own live as long as the process).
  1167. unsafe {
  1168. host.device
  1169. .CreateShaderResourceView(plane, Some(&view), cpu);
  1170. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1171. list.SetGraphicsRootSignature(&root);
  1172. list.SetPipelineState(&pipeline);
  1173. list.SetGraphicsRootDescriptorTable(0, gpu);
  1174. list.OMSetRenderTargets(0, None, false, Some(&target));
  1175. list.RSSetViewports(&[D3D12_VIEWPORT {
  1176. TopLeftX: 0.0,
  1177. TopLeftY: 0.0,
  1178. Width: width as f32,
  1179. Height: height as f32,
  1180. MinDepth: 0.0,
  1181. MaxDepth: 1.0,
  1182. }]);
  1183. list.RSSetScissorRects(&[RECT {
  1184. left: 0,
  1185. top: 0,
  1186. right: width as i32,
  1187. bottom: height as i32,
  1188. }]);
  1189. list.IASetPrimitiveTopology(
  1190. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1191. );
  1192. list.DrawInstanced(3, 1, 0, 0);
  1193. }
  1194. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1195. }
  1196. }
  1197. }
  1198. /// Records into `list` the copy of a depth texture into its colour twin
  1199. /// (`colour`) or of the twin into the depth texture, both already in their
  1200. /// copy states: whole textures of one size in one format family, which the
  1201. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1202. /// alone, through the twin's buffer.
  1203. fn record_twin_copy(
  1204. list: &ID3D12GraphicsCommandList,
  1205. depth: &ID3D12Resource,
  1206. twin: &crate::resource::Twin,
  1207. colour: bool,
  1208. ) {
  1209. let (from, to) = if colour {
  1210. (depth, &twin.colour.texture)
  1211. } else {
  1212. (&twin.colour.texture, depth)
  1213. };
  1214. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1215. // shortcut: the depth plane's twin is not given the plane (that is a
  1216. // pass the other way: the plane read by a shader, the twin as its
  1217. // target). The twin then lacks what draws and clears wrote to the
  1218. // plane since shaders last wrote the twin. In the title
  1219. // nothing writes that plane but the twin's pass (its 192 draws against
  1220. // it only test, run 29), so the twin lacks nothing. Counted.
  1221. if colour && twin.plane.is_some() {
  1222. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1223. }
  1224. let Some(through) = &twin.through else {
  1225. // SAFETY: an open list and two live textures.
  1226. unsafe { list.CopyResource(to, from) };
  1227. return;
  1228. };
  1229. // A stencil plane and its twin: each mip and slice of the plane goes
  1230. // into the buffer, laid out as the host lays the plane out for copies,
  1231. // and from the buffer into the other texture, whole subresources both
  1232. // times. In the depth texture the stencil plane's subresources follow
  1233. // the depth plane's; the twin has the one plane.
  1234. let Some(host) = host() else { return };
  1235. // SAFETY: a live texture.
  1236. let of = unsafe { depth.GetDesc() };
  1237. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1238. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1239. // SAFETY: a plain query writing `planes` footprints.
  1240. unsafe {
  1241. host.device.GetCopyableFootprints(
  1242. &of,
  1243. planes,
  1244. planes,
  1245. 0,
  1246. Some(rows.as_mut_ptr()),
  1247. None,
  1248. None,
  1249. None,
  1250. );
  1251. }
  1252. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1253. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1254. // SAFETY: a borrowed pointer the location never releases.
  1255. pResource: unsafe { std::mem::transmute_copy(texture) },
  1256. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1257. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1258. SubresourceIndex: index,
  1259. },
  1260. };
  1261. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1262. // SAFETY: as above.
  1263. pResource: unsafe { std::mem::transmute_copy(through) },
  1264. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1265. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1266. PlacedFootprint: *row,
  1267. },
  1268. };
  1269. let (common, source, dest) = (
  1270. D3D12_RESOURCE_STATE_COMMON,
  1271. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1272. D3D12_RESOURCE_STATE_COPY_DEST,
  1273. );
  1274. // SAFETY: an open list and live resources; the buffer was made as big
  1275. // as these footprints, and rests in the common state between copies.
  1276. unsafe {
  1277. list.ResourceBarrier(&[transition(through, common, dest)]);
  1278. for (i, row) in rows.iter().enumerate() {
  1279. let index = first_from + i as u32;
  1280. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1281. }
  1282. list.ResourceBarrier(&[transition(through, dest, source)]);
  1283. for (i, row) in rows.iter().enumerate() {
  1284. let index = first_to + i as u32;
  1285. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1286. }
  1287. list.ResourceBarrier(&[transition(through, source, common)]);
  1288. }
  1289. }
  1290. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1291. /// builds).
  1292. pub(crate) fn dred_on() -> bool {
  1293. static ON: OnceLock<bool> = OnceLock::new();
  1294. *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED") && !dred_faults() && !dred_light())
  1295. }
  1296. /// Breadcrumbs and the faulting address, but no markers and no texts
  1297. /// (`VICTORY_D3D12_DRED=light`): which list a removed device stopped in, at
  1298. /// which of its commands, and the pipelines the list binds; formatting a text
  1299. /// for every command is what makes the whole of it slow.
  1300. pub(crate) fn dred_light() -> bool {
  1301. static ON: OnceLock<bool> = OnceLock::new();
  1302. *ON.get_or_init(|| {
  1303. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "light")
  1304. })
  1305. }
  1306. /// Any of the three.
  1307. pub(crate) fn dred_any() -> bool {
  1308. dred_on() || dred_light() || dred_faults()
  1309. }
  1310. /// Whether only the faulting address of a removed device is kept
  1311. /// (`VICTORY_D3D12_DRED=faults`): no breadcrumbs, no markers and no texts, so
  1312. /// it costs next to nothing and can stay on while the title is played.
  1313. pub(crate) fn dred_faults() -> bool {
  1314. static ON: OnceLock<bool> = OnceLock::new();
  1315. *ON.get_or_init(|| {
  1316. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "faults")
  1317. })
  1318. }
  1319. /// The lists alive while device-removed data is on, by the number their name
  1320. /// ends in, with their marker texts and the pipelines they bind: a report made
  1321. /// on another thread than the one that submits has no lists of its own.
  1322. #[cfg(feature = "diagnostics")]
  1323. #[allow(clippy::type_complexity)]
  1324. static LIST_NOTES: Mutex<
  1325. std::collections::BTreeMap<u32, (std::sync::Weak<Mutex<Vec<Note>>>, std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>)>,
  1326. > = Mutex::new(std::collections::BTreeMap::new());
  1327. /// The number in the name of a list of ours ("victory host list 7", which the
  1328. /// debug layer ends with a note of its own in brackets).
  1329. #[cfg(feature = "diagnostics")]
  1330. fn list_number(name: &str) -> Option<u32> {
  1331. let rest = name.strip_prefix("victory host list ")?;
  1332. let digits = rest.split(' ').next()?;
  1333. (rest.len() == digits.len() || rest[digits.len()..].starts_with(" (")).then(|| digits.parse().ok()).flatten()
  1334. }
  1335. /// Indirect mesh dispatches since the last frame line: the largest group
  1336. /// count a record asked for, and the groups asked in all (from the lists'
  1337. /// budget buffers, a run late).
  1338. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1339. /// Whether a list's indirect-work budget lives in the card's own memory
  1340. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1341. /// before). The clamp charges it with atomics, at least two in a row for
  1342. /// every clamp; in mapped memory on a card of its own each of them
  1343. /// crosses the bus.
  1344. fn card_budget() -> bool {
  1345. static ON: OnceLock<bool> = OnceLock::new();
  1346. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1347. }
  1348. /// Whether each list of a submission runs and is timed on its own, slow
  1349. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1350. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1351. #[cfg(feature = "diagnostics")]
  1352. fn timing() -> bool {
  1353. static ON: OnceLock<bool> = OnceLock::new();
  1354. *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING"))
  1355. }
  1356. /// Names a host object for the device-removed report, which names the
  1357. /// allocations a page fault hit (only with device-removed data on), or for
  1358. /// the frame recorder (`VICTORY_RECORD`).
  1359. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1360. #[cfg(feature = "diagnostics")]
  1361. if crate::replay::record::on() {
  1362. let text = text();
  1363. crate::replay::record::name(object, &text);
  1364. if dred_any()
  1365. && let Ok(object) = object.cast::<ID3D12Object>()
  1366. {
  1367. // SAFETY: a plain call on a live object.
  1368. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1369. }
  1370. return;
  1371. }
  1372. if dred_any()
  1373. && let Ok(object) = object.cast::<ID3D12Object>()
  1374. {
  1375. // SAFETY: a plain call on a live object.
  1376. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1377. }
  1378. }
  1379. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1380. /// [`LISTS`]`[3]` until it is first reset.
  1381. struct Counted {
  1382. /// Not reset since it was made.
  1383. fresh: std::sync::atomic::AtomicBool,
  1384. }
  1385. impl Counted {
  1386. fn new() -> Counted {
  1387. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1388. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1389. Counted {
  1390. fresh: std::sync::atomic::AtomicBool::new(true),
  1391. }
  1392. }
  1393. /// The list is reset: it is in use.
  1394. fn used(&self) {
  1395. if self.fresh.swap(false, Ordering::Relaxed) {
  1396. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1397. }
  1398. }
  1399. }
  1400. impl Drop for Counted {
  1401. fn drop(&mut self) {
  1402. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1403. self.used();
  1404. }
  1405. }
  1406. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1407. /// mapping.
  1408. struct Chunk {
  1409. buffer: ID3D12Resource,
  1410. data: usize,
  1411. }
  1412. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1413. // written only by the list that holds the chunk.
  1414. unsafe impl Send for Chunk {}
  1415. /// Upload chunks handed out front to back: the chunks (each with its
  1416. /// bytes), the one in use and the bytes used in it.
  1417. #[derive(Default)]
  1418. struct Scratch {
  1419. chunks: Vec<(Chunk, u64)>,
  1420. current: usize,
  1421. used: u64,
  1422. }
  1423. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1424. unsafe impl Send for Scratch {}
  1425. impl Drop for Scratch {
  1426. fn drop(&mut self) {
  1427. give_chunks(std::mem::take(&mut self.chunks));
  1428. }
  1429. }
  1430. const SCRATCH_CHUNK: u64 = 4 << 20;
  1431. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1432. /// lists put a few constants or a rectangle's corners there, and every
  1433. /// list that did took 4 MiB of the PC's memory for it.
  1434. const SCRATCH_FIRST: u64 = 256 << 10;
  1435. /// The most bytes of chunks kept while no list holds them.
  1436. const SPARE_MOST: u64 = 128 << 20;
  1437. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1438. /// first needs one, a small one first, and gives all of them back when it
  1439. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1440. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1441. /// host lists of held submissions, which live for one submission, each
  1442. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1443. /// freed per frame of gameplay (run 60).
  1444. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1445. fn scratch_pool() -> bool {
  1446. static ON: OnceLock<bool> = OnceLock::new();
  1447. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1448. }
  1449. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1450. /// for one of the same size.
  1451. struct Spare<T> {
  1452. kept: Vec<(T, u64)>,
  1453. bytes: u64,
  1454. }
  1455. impl<T> Spare<T> {
  1456. const fn new() -> Self {
  1457. Spare { kept: Vec::new(), bytes: 0 }
  1458. }
  1459. /// A kept thing of `size` bytes, the one given last.
  1460. fn take(&mut self, size: u64) -> Option<T> {
  1461. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1462. self.bytes -= size;
  1463. Some(self.kept.remove(at).0)
  1464. }
  1465. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1466. /// `most`: then it comes back.
  1467. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1468. if self.bytes + size > most {
  1469. return Some(thing);
  1470. }
  1471. self.bytes += size;
  1472. self.kept.push((thing, size));
  1473. None
  1474. }
  1475. }
  1476. /// Scratch chunks no list holds.
  1477. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1478. /// Whether lists' scratch memory (constants and tables, which shaders read)
  1479. /// lies in the card's memory, written by the CPU through the bus
  1480. /// (`VICTORY_SCRATCH_BAR=1`; the default is upload memory, which the card
  1481. /// reads through it).
  1482. fn scratch_on_card() -> bool {
  1483. static ON: OnceLock<bool> = OnceLock::new();
  1484. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_BAR").is_some_and(|v| v == "1"))
  1485. }
  1486. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1487. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1488. if scratch_pool()
  1489. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1490. {
  1491. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1492. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1493. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1494. return Some(chunk);
  1495. }
  1496. let mapped = if scratch_on_card() { host.mapped_card_buffer(size, false) } else { None };
  1497. let (buffer, data) = match mapped {
  1498. Some(made) => made,
  1499. None => host.upload_buffer(size)?,
  1500. };
  1501. name(&buffer, || "list scratch".into());
  1502. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1503. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1504. Some(Chunk {
  1505. buffer,
  1506. data: data as usize,
  1507. })
  1508. }
  1509. /// A list is done with `chunks` (it was reset after its submissions ran,
  1510. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1511. /// without the pool.
  1512. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1513. if chunks.is_empty() {
  1514. return;
  1515. }
  1516. let mut freed = Vec::new();
  1517. {
  1518. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1519. for (chunk, size) in chunks {
  1520. let back = if scratch_pool() {
  1521. spare.give(chunk, size, SPARE_MOST)
  1522. } else {
  1523. Some(chunk)
  1524. };
  1525. match back {
  1526. None => {
  1527. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1528. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1529. }
  1530. Some(chunk) => {
  1531. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1532. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1533. freed.push(chunk);
  1534. }
  1535. }
  1536. }
  1537. }
  1538. // Freed outside the lock.
  1539. drop(freed);
  1540. }
  1541. /// What the host keeps for copies in the card's own memory
  1542. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1543. struct CardWork {
  1544. /// Before a submission's lists: what changed on the copies' CPU side
  1545. /// goes to their card side. Those not in use: a plan takes one and
  1546. /// gives it back when its submission has run (`Host::card_done`), so
  1547. /// that submissions sent ahead ([`late`]) each have their own.
  1548. sync: Vec<Prelude>,
  1549. /// After them, in the same submission: the compare of the declared
  1550. /// ranges with their bytes from before. As `sync`.
  1551. check: Vec<Prelude>,
  1552. /// After it ran: the pieces that differ come down.
  1553. fetch: Prelude,
  1554. root: ID3D12RootSignature,
  1555. pso: ID3D12PipelineState,
  1556. /// One dword per piece compared, odd where the piece differs: PC
  1557. /// memory, mapped (buffer, mapping, bytes).
  1558. differs: (ID3D12Resource, usize, u64),
  1559. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1560. fetched: Option<(ID3D12Resource, usize, u64)>,
  1561. /// The dwords of `differs` taken by plans whose results were not read
  1562. /// yet.
  1563. taken: u32,
  1564. /// Plans made and not done with (`Host::card_done`).
  1565. out: u32,
  1566. }
  1567. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1568. // under the submission lock.
  1569. unsafe impl Send for CardWork {}
  1570. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1571. /// The compare of a declared range of a copy in the card's memory with
  1572. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1573. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1574. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1575. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1576. /// byte just outside the range costs a fetch that finds nothing.
  1577. ///
  1578. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1579. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1580. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1581. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1582. /// those steps.
  1583. pub(crate) const CARD_COMPARE: &str = r#"
  1584. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1585. cbuffer Span : register(b0) {
  1586. uint first; // the first piece
  1587. uint skew; // where the copy starts in its piece 0
  1588. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1589. uint pieces;
  1590. uint out_at; // the first piece's dword in `differs`, in bytes
  1591. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1592. };
  1593. ByteAddressBuffer now : register(t0);
  1594. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1595. // last sent up (or hashed whole, the first time).
  1596. RWByteAddressBuffer hashes : register(u0);
  1597. RWByteAddressBuffer differs : register(u1);
  1598. groupshared uint4 parts[64];
  1599. [RootSignature(RS)]
  1600. [numthreads(64, 1, 1)]
  1601. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1602. uint piece = first + id.x;
  1603. uint lo = piece * 65536u;
  1604. lo = lo > skew ? lo - skew : 0u;
  1605. uint hi = min((piece + 1u) * 65536u - skew, size);
  1606. lo = lo & ~15u;
  1607. hi = (hi + 15u) & ~15u;
  1608. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1609. [loop]
  1610. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1611. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1612. h = h.yzwx ^ (h >> 15);
  1613. }
  1614. parts[thread] = h;
  1615. GroupMemoryBarrierWithGroupSync();
  1616. if (thread != 0u) return;
  1617. h = parts[0];
  1618. [loop]
  1619. for (uint i = 1u; i < 64u; ++i) {
  1620. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1621. h = h.yzwx ^ (h >> 15);
  1622. }
  1623. if (compare != 0u) {
  1624. // The flag, and above it 31 bits of the hash (`torn`).
  1625. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1626. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1627. // With the copy-back on its own thread: the next compare of the
  1628. // piece finds what is written from here on.
  1629. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1630. } else {
  1631. hashes.Store4(piece * 16u, h);
  1632. }
  1633. }
  1634. "#;
  1635. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1636. #[cfg(test)]
  1637. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1638. torn::hash(bytes)
  1639. }
  1640. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1641. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1642. /// parts a dispatch can hold.
  1643. ///
  1644. /// # Safety
  1645. /// The list is open with the compare's root signature, pipeline and buffers
  1646. /// set, and the pieces lie in the buffer.
  1647. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1648. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1649. let mut done = 0;
  1650. while done < span.pieces {
  1651. let n = (span.pieces - done).min(MOST);
  1652. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1653. // SAFETY: the caller's.
  1654. unsafe {
  1655. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1656. list.Dispatch(n, 1, 1);
  1657. }
  1658. done += n;
  1659. }
  1660. }
  1661. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1662. /// the card's memory are hashed in runs of pieces that touch, each piece
  1663. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1664. /// per range sent up.
  1665. ///
  1666. /// These passes are ours, they run on the card before every submission's
  1667. /// lists: a pass takes the time of one piece however few its pieces are.
  1668. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1669. /// a piece hashed when it need not be, or not hashed when it should, costs
  1670. /// a fetch that finds nothing and loses no shader write.
  1671. fn rehash_runs() -> bool {
  1672. static ON: OnceLock<bool> = OnceLock::new();
  1673. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1674. }
  1675. /// Since the last frame-rate line, of our own passes over copies in the
  1676. /// card's memory: hash passes after ranges were sent up, the pieces they
  1677. /// hashed, and compare passes after the lists.
  1678. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1679. /// Whether what shaders wrote to copies in the card's memory is merged
  1680. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1681. /// default). The pieces the card's compare found differing come down in
  1682. /// one fetch and were then merged one after the other on the thread that
  1683. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1684. /// with the copy's CPU side byte by byte and put into title memory through
  1685. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1686. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1687. /// landings do not come here: `crate::land` has threads of its own.)
  1688. fn wide_merge() -> bool {
  1689. static ON: OnceLock<bool> = OnceLock::new();
  1690. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1691. }
  1692. /// One declared range of a copy in the card's memory, in a submission.
  1693. struct CardRange {
  1694. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1695. /// As declared (title addresses), for the statistics.
  1696. declared: (usize, usize),
  1697. span: crate::shadow::CardSpan,
  1698. /// Its first piece's dword in the compare's results.
  1699. at: u32,
  1700. /// Whether the card compares it; else every piece is fetched.
  1701. compared: bool,
  1702. /// Looked at by `crate::picked`, and not declared: what is found changed
  1703. /// there was written through a view nobody declared. Not landed.
  1704. picked: bool,
  1705. }
  1706. impl CardPlan {
  1707. /// `crate::picked` is told where what it looked at changed, by the
  1708. /// compare's results.
  1709. fn picked_found(&self, differs: &[u32]) {
  1710. for r in self.ranges.iter().filter(|r| r.picked) {
  1711. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1712. if let Some(p) = changed {
  1713. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1714. }
  1715. }
  1716. }
  1717. }
  1718. /// What a submission does for copies in the card's memory.
  1719. struct CardPlan {
  1720. ranges: Vec<CardRange>,
  1721. /// The compare, run after the submission's lists.
  1722. check: Option<ID3D12CommandList>,
  1723. /// The copies whose card side was brought up to date, alive until the
  1724. /// submission has run.
  1725. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1726. /// The lists of ours the plan recorded (whether the compare, the
  1727. /// list), given back by `Host::card_done`.
  1728. lists: Vec<(bool, Prelude)>,
  1729. /// With [`relay`]: the number of the send to copies in the card's memory
  1730. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1731. sent_as: u64,
  1732. /// With [`upcheck`]: the look at what it sent up.
  1733. looks: Option<upcheck::Looks>,
  1734. /// With [`send`]: the memory its sends come from.
  1735. sends: Option<send::Memory>,
  1736. }
  1737. /// One piece of submission-time work, in recorded order.
  1738. enum Step {
  1739. /// A copy into title memory (destination, source, bytes): the title's
  1740. /// buffer copies, which later refreshes must see.
  1741. Copy(usize, usize, usize),
  1742. /// A copy of title memory into the list's own upload memory, and how
  1743. /// the card could bring the bytes instead.
  1744. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  1745. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1746. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1747. /// intervenes.
  1748. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1749. /// Work that may write title memory.
  1750. Run(Box<dyn Fn() + Send>),
  1751. /// Work that writes host memory only, and the title memory it reads
  1752. /// (from, to; empty for none).
  1753. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1754. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1755. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1756. /// Brings a texture's staging buffer up to date: once per submission,
  1757. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1758. Texture(std::sync::Arc<crate::texture::Staging>),
  1759. /// A title buffer copy that the list does on the card ([`place`]): what
  1760. /// is done on the CPU for it.
  1761. Placed(place::Placed),
  1762. }
  1763. /// What a list does on the CPU when it is submitted: copies between host
  1764. /// memory regions (title buffers, upload buffers and buffer copies), and
  1765. /// the upload buffers its GPU commands read, kept until the list is reset.
  1766. #[derive(Default)]
  1767. struct Deferred {
  1768. /// Destination, source, bytes.
  1769. copies: Vec<Step>,
  1770. uploads: Vec<ID3D12Resource>,
  1771. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1772. upload_bytes: u64,
  1773. /// Host objects the list's commands name (pipelines, root signatures,
  1774. /// descriptor heaps): the title may release its objects before it
  1775. /// submits the list.
  1776. kept: Vec<windows::core::IUnknown>,
  1777. /// Buffer ranges refreshed since the last title copy (host copy,
  1778. /// address, bytes): refreshing them again would find the same bytes.
  1779. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1780. /// Textures whose contents the list brings up to date.
  1781. textures: std::collections::HashSet<usize>,
  1782. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1783. /// bytes.
  1784. writes: Vec<(usize, crate::queue::Written, usize)>,
  1785. /// Textures read back (texture to buffer copies), done once the list
  1786. /// has run: the host buffer the list copies the texels into, the title
  1787. /// memory they go to, the bytes of a row, the rows, the title's row
  1788. /// pitch.
  1789. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1790. /// Whether the indirect-work budget is zeroed for this recording (a
  1791. /// step on the CPU, or in the list for the card's copy).
  1792. budget_zeroed: bool,
  1793. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1794. /// interface pointer) that a clamp in this recording left readable as
  1795. /// indirect arguments; 0 if none. It stays readable until the next
  1796. /// clamp into it ([`HostList::indirect_state`]).
  1797. indirect_readable: usize,
  1798. }
  1799. impl Deferred {
  1800. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1801. /// reset.
  1802. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1803. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1804. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1805. self.upload_bytes += size;
  1806. self.uploads.push(buffer);
  1807. }
  1808. }
  1809. impl Drop for Deferred {
  1810. fn drop(&mut self) {
  1811. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1812. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1813. }
  1814. }
  1815. /// Whether a queue's submissions go to the card without a wait for each
  1816. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1817. /// waits for every list on its own).
  1818. ///
  1819. /// Every submission was prepared, sent, waited for and copied back before
  1820. /// the next one was looked at, so the card stood idle while we prepared
  1821. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1822. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1823. /// other, on the one thread that submits.
  1824. ///
  1825. /// With the switch a queue's submission is sent and joins a line of
  1826. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1827. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1828. /// for the card, what their shaders wrote copied back once per byte, then
  1829. /// their bottom-of-pipe writes and the fence signals behind them, in
  1830. /// order) at the next point where the title, or our own preparing, can
  1831. /// observe what they do. Those points, exactly:
  1832. ///
  1833. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1834. /// read-back or map of a texture, a clear or upload run at once;
  1835. /// 2. the next submission reads title memory that a flight's shaders may
  1836. /// write: a title buffer copy, a fill of upload memory, a texture's
  1837. /// memory, any step that runs code of ours on title memory
  1838. /// ([`late_blocked`]);
  1839. /// 3. the next submission refreshes a range of a host copy that a flight's
  1840. /// shaders may write, and the title wrote a page of it since it was last
  1841. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1842. /// alone until the flight's writes are back, as it always did within a
  1843. /// submission;
  1844. /// 4. a queue stands at a wait for a memory value that no flight's
  1845. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1846. /// write ([`late_met`]);
  1847. /// 5. the title blocks on a fence without an event;
  1848. /// 6. the card has run every flight (a thread of ours waits for that:
  1849. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1850. ///
  1851. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1852. /// when the card has really run the work, later than before and never
  1853. /// earlier; a fence signalled on a queue while flights are in the air is
  1854. /// set behind them. A wait for a memory value that a flight's
  1855. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1856. /// the card behind that flight, which is the order the wait asks for.
  1857. ///
  1858. /// What it assumes beyond today: memory the title rewrites between two of
  1859. /// its submissions, without waiting for the first, may be seen by the
  1860. /// first's shaders (as on the console, where the card reads title memory
  1861. /// when it runs, not when the list is submitted).
  1862. pub(crate) fn late() -> bool {
  1863. late_stage() > 0
  1864. }
  1865. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1866. fn late_stage() -> u8 {
  1867. static STAGE: OnceLock<u8> = OnceLock::new();
  1868. *STAGE.get_or_init(|| {
  1869. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1870. return 0;
  1871. }
  1872. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1873. Ok("1") => 1,
  1874. Ok("2") => 2,
  1875. Ok("3") => 3,
  1876. // The relay alone: on top of stage 3.
  1877. Err(_) if crate::shadow::relay() => 3,
  1878. _ => 0,
  1879. }
  1880. })
  1881. }
  1882. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1883. /// longer a point. Where the title wrote a page that lies in a range a
  1884. /// flight's shaders may write, the bytes the title changed are found (the
  1885. /// page as it is now against what the copy held when the flight was
  1886. /// prepared) and put into the copy, and only those: what the flight's
  1887. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1888. /// flights are settled for it only where that cannot be done: memory that
  1889. /// is not write-watched, or a copy in the card's memory with more changed
  1890. /// runs than a submission should send up one by one.
  1891. ///
  1892. /// In run 92 (stage 1) this point settled the flights five times a frame
  1893. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1894. /// frame of waiting were left of 200.
  1895. ///
  1896. /// What differs from settling first: a byte both the title and a flight's
  1897. /// shader wrote is the title's if the shader wrote it first, the shader's
  1898. /// if it wrote it afterwards; settled first it was always the shader's.
  1899. /// The title writing a byte a shader of its own is writing is a race on
  1900. /// the console too.
  1901. fn late_exact() -> bool {
  1902. late_stage() > 1
  1903. }
  1904. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1905. /// no longer a point where flights are settled). The copy to the back
  1906. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1907. /// its own for each present in the air) and the swap chain is told to
  1908. /// present behind it; the queue's call returns, and the card finishes the
  1909. /// frame while the title records the next one. What the title is told
  1910. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1911. /// has run it, by the settling thread.
  1912. ///
  1913. /// What is left out with it: the look whether the presented frame is black
  1914. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1915. /// or listed is presented the old way. Once every second and a half a
  1916. /// submission settles the flights all the same, for the sweep that lets
  1917. /// idle host objects go (it needs nothing in the air).
  1918. pub(crate) fn late_free_present() -> bool {
  1919. late_stage() > 2
  1920. }
  1921. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1922. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1923. /// and is off with it, in the timing run and with kept snapshots).
  1924. ///
  1925. /// With [`late`] alone every settle does three things on the thread that
  1926. /// holds the submission lock: it waits for everything in the air, copies
  1927. /// back with the card standing, and only then goes on preparing. The frame
  1928. /// stays a relay: the card works about 242 ms of it and one thread
  1929. /// prepares, waits and copies back for about 220.
  1930. ///
  1931. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1932. /// soon as the card has run them, in the order they were sent and without
  1933. /// the submission lock: it fetches and merges what their shaders wrote to
  1934. /// copies in the card's memory, compares and merges the other copies,
  1935. /// frees the flights' ranges, and then does their read-backs, their
  1936. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1937. /// order. The submitting thread meanwhile prepares and sends the next
  1938. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  1939. /// that thread has landed everything in the air, at the same points as
  1940. /// before (the list in [`late`]), so whoever can observe title memory, a
  1941. /// fence or a present still does so only after the flights before it are
  1942. /// merged.
  1943. ///
  1944. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  1945. /// flight; a merge that never stores into memory the card may be writing;
  1946. /// sends to card copies numbered) and here: flights land in the order of
  1947. /// [`LINE`] by one thread, so a later flight's results never reach title
  1948. /// memory before an earlier flight's; the compare on the card stores the
  1949. /// hash it made, so each flight's compare flags exactly what changed since
  1950. /// the compare before it, however late the pieces are fetched; the fetch
  1951. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  1952. /// title bytes the card had received when it ran.
  1953. pub(crate) fn relay() -> bool {
  1954. static ON: OnceLock<bool> = OnceLock::new();
  1955. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  1956. }
  1957. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  1958. /// title memory a flight's shaders may write (a title buffer copy, a fill
  1959. /// of upload memory, a texture) waits only until the flights that declared
  1960. /// that memory have landed, not for everything in the air; and at
  1961. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  1962. /// both wait for everything.
  1963. fn relay_exact() -> bool {
  1964. static ON: OnceLock<bool> = OnceLock::new();
  1965. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  1966. // since the walls of the first room were found drawn in every run with
  1967. // this set and in fewer than half without it).
  1968. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  1969. }
  1970. /// Whether the pieces the relay fetches from the card's memory come over the
  1971. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  1972. /// draws.
  1973. ///
  1974. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  1975. /// and with the relay that is most of a frame: the thread that lands flights
  1976. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  1977. /// a few milliseconds of copying, and everything that waits for a landing
  1978. /// (the title's fences, reads of memory flights may write) waited with it.
  1979. ///
  1980. /// What changes: the fetch runs when its flights are done and beside later
  1981. /// submissions, so of the sends of title bytes it is only known to have run
  1982. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  1983. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  1984. /// the title's, newer than what the flights wrote. A later flight's bytes
  1985. /// may be in what is fetched, as before.
  1986. fn relay_copy() -> bool {
  1987. static ON: OnceLock<bool> = OnceLock::new();
  1988. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  1989. }
  1990. /// Told when something joins [`LINE`], for the thread that lands flights
  1991. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  1992. /// what queues hold.
  1993. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  1994. /// Told when flights have landed ([`relay`]): who waits for that looks
  1995. /// again.
  1996. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  1997. /// With [`relay`], the order of what we put on the queue: the number of
  1998. /// sends of changed ranges to copies in the card's memory so far
  1999. /// (`Host::card_before`). Held from the taking of the ranges until their
  2000. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  2001. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  2002. /// later one.
  2003. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  2004. /// Since the last frame-rate line, of the thread that lands flights
  2005. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  2006. /// card with nothing to land, microseconds it waited for fetches of card
  2007. /// copies' pieces, microseconds of landing in all.
  2008. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  2009. /// Of the line's things in order (a flight: the value signalled on the
  2010. /// host's fence behind it; a write or a signal behind a flight: `None`):
  2011. /// how many, from the front, can be landed when the card has reached
  2012. /// `completed`: everything ahead of the first flight it has not run. A
  2013. /// later flight never lands before an earlier one, and what follows a
  2014. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  2015. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  2016. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  2017. }
  2018. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  2019. /// holds, for every piece of every range of the plan, the copy, the
  2020. /// piece's number in the copy and whether the compare flagged it there (or
  2021. /// did not run). The pieces to fetch, under whichever range, in order: all
  2022. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  2023. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  2024. /// the hash, so the second of them may find it stored already and not
  2025. /// flag it.
  2026. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  2027. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  2028. pieces.sort_unstable();
  2029. pieces.dedup();
  2030. pieces
  2031. }
  2032. #[cfg(test)]
  2033. mod relay_tests {
  2034. use super::{flagged_pieces, landable};
  2035. /// Two flights and what follows each: nothing of the second lands
  2036. /// before the card has run it, and nothing behind a flight lands
  2037. /// before the flight.
  2038. #[test]
  2039. fn flights_land_in_the_order_they_were_sent() {
  2040. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  2041. let line = [Some(5), None, None, Some(6), None];
  2042. assert_eq!(landable(&line, 4), 0);
  2043. assert_eq!(landable(&line, 5), 3);
  2044. assert_eq!(landable(&line, 6), 5);
  2045. assert_eq!(landable(&line, u64::MAX), 5);
  2046. // Signals with no flight ahead land at once; behind one they wait.
  2047. assert_eq!(landable(&[None, None], 0), 2);
  2048. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  2049. assert_eq!(landable(&[], 3), 0);
  2050. // After the first three landed, the rest when its turn comes.
  2051. assert_eq!(landable(&line[3..], 5), 0);
  2052. assert_eq!(landable(&line[3..], 6), 2);
  2053. }
  2054. /// A piece flagged under one range of a plan is fetched under every
  2055. /// range that holds a part of it; pieces of other copies are not.
  2056. #[test]
  2057. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  2058. let (a, b) = (0x1000usize, 0x2000usize);
  2059. // Copy a: piece 3 under two ranges, flagged under the first only;
  2060. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  2061. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  2062. let fetch = flagged_pieces(&flags);
  2063. assert!(fetch.contains(&(a, 3)));
  2064. assert!(!fetch.contains(&(a, 4)));
  2065. assert!(!fetch.contains(&(b, 3)));
  2066. assert!(fetch.contains(&(b, 9)));
  2067. assert_eq!(fetch.len(), 2);
  2068. }
  2069. }
  2070. /// The most host lists in the air before the flights are settled
  2071. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  2072. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  2073. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  2074. /// 32 settled the flights three times a
  2075. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  2076. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  2077. /// descriptor slots, upload
  2078. /// memory and scratch chunks are held until then, and a frame's lists held
  2079. /// all at once ran the slots out before (run 45).
  2080. fn late_most() -> usize {
  2081. static MOST: OnceLock<usize> = OnceLock::new();
  2082. *MOST.get_or_init(|| {
  2083. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  2084. })
  2085. }
  2086. /// Whether a submission with bottom-of-pipe writes may fly
  2087. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  2088. /// the title is told at once, as before; for telling a title that polls
  2089. /// such a value from one that does not).
  2090. fn late_writes() -> bool {
  2091. static ON: OnceLock<bool> = OnceLock::new();
  2092. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  2093. }
  2094. /// Per host copy, the ranges a submission's shaders may write, as declared
  2095. /// (address, end).
  2096. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  2097. /// What [`Host::submit`] hands back for a submission it sent and did not
  2098. /// wait for.
  2099. struct Sent {
  2100. /// Its number among the submissions started.
  2101. number: u64,
  2102. card: Option<CardPlan>,
  2103. back: Vec<Declared>,
  2104. /// What was taken off it to be done on the card.
  2105. own: Option<card_steps::Taken>,
  2106. /// Its bottom-of-pipe writes.
  2107. writes: Vec<(usize, crate::queue::Written, usize)>,
  2108. }
  2109. /// A submission on the card that has not been waited for ([`late`]): its
  2110. /// host lists, taken from the title's (which it may reset meanwhile), and
  2111. /// what is to be done once it has run.
  2112. struct Flight {
  2113. number: u64,
  2114. /// The value signalled on the host's fence behind it.
  2115. fence: u64,
  2116. lists: Vec<crate::list::Detached>,
  2117. order: Vec<usize>,
  2118. card: Option<CardPlan>,
  2119. back: Vec<Declared>,
  2120. /// The list of ours that ran ahead of them ([`card_steps`]).
  2121. own: Option<card_steps::Taken>,
  2122. }
  2123. /// One thing in the line of what waits for the card, in order.
  2124. enum Late {
  2125. Run(Flight),
  2126. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  2127. Write(usize, crate::queue::Written, usize),
  2128. /// A fence (its address) signalled behind the flights before it.
  2129. Signal(usize, u64),
  2130. }
  2131. struct Line {
  2132. line: Vec<Late>,
  2133. /// The title memory the flights' shaders may write (address, end), in
  2134. /// order and joined.
  2135. written: Vec<(usize, usize)>,
  2136. /// Host lists in the flights.
  2137. lists: usize,
  2138. /// The value signalled on the host's fence behind the last flight.
  2139. target: u64,
  2140. /// A settle has taken the line and is not done: a signal still goes
  2141. /// behind it.
  2142. settling: bool,
  2143. /// Something was settled away from a queue's own calls: the helper
  2144. /// thread looks at what queues hold.
  2145. poke: bool,
  2146. /// Host lists of settled flights, reset and given back outside the
  2147. /// submission lock ([`land`]: a settle may run under a caller's own
  2148. /// locks).
  2149. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2150. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2151. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2152. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2153. /// With [`card_steps`]: what the flights being landed write.
  2154. landing: Vec<card_steps::Writer>,
  2155. }
  2156. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2157. // into; touched under the lock.
  2158. unsafe impl Send for Line {}
  2159. static LINE: Mutex<Line> = Mutex::new(Line {
  2160. line: Vec::new(),
  2161. written: Vec::new(),
  2162. lists: 0,
  2163. target: 0,
  2164. settling: false,
  2165. poke: false,
  2166. landed: Vec::new(),
  2167. in_hand: Vec::new(),
  2168. landing: Vec::new(),
  2169. });
  2170. /// Told when a flight joins [`LINE`] or it is poked.
  2171. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2172. fn line() -> std::sync::MutexGuard<'static, Line> {
  2173. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2174. }
  2175. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2176. const WHY_SYNC: usize = 2;
  2177. const WHY_CARD_DONE: usize = 3;
  2178. const WHY_VALUE: usize = 4;
  2179. const WHY_STALE: usize = 5;
  2180. const WHY_READ: usize = 6;
  2181. const WHY_RUN: usize = 7;
  2182. const WHY_MOST: usize = 8;
  2183. const WHY_WRITES: usize = 9;
  2184. const WHY_FENCE: usize = 10;
  2185. /// Since the last frame-rate line: submissions sent without a wait;
  2186. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2187. /// microseconds settles waited for the card; value waits met by a flight's
  2188. /// bottom-of-pipe write; fence signals set behind flights.
  2189. /// Then: the settles for title memory read, by what read it (a buffer
  2190. /// copy, a fill of upload memory, a texture).
  2191. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2192. /// Since the last frame-rate line: the microseconds settles waited for the
  2193. /// card, by why they settled (the `WHY_` places).
  2194. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2195. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2196. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2197. if from >= to {
  2198. return false;
  2199. }
  2200. let at = ranges.partition_point(|r| r.1 <= from);
  2201. ranges.get(at).is_some_and(|r| r.0 < to)
  2202. }
  2203. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2204. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2205. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2206. ranges.sort_unstable();
  2207. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2208. for &(from, to) in ranges.iter() {
  2209. match out.last_mut() {
  2210. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2211. _ => out.push((from, to)),
  2212. }
  2213. }
  2214. *ranges = out;
  2215. }
  2216. /// Whether anything is in the air.
  2217. fn flying() -> bool {
  2218. if !late() {
  2219. return false;
  2220. }
  2221. let line = line();
  2222. // (With the relay: also while flights are being landed.)
  2223. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2224. }
  2225. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2226. /// before they are settled, if so. Preparing reads title memory on the
  2227. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2228. /// runs steps of ours that may read or write it anywhere; what the
  2229. /// flights' shaders write is not there yet.
  2230. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2231. let (written, copies) = {
  2232. let line = line();
  2233. if line.written.is_empty() {
  2234. return None;
  2235. }
  2236. (line.written.clone(), card_steps::copies(&line))
  2237. };
  2238. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2239. }
  2240. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2241. /// flights when the title itself wrote the memory since they were given it
  2242. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2243. ///
  2244. /// The title's 174 MB heap is declared written as a whole (a root view has
  2245. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2246. /// bytes a frame, at a new place each time, waited for every flight's
  2247. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2248. /// named). The title writes those bytes just before the draw that reads
  2249. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2250. ///
  2251. /// Or no shader's write went into that page in the last 600 frames
  2252. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2253. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2254. /// before the page was taken.
  2255. ///
  2256. /// What can go wrong: a constant a flight's shader really writes, in a
  2257. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2258. /// for the first time, is read as it was before that flight.
  2259. fn fill_is_titles(src: usize, len: usize) -> bool {
  2260. const SMALL: usize = 64 << 10;
  2261. static ON: OnceLock<bool> = OnceLock::new();
  2262. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2263. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2264. }
  2265. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2266. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2267. /// in (start, bytes).
  2268. #[cfg(feature = "diagnostics")]
  2269. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2270. /// How often and how long, and the address the last one read.
  2271. #[cfg(feature = "diagnostics")]
  2272. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2273. /// What the wait that comes next is for, and why not on the card.
  2274. #[cfg(feature = "diagnostics")]
  2275. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2276. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2277. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2278. /// shaders.
  2279. #[cfg(feature = "diagnostics")]
  2280. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2281. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2282. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2283. /// raw address (1).
  2284. #[cfg(feature = "diagnostics")]
  2285. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2286. if len < 1 << 20 {
  2287. return;
  2288. }
  2289. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2290. let e = all
  2291. .get_or_insert_with(Default::default)
  2292. .entry((address as usize, (address + len) as usize, pipeline))
  2293. .or_insert_with(|| {
  2294. let shaders = match pipeline {
  2295. 0 => "a view in a table".into(),
  2296. 1 => "a raw address".into(),
  2297. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2298. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2299. }),
  2300. };
  2301. (0, shaders)
  2302. });
  2303. e.0 += 1;
  2304. }
  2305. #[cfg(feature = "diagnostics")]
  2306. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2307. let i = written.partition_point(|r| r.1 <= at);
  2308. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2309. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2310. let why = blamed.1;
  2311. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2312. }
  2313. /// Why [`card_steps`] left the submission to the wait that comes next.
  2314. #[cfg(feature = "diagnostics")]
  2315. fn refused(why: &'static str) {
  2316. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2317. }
  2318. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2319. #[cfg(feature = "diagnostics")]
  2320. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2321. if let Some((shadow, from, _)) = stale.first() {
  2322. let (start, len) = shadow.span();
  2323. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2324. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2325. }
  2326. }
  2327. /// The wait for what [`blame`] last named, or a wait of another reason than
  2328. /// title memory read, took `us`.
  2329. #[cfg(feature = "diagnostics")]
  2330. fn blamed(why: usize, us: u64) {
  2331. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2332. let (key, at) = match (why, named) {
  2333. (WHY_READ | WHY_STALE, Some(named)) => named,
  2334. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2335. _ => {
  2336. let kind = match why {
  2337. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2338. WHY_VALUE => "a memory value",
  2339. WHY_STALE => "title memory changed under shader writes",
  2340. WHY_RUN => "a step of ours",
  2341. WHY_MOST => "lists in the air",
  2342. WHY_FENCE => "a blocking fence wait",
  2343. _ => "another reason",
  2344. };
  2345. ((kind, "", 0, 0, 0), 0)
  2346. }
  2347. };
  2348. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2349. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2350. *e = (e.0 + 1, e.1 + us, at);
  2351. }
  2352. /// For the frame-rate line: the five that waited longest.
  2353. #[cfg(feature = "diagnostics")]
  2354. fn log_blame(frames: f64) {
  2355. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2356. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2357. let mut all: Vec<_> = all.into_iter().collect();
  2358. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2359. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2360. // The passes that declare it written, the ones that do so most.
  2361. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2362. for ((a, b, _), (n, shaders)) in &wide {
  2363. if *a < at + len && at < *b {
  2364. *passes.entry(shaders).or_default() += n;
  2365. }
  2366. }
  2367. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2368. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2369. let passes: Vec<String> =
  2370. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2371. tracing::info!(
  2372. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2373. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2374. us as f64 / 1e3 / frames,
  2375. n as f64 / frames,
  2376. passes.join(", "),
  2377. match (why.is_empty(), kind) {
  2378. (true, _) => "",
  2379. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2380. _ => "; not done on the card: ",
  2381. },
  2382. );
  2383. }
  2384. }
  2385. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2386. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2387. touches(written, src, src + len) && !fill_is_titles(src, len)
  2388. }
  2389. /// Whether they stop a title buffer copy, and if so whether by its source.
  2390. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2391. let read = read_blocked(written, src, len);
  2392. (read || touches(written, dst, dst + len)).then_some(read)
  2393. }
  2394. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2395. /// may write (in order, joined); `count` whether the kind of read is
  2396. /// counted for the frame line.
  2397. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2398. if written.is_empty() {
  2399. return None;
  2400. }
  2401. // Destinations of copies at their place, if a step reads them.
  2402. let mut placed: Vec<(usize, usize)> = Vec::new();
  2403. for list in runs {
  2404. for step in &list.deferred().copies {
  2405. match step {
  2406. &Step::Copy(dst, src, len) => {
  2407. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2408. if count {
  2409. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2410. #[cfg(feature = "diagnostics")]
  2411. if _read {
  2412. blame("a buffer copy's source", written, src, len);
  2413. } else {
  2414. blame("a buffer copy's destination", written, dst, len);
  2415. }
  2416. }
  2417. return Some(WHY_READ);
  2418. }
  2419. }
  2420. &Step::Fill(_, src, len, _) => {
  2421. if read_blocked(written, src, len) {
  2422. if count {
  2423. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2424. #[cfg(feature = "diagnostics")]
  2425. blame("a fill of upload memory", written, src, len);
  2426. }
  2427. return Some(WHY_READ);
  2428. }
  2429. }
  2430. Step::Texture(staging) => {
  2431. let (at, len) = staging.memory();
  2432. if touches(written, at, at + len) {
  2433. if count {
  2434. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2435. #[cfg(feature = "diagnostics")]
  2436. blame("a texture", written, at, len);
  2437. }
  2438. return Some(WHY_READ);
  2439. }
  2440. }
  2441. Step::Run(_) => return Some(WHY_RUN),
  2442. Step::Placed(p) => match p.waits(written) {
  2443. place::Waits::No => {}
  2444. place::Waits::ForReaders => placed.push((p.dst, p.dst + p.len)),
  2445. place::Waits::Yes => {
  2446. if count {
  2447. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2448. #[cfg(feature = "diagnostics")]
  2449. blame("a buffer copy at its place", written, p.src, p.len);
  2450. }
  2451. return Some(WHY_READ);
  2452. }
  2453. },
  2454. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2455. }
  2456. }
  2457. }
  2458. (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ)
  2459. }
  2460. /// With flights in the air, after the submission's write-watch asking:
  2461. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2462. /// may write and that the title wrote since it was last copied. The
  2463. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2464. /// the title's bytes there would reach the card a submission late.
  2465. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2466. use std::sync::Arc;
  2467. // Per copy, the span of what is refreshed (a flush brings that much
  2468. // up to date at most).
  2469. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2470. // Where each copy is in it, if shaders may be writing it (none begins to
  2471. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2472. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2473. for list in runs {
  2474. for step in &list.deferred().copies {
  2475. if let Step::Refresh(shadow, address, len) = step {
  2476. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2477. shadow.writes_pending().then(|| {
  2478. spans.push((shadow.clone(), *address, *address + *len));
  2479. spans.len() - 1
  2480. })
  2481. });
  2482. if let Some(i) = *place {
  2483. let s = &mut spans[i];
  2484. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2485. }
  2486. }
  2487. }
  2488. }
  2489. if late_exact() {
  2490. // The title's bytes are put in beside the flights' writes; a
  2491. // settle is still due where that could not be done. At most this
  2492. // many changed runs go up to copies in the card's memory, each a
  2493. // copy of its own there. With [`card_steps`] the pages of the
  2494. // title's ring of constants come here too, which were waited for
  2495. // before: hundreds of short runs each, at about 1.5 us a run.
  2496. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2497. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2498. return spans;
  2499. }
  2500. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2501. spans
  2502. }
  2503. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2504. /// air, if there are any, and is set when they are settled. Whether it
  2505. /// did; if not the caller sets the fence now.
  2506. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2507. if !late() {
  2508. return false;
  2509. }
  2510. let mut line = line();
  2511. if line.line.is_empty() && !line.settling {
  2512. return false;
  2513. }
  2514. line.line.push(Late::Signal(fence, value));
  2515. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2516. drop(line);
  2517. // A signal alone (behind a settle under way) has no flight to wake
  2518. // the helper thread for it.
  2519. LINE_MOVED.notify_one();
  2520. RELAY_MOVED.notify_one();
  2521. true
  2522. }
  2523. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2524. /// whether it is met once the flights in the air have run. A flight's
  2525. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2526. /// for the card: the part behind the wait goes to the card behind that
  2527. /// flight, which is the order the wait asks for. If the flights may write
  2528. /// the value in a way not known here (shaders, a timestamp, another
  2529. /// width), they are settled and memory is asked again.
  2530. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2531. let (address, bytes) = wait.place();
  2532. {
  2533. let line = line();
  2534. if line.line.is_empty() && line.in_hand.is_empty() {
  2535. return false;
  2536. }
  2537. let mut unsure = touches(&line.written, address, address + bytes);
  2538. // (With the relay: first the writes of flights being landed.)
  2539. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2540. Late::Write(at, what, n) => Some((at, what, n)),
  2541. _ => None,
  2542. }));
  2543. for (at, what, n) in writes {
  2544. if *at >= address + bytes || address >= *at + *n {
  2545. continue;
  2546. }
  2547. match what {
  2548. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2549. if wait.holds_for(*v) {
  2550. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2551. return true;
  2552. }
  2553. }
  2554. _ => unsure = true,
  2555. }
  2556. }
  2557. if !unsure {
  2558. return false;
  2559. }
  2560. }
  2561. settle_now(WHY_VALUE);
  2562. wait.met()
  2563. }
  2564. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2565. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2566. pub(crate) fn settle_now(why: usize) {
  2567. if !late() {
  2568. return;
  2569. }
  2570. let Some(host) = host() else {
  2571. return;
  2572. };
  2573. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2574. host.settle(&mut submitted, why);
  2575. }
  2576. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2577. pub(crate) fn settle_for_present() {
  2578. settle_now(WHY_SYNC);
  2579. }
  2580. pub(crate) fn settle_for_fence() {
  2581. settle_now(WHY_FENCE);
  2582. }
  2583. /// Resets the host lists of settled flights and keeps them for reuse, as
  2584. /// a queue does for the lists it ran (`crate::list::recycle`).
  2585. fn land() {
  2586. let landed = std::mem::take(&mut line().landed);
  2587. for (lists, order) in landed {
  2588. crate::list::recycle(lists, &order);
  2589. }
  2590. }
  2591. /// The thread that settles the flights once the card has run them all
  2592. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2593. /// at the next call that settles, and a title thread that polls such a
  2594. /// value while the submitting thread waits for that thread would never
  2595. /// see it.
  2596. fn late_helper() {
  2597. let Some(host) = host() else {
  2598. return;
  2599. };
  2600. // SAFETY: a plain event of our own.
  2601. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2602. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2603. return;
  2604. };
  2605. loop {
  2606. let target = {
  2607. let mut line = line();
  2608. loop {
  2609. if line.poke {
  2610. line.poke = false;
  2611. break None;
  2612. }
  2613. // (With the relay the flights are another thread's.)
  2614. if !relay() && !line.line.is_empty() && !line.settling {
  2615. break Some(line.target);
  2616. }
  2617. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2618. }
  2619. };
  2620. let Some(target) = target else {
  2621. land();
  2622. crate::queue::release_held(false);
  2623. continue;
  2624. };
  2625. // The card first, without the submission lock: the submitting
  2626. // thread prepares and sends meanwhile.
  2627. // SAFETY: our fence and event.
  2628. unsafe {
  2629. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2630. WaitForSingleObject(event, INFINITE);
  2631. }
  2632. }
  2633. {
  2634. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2635. // Something newer went up meanwhile: the card is waited for
  2636. // again, the submitting thread is not held up for it.
  2637. if line().target != target {
  2638. continue;
  2639. }
  2640. host.settle(&mut submitted, WHY_CARD_DONE);
  2641. }
  2642. land();
  2643. crate::queue::release_held(false);
  2644. }
  2645. }
  2646. /// Starts the threads of [`late`], once: the one that settles flights when
  2647. /// the card has run them and looks at what queues hold, and with [`relay`]
  2648. /// the one that lands flights.
  2649. fn late_threads() {
  2650. static HELPER: std::sync::Once = std::sync::Once::new();
  2651. HELPER.call_once(|| {
  2652. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2653. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2654. }
  2655. tracing::info!(
  2656. most = late_most(),
  2657. writes = late_writes(),
  2658. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2659. );
  2660. if relay() {
  2661. // Without it nothing would ever land.
  2662. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2663. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2664. }
  2665. tracing::info!(
  2666. exact = relay_exact(),
  2667. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2668. );
  2669. }
  2670. });
  2671. }
  2672. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2673. /// time flights have landed. Counted as a settle for `why`, and its time
  2674. /// as waiting for the card. The caller may hold the submission lock: the
  2675. /// thread that lands flights never takes it.
  2676. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2677. let mut line = line();
  2678. if done(&line) {
  2679. return;
  2680. }
  2681. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2682. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2683. let was_working = working(false);
  2684. let waiting = std::time::Instant::now();
  2685. while !done(&line) {
  2686. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2687. }
  2688. drop(line);
  2689. stood(waiting);
  2690. working(was_working);
  2691. let us = waiting.elapsed().as_micros() as u64;
  2692. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2693. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2694. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2695. #[cfg(feature = "diagnostics")]
  2696. blamed(why, us);
  2697. }
  2698. /// What the thread that lands flights fetches card copies' pieces with
  2699. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2700. /// behind the submission lock), and the memory the pieces come down to.
  2701. struct RelayFetch {
  2702. list: Prelude,
  2703. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2704. queue: Option<ID3D12CommandQueue>,
  2705. fence: ID3D12Fence,
  2706. event: HANDLE,
  2707. /// The last value signalled on `fence`.
  2708. sent: u64,
  2709. /// Buffer, mapping, bytes.
  2710. buffer: Option<(ID3D12Resource, usize, u64)>,
  2711. /// Pieces caught while a later flight was writing them.
  2712. suspects: torn::Suspects,
  2713. /// What earlier fetches brought of flights not landed yet.
  2714. had: crate::land::Had,
  2715. }
  2716. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2717. /// the first flights of the line it takes them, with what follows them,
  2718. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2719. /// the card, or for a flight. It takes neither the submission lock nor
  2720. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2721. /// lists and looking at what queues hold are left to [`late_helper`].
  2722. fn relay_worker() {
  2723. let Some(host) = host() else {
  2724. return;
  2725. };
  2726. // SAFETY: a plain event of our own.
  2727. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2728. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2729. };
  2730. let mut fetch: Option<RelayFetch> = None;
  2731. loop {
  2732. let next = {
  2733. let mut line = line();
  2734. loop {
  2735. if line.line.is_empty() {
  2736. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2737. continue;
  2738. }
  2739. let fences: Vec<Option<u64>> = line
  2740. .line
  2741. .iter()
  2742. .map(|l| match l {
  2743. Late::Run(flight) => Some(flight.fence),
  2744. _ => None,
  2745. })
  2746. .collect();
  2747. // SAFETY: a plain query.
  2748. let completed = unsafe { host.fence.GetCompletedValue() };
  2749. let n = landable(&fences, completed);
  2750. if n == 0 {
  2751. // The first thing is a flight the card has not run.
  2752. break Err(fences[0].unwrap_or(0));
  2753. }
  2754. line.settling = true;
  2755. let items: Vec<Late> = line.line.drain(..n).collect();
  2756. line.in_hand = items
  2757. .iter()
  2758. .filter_map(|l| match l {
  2759. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2760. _ => None,
  2761. })
  2762. .collect();
  2763. if card_steps::stage() > 0 {
  2764. line.landing = card_steps::writers(&items);
  2765. }
  2766. break Ok(items);
  2767. }
  2768. };
  2769. match next {
  2770. Ok(items) => host.relay_land(items, &mut fetch),
  2771. Err(target) => {
  2772. let waiting = std::time::Instant::now();
  2773. // SAFETY: the host's fence and this thread's event.
  2774. let waited = unsafe {
  2775. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2776. WaitForSingleObject(event, INFINITE);
  2777. })
  2778. };
  2779. if waited.is_err() {
  2780. std::thread::sleep(std::time::Duration::from_millis(1));
  2781. }
  2782. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2783. }
  2784. }
  2785. }
  2786. }
  2787. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2788. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2789. /// once, the pieces that differ found on several threads; but the merge is
  2790. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2791. /// are not done with here (each flight's are, afterwards). In two steps:
  2792. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  2793. /// which needs nothing that the fetch from the card's memory brings), and
  2794. /// the merge.
  2795. struct RelayBack {
  2796. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  2797. found: Option<Vec<Vec<(usize, usize)>>>,
  2798. }
  2799. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  2800. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2801. for (shadow, declared) in back {
  2802. if shadow.carded() {
  2803. continue;
  2804. }
  2805. let mut spans: Vec<(usize, usize)> = Vec::new();
  2806. join_ranges(&mut spans, declared.iter().copied());
  2807. for &(from, to) in &spans {
  2808. shadow.relay_compared(from, to - from);
  2809. }
  2810. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2811. }
  2812. RelayBack { work, found: None }
  2813. }
  2814. impl RelayBack {
  2815. /// Looks the ranges through, once; its time counts as `stat`.
  2816. fn look(&mut self, stat: usize) {
  2817. if self.work.is_empty() || self.found.is_some() {
  2818. return;
  2819. }
  2820. let scanning = std::time::Instant::now();
  2821. // Looked through without a lock: a piece that changes meanwhile (a
  2822. // later flight writing, the title's bytes going in) is found now or
  2823. // by that flight's landing, and the merge looks again under the
  2824. // lock.
  2825. self.found = Some(crate::shadow::find_all(&self.work));
  2826. crate::land::spent(stat, scanning);
  2827. #[cfg(feature = "diagnostics")]
  2828. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2829. }
  2830. /// What differs goes into title memory.
  2831. fn merge(mut self) {
  2832. use crate::land;
  2833. self.look(land::stat::SCAN);
  2834. let Some(found) = self.found else {
  2835. return;
  2836. };
  2837. let merging = std::time::Instant::now();
  2838. let mut written: Vec<u64> = Vec::new();
  2839. if land::on() {
  2840. // Pieces in the same block of title memory in one job, in order.
  2841. let pieces: Vec<(usize, usize, usize)> =
  2842. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  2843. let start = |i: usize| self.work[i].0.span().0 as usize;
  2844. let mut order: Vec<usize> = (0..pieces.len()).collect();
  2845. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  2846. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  2847. let jobs = land::jobs(&cut);
  2848. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  2849. land::each(jobs.len(), &|j| {
  2850. let working = std::time::Instant::now();
  2851. let mut notes = land::Notes::default();
  2852. for &p in &order[jobs[j].clone()] {
  2853. let (i, at, n) = pieces[p];
  2854. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  2855. }
  2856. notes.flush();
  2857. land::spent(land::stat::BACK_ALL, working);
  2858. });
  2859. land::count(land::stat::JOBS, jobs.len() as u64);
  2860. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  2861. } else {
  2862. let (mut now, mut title) = (Vec::new(), Vec::new());
  2863. for ((shadow, ..), found) in self.work.iter().zip(found) {
  2864. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  2865. written.push(found.into_iter().map(merge).sum());
  2866. }
  2867. }
  2868. land::spent(land::stat::BACK, merging);
  2869. for ((_, from, to), written) in self.work.iter().zip(written) {
  2870. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  2871. #[cfg(feature = "diagnostics")]
  2872. crate::copystat::compared(*from, to - from, written as usize);
  2873. let _ = (from, to);
  2874. }
  2875. }
  2876. }
  2877. /// For the frame-rate line, with [`late`]: what the line of flights did
  2878. /// per frame since the last one.
  2879. fn late_line(frames: f64) {
  2880. if !late() {
  2881. return;
  2882. }
  2883. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2884. tracing::info!(
  2885. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2886. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2887. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2888. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2889. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2890. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2891. s[0],
  2892. s[1],
  2893. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2894. s[12] / 1000.0,
  2895. s[WHY_SYNC],
  2896. s[WHY_CARD_DONE],
  2897. s[WHY_VALUE],
  2898. s[WHY_STALE],
  2899. s[WHY_READ],
  2900. s[15],
  2901. s[16],
  2902. s[17],
  2903. s[WHY_RUN],
  2904. late_most(),
  2905. s[WHY_MOST],
  2906. s[WHY_WRITES],
  2907. s[WHY_FENCE],
  2908. s[13],
  2909. s[14],
  2910. );
  2911. {
  2912. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2913. tracing::info!(
  2914. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2915. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2916. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2917. w[WHY_SYNC],
  2918. w[WHY_CARD_DONE],
  2919. w[WHY_VALUE],
  2920. w[WHY_STALE],
  2921. w[WHY_READ],
  2922. w[WHY_RUN],
  2923. w[WHY_MOST],
  2924. w[WHY_WRITES],
  2925. w[WHY_FENCE],
  2926. );
  2927. }
  2928. if relay() {
  2929. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2930. tracing::info!(
  2931. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2932. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2933. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2934. \"settles\" above are waits of other threads for it)",
  2935. r[1],
  2936. r[0],
  2937. r[2] / 1000.0,
  2938. r[3] / 1000.0,
  2939. r[4] / 1000.0,
  2940. );
  2941. if send::own() {
  2942. let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2943. tracing::info!(
  2944. "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
  2945. taking them out of the CPU sides",
  2946. t[0] / (1 << 20) as f64,
  2947. t[1],
  2948. t[2],
  2949. t[3] / 1000.0,
  2950. );
  2951. }
  2952. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2953. if t[0] > 0.0 {
  2954. tracing::info!(
  2955. "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",
  2956. t[0],
  2957. t[1],
  2958. t[2],
  2959. );
  2960. }
  2961. }
  2962. crate::land::log(frames);
  2963. if place::on() {
  2964. let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2965. tracing::info!(
  2966. "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",
  2967. t[0],
  2968. t[1] / 1024.0,
  2969. t[2],
  2970. t[3],
  2971. );
  2972. }
  2973. card_steps::log(frames);
  2974. crate::picked::log(frames);
  2975. #[cfg(feature = "diagnostics")]
  2976. log_blame(frames);
  2977. if late_exact() {
  2978. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  2979. tracing::info!(
  2980. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  2981. {runs:.0} changed runs, {:.2} MB",
  2982. bytes / (1 << 20) as f64
  2983. );
  2984. }
  2985. }
  2986. pub(crate) mod awake;
  2987. mod card_steps;
  2988. mod place;
  2989. mod send;
  2990. #[cfg(feature = "diagnostics")]
  2991. pub(crate) mod spans;
  2992. mod torn;
  2993. pub(crate) mod upcheck;
  2994. #[cfg(test)]
  2995. mod late_tests {
  2996. use super::{continues, join_ranges, touches};
  2997. /// Copies join only when both ends continue and the whole does not
  2998. /// overlap itself.
  2999. #[test]
  3000. fn copies_join_only_end_to_end_and_apart() {
  3001. // (destination, source, bytes)
  3002. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  3003. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  3004. // A gap, or only one side continues.
  3005. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  3006. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  3007. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  3008. // Together they would overlap: the second reads what the first wrote.
  3009. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  3010. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  3011. // They touch without overlapping.
  3012. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  3013. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  3014. }
  3015. /// Ranges are found by what they hold, not by where they start, and a
  3016. /// range that only touches another's end does not touch it.
  3017. #[test]
  3018. fn ranges_touch_where_they_overlap() {
  3019. let mut ranges = Vec::new();
  3020. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  3021. assert_eq!(ranges, [(10, 25), (40, 60)]);
  3022. join_ranges(&mut ranges, [(25, 40)]);
  3023. assert_eq!(ranges, [(10, 60)]);
  3024. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  3025. for (from, to, hit) in [
  3026. (0, 10, false),
  3027. (0, 11, true),
  3028. (24, 25, true),
  3029. (25, 40, false),
  3030. (25, 41, true),
  3031. (59, 200, true),
  3032. (60, 100, false),
  3033. (100, 101, true),
  3034. (101, 500, false),
  3035. (30, 30, false),
  3036. (50, 50, false),
  3037. ] {
  3038. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  3039. }
  3040. assert!(!touches(&[], 0, usize::MAX));
  3041. }
  3042. }
  3043. /// Whether a title buffer copy that continues the one recorded before it
  3044. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  3045. /// default).
  3046. ///
  3047. /// Each copy is done at submission through the kernel, which reports a
  3048. /// page that is not there instead of faulting (`copy_mapped`), tells the
  3049. /// write watch and the guards, and ends the refreshes gathered so far: a
  3050. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  3051. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  3052. /// continue the one before is counted either way and said on its own line
  3053. /// with the frame rate; the switch is worth that many kernel calls.
  3054. ///
  3055. /// Joined, the same bytes move: [`continues`] joins only copies whose
  3056. /// ranges, taken together, do not overlap, and nothing is recorded between
  3057. /// two steps that follow each other. What differs: a page that is not
  3058. /// mapped now fails the joined copy as a whole (it then goes page by page,
  3059. /// zeros for what cannot be read, as a single copy does), where before
  3060. /// only the copy that held it did.
  3061. fn join_copies() -> bool {
  3062. static ON: OnceLock<bool> = OnceLock::new();
  3063. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  3064. }
  3065. /// Since the last frame-rate line: title buffer copies recorded, and those
  3066. /// that continue the one before ([`join_copies`]).
  3067. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  3068. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  3069. /// where `last` ended, source and destination both, and the two as one do
  3070. /// not overlap (source over destination): then one copy of both moves the
  3071. /// bytes the two would move in turn.
  3072. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  3073. let ((d, s, n), (dst, src, len)) = (last, next);
  3074. let Some(all) = n.checked_add(len) else {
  3075. return false;
  3076. };
  3077. d.checked_add(n) == Some(dst)
  3078. && s.checked_add(n) == Some(src)
  3079. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  3080. }
  3081. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  3082. /// One list's lock at a time: a submission may name a list twice.
  3083. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  3084. let mut back: Vec<Declared> = Vec::new();
  3085. // Where each copy is in it, and the ranges seen: dispatches declare the
  3086. // same ranges thousands of times a frame.
  3087. let mut places: ByCopy<usize> = ByCopy::default();
  3088. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  3089. for list in runs {
  3090. for step in &list.deferred().copies {
  3091. if let Step::GpuWrite(shadow, address, len) = step {
  3092. let key = std::sync::Arc::as_ptr(shadow) as usize;
  3093. if !seen.insert((key, *address, *len)) {
  3094. continue;
  3095. }
  3096. let i = *places.entry(key).or_insert_with(|| {
  3097. back.push((shadow.clone(), Vec::new()));
  3098. back.len() - 1
  3099. });
  3100. back[i].1.push((*address, *address + *len));
  3101. }
  3102. }
  3103. }
  3104. back
  3105. }
  3106. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  3107. /// lines that say what the title's CPU was given while it decided whether
  3108. /// the camera is in a room. The values of the small read-backs
  3109. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  3110. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  3111. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  3112. /// copies found stale after their refresh (`shadow.rs`; only with
  3113. /// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
  3114. /// runtime, the read requests that fail (with 2: every request).
  3115. pub(crate) fn walls_trace() -> bool {
  3116. static ON: OnceLock<bool> = OnceLock::new();
  3117. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  3118. }
  3119. /// After `list` has run: the texels its read-backs copied into host
  3120. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  3121. ///
  3122. /// A submission that is waited for did this itself. One sent ahead
  3123. /// ([`late`]) did not, at any stage: the flights' lists were settled
  3124. /// without it, so the title read a buffer nobody wrote, as before read-backs
  3125. /// were made (the exposure metering's two small float targets, every frame).
  3126. fn read_backs(list: &HostList) {
  3127. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  3128. let mut data = std::ptr::null_mut();
  3129. // SAFETY: a read-back buffer of ours, written by the list that has
  3130. // run; the title's destination holds every row (checked when the
  3131. // copy was recorded).
  3132. unsafe {
  3133. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  3134. let from = data.cast::<u8>().cast_const();
  3135. for line in 0..*rows {
  3136. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  3137. }
  3138. // The walls trace: what the title is handed (one row of at
  3139. // most 24 values: its 5x1 and 1x1 float targets).
  3140. if walls_trace() && *rows == 1 && *row <= 96 {
  3141. let mut values = [0f32; 24];
  3142. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  3143. tracing::info!(
  3144. frame = crate::frame::current(),
  3145. to = format_args!("{:#x}", *at),
  3146. bytes = *row,
  3147. values = ?&values[..*row / 4],
  3148. "walls trace: a read-back lands in title memory"
  3149. );
  3150. }
  3151. buffer.Unmap(0, None);
  3152. }
  3153. }
  3154. }
  3155. }
  3156. /// After the card ran what declared `back`: what shaders wrote there goes
  3157. /// into title memory, and the ranges are done with.
  3158. fn hand_back(back: &[Declared]) {
  3159. if crate::shadow::wide_back() {
  3160. // Every range first (the pieces that differ, found on several
  3161. // threads), then the merges, in order, as below.
  3162. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3163. for (shadow, declared) in back {
  3164. if shadow.carded() {
  3165. continue;
  3166. }
  3167. let mut sorted = declared.clone();
  3168. sorted.sort_unstable();
  3169. let mut spans: Vec<(usize, usize)> = Vec::new();
  3170. for (from, to) in sorted {
  3171. match spans.last_mut() {
  3172. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3173. _ => spans.push((from, to)),
  3174. }
  3175. }
  3176. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3177. }
  3178. #[cfg(feature = "diagnostics")]
  3179. let scanning = std::time::Instant::now();
  3180. let found = crate::shadow::find_all(&work);
  3181. #[cfg(feature = "diagnostics")]
  3182. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3183. for ((shadow, from, to), found) in work.iter().zip(found) {
  3184. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3185. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3186. #[cfg(feature = "diagnostics")]
  3187. crate::copystat::compared(*from, to - from, written);
  3188. }
  3189. for (shadow, declared) in back {
  3190. shadow.copy_back_done(declared);
  3191. }
  3192. return;
  3193. }
  3194. for (shadow, declared) in back {
  3195. if shadow.carded() {
  3196. // Done before (`Host::card_back`).
  3197. shadow.copy_back_done(declared);
  3198. continue;
  3199. }
  3200. // Each byte compared once: the world declares dozens of views
  3201. // of its 174 MB heap that overlap almost entirely, and comparing
  3202. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3203. // MB shaders wrote. Only ranges that overlap or touch are
  3204. // joined: what lies between two was not given to shaders (the
  3205. // snapshot does not hold it).
  3206. let mut sorted = declared.clone();
  3207. sorted.sort_unstable();
  3208. let mut spans: Vec<(usize, usize)> = Vec::new();
  3209. for (from, to) in sorted {
  3210. match spans.last_mut() {
  3211. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3212. _ => spans.push((from, to)),
  3213. }
  3214. }
  3215. for (from, to) in spans {
  3216. let written = shadow.copy_back(from, to - from);
  3217. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3218. #[cfg(feature = "diagnostics")]
  3219. crate::copystat::compared(from, to - from, written);
  3220. }
  3221. shadow.copy_back_done(declared);
  3222. }
  3223. }
  3224. impl Host {
  3225. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3226. /// mesh shaders need both); logged once.
  3227. pub(crate) fn mesh_shaders(&self) -> bool {
  3228. static MESH: OnceLock<bool> = OnceLock::new();
  3229. *MESH.get_or_init(|| {
  3230. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3231. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3232. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3233. };
  3234. // SAFETY: each query writes its own structure of the given size.
  3235. let ok = unsafe {
  3236. self.device
  3237. .CheckFeatureSupport(
  3238. D3D12_FEATURE_D3D12_OPTIONS7,
  3239. (&raw mut options).cast(),
  3240. size_of_val(&options) as u32,
  3241. )
  3242. .is_ok()
  3243. && self
  3244. .device
  3245. .CheckFeatureSupport(
  3246. D3D12_FEATURE_SHADER_MODEL,
  3247. (&raw mut model).cast(),
  3248. size_of_val(&model) as u32,
  3249. )
  3250. .is_ok()
  3251. };
  3252. let mesh = ok
  3253. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3254. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3255. tracing::info!(mesh, "host mesh shader support");
  3256. mesh
  3257. })
  3258. }
  3259. /// Whether the host GPU supports the depth bounds test; logged once.
  3260. pub(crate) fn depth_bounds(&self) -> bool {
  3261. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3262. *BOUNDS.get_or_init(|| {
  3263. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3264. // SAFETY: writes `options` of the given size.
  3265. let ok = unsafe {
  3266. self.device
  3267. .CheckFeatureSupport(
  3268. D3D12_FEATURE_D3D12_OPTIONS2,
  3269. (&raw mut options).cast(),
  3270. size_of_val(&options) as u32,
  3271. )
  3272. .is_ok()
  3273. };
  3274. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3275. tracing::info!(supported, "host depth bounds support");
  3276. supported
  3277. })
  3278. }
  3279. /// A new list, open for recording.
  3280. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3281. #[cfg(feature = "diagnostics")]
  3282. let started = std::time::Instant::now();
  3283. #[cfg(feature = "diagnostics")]
  3284. let before = private_bytes();
  3285. let list = self.make_list();
  3286. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3287. // (May shrink while a list is made, on another thread's account:
  3288. // added as it is, the sum is what counts.)
  3289. #[cfg(feature = "diagnostics")]
  3290. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3291. #[cfg(feature = "diagnostics")]
  3292. {
  3293. use crate::copystat::{C, add};
  3294. add(C::HostLists, 1);
  3295. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3296. }
  3297. list
  3298. }
  3299. /// An allocator and a closed list for a prelude.
  3300. fn make_prelude(&self) -> Option<Prelude> {
  3301. // SAFETY: plain object creation.
  3302. let made: windows::core::Result<Prelude> = unsafe {
  3303. (|| {
  3304. let allocator: ID3D12CommandAllocator =
  3305. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3306. let list: ID3D12GraphicsCommandList =
  3307. self.device
  3308. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3309. list.Close()?;
  3310. Ok((allocator, list))
  3311. })()
  3312. };
  3313. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3314. match made {
  3315. Ok(prelude) => Some(prelude),
  3316. Err(e) => {
  3317. tracing::warn!(error = %e, "no host list for a prelude");
  3318. None
  3319. }
  3320. }
  3321. }
  3322. fn make_list(&self) -> windows::core::Result<HostList> {
  3323. // SAFETY: plain object creation.
  3324. unsafe {
  3325. let allocator: ID3D12CommandAllocator = self
  3326. .device
  3327. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3328. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3329. 0,
  3330. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3331. &allocator,
  3332. None,
  3333. )?;
  3334. let prelude = OnceLock::new();
  3335. if !lazy_prelude() {
  3336. let _ = prelude.set(self.make_prelude());
  3337. }
  3338. #[cfg(feature = "diagnostics")]
  3339. let notes = std::sync::Arc::<Mutex<Vec<Note>>>::default();
  3340. let pipelines = std::sync::Arc::<Mutex<std::collections::BTreeSet<String>>>::default();
  3341. #[cfg(feature = "diagnostics")]
  3342. if dred_on() || dred_light() {
  3343. static NUMBER: AtomicU32 = AtomicU32::new(0);
  3344. let number = NUMBER.fetch_add(1, Ordering::Relaxed);
  3345. name(&list, || format!("victory host list {number}"));
  3346. let mut all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  3347. if number.is_multiple_of(256) {
  3348. all.retain(|_, l| l.0.strong_count() > 0);
  3349. }
  3350. all.insert(number, (std::sync::Arc::downgrade(&notes), std::sync::Arc::downgrade(&pipelines)));
  3351. }
  3352. Ok(HostList {
  3353. allocator,
  3354. list,
  3355. deferred: Mutex::default(),
  3356. scratch: Mutex::default(),
  3357. states: Mutex::default(),
  3358. twins: Mutex::default(),
  3359. prelude,
  3360. pipelines,
  3361. budget: OnceLock::new(),
  3362. card_budget: OnceLock::new(),
  3363. indirect_args: Mutex::default(),
  3364. batch_args: Mutex::default(),
  3365. _alive: Counted::new(),
  3366. #[cfg(feature = "diagnostics")]
  3367. notes,
  3368. #[cfg(feature = "diagnostics")]
  3369. stamps: OnceLock::new(),
  3370. })
  3371. }
  3372. }
  3373. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3374. fn card_clock(&self) -> Option<&'static CardClock> {
  3375. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3376. static WATCH: std::sync::Once = std::sync::Once::new();
  3377. let clock = CLOCK
  3378. .get_or_init(|| {
  3379. // SAFETY: a plain fence on our device.
  3380. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3381. Some(CardClock {
  3382. fence,
  3383. state: Mutex::new((0, None)),
  3384. sent: std::sync::Condvar::new(),
  3385. })
  3386. })
  3387. .as_ref()?;
  3388. WATCH.call_once(|| {
  3389. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3390. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3391. }
  3392. });
  3393. Some(clock)
  3394. }
  3395. /// Lists of ours just went to the queue: the clock's signal goes
  3396. /// behind them, and an idle stretch of the card, if one was under way,
  3397. /// ends here ([`CARD_CLOCK_US`]).
  3398. fn card_sent(&self) {
  3399. let Some(clock) = self.card_clock() else {
  3400. return;
  3401. };
  3402. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3403. state.0 += 1;
  3404. // SAFETY: our queue and the clock's fence.
  3405. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3406. if let Some((since, worked_then)) = state.1.take() {
  3407. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3408. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3409. }
  3410. drop(state);
  3411. clock.sent.notify_one();
  3412. }
  3413. /// Whether the host has what copies in the card's memory need (three
  3414. /// lists and the compare); made at the first ask. A copy goes to the
  3415. /// card's memory only if it has.
  3416. pub(crate) fn card_ready(&self) -> bool {
  3417. static READY: OnceLock<bool> = OnceLock::new();
  3418. *READY.get_or_init(|| match self.make_card_work() {
  3419. Ok(work) => {
  3420. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3421. true
  3422. }
  3423. Err(e) => {
  3424. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3425. false
  3426. }
  3427. })
  3428. }
  3429. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3430. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3431. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3432. let mut code: Option<ID3DBlob> = None;
  3433. // SAFETY: the source and names live through the call; the out
  3434. // pointer is ours.
  3435. unsafe {
  3436. D3DCompile(
  3437. CARD_COMPARE.as_ptr().cast(),
  3438. CARD_COMPARE.len(),
  3439. windows::core::s!("card compare"),
  3440. None,
  3441. None,
  3442. windows::core::s!("main"),
  3443. windows::core::s!("cs_5_1"),
  3444. 0,
  3445. 0,
  3446. &mut code,
  3447. None,
  3448. )?;
  3449. }
  3450. let code = code.ok_or_else(windows::core::Error::empty)?;
  3451. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3452. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3453. // in one submission.
  3454. const RESULTS: u64 = 1 << 20;
  3455. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3456. name(&differs, || "card compare results".into());
  3457. // SAFETY: the blob's own bytes; the root signature is inside the
  3458. // shader.
  3459. unsafe {
  3460. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3461. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3462. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3463. pRootSignature: std::mem::transmute_copy(&root),
  3464. CS: D3D12_SHADER_BYTECODE {
  3465. pShaderBytecode: bytes.as_ptr().cast(),
  3466. BytecodeLength: bytes.len(),
  3467. },
  3468. ..Default::default()
  3469. })?;
  3470. #[cfg(feature = "diagnostics")]
  3471. name(&pso, || crate::replay::play::COMPARE.into());
  3472. Ok(CardWork {
  3473. sync: vec![list()?],
  3474. check: vec![list()?],
  3475. fetch: list()?,
  3476. root,
  3477. pso,
  3478. differs: (differs, data as usize, RESULTS),
  3479. fetched: None,
  3480. taken: 0,
  3481. out: 0,
  3482. })
  3483. }
  3484. }
  3485. /// Before a submission's lists run, for copies in the card's memory
  3486. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3487. /// the last submission goes to their card side (a list of ours, run
  3488. /// now; the submission's lists follow it on the queue), and the ranges
  3489. /// this submission's shaders may write get a compare to run after its
  3490. /// lists. `None` if there is nothing to do.
  3491. ///
  3492. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3493. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3494. /// `relay`).
  3495. /// `picked`: ranges that may be written too, and ranges to look at
  3496. /// (`crate::picked`).
  3497. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3498. use std::sync::Arc;
  3499. if !crate::shadow::cards() {
  3500. return None;
  3501. }
  3502. // The ranges this submission's shaders may write, per copy.
  3503. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3504. for list in runs {
  3505. for step in &list.deferred().copies {
  3506. if let Step::GpuWrite(shadow, address, len) = step
  3507. && shadow.carded()
  3508. {
  3509. let range = (*address, *address + *len);
  3510. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3511. Some((_, ranges)) => {
  3512. if !ranges.contains(&range) {
  3513. ranges.push(range);
  3514. }
  3515. }
  3516. None => declared.push((shadow.clone(), vec![range])),
  3517. }
  3518. }
  3519. }
  3520. }
  3521. let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
  3522. // (Of a copy with a declared range here, that says it.)
  3523. let looked: Vec<&crate::picked::Range> =
  3524. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3525. // With the relay: the order of the queue is held from here until
  3526. // what is taken is on the queue, and the taking is numbered.
  3527. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3528. let sent_as = match order.as_mut() {
  3529. Some(order) => {
  3530. **order += 1;
  3531. **order
  3532. }
  3533. None => 0,
  3534. };
  3535. let mut dirty = crate::shadow::card_dirty(sent_as);
  3536. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3537. return None;
  3538. }
  3539. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3540. let work = work.as_mut()?;
  3541. // A copy whose shader writes are declared for the first time gets
  3542. // its bytes from before, whole.
  3543. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3544. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3545. if shadow.card_make_before(|size| {
  3546. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3547. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3548. Some(before)
  3549. }) {
  3550. whole.push(shadow.clone());
  3551. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3552. dirty.push((shadow.clone(), Vec::new()));
  3553. }
  3554. }
  3555. }
  3556. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3557. let mut looks = None;
  3558. // The bytes as they are now, whatever later submissions put there.
  3559. let own = if send::own() { send::take(self, &dirty) } else { None };
  3560. if !dirty.is_empty() {
  3561. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3562. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3563. };
  3564. let (allocator, list) = &sync;
  3565. // SAFETY: the list's last run finished (it ran ahead of a
  3566. // submission that was waited for, and came back after that);
  3567. // live buffers, and the ranges lie in them.
  3568. let recorded = unsafe {
  3569. (|| -> windows::core::Result<()> {
  3570. allocator.Reset()?;
  3571. list.Reset(allocator, None)?;
  3572. if upcheck::on() {
  3573. looks = upcheck::record(self, list, &dirty);
  3574. }
  3575. // Every copy first, then one barrier call, then every
  3576. // pass: a wait between each copy and its pass had the
  3577. // card do them one after the other.
  3578. let mut sent = Vec::new();
  3579. if let Some(own) = &own {
  3580. own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
  3581. }
  3582. for (shadow, ranges) in &dirty {
  3583. let Some((staging, before, _)) = shadow.card_sides() else {
  3584. continue;
  3585. };
  3586. for &(a, b) in ranges {
  3587. if own.is_none() {
  3588. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3589. }
  3590. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3591. }
  3592. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3593. if own.is_none() && before.is_some() && !ranges.is_empty() {
  3594. sent.push(transition(
  3595. &shadow.buffer,
  3596. D3D12_RESOURCE_STATE_COPY_DEST,
  3597. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3598. ));
  3599. }
  3600. }
  3601. if !sent.is_empty() {
  3602. list.ResourceBarrier(&sent);
  3603. }
  3604. list.SetComputeRootSignature(&work.root);
  3605. list.SetPipelineState(&work.pso);
  3606. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3607. for (shadow, ranges) in &dirty {
  3608. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3609. continue;
  3610. };
  3611. // No twin (it cost the card the copy's size again,
  3612. // 399 MB in run 75): `before` holds a 128-bit hash
  3613. // of each 64 KiB piece. The pieces just sent up are
  3614. // hashed again, all of them the first time; the
  3615. // compare after the lists hashes the declared
  3616. // pieces and flags those whose hash is another.
  3617. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3618. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3619. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3620. vec![shadow.card_run(0, usize::MAX)]
  3621. } else {
  3622. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3623. };
  3624. // The same pieces in fewer passes (`rehash_runs`).
  3625. let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3626. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3627. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3628. for run in runs {
  3629. card_pass(list, &run, size as u32, 0, 0);
  3630. }
  3631. }
  3632. list.Close()?;
  3633. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3634. Ok(())
  3635. })()
  3636. };
  3637. if let Err(e) = recorded {
  3638. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3639. }
  3640. used.push((false, sync));
  3641. }
  3642. drop(order);
  3643. let mut plan = CardPlan {
  3644. ranges: Vec::new(),
  3645. check: None,
  3646. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3647. lists: used,
  3648. sent_as,
  3649. looks,
  3650. sends: own.map(send::Own::memory),
  3651. };
  3652. // Each byte once, as the copy-back joins the declared ranges. The
  3653. // results go behind those of plans still in the air.
  3654. let mut at = work.taken;
  3655. for (shadow, ranges) in &declared {
  3656. let mut sorted = ranges.clone();
  3657. sorted.sort_unstable();
  3658. let mut spans: Vec<(usize, usize)> = Vec::new();
  3659. for (from, to) in sorted {
  3660. match spans.last_mut() {
  3661. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3662. _ => spans.push((from, to)),
  3663. }
  3664. }
  3665. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3666. for (from, to) in spans {
  3667. let Some(span) = shadow.card_span(from, to) else {
  3668. continue;
  3669. };
  3670. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3671. plan.ranges.push(CardRange {
  3672. shadow: shadow.clone(),
  3673. declared: (from, to),
  3674. span,
  3675. at,
  3676. compared,
  3677. picked: false,
  3678. });
  3679. if compared {
  3680. at += span.pieces;
  3681. }
  3682. }
  3683. }
  3684. for (shadow, from, len) in looked {
  3685. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3686. if let Some(span) = shadow.card_span(*from, from + len)
  3687. && twin
  3688. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3689. {
  3690. plan.ranges.push(CardRange {
  3691. shadow: shadow.clone(),
  3692. declared: (*from, from + len),
  3693. span,
  3694. at,
  3695. compared: true,
  3696. picked: true,
  3697. });
  3698. at += span.pieces;
  3699. }
  3700. }
  3701. work.taken = at;
  3702. if plan.ranges.iter().any(|r| r.compared) {
  3703. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3704. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3705. };
  3706. let (allocator, list) = &check;
  3707. // SAFETY: the list's last run finished (its submission was
  3708. // waited for, and it came back after that); live buffers; the
  3709. // compare's own root signature.
  3710. let recorded = unsafe {
  3711. (|| -> windows::core::Result<ID3D12CommandList> {
  3712. allocator.Reset()?;
  3713. list.Reset(allocator, None)?;
  3714. // What the submission's shaders wrote, first.
  3715. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3716. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3717. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3718. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3719. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3720. pResource: std::mem::ManuallyDrop::new(None),
  3721. }),
  3722. },
  3723. }]);
  3724. list.SetComputeRootSignature(&work.root);
  3725. list.SetPipelineState(&work.pso);
  3726. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3727. for r in plan.ranges.iter().filter(|r| r.compared) {
  3728. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3729. continue;
  3730. };
  3731. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3732. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3733. // (What is only looked at keeps its hashes: what
  3734. // changed there is the next declared range's to land.)
  3735. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  3736. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3737. }
  3738. list.Close()?;
  3739. list.cast()
  3740. })()
  3741. };
  3742. match recorded {
  3743. Ok(list) => plan.check = Some(list),
  3744. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3745. }
  3746. plan.lists.push((true, check));
  3747. }
  3748. work.out += 1;
  3749. Some(plan)
  3750. }
  3751. /// With [`relay`]: whether the compare's result area is half taken by
  3752. /// plans in the air. It starts from the beginning only when no plan is
  3753. /// out, so the caller lets the flights land first.
  3754. fn card_results_low(&self) -> bool {
  3755. CARD_WORK
  3756. .lock()
  3757. .unwrap_or_else(|e| e.into_inner())
  3758. .as_ref()
  3759. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3760. }
  3761. /// The plan's submission has run and its results were read
  3762. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3763. /// when nothing of ours is on the card, so the compare's results start
  3764. /// from the beginning again.
  3765. fn card_done(&self, plan: CardPlan) {
  3766. if let Some(looks) = plan.looks {
  3767. looks.read();
  3768. }
  3769. if let Some(memory) = plan.sends {
  3770. send::give_back(memory);
  3771. }
  3772. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3773. let Some(work) = work.as_mut() else {
  3774. return;
  3775. };
  3776. for (check, list) in plan.lists {
  3777. if check { work.check.push(list) } else { work.sync.push(list) }
  3778. }
  3779. work.out = work.out.saturating_sub(1);
  3780. // With the relay other plans may be on the card, their results
  3781. // not read yet: the area starts again only when none is out.
  3782. if !relay() || work.out == 0 {
  3783. work.taken = 0;
  3784. }
  3785. }
  3786. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3787. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3788. // SAFETY: plain object creation.
  3789. let copying = relay_copy().then(|| unsafe {
  3790. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3791. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3792. let list: ID3D12GraphicsCommandList =
  3793. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3794. list.Close()?;
  3795. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3796. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3797. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3798. ..Default::default()
  3799. })?;
  3800. Ok(((allocator, list), queue))
  3801. })()
  3802. });
  3803. let (list, queue) = match copying {
  3804. Some(Ok((list, queue))) => (list, Some(queue)),
  3805. Some(Err(e)) => {
  3806. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3807. (self.make_prelude()?, None)
  3808. }
  3809. None => (self.make_prelude()?, None),
  3810. };
  3811. // SAFETY: plain objects of our own.
  3812. unsafe {
  3813. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3814. let event = CreateEventW(None, false, false, None).ok()?;
  3815. Some(RelayFetch {
  3816. list,
  3817. queue,
  3818. fence,
  3819. event,
  3820. sent: 0,
  3821. buffer: None,
  3822. suspects: torn::Suspects::default(),
  3823. had: crate::land::Had::default(),
  3824. })
  3825. }
  3826. }
  3827. /// [`relay`], on the thread that lands flights: for the plans of the
  3828. /// flights being landed (the card has run them), the pieces their
  3829. /// compares flagged are fetched, once each, with a list and a wait of
  3830. /// this thread's own, and what shaders wrote in them goes into title
  3831. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3832. /// no submission lock; a piece flagged under one range of a plan is
  3833. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3834. /// whatever was sent meanwhile, so it may bring a later flight's
  3835. /// bytes, which that flight's landing then finds merged already; and
  3836. /// nothing is sent back up. `plans` come with the value signalled behind
  3837. /// their flight. `meanwhile` is called while the fetch is on its way, if
  3838. /// there is one.
  3839. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  3840. use crate::land;
  3841. let gathering = std::time::Instant::now();
  3842. let differs = {
  3843. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3844. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3845. };
  3846. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3847. let mut total = 0u64;
  3848. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  3849. fetch.had.landing(first);
  3850. }
  3851. // SAFETY: the mapping of the results. The compares of these plans
  3852. // have run, and their dwords are given to no other plan before these
  3853. // are done with (`card_done`).
  3854. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  3855. if let Some(differs) = differs {
  3856. // Pieces caught while a later flight was at them (`torn`).
  3857. let suspects = fetch.as_ref().map(|f| &f.suspects);
  3858. let mut seen = std::collections::HashSet::new();
  3859. for &(plan, behind) in plans {
  3860. plan.picked_found(differs);
  3861. let flags: Vec<(usize, u32, bool)> = plan
  3862. .ranges
  3863. .iter()
  3864. .filter(|r| !r.picked)
  3865. .flat_map(|r| {
  3866. (0..r.span.pieces).map(move |p| {
  3867. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  3868. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  3869. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  3870. })
  3871. })
  3872. .collect();
  3873. let fetched = flagged_pieces(&flags);
  3874. for r in plan.ranges.iter().filter(|r| !r.picked) {
  3875. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3876. if upcheck::on() {
  3877. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  3878. }
  3879. for p in 0..r.span.pieces {
  3880. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  3881. continue;
  3882. }
  3883. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3884. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  3885. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  3886. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  3887. land::count(land::stat::HAD, 1);
  3888. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  3889. if land::skip_on() {
  3890. continue;
  3891. }
  3892. }
  3893. if upcheck::on() {
  3894. upcheck::fetched(r.shadow.id(), lo);
  3895. }
  3896. seen.insert((copy, lo, hi));
  3897. pieces.push((r.shadow.clone(), lo, hi, total));
  3898. total += (hi - lo) as u64;
  3899. }
  3900. }
  3901. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3902. }
  3903. }
  3904. }
  3905. if land::on() {
  3906. // In the order they are landed, each byte of a copy once.
  3907. let keys: Vec<land::Piece> =
  3908. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  3909. total = 0;
  3910. pieces = land::ordered(&keys)
  3911. .into_iter()
  3912. .map(|(i, title, len)| {
  3913. let shadow = &pieces[i].0;
  3914. let lo = title - shadow.span().0 as usize;
  3915. let at = total;
  3916. total += len as u64;
  3917. (shadow.clone(), lo, lo + len, at)
  3918. })
  3919. .collect();
  3920. }
  3921. land::spent(land::stat::GATHER, gathering);
  3922. if fetch.is_none() {
  3923. *fetch = self.make_relay_fetch();
  3924. }
  3925. // On the copy queue a later flight may be at a piece while it is
  3926. // fetched: the pieces come down whole, to be hashed.
  3927. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  3928. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  3929. if let Some(check) = &check {
  3930. total = check.total;
  3931. }
  3932. // The sends these flights ran behind, all a fetch on the copy queue
  3933. // is known to have run behind.
  3934. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  3935. if pieces.is_empty() {
  3936. // Nothing to fetch: every send so far is older than the next
  3937. // fetch, if that goes to the queue the sends went to.
  3938. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  3939. true => behind,
  3940. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  3941. };
  3942. crate::shadow::relay_fetched(after);
  3943. return;
  3944. }
  3945. let Some(f) = fetch.as_mut() else {
  3946. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  3947. };
  3948. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  3949. let size = total.next_multiple_of(16 << 20);
  3950. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3951. }
  3952. let Some((buffer, data, _)) = f.buffer.clone() else {
  3953. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  3954. };
  3955. f.sent += 1;
  3956. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  3957. let copy_queue = f.queue.clone();
  3958. let waiting = std::time::Instant::now();
  3959. // The flights the fetch runs behind: those in the line by now have
  3960. // been given to the queue. On the copy queue, those landed here.
  3961. let ahead = match copy_queue {
  3962. Some(_) => 0,
  3963. None => line().target,
  3964. };
  3965. // SAFETY: the list's last run was waited for by this thread; live
  3966. // buffers (the copies are held by the plans); the fence and the
  3967. // event are this thread's.
  3968. let ran = unsafe {
  3969. (|| -> windows::core::Result<u64> {
  3970. allocator.Reset()?;
  3971. list.Reset(&allocator, None)?;
  3972. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  3973. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  3974. }
  3975. list.Close()?;
  3976. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  3977. if let Some(queue) = &copy_queue {
  3978. queue.ExecuteCommandLists(&lists);
  3979. queue.Signal(&fence, sent)?;
  3980. meanwhile();
  3981. fence.SetEventOnCompletion(sent, event)?;
  3982. WaitForSingleObject(event, INFINITE);
  3983. return Ok(behind);
  3984. }
  3985. // In the order of the queue: the sends of title bytes so
  3986. // far are ahead of this fetch, every later one behind it.
  3987. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  3988. self.queue.ExecuteCommandLists(&lists);
  3989. let after = *order;
  3990. drop(order);
  3991. self.card_sent();
  3992. self.queue.Signal(&fence, sent)?;
  3993. meanwhile();
  3994. fence.SetEventOnCompletion(sent, event)?;
  3995. WaitForSingleObject(event, INFINITE);
  3996. Ok(after)
  3997. })()
  3998. };
  3999. let after = match ran {
  4000. Ok(after) => after,
  4001. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  4002. };
  4003. let us = waiting.elapsed().as_micros() as u64;
  4004. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  4005. {
  4006. use crate::shadow::CARD_STATS;
  4007. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4008. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4009. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4010. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  4011. }
  4012. let merging = std::time::Instant::now();
  4013. let mut written = 0;
  4014. if land::on() {
  4015. let titles: Vec<(usize, usize)> =
  4016. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  4017. let jobs = land::jobs(&titles);
  4018. let put = std::sync::atomic::AtomicU64::new(0);
  4019. land::each(jobs.len(), &|j| {
  4020. let working = std::time::Instant::now();
  4021. if let Some(check) = &check {
  4022. for i in jobs[j].clone() {
  4023. // SAFETY: as below.
  4024. unsafe { check.look(i, data) };
  4025. }
  4026. }
  4027. let mut notes = land::Notes::default();
  4028. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  4029. let addressed: Vec<(usize, usize, usize)> =
  4030. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  4031. // SAFETY: the mapping of the fetched bytes, `total` of
  4032. // them; the copy into it has run, and the next waits
  4033. // for this call.
  4034. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  4035. }
  4036. notes.flush();
  4037. land::spent(land::stat::CARD_ALL, working);
  4038. });
  4039. land::count(land::stat::JOBS, jobs.len() as u64);
  4040. written = put.into_inner();
  4041. } else {
  4042. let mut title = Vec::new();
  4043. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  4044. if let Some(check) = &check {
  4045. // SAFETY: as below.
  4046. unsafe { check.look(i, data) };
  4047. }
  4048. // SAFETY: the mapping of the fetched bytes, `total` of them;
  4049. // the copy into it has run.
  4050. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  4051. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  4052. shadow.walls_merged(gpu.len(), merged);
  4053. written += merged as u64;
  4054. }
  4055. }
  4056. land::spent(land::stat::CARD, merging);
  4057. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  4058. if let Some(f) = fetch.as_mut() {
  4059. if let Some(check) = &check {
  4060. check.done(&mut f.suspects);
  4061. }
  4062. f.had.fetched(
  4063. ahead,
  4064. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  4065. );
  4066. }
  4067. // Sends up to `after` are of no use to any later merge.
  4068. crate::shadow::relay_fetched(after);
  4069. }
  4070. /// [`relay`], on the thread that lands flights: `items` are the first
  4071. /// things of the line, flights the card has run and what follows them.
  4072. /// What their shaders wrote goes into title memory (copies in the
  4073. /// card's memory first, then the others, each byte once whichever
  4074. /// flights declared it); then every flight's ranges are done with;
  4075. /// then, in the line's order, each flight's read-backs, its
  4076. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  4077. /// is complete before the title is told anything.
  4078. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  4079. let landing = std::time::Instant::now();
  4080. {
  4081. let flights: Vec<&Flight> = items
  4082. .iter()
  4083. .filter_map(|l| match l {
  4084. Late::Run(flight) => Some(flight),
  4085. _ => None,
  4086. })
  4087. .collect();
  4088. if !flights.is_empty() {
  4089. // SAFETY: a plain query.
  4090. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4091. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  4092. fail(format_args!(
  4093. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  4094. flights.len(),
  4095. runs.len(),
  4096. self.removal_data(&runs),
  4097. last_notes(&runs)
  4098. ));
  4099. }
  4100. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  4101. // (Each byte once: the ranges are joined.)
  4102. let mut back: Vec<Declared> = Vec::new();
  4103. for flight in &flights {
  4104. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  4105. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4106. Some((_, all)) => all.extend_from_slice(ranges),
  4107. None => back.push((shadow.clone(), ranges.clone())),
  4108. }
  4109. }
  4110. }
  4111. let mut hand_back = relay_hand_back(&back);
  4112. self.relay_card_back(&plans, fetch, &mut || {
  4113. if crate::land::on() {
  4114. hand_back.look(crate::land::stat::SCAN_BESIDE);
  4115. }
  4116. });
  4117. hand_back.merge();
  4118. let finishing = std::time::Instant::now();
  4119. // Only now, and flight by flight: a range another flight
  4120. // in the air declared too stays closed to refreshes.
  4121. for flight in &flights {
  4122. for (shadow, ranges) in &flight.back {
  4123. shadow.copy_back_done(ranges);
  4124. }
  4125. }
  4126. crate::land::spent(crate::land::stat::DONE, finishing);
  4127. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4128. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  4129. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  4130. }
  4131. }
  4132. // In the order given: what tells the title the card is done.
  4133. let mut last = 0;
  4134. let mut landed = Vec::new();
  4135. let mut telling = std::time::Instant::now();
  4136. for item in items {
  4137. telling = match item {
  4138. Late::Run(flight) => {
  4139. last = flight.number;
  4140. for &i in &flight.order {
  4141. read_backs(flight.lists[i].host());
  4142. }
  4143. if let Some(card) = flight.card {
  4144. self.card_done(card);
  4145. }
  4146. if let Some(own) = flight.own {
  4147. own.landed();
  4148. }
  4149. landed.push((flight.lists, flight.order));
  4150. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  4151. }
  4152. Late::Write(at, what, bytes) => {
  4153. what.write(at as *mut u8, bytes);
  4154. crate::land::spent(crate::land::stat::TOLD, telling)
  4155. }
  4156. Late::Signal(fence, value) => {
  4157. crate::fence::set(fence as crate::object::This, value);
  4158. crate::land::spent(crate::land::stat::TOLD, telling)
  4159. }
  4160. };
  4161. }
  4162. if last > 0 {
  4163. FINISHED.store(last, Ordering::Release);
  4164. bury(last);
  4165. }
  4166. self.log_messages();
  4167. crate::land::spent(crate::land::stat::REST, telling);
  4168. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4169. {
  4170. let mut line = line();
  4171. let Line {
  4172. line: items,
  4173. written,
  4174. lists,
  4175. settling,
  4176. poke,
  4177. landed: kept,
  4178. in_hand,
  4179. landing,
  4180. ..
  4181. } = &mut *line;
  4182. kept.extend(landed);
  4183. in_hand.clear();
  4184. landing.clear();
  4185. // What is still in the air, from the flights that are.
  4186. written.clear();
  4187. *lists = 0;
  4188. let mut ranges = Vec::new();
  4189. for item in items.iter() {
  4190. if let Late::Run(flight) = item {
  4191. *lists += flight.order.len().max(1);
  4192. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  4193. }
  4194. }
  4195. join_ranges(written, ranges);
  4196. *settling = false;
  4197. // The landed lists are reset, and what queues hold looked at,
  4198. // by the helper thread (they take locks a waiter may hold).
  4199. *poke = true;
  4200. }
  4201. LINE_MOVED.notify_all();
  4202. LINE_LANDED.notify_all();
  4203. }
  4204. /// After a submission ran, for copies in the card's memory: the pieces
  4205. /// of the declared ranges that the compare found differing (all of a
  4206. /// range it did not compare) are fetched, with one more wait for the
  4207. /// card, and what shaders wrote in them goes into title memory.
  4208. /// `submitted` is the last value signalled on the fence. `seen` holds
  4209. /// the pieces fetched already since the card was last waited for
  4210. /// (several submissions settled together name the same ones).
  4211. fn card_back(
  4212. &self,
  4213. plan: &CardPlan,
  4214. submitted: &mut u64,
  4215. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4216. ) {
  4217. if plan.ranges.is_empty() {
  4218. return;
  4219. }
  4220. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4221. let Some(work) = work.as_mut() else {
  4222. return;
  4223. };
  4224. // SAFETY: the mapping of the results, which the compare (it has
  4225. // run) wrote.
  4226. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4227. // The pieces to fetch: the range, the offsets in its copy, and
  4228. // where the bytes come down.
  4229. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4230. let mut total = 0u64;
  4231. plan.picked_found(differs);
  4232. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4233. for p in 0..r.span.pieces {
  4234. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4235. continue;
  4236. }
  4237. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4238. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4239. pieces.push((i, lo, hi, total));
  4240. total += (hi - lo) as u64;
  4241. }
  4242. }
  4243. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4244. }
  4245. let mut written = vec![0usize; plan.ranges.len()];
  4246. if !pieces.is_empty() {
  4247. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4248. let size = total.next_multiple_of(16 << 20);
  4249. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4250. }
  4251. let Some((fetched, data, _)) = &work.fetched else {
  4252. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4253. };
  4254. let waiting = std::time::Instant::now();
  4255. let (allocator, list) = &work.fetch;
  4256. // SAFETY: the list's last run was waited for; live buffers; the
  4257. // fence and event are ours, under the submission lock.
  4258. let ran = unsafe {
  4259. (|| -> windows::core::Result<()> {
  4260. allocator.Reset()?;
  4261. list.Reset(allocator, None)?;
  4262. for &(i, lo, hi, at) in &pieces {
  4263. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4264. }
  4265. list.Close()?;
  4266. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4267. self.card_sent();
  4268. *submitted += 1;
  4269. self.queue.Signal(&self.fence, *submitted)?;
  4270. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4271. let was_working = working(false);
  4272. WaitForSingleObject(self.event, INFINITE);
  4273. stood(waiting);
  4274. working(was_working);
  4275. Ok(())
  4276. })()
  4277. };
  4278. if let Err(e) = ran {
  4279. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4280. }
  4281. {
  4282. use crate::shadow::CARD_STATS;
  4283. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4284. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4285. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4286. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4287. }
  4288. if wide_merge() && pieces.len() >= 8 {
  4289. // The pieces are apart from one another (each its own bytes
  4290. // of its copy and of title memory): several at a time.
  4291. let fetched = *data;
  4292. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4293. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4294. let each = pieces.len().div_ceil(8);
  4295. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4296. .chunks(each)
  4297. .map(|chunk| {
  4298. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4299. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4300. let counts = counts.clone();
  4301. Box::new(move || {
  4302. let mut title = Vec::new();
  4303. for (shadow, i, lo, hi, at) in chunk {
  4304. // SAFETY: the mapping of the fetched bytes;
  4305. // the copy into it has run, and the caller
  4306. // waits for this job.
  4307. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4308. let merged = shadow.card_merge(lo, gpu, &mut title);
  4309. shadow.walls_merged(gpu.len(), merged);
  4310. counts[i].fetch_add(merged, Ordering::Relaxed);
  4311. }
  4312. }) as Box<dyn FnOnce() + Send>
  4313. })
  4314. .collect();
  4315. crate::shadow::wide_run(jobs);
  4316. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4317. *written += count.load(Ordering::Relaxed);
  4318. }
  4319. } else {
  4320. let mut title = Vec::new();
  4321. for &(i, lo, hi, at) in &pieces {
  4322. // SAFETY: the mapping of the fetched bytes, `total` of
  4323. // them; the copy into it has run.
  4324. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4325. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4326. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4327. written[i] += merged;
  4328. }
  4329. }
  4330. }
  4331. for (r, written) in plan.ranges.iter().zip(written) {
  4332. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4333. let (from, to) = r.declared;
  4334. #[cfg(feature = "diagnostics")]
  4335. crate::copystat::compared(from, to - from, written);
  4336. let _ = (from, to);
  4337. }
  4338. }
  4339. /// Runs closed lists and waits for them, and with [`late`] for
  4340. /// everything sent to the card before them, which is settled first.
  4341. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4342. let _ = self.submit(runs, false);
  4343. }
  4344. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4345. /// from the title's, go to the card in `order` and are not waited for.
  4346. /// They join the line of flights and are settled, with the others in
  4347. /// the air, at the next point where what they do can be observed
  4348. /// ([`late`] lists those points); their host lists are reset and kept
  4349. /// for reuse then, as a queue does for the lists it ran.
  4350. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4351. if order.is_empty() {
  4352. crate::list::recycle(lists, &order);
  4353. return;
  4354. }
  4355. late_threads();
  4356. let sent = {
  4357. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4358. self.submit(&runs, true)
  4359. };
  4360. let Some((mut submitted, sent)) = sent else {
  4361. // (Not reached: a submission sent ahead always comes back.)
  4362. crate::list::recycle(lists, &order);
  4363. return;
  4364. };
  4365. let told = !sent.writes.is_empty();
  4366. let most = {
  4367. let mut line = line();
  4368. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4369. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4370. *flying += order.len();
  4371. *target = *submitted;
  4372. items.push(Late::Run(Flight {
  4373. number: sent.number,
  4374. fence: *target,
  4375. lists,
  4376. order,
  4377. card: sent.card,
  4378. back: sent.back,
  4379. own: sent.own,
  4380. }));
  4381. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4382. *flying >= late_most()
  4383. };
  4384. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4385. RELAY_MOVED.notify_one();
  4386. if told && !late_writes() {
  4387. self.settle(&mut submitted, WHY_WRITES);
  4388. } else if most && relay_exact() {
  4389. // Until there are fewer, not until there are none.
  4390. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4391. } else if most {
  4392. self.settle(&mut submitted, WHY_MOST);
  4393. } else {
  4394. LINE_MOVED.notify_one();
  4395. }
  4396. drop(submitted);
  4397. land();
  4398. }
  4399. /// Sends `list`, a closed list of ours (the present's copy), as a
  4400. /// flight ([`late_free_present`]): not waited for, settled with the
  4401. /// others. The caller keeps the list and does not reset it before the
  4402. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4403. /// it ran and was waited for after all.
  4404. fn execute_own(&self, list: &HostList) -> u64 {
  4405. late_threads();
  4406. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4407. return 0;
  4408. };
  4409. let number = sent.number;
  4410. {
  4411. let mut line = line();
  4412. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4413. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4414. *flying += 1;
  4415. *target = *submitted;
  4416. items.push(Late::Run(Flight {
  4417. number,
  4418. fence: *target,
  4419. lists: Vec::new(),
  4420. order: Vec::new(),
  4421. card: sent.card,
  4422. back: sent.back,
  4423. own: sent.own,
  4424. }));
  4425. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4426. }
  4427. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4428. LINE_MOVED.notify_one();
  4429. RELAY_MOVED.notify_one();
  4430. drop(submitted);
  4431. number
  4432. }
  4433. /// Waits for the card to run every flight in the air ([`late`]) and
  4434. /// does what they left to do, as [`Host::execute`] does for one
  4435. /// submission after its wait: the pieces their shaders wrote in copies
  4436. /// in the card's memory are fetched and merged (each once), the ranges
  4437. /// they declared in the other copies are compared and copied back
  4438. /// (each byte once, whichever flights declared it), and then, in the
  4439. /// order they were given: their bottom-of-pipe writes and the fence
  4440. /// signals behind them. `submitted` is the submission lock's value;
  4441. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4442. ///
  4443. /// Everything in the air is settled, never the first flights alone:
  4444. /// the merge writes the copies' CPU side, which a flight still on the
  4445. /// card may be writing too.
  4446. fn settle(&self, submitted: &mut u64, why: usize) {
  4447. if !late() {
  4448. return;
  4449. }
  4450. if relay() {
  4451. // Nothing is settled here: the thread that lands flights does
  4452. // it, in order, and this waits until nothing is in the air and
  4453. // nothing is being landed. Every point that settled before
  4454. // comes here, so each still sees title memory, fences and
  4455. // bottom-of-pipe values as after a settle.
  4456. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4457. return;
  4458. }
  4459. let was_working = working(true);
  4460. let mut counted = false;
  4461. loop {
  4462. let items = {
  4463. let mut line = line();
  4464. if line.line.is_empty() {
  4465. line.settling = false;
  4466. break;
  4467. }
  4468. line.settling = true;
  4469. line.written.clear();
  4470. line.lists = 0;
  4471. std::mem::take(&mut line.line)
  4472. };
  4473. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4474. if !counted {
  4475. counted = true;
  4476. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4477. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4478. }
  4479. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4480. if flights > 0 {
  4481. submitting(2, flights);
  4482. let waiting = std::time::Instant::now();
  4483. // SAFETY: the fence and event are ours, under the
  4484. // submission lock; `submitted` is the last value signalled.
  4485. unsafe {
  4486. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4487. Ok(()) => {
  4488. working(false);
  4489. WaitForSingleObject(self.event, INFINITE);
  4490. stood(waiting);
  4491. working(true);
  4492. }
  4493. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4494. }
  4495. }
  4496. let gpu = waiting.elapsed();
  4497. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4498. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4499. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4500. #[cfg(feature = "diagnostics")]
  4501. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4502. format!("{flights} submissions sent ahead, settled together")
  4503. });
  4504. // SAFETY: a plain query.
  4505. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4506. let runs: Vec<&HostList> = items
  4507. .iter()
  4508. .filter_map(|i| match i {
  4509. Late::Run(f) => Some(f),
  4510. _ => None,
  4511. })
  4512. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4513. .collect();
  4514. fail(format_args!(
  4515. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4516. runs.len(),
  4517. self.removal_data(&runs),
  4518. last_notes(&runs)
  4519. ));
  4520. }
  4521. submitting(3, flights);
  4522. let copying = std::time::Instant::now();
  4523. let mut seen = std::collections::HashSet::new();
  4524. let mut back: Vec<Declared> = Vec::new();
  4525. for item in &items {
  4526. let Late::Run(flight) = item else {
  4527. continue;
  4528. };
  4529. if let Some(card) = &flight.card {
  4530. self.card_back(card, submitted, &mut seen);
  4531. }
  4532. for (shadow, ranges) in &flight.back {
  4533. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4534. Some((_, all)) => {
  4535. for range in ranges {
  4536. if !all.contains(range) {
  4537. all.push(*range);
  4538. }
  4539. }
  4540. }
  4541. None => back.push((shadow.clone(), ranges.clone())),
  4542. }
  4543. }
  4544. }
  4545. hand_back(&back);
  4546. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4547. }
  4548. // In the order given: what tells the title the card is done.
  4549. let mut last = 0;
  4550. let mut landed = Vec::new();
  4551. for item in items {
  4552. match item {
  4553. Late::Run(flight) => {
  4554. last = flight.number;
  4555. for &i in &flight.order {
  4556. read_backs(flight.lists[i].host());
  4557. }
  4558. if let Some(card) = flight.card {
  4559. self.card_done(card);
  4560. }
  4561. landed.push((flight.lists, flight.order));
  4562. }
  4563. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4564. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4565. }
  4566. }
  4567. if last > 0 {
  4568. FINISHED.store(last, Ordering::Release);
  4569. bury(last);
  4570. }
  4571. line().landed.extend(landed);
  4572. }
  4573. if counted {
  4574. self.log_messages();
  4575. submitting(0, 0);
  4576. // What was settled may be what a queue stands at, and the
  4577. // caller may not be one that looks (a read-back, a present).
  4578. if why != WHY_CARD_DONE {
  4579. line().poke = true;
  4580. LINE_MOVED.notify_one();
  4581. }
  4582. }
  4583. working(was_working);
  4584. }
  4585. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4586. /// copies, which flights may be writing and the title wrote too
  4587. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4588. /// those of the submission's one asking, which is made again.
  4589. ///
  4590. /// With [`card_steps`] only the flights that declared them: a range of
  4591. /// a copy nobody declared any more is refreshed like any other. What
  4592. /// they landed is title memory written, so everything is asked and
  4593. /// looked at again; what is left after three times waits as before.
  4594. fn settle_stale(
  4595. &self,
  4596. submitted: &mut u64,
  4597. runs: &[&HostList],
  4598. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4599. ranges: &[(usize, usize)],
  4600. ) {
  4601. if relay_exact() && card_steps::stage() > 0 {
  4602. for _ in 0..3 {
  4603. #[cfg(feature = "diagnostics")]
  4604. blame_stale(&stale);
  4605. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4606. crate::watch::ask_once(ranges);
  4607. stale = stale_under_flights(runs);
  4608. if stale.is_empty() {
  4609. return;
  4610. }
  4611. }
  4612. }
  4613. #[cfg(feature = "diagnostics")]
  4614. blame_stale(&stale);
  4615. self.settle(submitted, WHY_STALE);
  4616. crate::watch::ask_once(ranges);
  4617. }
  4618. /// [`Host::execute`], or with `late` the first half of
  4619. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4620. /// to be done once they have run comes back with the submission lock
  4621. /// still held.
  4622. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4623. #[cfg(feature = "diagnostics")]
  4624. let called = std::time::Instant::now();
  4625. #[cfg(feature = "diagnostics")]
  4626. crate::copystat::submission_begins();
  4627. // One submission at a time from preparation to copy-back: snapshots
  4628. // and the ranges shaders write are per host copy, not per submission.
  4629. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4630. let was_working = working(true);
  4631. submitting(1, runs.len());
  4632. // Flights in the air ([`late`]): a submission that is waited for
  4633. // settles them first, one sent ahead only if preparing it reads
  4634. // what they write.
  4635. // Or the reads are done on the card, behind the flights.
  4636. let own = if late { self.card_steps(runs) } else { None };
  4637. if !late {
  4638. self.settle(&mut submitted, WHY_SYNC);
  4639. } else if own.is_none()
  4640. && let Some(why) = late_blocked(runs)
  4641. {
  4642. if relay_exact() && why == WHY_READ {
  4643. // Only until the flights that may write what is read have
  4644. // landed: their copy-back's end, not the card's other work.
  4645. relay_wait(why, |line| {
  4646. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4647. });
  4648. } else {
  4649. self.settle(&mut submitted, why);
  4650. }
  4651. }
  4652. // Descriptors the title copied into placed heaps directly, before
  4653. // command lists that index those slots are submitted.
  4654. crate::descriptor::sync_heaps();
  4655. // That list runs first, and is one of the submission's from here on.
  4656. let with: Vec<&HostList>;
  4657. let runs = match &own {
  4658. Some(own) => {
  4659. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4660. &with[..]
  4661. }
  4662. None => runs,
  4663. };
  4664. let behind = late && flying();
  4665. // Before this submission counts as started: what the sweep lets go
  4666. // of is named by no list, and nothing runs now (behind flights the
  4667. // sweep waits for a submission that finds none in the air: there is
  4668. // one at every present).
  4669. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4670. if !behind {
  4671. if upcheck::on() {
  4672. upcheck::at_rest(self);
  4673. }
  4674. sweep();
  4675. SWEPT.store(now_ms(), Ordering::Relaxed);
  4676. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4677. // With the present sent ahead nothing else brings a moment
  4678. // with nothing in the air: one is made for the sweep.
  4679. self.settle(&mut submitted, WHY_SYNC);
  4680. if upcheck::on() {
  4681. upcheck::at_rest(self);
  4682. }
  4683. sweep();
  4684. SWEPT.store(now_ms(), Ordering::Relaxed);
  4685. }
  4686. let behind = late && flying();
  4687. // The slots that waited for a texture's host copy, before the
  4688. // lists that may read them run.
  4689. crate::descriptor::make_waiting();
  4690. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4691. // The ranges shaders write are counted for it (with the relay).
  4692. crate::shadow::preparing(this_submission);
  4693. let started = std::time::Instant::now();
  4694. #[cfg(feature = "diagnostics")]
  4695. let lock = (started - called).as_micros() as u64;
  4696. #[cfg(feature = "diagnostics")]
  4697. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4698. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4699. // Where each run's lists start in `lists`.
  4700. let mut firsts = Vec::with_capacity(runs.len());
  4701. let mut batch = Batch::default();
  4702. #[cfg(feature = "diagnostics")]
  4703. let split = Split::begin();
  4704. // The time a settle of flights takes inside this preparing: the
  4705. // wait for the card and the copy-back have their own places on the
  4706. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4707. let mut settled = std::time::Duration::ZERO;
  4708. // One write-watch asking for everything the submission refreshes
  4709. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4710. if crate::watch::once() {
  4711. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  4712. for list in runs {
  4713. for step in &list.deferred().copies {
  4714. if let Step::Refresh(shadow, address, len) = step
  4715. && shadow.asked_ahead()
  4716. {
  4717. let span = spans
  4718. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4719. .or_insert((*address, *address + *len));
  4720. *span = (span.0.min(*address), span.1.max(*address + *len));
  4721. }
  4722. }
  4723. }
  4724. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4725. #[cfg(feature = "diagnostics")]
  4726. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  4727. crate::watch::ask_once(&ranges);
  4728. #[cfg(feature = "diagnostics")]
  4729. split.part(0);
  4730. // Behind flights: the title wrote memory that a flight's shaders
  4731. // may write too, and this submission refreshes it. The flights
  4732. // are settled, and the asking made again: the copy-back wrote
  4733. // title memory, which other copies of it must see.
  4734. if upcheck::on() {
  4735. upcheck::order(runs);
  4736. if behind {
  4737. upcheck::reads(runs);
  4738. }
  4739. }
  4740. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  4741. if !stale.is_empty() {
  4742. let settling = std::time::Instant::now();
  4743. self.settle_stale(&mut submitted, runs, stale, &ranges);
  4744. settled += settling.elapsed();
  4745. }
  4746. } else if behind && !stale_under_flights(runs).is_empty() {
  4747. let settling = std::time::Instant::now();
  4748. self.settle(&mut submitted, WHY_STALE);
  4749. settled += settling.elapsed();
  4750. }
  4751. #[cfg(feature = "diagnostics")]
  4752. split.part(1);
  4753. // What flights in the air may write.
  4754. let air = line().written.clone();
  4755. for list in runs {
  4756. list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4757. firsts.push(lists.len());
  4758. if let Some(prelude) = list.prelude() {
  4759. lists.push(Some(prelude));
  4760. }
  4761. lists.push(list.list.cast().ok());
  4762. }
  4763. batch.flush();
  4764. crate::watch::ask_once_end();
  4765. #[cfg(feature = "diagnostics")]
  4766. split.part(2);
  4767. // The snapshots of the ranges shaders may write, if they were left
  4768. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4769. // lists have not gone to the card.
  4770. {
  4771. #[cfg(feature = "diagnostics")]
  4772. let snapshots = std::time::Instant::now();
  4773. crate::shadow::take_snapshots();
  4774. #[cfg(feature = "diagnostics")]
  4775. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4776. }
  4777. #[cfg(feature = "diagnostics")]
  4778. split.part(3);
  4779. // Copies in the card's memory: what changed on their CPU side goes
  4780. // up ahead of the lists, and a compare of what the shaders may
  4781. // write follows them in the same submission.
  4782. let flown = late && relay();
  4783. if flown && self.card_results_low() {
  4784. let settling = std::time::Instant::now();
  4785. self.settle(&mut submitted, WHY_MOST);
  4786. settled += settling.elapsed();
  4787. }
  4788. // What shaders may write through views they pick: last, so that no
  4789. // refresh of this submission leaves it alone.
  4790. let picked = crate::picked::declare(runs);
  4791. for (shadow, at, len) in &picked.written {
  4792. shadow.writing(*at, *len);
  4793. }
  4794. let card = self.card_before(runs, &picked, flown);
  4795. // The sends are taken: from here on the references hold what the
  4796. // copies in the lists put.
  4797. for (shadow, at, bytes) in batch.placed.drain(..) {
  4798. shadow.placed_copy(at, &bytes);
  4799. }
  4800. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4801. lists.push(Some(check));
  4802. }
  4803. #[cfg(feature = "diagnostics")]
  4804. split.part(4);
  4805. let prepared = std::time::Instant::now();
  4806. if late {
  4807. *submitted += 1;
  4808. #[cfg(feature = "diagnostics")]
  4809. if let Some([front, behind]) = self.span_lists() {
  4810. lists.insert(0, Some(front));
  4811. lists.push(Some(behind));
  4812. }
  4813. // SAFETY: closed lists; the fence is ours.
  4814. let signalled = unsafe {
  4815. self.queue.ExecuteCommandLists(&lists);
  4816. self.queue.Signal(&self.fence, *submitted)
  4817. };
  4818. awake::sent(&self.device);
  4819. self.card_sent();
  4820. if let Err(e) = signalled {
  4821. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4822. }
  4823. #[cfg(feature = "diagnostics")]
  4824. split.part(5);
  4825. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4826. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4827. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4828. submitting(0, 0);
  4829. #[cfg(feature = "diagnostics")]
  4830. crate::copystat::submission_ends(lock);
  4831. let sent = Sent {
  4832. number: this_submission,
  4833. card,
  4834. back,
  4835. own,
  4836. writes,
  4837. };
  4838. working(was_working);
  4839. return Some((submitted, sent));
  4840. }
  4841. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4842. #[cfg(feature = "diagnostics")]
  4843. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4844. firsts
  4845. .iter()
  4846. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4847. .map(|(&a, &b)| &lists[a..b])
  4848. .collect()
  4849. } else {
  4850. vec![&lists[..]]
  4851. };
  4852. #[cfg(not(feature = "diagnostics"))]
  4853. let groups = [&lists[..]];
  4854. submitting(2, runs.len());
  4855. for (i, group) in groups.iter().enumerate() {
  4856. *submitted += 1;
  4857. let started = std::time::Instant::now();
  4858. // SAFETY: closed lists; the fence and event are ours.
  4859. unsafe {
  4860. self.queue.ExecuteCommandLists(group);
  4861. self.card_sent();
  4862. let waited = self
  4863. .queue
  4864. .Signal(&self.fence, *submitted)
  4865. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4866. match waited {
  4867. Ok(()) => {
  4868. working(false);
  4869. WaitForSingleObject(self.event, INFINITE);
  4870. stood(started);
  4871. working(true);
  4872. }
  4873. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4874. }
  4875. }
  4876. // With timing on each group is one of `runs` (and the compare
  4877. // of copies in the card's memory, with the last): every
  4878. // command's time on the card goes to the sums by pipeline.
  4879. #[cfg(feature = "diagnostics")]
  4880. if timing() {
  4881. // SAFETY: a plain query.
  4882. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4883. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4884. crate::copystat::command_took(&op, ms);
  4885. }
  4886. }
  4887. // A submission of one list was never named here (`groups.len()
  4888. // > 1` was the test): the two 50 ms lists of the gameplay
  4889. // frame, each a submission of its own, printed nothing.
  4890. #[cfg(feature = "diagnostics")]
  4891. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4892. // SAFETY: a plain query.
  4893. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4894. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4895. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4896. for (ms, op) in runs[i].slowest(frequency, 6) {
  4897. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4898. }
  4899. }
  4900. let _ = (i, started);
  4901. }
  4902. let _ = &firsts;
  4903. FINISHED.store(this_submission, Ordering::Release);
  4904. bury(this_submission);
  4905. let gpu = prepared.elapsed();
  4906. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4907. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4908. #[cfg(feature = "diagnostics")]
  4909. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4910. let pipelines: std::collections::BTreeSet<String> = runs
  4911. .iter()
  4912. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4913. .collect();
  4914. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  4915. text.chars().take(1200).collect()
  4916. });
  4917. // The host resets a device whose submission runs for about 2 s.
  4918. if gpu > std::time::Duration::from_millis(250) {
  4919. let pipelines: std::collections::BTreeSet<String> = runs
  4920. .iter()
  4921. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4922. .collect();
  4923. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  4924. }
  4925. // SAFETY: a plain query.
  4926. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4927. fail(format_args!(
  4928. "host GPU device removed after a submission of {} lists{}{}",
  4929. runs.len(),
  4930. self.removal_data(runs),
  4931. last_notes(runs)
  4932. ));
  4933. }
  4934. submitting(3, runs.len());
  4935. // What shaders wrote goes back before the bottom-of-pipe writes,
  4936. // which tell the title the GPU is done; each range once per
  4937. // submission, however many dispatches declared it (the world's
  4938. // passes declare the same big ranges dozens of times).
  4939. let copying = std::time::Instant::now();
  4940. // For copies in the card's memory the compare has run there: the
  4941. // pieces that differ are fetched and merged.
  4942. if let Some(card) = &card {
  4943. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  4944. }
  4945. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4946. hand_back(&back);
  4947. if let Some(card) = card {
  4948. self.card_done(card);
  4949. }
  4950. #[cfg(feature = "diagnostics")]
  4951. if !back.is_empty() {
  4952. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  4953. }
  4954. // Nothing of this submission goes back to the title: no range of
  4955. // shader writes, no value written when it is done. The wait for
  4956. // such a one is only for order and for what the card still holds.
  4957. #[cfg(feature = "diagnostics")]
  4958. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  4959. use crate::copystat::{C, add};
  4960. add(C::NothingBack, 1);
  4961. add(C::NothingBackUs, gpu.as_micros() as u64);
  4962. }
  4963. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4964. for list in runs {
  4965. // Read backs first: a value written at the bottom of the pipe
  4966. // may be what tells the title that they are there.
  4967. read_backs(list);
  4968. for &(at, what, bytes) in &list.deferred().writes {
  4969. what.write(at as *mut u8, bytes);
  4970. }
  4971. }
  4972. self.log_messages();
  4973. submitting(0, 0);
  4974. #[cfg(feature = "diagnostics")]
  4975. crate::copystat::submission_ends(lock);
  4976. // With the relay: nothing is in the air now, so no fetch still to
  4977. // be merged is older than the sends to card copies so far, and
  4978. // their notes can go.
  4979. if relay() {
  4980. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  4981. }
  4982. working(was_working);
  4983. None
  4984. }
  4985. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  4986. /// it lies in (by the names we give them) or the title memory copy just
  4987. /// below it; for each list that did not finish, the command it stopped
  4988. /// at and what the draws and dispatches in flight there run (or, in
  4989. /// lists that never started, the pipelines they bind).
  4990. fn removal_data(&self, runs: &[&HostList]) -> String {
  4991. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  4992. return String::new();
  4993. };
  4994. let mut text = String::new();
  4995. let mut fault_va = None;
  4996. // SAFETY: the outputs are the runtime's, valid while the device
  4997. // lives; nodes are walked as linked, histories have their counts.
  4998. unsafe {
  4999. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  5000. && fault.PageFaultVA != 0
  5001. {
  5002. let va = fault.PageFaultVA;
  5003. fault_va = Some(va);
  5004. text.push_str(&format!("; page fault at {va:#x}"));
  5005. for (what, head) in [
  5006. ("inside", fault.pHeadExistingAllocationNode),
  5007. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  5008. ] {
  5009. let mut names = Vec::new();
  5010. let mut node = head;
  5011. while let Some(n) = node.as_ref()
  5012. && names.len() < 8
  5013. {
  5014. let name = if n.ObjectNameW.is_null() {
  5015. "unnamed".to_owned()
  5016. } else {
  5017. n.ObjectNameW.to_string().unwrap_or_default()
  5018. };
  5019. names.push(format!("{name} (type {})", n.AllocationType.0));
  5020. node = n.pNext;
  5021. }
  5022. if !names.is_empty() {
  5023. text.push_str(&format!("; {what} {names:?}"));
  5024. }
  5025. }
  5026. text.push_str(&crate::shadow::near(va));
  5027. text.push_str(&crate::descriptor::host::near_heaps(va));
  5028. }
  5029. // The plain output: the extended one (with marker texts) came
  5030. // back without stopped lists on this host.
  5031. if dred_faults() {
  5032. return text;
  5033. }
  5034. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  5035. Ok(crumbs) => crumbs,
  5036. Err(e) => {
  5037. text.push_str(&format!("; no breadcrumbs ({e})"));
  5038. return text;
  5039. }
  5040. };
  5041. // Every list's progress (done/count), in the runtime's order.
  5042. let mut progress = Vec::new();
  5043. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  5044. while let Some(p) = node.as_ref() {
  5045. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5046. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  5047. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  5048. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  5049. node = p.pNext;
  5050. }
  5051. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  5052. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  5053. while let Some(p) = plain.as_ref() {
  5054. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5055. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  5056. let history =
  5057. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  5058. text.push_str(&format!(
  5059. "; a list stopped at command {done} of {} (op {})",
  5060. p.BreadcrumbCount, history[done as usize].0
  5061. ));
  5062. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  5063. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  5064. let named = [
  5065. (!p.pCommandListDebugNameW.is_null()).then(|| p.pCommandListDebugNameW.to_string().unwrap_or_default()),
  5066. (!p.pCommandListDebugNameA.is_null()).then(|| {
  5067. std::ffi::CStr::from_ptr(p.pCommandListDebugNameA.cast()).to_string_lossy().into_owned()
  5068. }),
  5069. ]
  5070. .into_iter()
  5071. .flatten()
  5072. .next()
  5073. .unwrap_or_default();
  5074. text.push_str(&format!(" of \"{named}\""));
  5075. // Not one of the caller's: by the name.
  5076. #[cfg(feature = "diagnostics")]
  5077. let by_name = list_number(&named).and_then(|n| {
  5078. let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  5079. all.get(&n).map(|(notes, pipelines)| (notes.upgrade(), pipelines.upgrade()))
  5080. });
  5081. #[cfg(not(feature = "diagnostics"))]
  5082. #[allow(clippy::type_complexity)]
  5083. let by_name: Option<(Option<()>, Option<std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>>)> = None;
  5084. #[cfg(feature = "diagnostics")]
  5085. let noted = run.map(|r| r.notes.clone()).or_else(|| by_name.as_ref().and_then(|b| b.0.clone()));
  5086. let bound = run.map(|r| r.pipelines.clone()).or_else(|| by_name.as_ref().and_then(|b| b.1.clone()));
  5087. // The k-th marker command is the k-th note.
  5088. #[cfg(feature = "diagnostics")]
  5089. let markers: Vec<(u32, String)> = noted.map_or_else(Vec::new, |notes| {
  5090. let notes = notes.lock().unwrap_or_else(|e| e.into_inner());
  5091. history
  5092. .iter()
  5093. .enumerate()
  5094. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  5095. .zip(notes.iter())
  5096. .map(|((at, _), (note, range))| {
  5097. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  5098. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  5099. })
  5100. .collect()
  5101. });
  5102. #[cfg(not(feature = "diagnostics"))]
  5103. let markers: Vec<(u32, String)> = Vec::new();
  5104. #[cfg(not(feature = "diagnostics"))]
  5105. let _ = fault_va;
  5106. if done > 0 {
  5107. text.push_str(&in_flight(history, &markers, done as usize));
  5108. }
  5109. // (Without markers a list that stopped midway says what
  5110. // it may have been at only by what it binds.)
  5111. if (done == 0 || markers.is_empty())
  5112. && let Some(bound) = bound
  5113. {
  5114. let pipelines = bound.lock().unwrap_or_else(|e| e.into_inner());
  5115. text.push_str(&format!(", its pipelines {pipelines:?}"));
  5116. }
  5117. }
  5118. plain = p.pNext;
  5119. }
  5120. }
  5121. text
  5122. }
  5123. /// Moves the debug layer's messages into our log; returns the first
  5124. /// error among them.
  5125. pub(crate) fn log_messages(&self) -> Option<String> {
  5126. let Some(queue) = &self.messages else {
  5127. return None;
  5128. };
  5129. let mut first_error = None;
  5130. // SAFETY: each message is read into a buffer of the size the queue
  5131. // reports, then the queue is emptied.
  5132. unsafe {
  5133. for i in 0..queue.GetNumStoredMessages() {
  5134. let mut size = 0;
  5135. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  5136. continue;
  5137. }
  5138. let mut buffer = vec![0u64; size.div_ceil(8)];
  5139. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  5140. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  5141. let m = &*message;
  5142. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  5143. let text = String::from_utf8_lossy(text);
  5144. let text = text.trim_end_matches('\0');
  5145. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  5146. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  5147. first_error = Some(text.to_owned());
  5148. }
  5149. }
  5150. }
  5151. queue.ClearStoredMessages();
  5152. }
  5153. first_error
  5154. }
  5155. /// A host render target view of `resource`, valid until it is recorded.
  5156. pub(crate) fn rtv(
  5157. &self,
  5158. resource: Option<&ID3D12Resource>,
  5159. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  5160. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5161. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5162. // SAFETY: a slot of our heap and a live resource, or none with a
  5163. // description (a typed null view).
  5164. unsafe {
  5165. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  5166. handle.ptr += (slot * self.rtv_size) as usize;
  5167. self.device
  5168. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  5169. handle
  5170. }
  5171. }
  5172. /// A host depth view of `resource`, valid until it is recorded.
  5173. pub(crate) fn dsv(
  5174. &self,
  5175. resource: &ID3D12Resource,
  5176. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  5177. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5178. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5179. // SAFETY: a slot of our heap and a live resource.
  5180. unsafe {
  5181. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  5182. handle.ptr += (slot * self.dsv_size) as usize;
  5183. self.device
  5184. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  5185. handle
  5186. }
  5187. }
  5188. }
  5189. impl HostList {
  5190. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  5191. #[cfg(feature = "diagnostics")]
  5192. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  5193. if !timing() {
  5194. return None;
  5195. }
  5196. self.stamps
  5197. .get_or_init(|| {
  5198. let device = &host()?.device;
  5199. let mut heap: Option<ID3D12QueryHeap> = None;
  5200. let mut back: Option<ID3D12Resource> = None;
  5201. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  5202. let desc = D3D12_RESOURCE_DESC {
  5203. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5204. Width: u64::from(STAMPS) * 8,
  5205. Height: 1,
  5206. DepthOrArraySize: 1,
  5207. MipLevels: 1,
  5208. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  5209. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5210. ..Default::default()
  5211. };
  5212. // SAFETY: plain object creation.
  5213. unsafe {
  5214. device
  5215. .CreateQueryHeap(
  5216. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  5217. &mut heap,
  5218. )
  5219. .ok()?;
  5220. device
  5221. .CreateCommittedResource(
  5222. &readback,
  5223. D3D12_HEAP_FLAG_NONE,
  5224. &desc,
  5225. D3D12_RESOURCE_STATE_COPY_DEST,
  5226. None,
  5227. &mut back,
  5228. )
  5229. .ok()?;
  5230. }
  5231. Some((heap?, back?))
  5232. })
  5233. .as_ref()
  5234. }
  5235. /// The noted commands that took longest on the GPU, longest first, as
  5236. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  5237. #[cfg(feature = "diagnostics")]
  5238. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  5239. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  5240. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  5241. return Vec::new();
  5242. };
  5243. let mut data = std::ptr::null_mut();
  5244. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  5245. // SAFETY: a read-back buffer the finished list resolved into.
  5246. let stamps: Vec<u64> = unsafe {
  5247. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  5248. return Vec::new();
  5249. }
  5250. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  5251. back.Unmap(0, None);
  5252. s
  5253. };
  5254. let mut times: Vec<(f64, String)> = (0..count)
  5255. .map(|i| {
  5256. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5257. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5258. })
  5259. .collect();
  5260. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5261. times.truncate(n);
  5262. times
  5263. }
  5264. pub(crate) fn close(&self) {
  5265. self.twins_to_depth();
  5266. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5267. if let Some((scratch, _)) = scratch {
  5268. self.indirect_common(&scratch);
  5269. }
  5270. self.batches_common();
  5271. self.card_budget_out();
  5272. #[cfg(feature = "diagnostics")]
  5273. if let Some((heap, back)) = self.stamps() {
  5274. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5275. // SAFETY: an open list, our heap and read-back buffer.
  5276. unsafe {
  5277. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5278. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5279. }
  5280. }
  5281. // SAFETY: our list.
  5282. if let Err(e) = unsafe { self.list.Close() } {
  5283. fail(format_args!(
  5284. "a host command list did not close ({e}): a command recorded into it was invalid"
  5285. ));
  5286. }
  5287. }
  5288. /// Only after the list's last submission finished (every one is waited
  5289. /// for).
  5290. pub(crate) fn reset(&self) {
  5291. #[cfg(feature = "diagnostics")]
  5292. let started = std::time::Instant::now();
  5293. self._alive.used();
  5294. *self.deferred() = Deferred::default();
  5295. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5296. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5297. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5298. #[cfg(feature = "diagnostics")]
  5299. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5300. {
  5301. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5302. (scratch.current, scratch.used) = (0, 0);
  5303. // Every submission of the list has run: nothing reads its
  5304. // scratch memory any more, and the next list to ask takes it.
  5305. if scratch_pool() {
  5306. give_chunks(std::mem::take(&mut scratch.chunks));
  5307. }
  5308. }
  5309. // SAFETY: the list is not executing.
  5310. let reset = unsafe {
  5311. self.allocator
  5312. .Reset()
  5313. .and_then(|()| self.list.Reset(&self.allocator, None))
  5314. };
  5315. if let Err(e) = reset {
  5316. fail(format_args!("a host command list did not reset ({e})"));
  5317. }
  5318. #[cfg(feature = "diagnostics")]
  5319. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5320. }
  5321. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5322. /// list: the host texture and the state it leaves, if that is a change.
  5323. /// The list's first use of a texture records nothing: its prelude brings
  5324. /// the texture there at submission.
  5325. pub(crate) fn transition(
  5326. &self,
  5327. resource: crate::object::This,
  5328. wanted: u32,
  5329. ) -> Option<(&'static ID3D12Resource, u32)> {
  5330. let texture = crate::resource::host_resource(resource)?;
  5331. let copy = crate::resource::host_copy(resource)?;
  5332. let wanted = legal_state(texture, wanted);
  5333. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5334. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5335. std::collections::hash_map::Entry::Vacant(v) => {
  5336. v.insert((wanted, wanted, copy));
  5337. None
  5338. }
  5339. std::collections::hash_map::Entry::Occupied(mut o) => {
  5340. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5341. (before != wanted).then_some((texture, before))
  5342. }
  5343. }
  5344. }
  5345. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5346. /// as [`HostList::transition`] does a title resource's host copy, and
  5347. /// records the barrier: for textures that are not a title resource's
  5348. /// host copy (colour twins) and for the copies between the two.
  5349. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5350. let wanted = legal_state(&copy.texture, wanted);
  5351. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5352. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5353. std::collections::hash_map::Entry::Vacant(v) => {
  5354. v.insert((wanted, wanted, copy.clone()));
  5355. None
  5356. }
  5357. std::collections::hash_map::Entry::Occupied(mut o) => {
  5358. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5359. (before != wanted).then_some(before)
  5360. }
  5361. };
  5362. drop(states);
  5363. if let Some(before) = before {
  5364. let barrier = transition(
  5365. &copy.texture,
  5366. D3D12_RESOURCE_STATES(before as i32),
  5367. D3D12_RESOURCE_STATES(wanted as i32),
  5368. );
  5369. // SAFETY: an open list and a live texture.
  5370. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5371. }
  5372. }
  5373. /// A use of title texture `resource` about to be recorded, if it is a
  5374. /// depth texture with a colour twin (false if it is not): of the twin
  5375. /// (`colour`: unordered access) or of the depth texture (depth target,
  5376. /// clear, shader read, copy, resolve), writing it or only reading. The
  5377. /// side used is first brought up to date: by a copy recorded here if
  5378. /// this list wrote the other side since, by the list's prelude if the
  5379. /// list uses the side as it finds it. The twin is left in the
  5380. /// unordered access state; the caller moves the depth texture to the
  5381. /// state its use needs, as for any texture. A twin still ahead when the
  5382. /// list closes is copied then (`twins_to_depth`).
  5383. /// shortcut: every depth target bound for a draw counts as written
  5384. /// (also when the draw only tests), and every unordered access view a
  5385. /// shader names as written; views a shader picks from the heap by a
  5386. /// computed index are not seen here at all.
  5387. pub(crate) fn twin_use(
  5388. &self,
  5389. resource: crate::object::This,
  5390. colour: bool,
  5391. write: bool,
  5392. ) -> bool {
  5393. const UNORDERED_ACCESS: u32 = 0x8;
  5394. // Asked for every texture a draw reads: most have no twin.
  5395. let Some(twin) = crate::resource::twin(resource) else {
  5396. return false;
  5397. };
  5398. let Some(depth) = crate::resource::host_copy(resource) else {
  5399. return false;
  5400. };
  5401. let side = usize::from(colour);
  5402. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5403. let u = twins
  5404. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5405. .or_insert_with(|| TwinUse {
  5406. depth: depth.clone(),
  5407. twin: twin.clone(),
  5408. needs: [false; 2],
  5409. behind: [None; 2],
  5410. writing: false,
  5411. late: false,
  5412. });
  5413. let copy = match u.behind[side] {
  5414. Some(behind) => behind,
  5415. None => {
  5416. u.needs[side] = true;
  5417. false
  5418. }
  5419. };
  5420. u.behind[side] = Some(false);
  5421. match (write, colour) {
  5422. // Shaders write the twin when the draw or dispatch runs: what
  5423. // the same one reads of the depth texture is prepared before
  5424. // (`twins_written`).
  5425. (true, true) => u.writing = true,
  5426. (true, false) => u.behind[1] = Some(true),
  5427. (false, _) => {}
  5428. }
  5429. // shortcut: the depth plane's twin is not drawn into the plane
  5430. // here: the pass sets a pipeline and a target of ours, which a list
  5431. // still recording the title's commands cannot take. This use sees
  5432. // the plane as it was; the pass runs when the list closes
  5433. // (`twins_to_depth`). Counted.
  5434. if copy && !colour && twin.plane.is_some() {
  5435. u.late = true;
  5436. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5437. }
  5438. drop(twins);
  5439. if copy {
  5440. self.twin_copy(&depth, &twin, colour);
  5441. } else if colour {
  5442. self.settle(&twin.colour, UNORDERED_ACCESS);
  5443. }
  5444. // The depth plane's twin is written through unordered access too.
  5445. if colour && let Some(plane) = &twin.plane {
  5446. self.settle(plane, UNORDERED_ACCESS);
  5447. }
  5448. true
  5449. }
  5450. /// Records the pass that draws the twin of the depth plane of `depth`
  5451. /// into the plane, if `twin` has one, with the moves to the states the
  5452. /// pass needs; the twin is left in the unordered access state. Only
  5453. /// for a list that records nothing of the title's afterwards
  5454. /// (`record_plane_pass`).
  5455. fn pass_plane(
  5456. &self,
  5457. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5458. twin: &crate::resource::Twin,
  5459. ) {
  5460. const UNORDERED_ACCESS: u32 = 0x8;
  5461. const DEPTH_WRITE: u32 = 0x10;
  5462. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5463. let Some(plane) = &twin.plane else { return };
  5464. self.settle(depth, DEPTH_WRITE);
  5465. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5466. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5467. self.settle(plane, UNORDERED_ACCESS);
  5468. }
  5469. /// Records the copy of a depth texture into its colour twin (`colour`)
  5470. /// or of the twin into the depth texture, with the moves to the copy
  5471. /// states. The twin is left in the unordered access state.
  5472. fn twin_copy(
  5473. &self,
  5474. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5475. twin: &crate::resource::Twin,
  5476. colour: bool,
  5477. ) {
  5478. const UNORDERED_ACCESS: u32 = 0x8;
  5479. const COPY_DEST: u32 = 0x400;
  5480. const COPY_SOURCE: u32 = 0x800;
  5481. let (from, to) = if colour {
  5482. (depth, &twin.colour)
  5483. } else {
  5484. (&twin.colour, depth)
  5485. };
  5486. self.settle(from, COPY_SOURCE);
  5487. self.settle(to, COPY_DEST);
  5488. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5489. self.settle(&twin.colour, UNORDERED_ACCESS);
  5490. }
  5491. /// Before the list closes: the depth textures whose twins it wrote last
  5492. /// are given what was written, and left readable by shaders. Shaders
  5493. /// that pick a view from the heap by a computed index are not seen by
  5494. /// `twin_use` and read the depth texture in lists that never name it
  5495. /// (in a captured frame of the title no table names a shadow
  5496. /// map for reading but the pass that fills the next one).
  5497. fn twins_to_depth(&self) {
  5498. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5499. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5500. let written: Vec<_> = twins
  5501. .values_mut()
  5502. .filter(|u| u.behind[0] == Some(true) || u.late)
  5503. .map(|u| {
  5504. // Not copied again if the list copied since the last write
  5505. // and only the depth plane's pass is left.
  5506. let copy = u.behind[0] == Some(true);
  5507. u.behind[0] = Some(false);
  5508. u.late = false;
  5509. (u.depth.clone(), u.twin.clone(), copy)
  5510. })
  5511. .collect();
  5512. drop(twins);
  5513. for (depth, twin, copy) in &written {
  5514. if *copy {
  5515. self.twin_copy(depth, twin, false);
  5516. }
  5517. // Nothing of the title's is recorded after this: the pass may
  5518. // leave its own pipeline and target set.
  5519. self.pass_plane(depth, twin);
  5520. self.settle(depth, SHADER_RESOURCE);
  5521. }
  5522. }
  5523. /// The draw or dispatch just prepared is recorded: the twins it writes
  5524. /// now hold what their depth textures lack.
  5525. pub(crate) fn twins_written(&self) {
  5526. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5527. for u in twins.values_mut().filter(|u| u.writing) {
  5528. u.writing = false;
  5529. u.behind[0] = Some(true);
  5530. }
  5531. }
  5532. /// At submission: the list that moves each texture this list uses from
  5533. /// its real state to the one the list starts with; the textures' real
  5534. /// states become those the list ends with. For depth textures with a
  5535. /// colour twin it first copies the side the list uses as it finds it
  5536. /// from the other, if a list submitted earlier left it behind.
  5537. fn prelude(&self) -> Option<ID3D12CommandList> {
  5538. const COPY_DEST: u32 = 0x400;
  5539. const COPY_SOURCE: u32 = 0x800;
  5540. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5541. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5542. // The copies (depth texture, twin, whether into the twin); the
  5543. // sides are then as this list leaves them.
  5544. let mut syncs = Vec::new();
  5545. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5546. for u in twins.values() {
  5547. let real = u.twin.behind.load(Ordering::Relaxed);
  5548. let mut behind = [real & 1 != 0, real & 2 != 0];
  5549. for side in [0, 1] {
  5550. if u.needs[side] && behind[side] {
  5551. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5552. behind = [false; 2];
  5553. }
  5554. }
  5555. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5556. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5557. u.twin.behind.store(left, Ordering::Relaxed);
  5558. }
  5559. drop(twins);
  5560. // A copy runs with its textures in the copy states: each moves
  5561. // there from its real state, and from there to the state the list
  5562. // starts with (back to its real state if the list does not use it).
  5563. let mut to_copy = Vec::new();
  5564. let mut barriers = Vec::new();
  5565. let mut copying = std::collections::HashMap::new();
  5566. for (depth, twin, colour) in &syncs {
  5567. let (from, to) = if *colour {
  5568. (depth, &twin.colour)
  5569. } else {
  5570. (&twin.colour, depth)
  5571. };
  5572. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  5573. let key = std::sync::Arc::as_ptr(texture) as usize;
  5574. let real = texture.state.load(Ordering::Relaxed);
  5575. copying.insert(key, state);
  5576. if real != state {
  5577. to_copy.push(transition(
  5578. &texture.texture,
  5579. host_state(real),
  5580. host_state(state),
  5581. ));
  5582. if !states.contains_key(&key) {
  5583. barriers.push(transition(
  5584. &texture.texture,
  5585. host_state(state),
  5586. host_state(real),
  5587. ));
  5588. }
  5589. }
  5590. }
  5591. }
  5592. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5593. let real = copy.state.swap(*last, Ordering::Relaxed);
  5594. let real = copying.get(key).copied().unwrap_or(real);
  5595. (real != *first)
  5596. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5597. }));
  5598. if barriers.is_empty() && syncs.is_empty() {
  5599. return None;
  5600. }
  5601. let Some((allocator, list)) = self
  5602. .prelude
  5603. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5604. .as_ref()
  5605. else {
  5606. fail(format_args!("no host list for a state prelude"));
  5607. };
  5608. // SAFETY: the prelude is not executing (every submission is waited
  5609. // for); the textures are live.
  5610. let recorded = unsafe {
  5611. allocator.Reset().and_then(|()| {
  5612. list.Reset(allocator, None)?;
  5613. if !to_copy.is_empty() {
  5614. list.ResourceBarrier(&to_copy);
  5615. }
  5616. for (depth, twin, colour) in &syncs {
  5617. record_twin_copy(list, &depth.texture, twin, *colour);
  5618. }
  5619. if !barriers.is_empty() {
  5620. list.ResourceBarrier(&barriers);
  5621. }
  5622. list.Close()
  5623. })
  5624. };
  5625. if let Err(e) = recorded {
  5626. fail(format_args!("a host state prelude did not record ({e})"));
  5627. }
  5628. list.cast().ok()
  5629. }
  5630. /// Notes what the command about to be recorded does, as a marker
  5631. /// command whose text the list keeps (diagnostics, with device-removed
  5632. /// data on): the report pairs the breadcrumbs' marker commands with the
  5633. /// texts in order and names the commands a fault stopped among.
  5634. #[cfg(feature = "diagnostics")]
  5635. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5636. self.note(what, None);
  5637. }
  5638. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5639. /// `(address, bytes)`: the report places the faulting address in it.
  5640. #[cfg(feature = "diagnostics")]
  5641. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5642. self.note(what, Some(range));
  5643. }
  5644. #[cfg(feature = "diagnostics")]
  5645. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5646. if !dred_on() {
  5647. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5648. return;
  5649. }
  5650. {
  5651. let started = std::time::Instant::now();
  5652. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5653. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5654. // SAFETY: an open list and our query heap.
  5655. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5656. }
  5657. let what = what();
  5658. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5659. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5660. const UNICODE: u32 = 0;
  5661. // SAFETY: an open list; the marker is copied when recorded.
  5662. unsafe {
  5663. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5664. };
  5665. self.notes
  5666. .lock()
  5667. .unwrap_or_else(|e| e.into_inner())
  5668. .push((what, range));
  5669. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5670. }
  5671. }
  5672. /// Whether nothing recorded since the list was opened does any work:
  5673. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5674. /// upload or resolve (they defer a step or move a texture's state), no
  5675. /// bottom-of-pipe write. State set on the list does not count.
  5676. pub(crate) fn untouched(&self) -> bool {
  5677. {
  5678. let deferred = self.deferred();
  5679. if !(deferred.copies.is_empty()
  5680. && deferred.uploads.is_empty()
  5681. && deferred.kept.is_empty()
  5682. && deferred.textures.is_empty()
  5683. && deferred.writes.is_empty()
  5684. && deferred.backs.is_empty())
  5685. {
  5686. return false;
  5687. }
  5688. }
  5689. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5690. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5691. }
  5692. /// Notes a pipeline the list binds.
  5693. pub(crate) fn used_pipeline(&self, name: &str) {
  5694. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5695. if !pipelines.contains(name) {
  5696. pipelines.insert(name.to_owned());
  5697. }
  5698. }
  5699. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5700. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5701. }
  5702. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5703. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5704. let mut deferred = self.deferred();
  5705. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5706. // A copy that goes on where the one recorded just before it ended,
  5707. // source and destination both: with `join_copies` the two are one
  5708. // step.
  5709. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5710. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5711. {
  5712. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5713. if join_copies() {
  5714. *n += len;
  5715. return;
  5716. }
  5717. }
  5718. deferred
  5719. .copies
  5720. .push(Step::Copy(dst as usize, src as usize, len));
  5721. deferred.refreshed.clear();
  5722. }
  5723. /// Copies `len` bytes of title memory at `src` into the list's upload
  5724. /// memory at `dst` when the list is submitted.
  5725. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5726. self.deferred()
  5727. .copies
  5728. .push(Step::Fill(dst as usize, src as usize, len, None));
  5729. }
  5730. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5731. /// title heap's address, and the slot) shows.
  5732. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5733. self.deferred()
  5734. .copies
  5735. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  5736. }
  5737. /// As [`HostList::defer_fill`], for the beginning of a buffer
  5738. /// [`HostList::upload`] made.
  5739. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  5740. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  5741. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  5742. }
  5743. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5744. /// when the list is submitted (once per range until a title copy
  5745. /// intervenes), keeping the copy alive until the list is reset.
  5746. pub(crate) fn defer_refresh(
  5747. &self,
  5748. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5749. address: usize,
  5750. len: usize,
  5751. ) {
  5752. let mut deferred = self.deferred();
  5753. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5754. if deferred.refreshed.insert(key) {
  5755. deferred
  5756. .copies
  5757. .push(Step::Refresh(shadow.clone(), address, len));
  5758. }
  5759. }
  5760. /// Shaders of the list write `[address, address + len)` of a buffer's
  5761. /// host copy: copied back into title memory once the list has run.
  5762. pub(crate) fn defer_gpu_write(
  5763. &self,
  5764. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5765. address: usize,
  5766. len: usize,
  5767. ) {
  5768. self.deferred()
  5769. .copies
  5770. .push(Step::GpuWrite(shadow.clone(), address, len));
  5771. }
  5772. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5773. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5774. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5775. /// the list is reset.
  5776. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5777. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5778. }
  5779. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5780. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5781. self.deferred().writes.push((dst as usize, what, bytes));
  5782. }
  5783. /// A mapped upload buffer of `size` bytes, alive until the list is
  5784. /// reset.
  5785. ///
  5786. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5787. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5788. // With [`card_steps`] the card may be the one that fills it.
  5789. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  5790. name(&buffer, || format!("list upload {size:#x}"));
  5791. self.deferred().hold_upload(buffer.clone(), size);
  5792. Some((buffer, data))
  5793. }
  5794. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5795. /// reset: the host GPU address and the CPU pointer.
  5796. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5797. let (buffer, at, data) = self.scratch_at(len)?;
  5798. // SAFETY: a live buffer.
  5799. Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data))
  5800. }
  5801. /// [`HostList::scratch`]: the buffer, the offset in it and the CPU
  5802. /// pointer.
  5803. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  5804. let host = host()?;
  5805. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5806. let len = len.max(1).next_multiple_of(256);
  5807. if len > SCRATCH_CHUNK {
  5808. let (buffer, data) = host.upload_buffer(len)?;
  5809. name(&buffer, || format!("list scratch {len:#x}"));
  5810. self.deferred().hold_upload(buffer.clone(), len);
  5811. return Some((buffer, 0, data));
  5812. }
  5813. // The chunk in use while `len` fits in what is left of it, else the
  5814. // next one (a list's first chunk may be a small one).
  5815. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5816. (s.current, s.used) = (s.current + 1, 0);
  5817. }
  5818. if s.current == s.chunks.len() {
  5819. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  5820. SCRATCH_FIRST
  5821. } else {
  5822. SCRATCH_CHUNK
  5823. };
  5824. let chunk = take_chunk(host, size)?;
  5825. s.chunks.push((chunk, size));
  5826. s.used = 0;
  5827. }
  5828. let (data, buffer) = (s.chunks[s.current].0.data, s.chunks[s.current].0.buffer.clone());
  5829. let at = s.used;
  5830. s.used += len;
  5831. Some((buffer, at, (data + at as usize) as *mut u8))
  5832. }
  5833. /// The bytes of scratch chunks the list holds now (after a reset:
  5834. /// none while lists share their chunks).
  5835. pub(crate) fn scratch_kept(&self) -> u64 {
  5836. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5837. scratch.chunks.iter().map(|c| c.1).sum()
  5838. }
  5839. /// The host address of the list's indirect-work budget, zeroed at each
  5840. /// submission of the list from the first use after a reset on.
  5841. pub(crate) fn budget(&self) -> Option<u64> {
  5842. let (buffer, data) = self
  5843. .budget
  5844. .get_or_init(|| {
  5845. let (b, d) = host()?.shared_buffer(256)?;
  5846. Some((b, d as usize))
  5847. })
  5848. .as_ref()?;
  5849. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5850. let mut deferred = self.deferred();
  5851. if !deferred.budget_zeroed {
  5852. deferred.budget_zeroed = true;
  5853. let at = *data;
  5854. // SAFETY: the list's own mapped words, written before it runs.
  5855. // The words after the budget hold what the clamp noted about the
  5856. // list's last run (mesh dispatches: the largest group count
  5857. // asked for, the groups asked in all; with the card's copy, as
  5858. // the list's end copied them here): taken, then zeroed.
  5859. let notes = Box::new(move || unsafe {
  5860. let words = at as *mut u32;
  5861. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  5862. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  5863. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  5864. for k in 0..3 {
  5865. words.add(k).write_volatile(0);
  5866. }
  5867. });
  5868. deferred.copies.push(Step::Host(notes, (0, 0)));
  5869. drop(deferred);
  5870. if let Some(card) = card {
  5871. self.zero_card_budget(card);
  5872. }
  5873. }
  5874. // SAFETY: a live buffer.
  5875. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  5876. }
  5877. /// The budget's words in the card's own memory ([`card_budget`]), if
  5878. /// the list can zero them itself (`WriteBufferImmediate`).
  5879. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  5880. if !card_budget() {
  5881. return None;
  5882. }
  5883. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  5884. let buffer = host()?.uav_buffer(256)?;
  5885. name(&buffer, || "indirect budget".to_owned());
  5886. Some(buffer)
  5887. }
  5888. /// Records, before the list's first clamp, the zeroing of the card's
  5889. /// copy of the budget: common, written as a copy, then left for
  5890. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  5891. fn zero_card_budget(&self, card: &ID3D12Resource) {
  5892. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  5893. return;
  5894. };
  5895. // SAFETY: a live buffer.
  5896. let at = unsafe { card.GetGPUVirtualAddress() };
  5897. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  5898. Dest: at + offset,
  5899. Value: 0,
  5900. });
  5901. // SAFETY: an open list; the buffer is the list's own and in the
  5902. // common state at the start of every recording.
  5903. unsafe {
  5904. self.list.ResourceBarrier(&[transition(
  5905. card,
  5906. D3D12_RESOURCE_STATE_COMMON,
  5907. D3D12_RESOURCE_STATE_COPY_DEST,
  5908. )]);
  5909. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  5910. self.list.ResourceBarrier(&[transition(
  5911. card,
  5912. D3D12_RESOURCE_STATE_COPY_DEST,
  5913. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5914. )]);
  5915. }
  5916. }
  5917. /// Before the list closes, if this recording charged the card's copy
  5918. /// of the budget: its notes on mesh records go to the mapped words
  5919. /// (read at the next submission), and it goes back to common.
  5920. fn card_budget_out(&self) {
  5921. if !self.deferred().budget_zeroed {
  5922. return;
  5923. }
  5924. let (Some(Some(card)), Some(Some((mapped, _)))) =
  5925. (self.card_budget.get(), self.budget.get())
  5926. else {
  5927. return;
  5928. };
  5929. // SAFETY: an open list; both buffers are the list's own. The
  5930. // mapped one is promoted from common to the copy destination.
  5931. unsafe {
  5932. self.list.ResourceBarrier(&[transition(
  5933. card,
  5934. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5935. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5936. )]);
  5937. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  5938. self.list.ResourceBarrier(&[transition(
  5939. card,
  5940. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5941. D3D12_RESOURCE_STATE_COMMON,
  5942. )]);
  5943. }
  5944. }
  5945. /// A device-local unordered-access buffer of at least `size` bytes for
  5946. /// clamped indirect arguments, reused across executions and resets of the
  5947. /// list. Smaller buffers replaced mid-list stay alive until
  5948. /// [`HostList::reset`].
  5949. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  5950. let needed = size.max(64 << 10);
  5951. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  5952. if let Some((buffer, cap)) = &*slot
  5953. && *cap >= needed
  5954. {
  5955. return Some(buffer.clone());
  5956. }
  5957. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  5958. let alloc = prev
  5959. .saturating_mul(2)
  5960. .max(needed)
  5961. .next_multiple_of(64 << 10);
  5962. let buffer = host()?.uav_buffer(alloc)?;
  5963. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  5964. let old = slot.replace((buffer.clone(), alloc));
  5965. drop(slot);
  5966. if let Some((old_buf, _)) = old {
  5967. // It ends the list common, as every scratch buffer does.
  5968. self.indirect_common(&old_buf);
  5969. self.keep(&old_buf);
  5970. }
  5971. Some(buffer)
  5972. }
  5973. /// Where the next batch of clamped records goes: a device-local buffer
  5974. /// the list keeps from recording to recording, the batch's place in it
  5975. /// and the state the buffer is in. Every batch of a recording has a place
  5976. /// of its own: the executions before it may still read theirs.
  5977. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  5978. use crate::indirect::batch::{JOBS, SLOT};
  5979. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5980. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  5981. if buffer == args.0.len() {
  5982. let size = u64::from(BATCHES * JOBS * SLOT);
  5983. let made = host()?.uav_buffer(size)?;
  5984. name(&made, || format!("indirect batches {size:#x}"));
  5985. args.0.push(made);
  5986. }
  5987. args.1 += 1;
  5988. // (Its first batch finds it as the recording before left it:
  5989. // `batches_common`.)
  5990. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  5991. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  5992. }
  5993. /// Before the list closes: the scratch buffers of the batched clamps go
  5994. /// back to the common state, where the next recording expects them.
  5995. fn batches_common(&self) {
  5996. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5997. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  5998. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  5999. .iter()
  6000. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  6001. .collect();
  6002. if !barriers.is_empty() {
  6003. // SAFETY: an open list and live buffers this recording left in
  6004. // `INDIRECT_ARGUMENT`.
  6005. unsafe { self.list.ResourceBarrier(&barriers) };
  6006. }
  6007. }
  6008. /// Moves `scratch` back to the common state if a clamp left it readable
  6009. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  6010. /// list's first clamp expects it. Done before the list closes and before
  6011. /// a bigger scratch buffer replaces it: one barrier per list (where
  6012. /// there was one per indirect execution), and the list ends as it
  6013. /// begins however it is submitted.
  6014. fn indirect_common(&self, scratch: &ID3D12Resource) {
  6015. {
  6016. let mut deferred = self.deferred();
  6017. if deferred.indirect_readable != scratch.as_raw() as usize {
  6018. return;
  6019. }
  6020. deferred.indirect_readable = 0;
  6021. }
  6022. let barrier = transition(
  6023. scratch,
  6024. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  6025. D3D12_RESOURCE_STATE_COMMON,
  6026. );
  6027. // SAFETY: an open list and a live buffer this recording left in
  6028. // `INDIRECT_ARGUMENT`.
  6029. unsafe { self.list.ResourceBarrier(&[barrier]) };
  6030. }
  6031. /// The state the list's indirect scratch buffer `scratch` is in at this
  6032. /// point of the recording: indirect arguments if a clamp in this
  6033. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  6034. /// common: the state a buffer is made in, and the one a recording
  6035. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  6036. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  6037. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  6038. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  6039. } else {
  6040. D3D12_RESOURCE_STATE_COMMON
  6041. }
  6042. }
  6043. /// A clamp recorded in this list left `scratch` readable as indirect
  6044. /// arguments. It stays so for every execution that reads it, until the
  6045. /// next clamp moves it back to unordered access.
  6046. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  6047. self.deferred().indirect_readable = scratch.as_raw() as usize;
  6048. }
  6049. /// Keeps `object` alive until the list is reset.
  6050. pub(crate) fn keep(&self, object: &impl Interface) {
  6051. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  6052. self.deferred().kept.push(object);
  6053. }
  6054. }
  6055. /// Whether this is the first time since the reset that the list asks
  6056. /// about `key` (a texture to bring up to date).
  6057. pub(crate) fn first_use(&self, key: usize) -> bool {
  6058. self.deferred().textures.insert(key)
  6059. }
  6060. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  6061. /// reset.
  6062. pub(crate) fn used(&self, key: usize) -> bool {
  6063. self.deferred().textures.contains(&key)
  6064. }
  6065. /// Runs `work` when the list is submitted, in order with its copies.
  6066. /// `work` may write title memory (refreshes after it copy again).
  6067. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  6068. self.deferred().copies.push(Step::Run(Box::new(work)));
  6069. self.deferred().refreshed.clear();
  6070. }
  6071. /// As [`HostList::defer`], for work that writes only host memory.
  6072. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  6073. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  6074. }
  6075. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  6076. /// memory at `from`.
  6077. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  6078. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  6079. }
  6080. /// Brings a texture's staging buffer up to date when the list is
  6081. /// submitted, keeping it alive until the list is reset.
  6082. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  6083. self.deferred().copies.push(Step::Texture(staging));
  6084. }
  6085. /// Runs the list's submission-time steps; refreshes go into `batch`
  6086. /// (the title's big buffers, a 174 MB one among them, are read by most
  6087. /// lists of a submission, through many ranges). Copies and fills that
  6088. /// `taken` names (by their place) are left out: they are done on the
  6089. /// card ([`card_steps`]).
  6090. fn run_deferred(&self, batch: &mut Batch, air: &[(usize, usize)], taken: impl Fn(usize) -> bool) {
  6091. #[cfg(feature = "diagnostics")]
  6092. use crate::copystat::{C, add};
  6093. // The time and the bytes of the copies and fills, some 13,000 a
  6094. // frame between 20,000 refreshes: summed here and added once.
  6095. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  6096. #[cfg(feature = "diagnostics")]
  6097. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  6098. for (i, step) in self.deferred().copies.iter().enumerate() {
  6099. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  6100. continue;
  6101. }
  6102. let (started, copied) = match step {
  6103. &Step::Copy(dst, src, len) => {
  6104. let started = std::time::Instant::now();
  6105. #[cfg(feature = "diagnostics")]
  6106. {
  6107. copies += 1;
  6108. }
  6109. batch.title_written();
  6110. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  6111. // With the submission's one asking: the journal learns it.
  6112. crate::watch::wrote(dst, len);
  6113. // What the card holds there may be another value although
  6114. // ours did not change.
  6115. if send::own() {
  6116. crate::shadow::send_copied(dst, len);
  6117. }
  6118. (started, len)
  6119. }
  6120. &Step::Fill(dst, src, len, _) => {
  6121. let started = std::time::Instant::now();
  6122. #[cfg(feature = "diagnostics")]
  6123. {
  6124. copies += 1;
  6125. }
  6126. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6127. (started, len)
  6128. }
  6129. Step::Placed(p) => {
  6130. let started = std::time::Instant::now();
  6131. let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len);
  6132. if free {
  6133. batch.title_written();
  6134. }
  6135. if let Some(bytes) = p.prepare(free) {
  6136. batch.placed.push((p.shadow.clone(), p.dst, bytes));
  6137. }
  6138. (started, p.len)
  6139. }
  6140. Step::Refresh(shadow, address, len) => {
  6141. #[cfg(feature = "diagnostics")]
  6142. {
  6143. refreshes += 1;
  6144. refreshed += *len as u64;
  6145. }
  6146. batch.add(shadow, *address, *len);
  6147. continue;
  6148. }
  6149. Step::Run(work) | Step::Host(work, _) => {
  6150. #[cfg(feature = "diagnostics")]
  6151. let started = std::time::Instant::now();
  6152. if matches!(step, Step::Run(_)) {
  6153. batch.title_written();
  6154. }
  6155. work();
  6156. // It wrote title memory, where is not known here: the
  6157. // submission's one asking ends, later refreshes ask anew.
  6158. if matches!(step, Step::Run(_)) {
  6159. crate::watch::ask_once_end();
  6160. }
  6161. #[cfg(feature = "diagnostics")]
  6162. {
  6163. add(C::Runs, 1);
  6164. add(C::RunUs, started.elapsed().as_micros() as u64);
  6165. }
  6166. continue;
  6167. }
  6168. Step::GpuWrite(shadow, address, len) => {
  6169. // The shaders start from the title's data: this copy's
  6170. // pending refresh first. The other copies' wait for
  6171. // the next flush of all (flushing all of them at every
  6172. // range a dispatch writes made thousands of write-watch
  6173. // askings a frame).
  6174. batch.flush_one(shadow);
  6175. #[cfg(feature = "diagnostics")]
  6176. let snapshot = std::time::Instant::now();
  6177. shadow.writing(*address, *len);
  6178. #[cfg(feature = "diagnostics")]
  6179. {
  6180. add(C::GpuWrites, 1);
  6181. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  6182. }
  6183. continue;
  6184. }
  6185. Step::Texture(staging) => {
  6186. if batch.texture_due(staging) {
  6187. batch.due.push(staging.clone());
  6188. if !wide_textures() {
  6189. batch.refresh_textures();
  6190. }
  6191. }
  6192. continue;
  6193. }
  6194. };
  6195. us += started.elapsed();
  6196. bytes += copied as u64;
  6197. }
  6198. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  6199. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  6200. #[cfg(feature = "diagnostics")]
  6201. {
  6202. add(C::Copies, copies);
  6203. add(C::CopyBytes, bytes);
  6204. add(C::Refreshes, refreshes);
  6205. add(C::RefreshBytes, refreshed);
  6206. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  6207. }
  6208. }
  6209. }
  6210. /// A table by a copy's address.
  6211. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  6212. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  6213. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  6214. /// but our own.
  6215. #[derive(Default)]
  6216. pub(crate) struct AddressHash(u64);
  6217. impl std::hash::Hasher for AddressHash {
  6218. fn finish(&self) -> u64 {
  6219. self.0
  6220. }
  6221. fn write(&mut self, bytes: &[u8]) {
  6222. for &b in bytes {
  6223. self.write_usize(usize::from(b));
  6224. }
  6225. }
  6226. fn write_usize(&mut self, n: usize) {
  6227. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  6228. self.0 = h ^ (h >> 32);
  6229. }
  6230. }
  6231. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  6232. /// preparing: the write-watch asking for a submission; the title's bytes put
  6233. /// in under flights' writes; the lists' steps, the refreshes among them; the
  6234. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  6235. /// of the steps: the refreshes, and the copies and fills (those with the
  6236. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  6237. /// is of. Of the refreshes, those before ranges are given to shaders, one
  6238. /// copy at a time: nanoseconds, and how many.
  6239. #[cfg(feature = "diagnostics")]
  6240. static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  6241. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  6242. /// those known to copy nothing, and those done on several threads.
  6243. #[cfg(feature = "diagnostics")]
  6244. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  6245. /// Counts into [`SPLIT`].
  6246. #[cfg(feature = "diagnostics")]
  6247. struct Split(std::cell::Cell<std::time::Instant>);
  6248. #[cfg(feature = "diagnostics")]
  6249. impl Split {
  6250. fn begin() -> Split {
  6251. Split(std::cell::Cell::new(std::time::Instant::now()))
  6252. }
  6253. /// Nanoseconds since the last part.
  6254. fn so_far(&self) -> u64 {
  6255. self.0.get().elapsed().as_nanos() as u64
  6256. }
  6257. /// What came since the last part was part `i`.
  6258. fn part(&self, i: usize) {
  6259. let now = std::time::Instant::now();
  6260. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  6261. }
  6262. }
  6263. /// The split of the preparing, per frame, for the frame-rate line.
  6264. #[cfg(feature = "diagnostics")]
  6265. fn split_line(frames: f64) {
  6266. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6267. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  6268. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  6269. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6270. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
  6271. tracing::info!(
  6272. "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' \
  6273. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  6274. 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 \
  6275. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
  6276. ms[0],
  6277. ms[8],
  6278. ms[1],
  6279. ms[2],
  6280. ms[6],
  6281. f[0],
  6282. f[1],
  6283. f[2],
  6284. f[3],
  6285. ms[9],
  6286. ms[10] * 1e6,
  6287. ms[7],
  6288. ms[3],
  6289. ms[4],
  6290. ms[5],
  6291. if crate::watch::light() { "on" } else { "off" },
  6292. );
  6293. tracing::info!(
  6294. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6295. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6296. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6297. waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
  6298. as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
  6299. a[0],
  6300. a[1] / 1024.0,
  6301. a[11] / 1e6,
  6302. a[12],
  6303. a[10],
  6304. a[9],
  6305. a[2],
  6306. a[3],
  6307. a[4],
  6308. a[5],
  6309. a[6],
  6310. a[7] / 1e6,
  6311. a[8] / 1e6,
  6312. s[0] / 1048576.0,
  6313. s[1] / 1048576.0,
  6314. s[2] / 1048576.0,
  6315. s[3],
  6316. );
  6317. tracing::info!(
  6318. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures",
  6319. h[0],
  6320. h[1],
  6321. h[2],
  6322. );
  6323. }
  6324. /// Whether a submission's refreshes of host copies run on several threads,
  6325. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6326. ///
  6327. /// A submission brings some sixty copies up to date, one after the other
  6328. /// on the submitting thread: for each, the pages the title wrote are asked
  6329. /// for and read through the kernel into the copy. That is the frame line's
  6330. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6331. /// another: each refresh writes its own copy and its own notes, and reads
  6332. /// title memory. With the switch the copies of a flush (four or more) are
  6333. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6334. /// The write-watch journal and the guards are behind their own locks, as
  6335. /// they are for the title's threads.
  6336. fn wide_refresh() -> bool {
  6337. static ON: OnceLock<bool> = OnceLock::new();
  6338. *ON.get_or_init(|| {
  6339. wide_refresh_enabled(
  6340. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6341. std::thread::available_parallelism().ok().map(|n| n.get()),
  6342. )
  6343. })
  6344. }
  6345. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6346. match setting {
  6347. Some("1") => true,
  6348. Some("0") => false,
  6349. _ => logical_cpus.is_some_and(|n| n >= 4),
  6350. }
  6351. }
  6352. #[cfg(test)]
  6353. mod wide_refresh_tests {
  6354. use super::wide_refresh_enabled;
  6355. #[test]
  6356. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6357. assert!(wide_refresh_enabled(None, Some(4)));
  6358. assert!(wide_refresh_enabled(None, Some(16)));
  6359. assert!(!wide_refresh_enabled(None, Some(2)));
  6360. assert!(!wide_refresh_enabled(None, None));
  6361. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6362. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6363. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6364. }
  6365. }
  6366. /// A submission's refreshes not done yet, merged per buffer copy into the
  6367. /// range that covers them: done before a step that writes title memory or
  6368. /// gives a range to shaders, and before the lists run.
  6369. ///
  6370. /// Also the textures brought up to date in the submission so far: most
  6371. /// lists of a world submission sample the same textures, and a texture in
  6372. /// physical-page memory is hashed whole each time it is checked. Checked
  6373. /// once, it is checked again only after a step that writes title memory.
  6374. #[derive(Default)]
  6375. struct Batch {
  6376. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6377. /// Where each copy (by address) is in `refreshes`: the list that makes
  6378. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6379. /// for every refresh of a submission was tens of millions of
  6380. /// comparisons a frame.
  6381. index: ByCopy<usize>,
  6382. /// Staging buffers (by address) refreshed since the last title write,
  6383. /// or due to be.
  6384. textures: std::collections::HashSet<usize>,
  6385. /// Those due ([`Batch::refresh_textures`]).
  6386. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6387. /// What copies at their place in the submission's lists put into title
  6388. /// memory ([`place`]): the host copy, the title address, the bytes.
  6389. placed: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, Vec<u8>)>,
  6390. }
  6391. /// Whether a submission's textures are brought up to date on several
  6392. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6393. /// name them, as before).
  6394. ///
  6395. /// They are read, hashed and, if they changed, detiled into their staging
  6396. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6397. /// its own buffer, notes and lock, and is refreshed by the title's own
  6398. /// threads as it is. They are done before the next step that writes title
  6399. /// memory, as the copies' refreshes are, and before the lists go to the
  6400. /// card. What is new: the note of a list that its upload takes what the
  6401. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6402. /// an earlier list of the submission asked for, not behind it. The texture
  6403. /// is then uploaded by a later list too, once more than needed.
  6404. fn wide_textures() -> bool {
  6405. static ON: OnceLock<bool> = OnceLock::new();
  6406. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6407. }
  6408. impl Batch {
  6409. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6410. let end = address + len;
  6411. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6412. match self.index.get(&key) {
  6413. Some(&at) => {
  6414. let r = &mut self.refreshes[at];
  6415. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6416. }
  6417. None => {
  6418. self.index.insert(key, self.refreshes.len());
  6419. self.refreshes.push((shadow.clone(), address, end));
  6420. }
  6421. }
  6422. }
  6423. /// Before shaders are given a range of `shadow`'s copy: its pending
  6424. /// refresh is done, the others stay pending.
  6425. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  6426. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  6427. return;
  6428. };
  6429. let (shadow, from, to) = self.refreshes.swap_remove(at);
  6430. // The last entry took its place.
  6431. if let Some(moved) = self.refreshes.get(at) {
  6432. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  6433. }
  6434. #[cfg(feature = "diagnostics")]
  6435. let started = std::time::Instant::now();
  6436. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  6437. Self::update(&shadow, from, to);
  6438. }
  6439. #[cfg(feature = "diagnostics")]
  6440. {
  6441. let ns = started.elapsed().as_nanos() as u64;
  6442. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6443. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6444. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  6445. }
  6446. }
  6447. /// Brings `[from, to)` of a copy up to date, timed.
  6448. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  6449. let started = std::time::Instant::now();
  6450. let copied = shadow.update(from, to - from);
  6451. let us = started.elapsed().as_micros() as u64;
  6452. #[cfg(feature = "diagnostics")]
  6453. crate::copystat::range(from, to - from, us, 0);
  6454. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  6455. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  6456. }
  6457. /// Whether `staging` is still to be refreshed in this submission (and
  6458. /// notes it refreshed).
  6459. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  6460. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  6461. }
  6462. /// Before a step that writes title memory: pending refreshes are done
  6463. /// first, and textures are checked again after it.
  6464. fn title_written(&mut self) {
  6465. self.flush();
  6466. self.textures.clear();
  6467. }
  6468. /// The textures due are brought up to date.
  6469. fn refresh_textures(&mut self) {
  6470. if self.due.len() < 2 || !wide_textures() {
  6471. self.due.drain(..).for_each(|staging| staging.refresh());
  6472. return;
  6473. }
  6474. // The time counted is the time it took, not the threads' sum.
  6475. let started = std::time::Instant::now();
  6476. let before = PREPARING[2].load(Ordering::Relaxed);
  6477. let due = std::mem::take(&mut self.due);
  6478. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  6479. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  6480. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6481. }
  6482. fn flush(&mut self) {
  6483. self.refresh_textures();
  6484. self.index.clear();
  6485. if self.refreshes.is_empty() {
  6486. return;
  6487. }
  6488. #[cfg(feature = "diagnostics")]
  6489. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  6490. self.flush_all();
  6491. #[cfg(feature = "diagnostics")]
  6492. {
  6493. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6494. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  6495. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  6496. }
  6497. }
  6498. fn flush_all(&mut self) {
  6499. // Most of a flush's copies are as they were: they are told so here,
  6500. // from what the submission's asking found, before anything is asked
  6501. // and any thread woken. (Thousands of them, the heap's buffer views
  6502. // once a frame: on the threads, below.)
  6503. const FEW: usize = 256;
  6504. let light = crate::watch::light();
  6505. if light && self.refreshes.len() <= FEW {
  6506. let started = std::time::Instant::now();
  6507. #[cfg(feature = "diagnostics")]
  6508. let all = self.refreshes.len();
  6509. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  6510. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6511. #[cfg(feature = "diagnostics")]
  6512. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  6513. }
  6514. // One write-watch asking for the copies that lie close together,
  6515. // not one per copy.
  6516. let ahead = self.refreshes.len() > 1;
  6517. if ahead {
  6518. let started = std::time::Instant::now();
  6519. let ranges: Vec<(usize, usize)> = self
  6520. .refreshes
  6521. .iter()
  6522. .filter(|r| r.0.asked_ahead())
  6523. .map(|r| (r.1, r.2))
  6524. .collect();
  6525. crate::watch::ask_ahead(&ranges);
  6526. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6527. }
  6528. if wide_refresh() && self.refreshes.len() >= 4 {
  6529. // Each copy on its own, several at a time: a copy's refresh
  6530. // writes that copy and reads title memory, nothing of another's.
  6531. // The time counted is the time it took, not the threads' sum.
  6532. let started = std::time::Instant::now();
  6533. let before = PREPARING[0].load(Ordering::Relaxed);
  6534. #[cfg(feature = "diagnostics")]
  6535. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  6536. if light {
  6537. // A number to a free thread, not a job to each copy.
  6538. let refreshes = std::mem::take(&mut self.refreshes);
  6539. crate::shadow::wide_each(refreshes.len(), move |i| {
  6540. let (shadow, from, to) = &refreshes[i];
  6541. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  6542. #[cfg(feature = "diagnostics")]
  6543. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  6544. return;
  6545. }
  6546. Self::update(shadow, *from, *to);
  6547. });
  6548. } else {
  6549. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  6550. .refreshes
  6551. .drain(..)
  6552. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  6553. .collect();
  6554. crate::shadow::wide_run(jobs);
  6555. }
  6556. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6557. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6558. } else {
  6559. for (shadow, from, to) in self.refreshes.drain(..) {
  6560. Self::update(&shadow, from, to);
  6561. }
  6562. }
  6563. if ahead {
  6564. crate::watch::ask_ahead_done();
  6565. }
  6566. }
  6567. }
  6568. /// Copies title memory at submission. The ranges were checked against their
  6569. /// resources when recorded, but the title may since have unmapped pages of
  6570. /// them (tiled memory, page mappings), which read as zeros here; a title
  6571. /// destination (`title_dst`) that is not all mapped is left alone.
  6572. ///
  6573. /// The source is read through the kernel (`ReadProcessMemory`), which
  6574. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  6575. /// cost about 2 ms per copy in the title's big pools (it walks the page
  6576. /// tables to the region's end), which made copies run at 100-200 MB/s.
  6577. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  6578. #[cfg(feature = "diagnostics")]
  6579. match crate::copystat::mode() {
  6580. 1 => {
  6581. // SAFETY: timing only: the caller vouches for the source.
  6582. unsafe { std::ptr::copy(src, dst, len) };
  6583. return;
  6584. }
  6585. 2 => return,
  6586. _ => {}
  6587. }
  6588. if len == 0 {
  6589. return;
  6590. }
  6591. // A title destination that is not all mapped is left alone. Asking
  6592. // Windows first (`VirtualQuery`) walks the page tables to the end of
  6593. // the destination's region: in the title's big blocks that is
  6594. // milliseconds a copy, and it was a seventh of the submitting thread's
  6595. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  6596. // says the same when it fails, so the question is only asked then.
  6597. // `VICTORY_COPY_ASK=1` asks first, as before.
  6598. static ASK: OnceLock<bool> = OnceLock::new();
  6599. let ask_first = title_dst
  6600. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  6601. if ask_first && !crate::texture::committed(dst, len) {
  6602. return;
  6603. }
  6604. if title_dst {
  6605. // The kernel writes the destination: it must not be guarded.
  6606. crate::watch::writing(dst as usize, len);
  6607. }
  6608. #[cfg(feature = "diagnostics")]
  6609. let moved = std::time::Instant::now();
  6610. let since = crate::watch::changes();
  6611. // (A title destination that is away only while the runtime changes a
  6612. // mapping beside it is written when that is done.)
  6613. let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
  6614. #[cfg(feature = "diagnostics")]
  6615. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  6616. if whole {
  6617. return;
  6618. }
  6619. // The copy failed: a source page is not there, or the destination is
  6620. // not all mapped. Then the destination stays as it is (the kernel may
  6621. // have written its first pages).
  6622. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  6623. crate::watch::lost("a copy of the title's", dst as usize, len);
  6624. return;
  6625. }
  6626. #[cfg(feature = "diagnostics")]
  6627. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  6628. #[cfg(feature = "diagnostics")]
  6629. let sparse = std::time::Instant::now();
  6630. if !title_dst && len >= 64 << 10 {
  6631. read_sparse(src, dst, len);
  6632. } else {
  6633. read_pieces(src, dst, len);
  6634. }
  6635. #[cfg(feature = "diagnostics")]
  6636. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  6637. }
  6638. /// After a failed bulk read into host memory, skip contiguous holes. Never
  6639. /// cache the query across copies: the title may remap the same address.
  6640. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  6641. use windows_sys::Win32::System::Memory::{
  6642. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  6643. };
  6644. let mut offset = 0;
  6645. while offset < len {
  6646. let at = src.wrapping_add(offset);
  6647. let to = dst.wrapping_add(offset);
  6648. let remaining = len - offset;
  6649. // SAFETY: the query inspects an address and fills a local structure.
  6650. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  6651. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  6652. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  6653. .saturating_sub(at as usize).min(remaining);
  6654. if size != size_of_val(&info) || n == 0 {
  6655. read_pieces(at, to, remaining);
  6656. break;
  6657. }
  6658. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  6659. #[cfg(feature = "diagnostics")]
  6660. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6661. // SAFETY: this path is only used with a writable host destination.
  6662. unsafe { to.write_bytes(0, n) };
  6663. } else if !read(at, to, n) {
  6664. // A mapping may change between query and read.
  6665. read_pieces(at, to, n);
  6666. }
  6667. offset += n;
  6668. }
  6669. }
  6670. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  6671. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  6672. // that fails), zeros for what cannot be read.
  6673. for_pieces(src as usize, len, 64 << 10, |at, n| {
  6674. let to = dst.wrapping_add(at - src as usize);
  6675. if !read(at as *const u8, to, n) {
  6676. for_pieces(at, n, 4 << 10, |at, n| {
  6677. let to = dst.wrapping_add(at - src as usize);
  6678. if !read(at as *const u8, to, n) {
  6679. #[cfg(feature = "diagnostics")]
  6680. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6681. zero(to, n);
  6682. }
  6683. });
  6684. }
  6685. });
  6686. }
  6687. /// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
  6688. /// destination of a title's copy), which can go between the question whether
  6689. /// it is there and this.
  6690. fn zero(to: *mut u8, n: usize) {
  6691. static ZEROS: [u8; 4096] = [0; 4096];
  6692. if n <= ZEROS.len() && crate::safecopy::on() {
  6693. // SAFETY: a destination that is not there fails the copy.
  6694. if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
  6695. crate::watch::lost("zeros", to as usize, n);
  6696. }
  6697. return;
  6698. }
  6699. // SAFETY: inside the destination, which is mapped.
  6700. unsafe { to.write_bytes(0, n) };
  6701. }
  6702. /// Reads title memory at `src` into `dst`; false if a page of it is not
  6703. /// readable.
  6704. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  6705. read(src, dst.as_mut_ptr(), dst.len())
  6706. }
  6707. /// Reads what is there of the `dst.len()` bytes of title memory at `src`,
  6708. /// zeros for the rest; returns how many bytes were there. Safe while the
  6709. /// runtime remaps title memory (the kernel, or a copy that takes the fault,
  6710. /// reads). What the runtime's record says is mapped is read in one go each,
  6711. /// and by pieces where that fails; memory it has no record of by pieces.
  6712. pub(crate) fn read_there(src: *const u8, dst: &mut [u8]) -> usize {
  6713. dst.fill(0);
  6714. let (start, len) = (src as usize, dst.len());
  6715. let mut got = 0;
  6716. let mut runs = crate::inplace::shown_runs(start, len);
  6717. if runs.is_empty() {
  6718. runs.push((start, len));
  6719. }
  6720. for (at, n) in runs {
  6721. let piece = &mut dst[at - start..at - start + n];
  6722. if read_into(at as *const u8, piece) {
  6723. got += n;
  6724. continue;
  6725. }
  6726. // (What failed may have written its first pages.)
  6727. piece.fill(0);
  6728. for_pieces(at, n, 64 << 10, |from, n| {
  6729. let piece = &mut dst[from - start..from - start + n];
  6730. if read_into(from as *const u8, piece) {
  6731. got += n;
  6732. return;
  6733. }
  6734. piece.fill(0);
  6735. for_pieces(from, n, 4 << 10, |from, n| {
  6736. let piece = &mut dst[from - start..from - start + n];
  6737. if read_into(from as *const u8, piece) {
  6738. got += n;
  6739. } else {
  6740. piece.fill(0);
  6741. }
  6742. });
  6743. });
  6744. }
  6745. got
  6746. }
  6747. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  6748. /// readable.
  6749. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  6750. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  6751. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6752. if crate::safecopy::on() {
  6753. // SAFETY: the destination is mapped writable memory of `len` bytes;
  6754. // a source page that is not there fails the copy.
  6755. return unsafe { crate::safecopy::copy(dst, src, len) };
  6756. }
  6757. let mut done = 0;
  6758. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  6759. // kernel checks the source.
  6760. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  6761. }
  6762. #[link(name = "ntdll", kind = "raw-dylib")]
  6763. unsafe extern "system" {
  6764. /// The kernel's write into a process's memory, `(process, address,
  6765. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  6766. /// the range is not there or not writable. It changes no protection.
  6767. fn NtWriteVirtualMemory(
  6768. process: *mut std::ffi::c_void,
  6769. base: *mut std::ffi::c_void,
  6770. buffer: *const std::ffi::c_void,
  6771. size: usize,
  6772. written: *mut usize,
  6773. ) -> i32;
  6774. }
  6775. /// Whether title memory is written with the kernel's own call
  6776. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  6777. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  6778. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  6779. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  6780. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  6781. fn direct_writes() -> bool {
  6782. static ON: OnceLock<bool> = OnceLock::new();
  6783. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  6784. }
  6785. /// Copies host memory into title memory after a submission (what shaders
  6786. /// wrote), leaving pages that are not mapped alone.
  6787. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  6788. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  6789. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6790. let direct = direct_writes();
  6791. let since = crate::watch::changes();
  6792. let write = |at: usize, n: usize| {
  6793. let from = src.wrapping_add(at - dst as usize);
  6794. if crate::safecopy::on() {
  6795. // SAFETY: the source is ours; a destination page that is not
  6796. // there, or not writable, fails the copy.
  6797. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  6798. }
  6799. let mut done = 0;
  6800. if direct {
  6801. // SAFETY: as below; the kernel checks the destination and
  6802. // writes nothing it cannot (the caller opened its guards:
  6803. // `crate::watch::writing`).
  6804. return unsafe {
  6805. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  6806. };
  6807. }
  6808. // SAFETY: the source is our mapped host copy; the kernel checks the
  6809. // destination.
  6810. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  6811. };
  6812. if len == 0 || write(dst as usize, len) {
  6813. return;
  6814. }
  6815. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  6816. if !write(at, n) {
  6817. for_pieces(at, n, 4 << 10, |at, n| {
  6818. if write(at, n) {
  6819. return;
  6820. }
  6821. // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
  6822. // refresh guarded the block again since the caller opened
  6823. // it; and any where the runtime was changing a mapping.
  6824. crate::watch::writing(at, n);
  6825. if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
  6826. crate::watch::lost("a host copy's bytes", at, n);
  6827. }
  6828. });
  6829. }
  6830. });
  6831. }
  6832. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  6833. /// `step`.
  6834. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  6835. let end = start + len;
  6836. let mut at = start;
  6837. while at < end {
  6838. let next = ((at / step + 1) * step).min(end);
  6839. f(at, next - at);
  6840. at = next;
  6841. }
  6842. }
  6843. impl Host {
  6844. /// The queue everything of ours runs on, for a call that must go to it
  6845. /// in order with the lists (`crate::tiles`: a texture's levels are
  6846. /// given memory ahead of the list that uploads them).
  6847. pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
  6848. &self.queue
  6849. }
  6850. /// A buffer in the upload heap, mapped for writing.
  6851. /// A buffer of `size` bytes the card writes and we read (a read back),
  6852. /// in the state copies into it need.
  6853. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  6854. let heap = D3D12_HEAP_PROPERTIES {
  6855. Type: D3D12_HEAP_TYPE_READBACK,
  6856. ..Default::default()
  6857. };
  6858. let desc = D3D12_RESOURCE_DESC {
  6859. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6860. Width: size.max(1),
  6861. Height: 1,
  6862. DepthOrArraySize: 1,
  6863. MipLevels: 1,
  6864. SampleDesc: DXGI_SAMPLE_DESC {
  6865. Count: 1,
  6866. Quality: 0,
  6867. },
  6868. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6869. ..Default::default()
  6870. };
  6871. let mut buffer: Option<ID3D12Resource> = None;
  6872. // SAFETY: plain creation of a read-back buffer.
  6873. let made = unsafe {
  6874. self.device.CreateCommittedResource(
  6875. &heap,
  6876. D3D12_HEAP_FLAG_NONE,
  6877. &desc,
  6878. D3D12_RESOURCE_STATE_COPY_DEST,
  6879. None,
  6880. &mut buffer,
  6881. )
  6882. };
  6883. match made {
  6884. Ok(()) => buffer,
  6885. Err(e) => {
  6886. tracing::warn!(error = %e, size, "no read-back buffer");
  6887. None
  6888. }
  6889. }
  6890. }
  6891. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6892. MADE[0].fetch_add(1, Ordering::Relaxed);
  6893. MADE[1].fetch_add(size, Ordering::Relaxed);
  6894. let heap = D3D12_HEAP_PROPERTIES {
  6895. Type: D3D12_HEAP_TYPE_UPLOAD,
  6896. ..Default::default()
  6897. };
  6898. let desc = D3D12_RESOURCE_DESC {
  6899. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6900. Width: size.max(1),
  6901. Height: 1,
  6902. DepthOrArraySize: 1,
  6903. MipLevels: 1,
  6904. SampleDesc: DXGI_SAMPLE_DESC {
  6905. Count: 1,
  6906. Quality: 0,
  6907. },
  6908. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6909. ..Default::default()
  6910. };
  6911. let mut buffer: Option<ID3D12Resource> = None;
  6912. let mut data = std::ptr::null_mut();
  6913. // SAFETY: plain creation and mapping of an upload buffer.
  6914. let made = unsafe {
  6915. self.device
  6916. .CreateCommittedResource(
  6917. &heap,
  6918. D3D12_HEAP_FLAG_NONE,
  6919. &desc,
  6920. D3D12_RESOURCE_STATE_GENERIC_READ,
  6921. None,
  6922. &mut buffer,
  6923. )
  6924. .and_then(|()| {
  6925. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  6926. b.Map(0, None, Some(&mut data))
  6927. })
  6928. };
  6929. match made {
  6930. Ok(()) => Some((buffer?, data.cast())),
  6931. Err(e) => {
  6932. tracing::warn!(error = %e, size, "no upload buffer");
  6933. None
  6934. }
  6935. }
  6936. }
  6937. }
  6938. /// The swap chain formats a presented texture can be copied into: its own
  6939. /// family's.
  6940. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  6941. Some(match format.0 {
  6942. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  6943. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  6944. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  6945. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  6946. _ => return None,
  6947. })
  6948. }
  6949. const BUFFERS: u32 = 2;
  6950. struct Presenter {
  6951. swap_chain: IDXGISwapChain3,
  6952. width: u32,
  6953. height: u32,
  6954. format: DXGI_FORMAT,
  6955. copy: HostList,
  6956. /// With presents sent ahead ([`late_free_present`]): a list for each
  6957. /// present in the air, and the submission it last flew as (it is used
  6958. /// again once that one has finished).
  6959. ahead: Vec<(HostList, u64)>,
  6960. hwnd: HWND,
  6961. meter: Meter,
  6962. }
  6963. /// The frame rate, shown in the window's caption every second and logged
  6964. /// every few seconds.
  6965. struct Meter {
  6966. since: std::time::Instant,
  6967. frames: u32,
  6968. #[cfg(feature = "diagnostics")]
  6969. copy_stats_frames: u64,
  6970. drawn: u64,
  6971. logged: std::time::Instant,
  6972. /// The caption the window had, once read.
  6973. caption: Option<Vec<u16>>,
  6974. }
  6975. impl Meter {
  6976. fn new() -> Self {
  6977. let now = std::time::Instant::now();
  6978. Meter {
  6979. since: now,
  6980. frames: 0,
  6981. #[cfg(feature = "diagnostics")]
  6982. copy_stats_frames: 0,
  6983. drawn: crate::draw::drawn(),
  6984. logged: now,
  6985. caption: None,
  6986. }
  6987. }
  6988. /// Counts a presented frame.
  6989. fn frame(&mut self, hwnd: HWND) {
  6990. #[cfg(feature = "diagnostics")]
  6991. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  6992. #[cfg(feature = "diagnostics")]
  6993. crate::copystat::presented();
  6994. self.frames += 1;
  6995. #[cfg(feature = "diagnostics")]
  6996. {
  6997. self.copy_stats_frames += 1;
  6998. }
  6999. let elapsed = self.since.elapsed();
  7000. if elapsed < std::time::Duration::from_secs(1) {
  7001. return;
  7002. }
  7003. let drawn = crate::draw::drawn();
  7004. let frames = f64::from(self.frames);
  7005. let fps = frames / elapsed.as_secs_f64();
  7006. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  7007. let draws = (drawn - self.drawn) as f64 / frames;
  7008. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  7009. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  7010. let [cpu, gpu] = [0, 1].map(|i| {
  7011. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  7012. });
  7013. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  7014. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  7015. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  7016. });
  7017. let [back_ms, back_mb] = [0, 1].map(|i| {
  7018. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  7019. });
  7020. let dropped = crate::draw::take_dropped() as f64 / frames;
  7021. let indirect = crate::list::take_indirect() as f64 / frames;
  7022. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  7023. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  7024. tracing::info!(
  7025. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  7026. );
  7027. crate::shadow::exact_line(frames);
  7028. crate::descriptor::sync_line(frames);
  7029. late_line(frames);
  7030. card_clock_line(frames, ms);
  7031. #[cfg(feature = "diagnostics")]
  7032. spans::line(frames);
  7033. crate::shadow::back_line(frames);
  7034. #[cfg(feature = "diagnostics")]
  7035. split_line(frames);
  7036. {
  7037. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7038. if passes + compares > 0.0 {
  7039. tracing::info!(
  7040. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  7041. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  7042. if rehash_runs() { "on" } else { "off" }
  7043. );
  7044. }
  7045. }
  7046. {
  7047. let [own, asking, still, all] =
  7048. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  7049. if all >= 1.0 {
  7050. tracing::info!(
  7051. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  7052. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  7053. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  7054. );
  7055. }
  7056. let [through, left, filled, short] =
  7057. [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7058. if through + left + filled > 0.0 {
  7059. tracing::info!(
  7060. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  7061. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \
  7062. {filled:.1} first fillings from the pages there (VICTORY_TEXTURE_FILL=0: left empty), {short:.1} of them \
  7063. with less than was mapped (looked at again)"
  7064. );
  7065. }
  7066. }
  7067. {
  7068. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7069. if copies > 0.0 {
  7070. tracing::info!(
  7071. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  7072. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  7073. if join_copies() { "on" } else { "off" }
  7074. );
  7075. }
  7076. }
  7077. // Passes over the heap's buffer views for shaders that pick them by index.
  7078. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  7079. let picked_ms =
  7080. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  7081. // Copies between depth textures and their colour twins, each way.
  7082. let [twin_to_depth, twin_to_colour] =
  7083. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7084. // Depth planes drawn from their twins.
  7085. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  7086. // Copies in the card's memory (`crate::shadow::cards`).
  7087. let card = crate::shadow::card_stats();
  7088. #[cfg(feature = "diagnostics")]
  7089. let slow = crate::watch::slow_asks();
  7090. // Over the same frames as the counts above.
  7091. #[cfg(feature = "diagnostics")]
  7092. let drops = crate::pipeline::take_drops();
  7093. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  7094. self.logged = std::time::Instant::now();
  7095. tracing::info!(
  7096. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  7097. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  7098. );
  7099. crate::tiles::status();
  7100. {
  7101. let [queued, due, away, partly, oldest] =
  7102. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  7103. let [same, parts, tails] =
  7104. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  7105. tracing::info!(
  7106. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  7107. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  7108. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  7109. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  7110. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  7111. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  7112. {} made slots found unmapped and made null",
  7113. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  7114. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  7115. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  7116. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  7117. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  7118. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  7119. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  7120. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  7121. );
  7122. }
  7123. {
  7124. let mode = crate::watch::page_writes();
  7125. let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
  7126. let [kept, dropped, slots, uploaded] =
  7127. [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
  7128. tracing::info!(
  7129. "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)",
  7130. bytes >> 20,
  7131. if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
  7132. if mode & 4 != 0 { "told as well" } else { "counted only" },
  7133. if mode & 2 != 0 { "made due again" } else { "left as they were" }
  7134. );
  7135. }
  7136. #[cfg(feature = "diagnostics")]
  7137. tracing::info!(
  7138. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  7139. slow[0] as f64 / frames,
  7140. slow[1] as f64 / 1e3 / frames,
  7141. slow[2] as f64 / 1e3
  7142. );
  7143. if crate::shadow::cards() {
  7144. let per_frame = |i: usize| card[i] as f64 / frames;
  7145. tracing::info!(
  7146. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  7147. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  7148. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  7149. card[7],
  7150. card[8] >> 20,
  7151. card[9] >> 20,
  7152. per_frame(0) / 1e6,
  7153. per_frame(1),
  7154. per_frame(2),
  7155. per_frame(3),
  7156. per_frame(4) / 1e6,
  7157. per_frame(5),
  7158. per_frame(6) / 1e3
  7159. );
  7160. }
  7161. tracing::info!(
  7162. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  7163. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  7164. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  7165. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  7166. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  7167. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  7168. {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}",
  7169. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  7170. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  7171. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  7172. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  7173. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  7174. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  7175. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  7176. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  7177. refused = format!(
  7178. "{} ({} 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",
  7179. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  7180. crate::shadow::OWN_MADE.load(Ordering::Relaxed),
  7181. crate::resource::TWINS[0].load(Ordering::Relaxed),
  7182. crate::resource::TWINS[1].load(Ordering::Relaxed),
  7183. crate::resource::PLANES[1].load(Ordering::Relaxed),
  7184. crate::resource::PLANES[2].load(Ordering::Relaxed)
  7185. ),
  7186. making = crate::pipeline::making(),
  7187. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  7188. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  7189. );
  7190. #[cfg(feature = "diagnostics")]
  7191. {
  7192. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7193. tracing::info!(
  7194. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  7195. put[0],
  7196. put[1],
  7197. put[2] / 1e6,
  7198. put[3]
  7199. );
  7200. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  7201. for (why, n) in drops.iter().take(40) {
  7202. tracing::info!(
  7203. "dropped {:.1}/frame without a host pipeline: {why}",
  7204. *n as f64 / frames
  7205. );
  7206. }
  7207. }
  7208. }
  7209. if self.caption.is_none() {
  7210. // The window's own text, read without a message.
  7211. let mut buffer = vec![0u16; 512];
  7212. // SAFETY: a window handle and a buffer of that length.
  7213. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  7214. buffer.truncate(n.max(0) as usize);
  7215. self.caption = Some(buffer);
  7216. }
  7217. let Some(caption) = &self.caption else { return };
  7218. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  7219. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  7220. text.push(0);
  7221. // Setting the text waits for the window's thread (a title thread,
  7222. // which may not pump for a while), so a thread of ours does it and
  7223. // presenting never waits; it takes the newest text when free.
  7224. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  7225. static SETTER: std::sync::Once = std::sync::Once::new();
  7226. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  7227. SETTER.call_once(|| {
  7228. let _ = std::thread::Builder::new()
  7229. .name("victory-caption".into())
  7230. .spawn(|| {
  7231. loop {
  7232. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  7233. match next {
  7234. // SAFETY: a window handle and a NUL-terminated text.
  7235. Some((hwnd, text)) => unsafe {
  7236. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  7237. },
  7238. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  7239. }
  7240. }
  7241. });
  7242. });
  7243. }
  7244. }
  7245. impl Host {
  7246. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  7247. /// as frame `frame` (saved if captures are on). `None` if nothing was
  7248. /// shown; else, in diagnostics builds, whether the frame was black.
  7249. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  7250. // SAFETY: a live resource.
  7251. let desc = unsafe { texture.GetDesc() };
  7252. let Some(format) = swap_format(desc.Format) else {
  7253. tracing::warn!(format = desc.Format.0, "cannot present this format");
  7254. return None;
  7255. };
  7256. let (width, height) = (desc.Width as u32, desc.Height);
  7257. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  7258. if presenter.is_none() {
  7259. *presenter = match self.presenter(width, height, format) {
  7260. Ok(p) => Some(p),
  7261. Err(e) => {
  7262. tracing::warn!(error = %e, "no swap chain");
  7263. return None;
  7264. }
  7265. };
  7266. }
  7267. let p = presenter.as_mut()?;
  7268. if (p.width, p.height, p.format) != (width, height, format) {
  7269. // Presents sent ahead hold back buffers until they have run.
  7270. settle_now(WHY_SYNC);
  7271. // SAFETY: no back buffer is held; every submission was waited for.
  7272. let resized = unsafe {
  7273. p.swap_chain
  7274. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  7275. };
  7276. match resized {
  7277. Ok(()) => {
  7278. (p.width, p.height, p.format) = (width, height, format);
  7279. tracing::info!(
  7280. width,
  7281. height,
  7282. format = format.0,
  7283. frame,
  7284. "the swap chain's buffers were made again for another size or format"
  7285. );
  7286. self.log_video_memory("right after the swap chain's buffers were made again");
  7287. }
  7288. Err(e) => {
  7289. tracing::warn!(error = %e, width, height, "swap chain not resized");
  7290. return None;
  7291. }
  7292. }
  7293. }
  7294. let state = D3D12_RESOURCE_STATES(state as i32);
  7295. // SAFETY: our swap chain, list and a live source texture.
  7296. unsafe {
  7297. let index = p.swap_chain.GetCurrentBackBufferIndex();
  7298. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  7299. return None;
  7300. };
  7301. // Sent ahead ([`late_free_present`]) unless the frame is to be
  7302. // read back at once (a saved or listed frame): then a list of
  7303. // its own, one whose last flight has finished or a new one.
  7304. #[cfg(feature = "diagnostics")]
  7305. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  7306. #[cfg(not(feature = "diagnostics"))]
  7307. let read_now = false;
  7308. let slot = if late_free_present() && !read_now {
  7309. let finished = FINISHED.load(Ordering::Acquire);
  7310. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  7311. let list = self.new_list().ok()?;
  7312. list.close();
  7313. p.ahead.push((list, 0));
  7314. Some(p.ahead.len() - 1)
  7315. })
  7316. } else {
  7317. None
  7318. };
  7319. let copy = match slot {
  7320. Some(i) => &p.ahead[i].0,
  7321. None => &p.copy,
  7322. };
  7323. copy.reset();
  7324. let list = &copy.list;
  7325. list.ResourceBarrier(&[
  7326. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  7327. transition(
  7328. &back,
  7329. D3D12_RESOURCE_STATE_PRESENT,
  7330. D3D12_RESOURCE_STATE_COPY_DEST,
  7331. ),
  7332. ]);
  7333. list.CopyResource(&back, texture);
  7334. #[cfg(feature = "diagnostics")]
  7335. let capture = crate::capture::wanted(frame)
  7336. .then(|| crate::capture::read_back(&self.device, list, texture))
  7337. .flatten();
  7338. #[cfg(feature = "diagnostics")]
  7339. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  7340. #[cfg(not(feature = "diagnostics"))]
  7341. let _ = frame;
  7342. list.ResourceBarrier(&[
  7343. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  7344. transition(
  7345. &back,
  7346. D3D12_RESOURCE_STATE_COPY_DEST,
  7347. D3D12_RESOURCE_STATE_PRESENT,
  7348. ),
  7349. ]);
  7350. copy.close();
  7351. match slot {
  7352. Some(i) => {
  7353. let flown = self.execute_own(copy);
  7354. p.ahead[i].1 = flown;
  7355. }
  7356. None => self.execute(&[copy]),
  7357. }
  7358. #[cfg(feature = "diagnostics")]
  7359. if let Some((buffer, footprint)) = capture {
  7360. crate::capture::save_read_back(frame, &buffer, &footprint);
  7361. }
  7362. #[cfg(feature = "diagnostics")]
  7363. crate::replay::record::present(texture, state);
  7364. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  7365. p.meter.frame(p.hwnd);
  7366. #[cfg(feature = "diagnostics")]
  7367. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  7368. #[cfg(not(feature = "diagnostics"))]
  7369. Some(false)
  7370. }
  7371. }
  7372. fn presenter(
  7373. &self,
  7374. width: u32,
  7375. height: u32,
  7376. format: DXGI_FORMAT,
  7377. ) -> windows::core::Result<Presenter> {
  7378. let hwnd = match title_window() {
  7379. Some(hwnd) => hwnd,
  7380. None => window(width, height)?,
  7381. };
  7382. self.log_video_memory("right before the swap chain is made");
  7383. // SAFETY: plain object creation for our window.
  7384. unsafe {
  7385. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  7386. let desc = DXGI_SWAP_CHAIN_DESC1 {
  7387. Width: width,
  7388. Height: height,
  7389. Format: format,
  7390. SampleDesc: DXGI_SAMPLE_DESC {
  7391. Count: 1,
  7392. Quality: 0,
  7393. },
  7394. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  7395. BufferCount: BUFFERS,
  7396. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  7397. ..Default::default()
  7398. };
  7399. let swap_chain = factory
  7400. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  7401. .cast::<IDXGISwapChain3>()?;
  7402. let copy = self.new_list()?;
  7403. copy.close();
  7404. tracing::info!(width, height, format = format.0, "presenting to a window");
  7405. self.log_video_memory("right after the swap chain is made");
  7406. Ok(Presenter {
  7407. swap_chain,
  7408. width,
  7409. height,
  7410. format,
  7411. copy,
  7412. ahead: Vec::new(),
  7413. hwnd,
  7414. meter: Meter::new(),
  7415. })
  7416. }
  7417. }
  7418. }
  7419. /// A visible top-level window of this process: the one the title made, if
  7420. /// it made one.
  7421. fn title_window() -> Option<HWND> {
  7422. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  7423. let mut process = 0;
  7424. // SAFETY: a window handle from the enumeration; `found` is ours.
  7425. unsafe {
  7426. GetWindowThreadProcessId(hwnd, Some(&mut process));
  7427. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  7428. && IsWindowVisible(hwnd).as_bool()
  7429. {
  7430. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  7431. return false.into();
  7432. }
  7433. }
  7434. true.into()
  7435. }
  7436. let mut found: Option<HWND> = None;
  7437. // SAFETY: the callback only writes `found`, which outlives the call.
  7438. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  7439. found
  7440. }
  7441. /// `state` without the bits the host texture's flags forbid: the console
  7442. /// lets the title name states its own resources allow (unordered access on
  7443. /// a depth target, whose host copy cannot have both).
  7444. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  7445. // SAFETY: a plain query.
  7446. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  7447. }
  7448. /// [`legal_state`] for a texture with resource flags `flags`.
  7449. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  7450. // (flag, set or clear forbids, state bits): render target, unordered
  7451. // access, depth, denied shader resource.
  7452. const FORBIDDEN: [(u32, bool, u32); 4] = [
  7453. (0x1, false, 0x4),
  7454. (0x4, false, 0x8),
  7455. (0x2, false, 0x10 | 0x20),
  7456. (0x8, true, 0x40 | 0x80),
  7457. ];
  7458. FORBIDDEN
  7459. .iter()
  7460. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  7461. .fold(state, |s, &(_, _, bits)| s & !bits)
  7462. }
  7463. impl Host {
  7464. /// The card's memory as the system accounts it to this process, in
  7465. /// bytes: the budget and the use of the card's own memory, then of the
  7466. /// PC's memory shared with the card (where the system moves what does
  7467. /// not fit on the card).
  7468. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  7469. let adapter = self.adapter.as_ref()?;
  7470. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7471. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7472. // SAFETY: plain queries that fill our structures.
  7473. unsafe {
  7474. adapter
  7475. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7476. .ok()?;
  7477. adapter
  7478. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7479. .ok()?;
  7480. }
  7481. // The card's budget moved by 256 MB or more since the last look:
  7482. // said at once, with what was in use at the last look, so the log
  7483. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  7484. // the first world frame in runs 179 to 185, and the memory line,
  7485. // seconds later, was the first to show it. We reserve nothing
  7486. // and make the swap chain once, at the start.)
  7487. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  7488. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  7489. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  7490. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  7491. tracing::info!(
  7492. "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",
  7493. last[0] >> 20,
  7494. own.Budget >> 20,
  7495. crate::frame::current(),
  7496. last[1] >> 20,
  7497. last[2] >> 20
  7498. );
  7499. self.log_video_memory("right after that change");
  7500. }
  7501. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  7502. }
  7503. /// Both of the system's memory groups for this process, in bytes: for
  7504. /// the card's own memory and then for the PC's memory shared with the
  7505. /// card, the budget, the use, what could still be reserved and what
  7506. /// is reserved (the layer reserves none).
  7507. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  7508. let adapter = self.adapter.as_ref()?;
  7509. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7510. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7511. // SAFETY: plain queries that fill our structures.
  7512. unsafe {
  7513. adapter
  7514. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7515. .ok()?;
  7516. adapter
  7517. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7518. .ok()?;
  7519. }
  7520. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  7521. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  7522. };
  7523. Some([all(&own), all(&shared)])
  7524. }
  7525. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  7526. pub(crate) fn log_video_memory(&self, when: &str) {
  7527. let Some([own, shared]) = self.video_memory_groups() else {
  7528. return;
  7529. };
  7530. tracing::info!(
  7531. "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)",
  7532. when,
  7533. own[0] >> 20,
  7534. own[1] >> 20,
  7535. own[2] >> 20,
  7536. own[3] >> 20,
  7537. shared[0] >> 20,
  7538. shared[1] >> 20,
  7539. shared[2] >> 20,
  7540. shared[3] >> 20
  7541. );
  7542. }
  7543. /// A buffer in system memory that the CPU maps (write-back, so reading
  7544. /// it is fast too) and shaders read and write: for host copies of title
  7545. /// memory that shaders write, which upload memory cannot be. Starts in
  7546. /// the common state (buffers move out of it implicitly).
  7547. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7548. MADE[2].fetch_add(1, Ordering::Relaxed);
  7549. MADE[3].fetch_add(size, Ordering::Relaxed);
  7550. let heap = D3D12_HEAP_PROPERTIES {
  7551. Type: D3D12_HEAP_TYPE_CUSTOM,
  7552. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  7553. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  7554. ..Default::default()
  7555. };
  7556. let desc = D3D12_RESOURCE_DESC {
  7557. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7558. Width: size.max(1),
  7559. Height: 1,
  7560. DepthOrArraySize: 1,
  7561. MipLevels: 1,
  7562. SampleDesc: DXGI_SAMPLE_DESC {
  7563. Count: 1,
  7564. Quality: 0,
  7565. },
  7566. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7567. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7568. ..Default::default()
  7569. };
  7570. let mut buffer: Option<ID3D12Resource> = None;
  7571. let mut data = std::ptr::null_mut();
  7572. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7573. let made = unsafe {
  7574. self.device
  7575. .CreateCommittedResource(
  7576. &heap,
  7577. D3D12_HEAP_FLAG_NONE,
  7578. &desc,
  7579. D3D12_RESOURCE_STATE_COMMON,
  7580. None,
  7581. &mut buffer,
  7582. )
  7583. .and_then(|()| {
  7584. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7585. b.Map(0, None, Some(&mut data))
  7586. })
  7587. };
  7588. match made {
  7589. Ok(()) => Some((buffer?, data.cast())),
  7590. Err(e) => {
  7591. tracing::warn!(error = %e, size, "no shared buffer");
  7592. None
  7593. }
  7594. }
  7595. }
  7596. /// Whether buffers can lie in the card's memory and be mapped by the CPU
  7597. /// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver
  7598. /// that offer it); logged once.
  7599. pub(crate) fn mapped_card_memory(&self) -> bool {
  7600. static THERE: OnceLock<bool> = OnceLock::new();
  7601. *THERE.get_or_init(|| {
  7602. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default();
  7603. // SAFETY: writes `options` of the given size.
  7604. let ok = unsafe {
  7605. self.device
  7606. .CheckFeatureSupport(
  7607. D3D12_FEATURE_D3D12_OPTIONS16,
  7608. (&raw mut options).cast(),
  7609. size_of_val(&options) as u32,
  7610. )
  7611. .is_ok()
  7612. };
  7613. let supported = ok && options.GPUUploadHeapSupported.as_bool();
  7614. tracing::info!(supported, "card memory the CPU maps");
  7615. supported
  7616. })
  7617. }
  7618. /// A buffer in the card's own memory that the CPU maps, shaders read and
  7619. /// (with `written`) may write. The CPU should only write it: a read of the
  7620. /// mapping crosses the bus a few bytes at a time.
  7621. pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> {
  7622. if !self.mapped_card_memory() {
  7623. return None;
  7624. }
  7625. MADE[4].fetch_add(1, Ordering::Relaxed);
  7626. MADE[5].fetch_add(size, Ordering::Relaxed);
  7627. let heap = D3D12_HEAP_PROPERTIES {
  7628. Type: D3D12_HEAP_TYPE_GPU_UPLOAD,
  7629. ..Default::default()
  7630. };
  7631. let desc = D3D12_RESOURCE_DESC {
  7632. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7633. Width: size.max(1),
  7634. Height: 1,
  7635. DepthOrArraySize: 1,
  7636. MipLevels: 1,
  7637. SampleDesc: DXGI_SAMPLE_DESC {
  7638. Count: 1,
  7639. Quality: 0,
  7640. },
  7641. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7642. Flags: if written {
  7643. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
  7644. } else {
  7645. D3D12_RESOURCE_FLAG_NONE
  7646. },
  7647. ..Default::default()
  7648. };
  7649. let mut buffer: Option<ID3D12Resource> = None;
  7650. let mut data = std::ptr::null_mut();
  7651. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7652. let made = unsafe {
  7653. self.device
  7654. .CreateCommittedResource(
  7655. &heap,
  7656. D3D12_HEAP_FLAG_NONE,
  7657. &desc,
  7658. D3D12_RESOURCE_STATE_COMMON,
  7659. None,
  7660. &mut buffer,
  7661. )
  7662. .and_then(|()| {
  7663. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7664. b.Map(0, None, Some(&mut data))
  7665. })
  7666. };
  7667. match made {
  7668. Ok(()) => Some((buffer?, data.cast())),
  7669. Err(e) => {
  7670. tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps");
  7671. None
  7672. }
  7673. }
  7674. }
  7675. /// A device-local buffer shaders may write (unordered access) and indirect
  7676. /// execution may read, starting in the common state.
  7677. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7678. MADE[4].fetch_add(1, Ordering::Relaxed);
  7679. MADE[5].fetch_add(size, Ordering::Relaxed);
  7680. let heap = D3D12_HEAP_PROPERTIES {
  7681. Type: D3D12_HEAP_TYPE_DEFAULT,
  7682. ..Default::default()
  7683. };
  7684. let desc = D3D12_RESOURCE_DESC {
  7685. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7686. Width: size.max(1),
  7687. Height: 1,
  7688. DepthOrArraySize: 1,
  7689. MipLevels: 1,
  7690. SampleDesc: DXGI_SAMPLE_DESC {
  7691. Count: 1,
  7692. Quality: 0,
  7693. },
  7694. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7695. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7696. ..Default::default()
  7697. };
  7698. let mut buffer: Option<ID3D12Resource> = None;
  7699. // SAFETY: plain creation of a device-local buffer.
  7700. let made = unsafe {
  7701. self.device.CreateCommittedResource(
  7702. &heap,
  7703. D3D12_HEAP_FLAG_NONE,
  7704. &desc,
  7705. D3D12_RESOURCE_STATE_COMMON,
  7706. None,
  7707. &mut buffer,
  7708. )
  7709. };
  7710. match made {
  7711. Ok(()) => buffer,
  7712. Err(e) => {
  7713. tracing::warn!(error = %e, size, "no unordered-access buffer");
  7714. None
  7715. }
  7716. }
  7717. }
  7718. }
  7719. /// For adapters without device-removed data (the software one): the last
  7720. /// commands each list of the failed submission noted (diagnostics, with
  7721. /// `VICTORY_D3D12_DRED`).
  7722. fn last_notes(runs: &[&HostList]) -> String {
  7723. #[cfg(feature = "diagnostics")]
  7724. {
  7725. let mut text = String::new();
  7726. for (i, r) in runs.iter().enumerate() {
  7727. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  7728. for (n, _) in notes.iter().rev().take(6).rev() {
  7729. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  7730. }
  7731. }
  7732. text
  7733. }
  7734. #[cfg(not(feature = "diagnostics"))]
  7735. {
  7736. let _ = runs;
  7737. String::new()
  7738. }
  7739. }
  7740. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  7741. /// command reads (diagnostics).
  7742. #[cfg(feature = "diagnostics")]
  7743. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  7744. let end = start + bytes;
  7745. if va < start {
  7746. format!(" (fault {:#x} below its source)", start - va)
  7747. } else if va < end {
  7748. format!(" (fault at source +{:#x})", va - start)
  7749. } else {
  7750. format!(" (fault {:#x} past its source's end)", va - end)
  7751. }
  7752. }
  7753. /// The commands that may have been running where a list stopped at
  7754. /// command `done`: those between the barriers around it (work between
  7755. /// barriers overlaps on the GPU), by kind, and what the markers just
  7756. /// before them say (`HostList::note_op`: diagnostics builds with
  7757. /// device-removed data on).
  7758. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  7759. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  7760. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  7761. let to = history[done..]
  7762. .iter()
  7763. .position(barrier)
  7764. .map_or(history.len(), |b| (done + b).max(done + 1));
  7765. let mut text = format!(", commands {from}..{to} between its barriers:");
  7766. let mut shown = 0;
  7767. // From just before the command the GPU had not finished: the first
  7768. // twelve after the barrier named draws long done when a list of 79
  7769. // mesh draws stopped at its 45th (run 41).
  7770. for i in from.max(done.saturating_sub(4))..to {
  7771. let op = history[i];
  7772. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  7773. continue;
  7774. }
  7775. shown += 1;
  7776. let marker = i
  7777. .checked_sub(1)
  7778. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  7779. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  7780. .map_or("no marker", |(_, s)| s.as_str());
  7781. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  7782. }
  7783. text
  7784. }
  7785. pub(crate) fn transition(
  7786. resource: &ID3D12Resource,
  7787. before: D3D12_RESOURCE_STATES,
  7788. after: D3D12_RESOURCE_STATES,
  7789. ) -> D3D12_RESOURCE_BARRIER {
  7790. D3D12_RESOURCE_BARRIER {
  7791. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  7792. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  7793. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  7794. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  7795. // SAFETY: a borrowed pointer; the barrier never releases it.
  7796. pResource: unsafe { std::mem::transmute_copy(resource) },
  7797. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  7798. StateBefore: before,
  7799. StateAfter: after,
  7800. }),
  7801. },
  7802. }
  7803. }
  7804. /// A window of the given client size, owned by its own message thread.
  7805. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7806. let (sender, receiver) = std::sync::mpsc::channel();
  7807. std::thread::Builder::new()
  7808. .name("victory-window".into())
  7809. .spawn(move || {
  7810. let made = make_window(width, height);
  7811. let ok = made.is_ok();
  7812. let _ = sender.send(made.map(|h| h.0 as usize));
  7813. if ok {
  7814. pump();
  7815. }
  7816. })
  7817. .map_err(|_| windows::core::Error::empty())?;
  7818. let hwnd = receiver
  7819. .recv()
  7820. .map_err(|_| windows::core::Error::empty())??;
  7821. Ok(HWND(hwnd as *mut _))
  7822. }
  7823. extern "system" fn window_proc(
  7824. hwnd: HWND,
  7825. message: u32,
  7826. wparam: WPARAM,
  7827. lparam: LPARAM,
  7828. ) -> LRESULT {
  7829. // SAFETY: the default handling for our window.
  7830. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  7831. }
  7832. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7833. const CLASS: PCWSTR = w!("VIctory");
  7834. // SAFETY: registers our class once and creates a window of it.
  7835. unsafe {
  7836. let instance = GetModuleHandleW(None)?;
  7837. let class = WNDCLASSEXW {
  7838. cbSize: size_of::<WNDCLASSEXW>() as u32,
  7839. lpfnWndProc: Some(window_proc),
  7840. hInstance: instance.into(),
  7841. lpszClassName: CLASS,
  7842. hCursor: LoadCursorW(None, IDC_ARROW)?,
  7843. ..Default::default()
  7844. };
  7845. RegisterClassExW(&class);
  7846. let mut rect = RECT {
  7847. left: 0,
  7848. top: 0,
  7849. right: width as i32,
  7850. bottom: height as i32,
  7851. };
  7852. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  7853. CreateWindowExW(
  7854. WINDOW_EX_STYLE(0),
  7855. CLASS,
  7856. w!("VIctory"),
  7857. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  7858. CW_USEDEFAULT,
  7859. CW_USEDEFAULT,
  7860. rect.right - rect.left,
  7861. rect.bottom - rect.top,
  7862. None,
  7863. None,
  7864. Some(instance.into()),
  7865. None,
  7866. )
  7867. }
  7868. }
  7869. fn pump() {
  7870. let mut message = MSG::default();
  7871. // SAFETY: the standard message loop of this thread's window.
  7872. unsafe {
  7873. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  7874. let _ = TranslateMessage(&message);
  7875. DispatchMessageW(&message);
  7876. }
  7877. }
  7878. }
  7879. #[cfg(test)]
  7880. mod trail {
  7881. /// The trail keeps the newest things, and the report made when the
  7882. /// host device is removed says them and the pipeline library's state
  7883. /// (no card is asked for any of it).
  7884. #[test]
  7885. fn the_removal_report_says_the_newest_things_done() {
  7886. for n in 0..super::TRAIL_MOST + 5 {
  7887. super::trail(|| format!("thing {n} done"));
  7888. }
  7889. let text = super::removal_context();
  7890. assert!(text.contains("the submitting thread was"));
  7891. assert!(text.contains("pipeline library: no call running"));
  7892. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  7893. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  7894. }
  7895. }
  7896. #[cfg(test)]
  7897. mod spare {
  7898. use super::Spare;
  7899. /// Kept things come back by size, the last given first, and nothing is
  7900. /// kept past the limit.
  7901. #[test]
  7902. fn kept_things_come_back_by_size_within_the_limit() {
  7903. let mut spare: Spare<u32> = Spare::new();
  7904. assert_eq!(spare.take(4), None);
  7905. assert_eq!(spare.give(1, 4, 10), None);
  7906. assert_eq!(spare.give(2, 1, 10), None);
  7907. assert_eq!(spare.give(3, 4, 10), None);
  7908. assert_eq!(spare.bytes, 9);
  7909. // Past the limit: handed back, nothing changes.
  7910. assert_eq!(spare.give(4, 4, 10), Some(4));
  7911. assert_eq!(spare.bytes, 9);
  7912. assert_eq!(spare.take(2), None, "no thing of that size");
  7913. assert_eq!(spare.take(4), Some(3));
  7914. assert_eq!(spare.take(4), Some(1));
  7915. assert_eq!(spare.take(4), None);
  7916. assert_eq!(spare.take(1), Some(2));
  7917. assert_eq!(spare.bytes, 0);
  7918. assert!(spare.kept.is_empty());
  7919. }
  7920. }
  7921. #[cfg(test)]
  7922. mod refresh_tests {
  7923. use super::Batch;
  7924. use crate::shadow::Shadow;
  7925. use std::sync::Arc;
  7926. use windows_sys::Win32::System::Memory::{
  7927. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  7928. VirtualAlloc,
  7929. };
  7930. const PAGE: usize = 64 << 10;
  7931. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  7932. /// Title memory for the tests (never given back: copies of it stay in
  7933. /// the guards): write-watched, or a view of a section.
  7934. fn title(len: usize, view: bool) -> usize {
  7935. // SAFETY: plain allocations.
  7936. let at = unsafe {
  7937. if view {
  7938. let section =
  7939. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  7940. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  7941. // As the runtime tells of it.
  7942. crate::title_memory_section(section as usize, len as u64, true);
  7943. crate::title_memory_remapped(at, len);
  7944. crate::title_memory_view(at, len, section as usize, 0);
  7945. at
  7946. } else {
  7947. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  7948. }
  7949. };
  7950. assert_ne!(at, 0);
  7951. at
  7952. }
  7953. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  7954. /// and every fourth page not there: as a title that streams has it.
  7955. fn with_holes(blocks: usize) -> usize {
  7956. use windows_sys::Win32::System::Memory::{
  7957. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  7958. VirtualAlloc2, VirtualFree,
  7959. };
  7960. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7961. // SAFETY: a placeholder and a section of our own.
  7962. unsafe {
  7963. let at = VirtualAlloc2(
  7964. GetCurrentProcess(),
  7965. std::ptr::null(),
  7966. blocks * PAGE,
  7967. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  7968. PAGE_NOACCESS,
  7969. std::ptr::null_mut(),
  7970. 0,
  7971. ) as usize;
  7972. assert_ne!(at, 0);
  7973. let len = blocks * PAGE;
  7974. let section =
  7975. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  7976. for block in (0..blocks).filter(|b| b % 4 != 3) {
  7977. let to = at + block * PAGE;
  7978. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  7979. let view = MapViewOfFile3(
  7980. section,
  7981. GetCurrentProcess(),
  7982. to as *const _,
  7983. (block * PAGE) as u64,
  7984. PAGE,
  7985. MEM_REPLACE_PLACEHOLDER,
  7986. PAGE_READWRITE,
  7987. std::ptr::null_mut(),
  7988. 0,
  7989. );
  7990. assert_eq!(view.Value as usize, to);
  7991. crate::title_memory_remapped(to, PAGE);
  7992. }
  7993. at
  7994. }
  7995. }
  7996. fn memory(len: usize) -> *mut u8 {
  7997. // SAFETY: a plain allocation.
  7998. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  7999. }
  8000. struct Random(u64);
  8001. impl Random {
  8002. fn below(&mut self, n: usize) -> usize {
  8003. self.0 ^= self.0 << 13;
  8004. self.0 ^= self.0 >> 7;
  8005. self.0 ^= self.0 << 17;
  8006. (self.0 >> 11) as usize % n
  8007. }
  8008. }
  8009. /// Prepares as a submission does: one asking for all the ranges, the
  8010. /// refreshes in several flushes, the asking's end.
  8011. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  8012. // One at a time, as submissions are.
  8013. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  8014. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  8015. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  8016. crate::watch::ask_once(&asked);
  8017. let mut batch = Batch::default();
  8018. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  8019. for (shadow, at, len) in part {
  8020. batch.add(shadow, *at, *len);
  8021. }
  8022. batch.flush();
  8023. }
  8024. crate::watch::ask_once_end();
  8025. }
  8026. /// Whatever is written where, by the title or by us, and whichever
  8027. /// copies (of both kinds of memory, over one another, none on a page
  8028. /// line) are refreshed in which ranges: a refreshed range holds what
  8029. /// title memory holds.
  8030. #[test]
  8031. fn refreshed_ranges_hold_title_memory() {
  8032. // SAFETY (all blocks): title memory and copies of the test's own,
  8033. // written by this thread and, in `Batch::flush`, by the threads that
  8034. // refresh, which are done when it returns.
  8035. let mut random = Random(0x1234_5678_9ABC_DEF1);
  8036. const LEN: usize = 24 * PAGE;
  8037. let regions = [title(LEN, false), title(LEN, true)];
  8038. let mut copies = Vec::new();
  8039. for &region in &regions {
  8040. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  8041. let data = memory(to - from);
  8042. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  8043. }
  8044. }
  8045. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  8046. for round in 0..600 {
  8047. for _ in 0..random.below(4) {
  8048. let at = regions[random.below(2)] + random.below(LEN - 64);
  8049. let n = 1 + random.below(60);
  8050. if random.below(3) == 0 {
  8051. // What shaders wrote.
  8052. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  8053. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  8054. Shadow::put(at, &was, &now);
  8055. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  8056. continue;
  8057. }
  8058. for i in 0..n {
  8059. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  8060. }
  8061. }
  8062. let mut ranges = Vec::new();
  8063. for (shadow, _) in &copies {
  8064. if random.below(3) == 0 {
  8065. continue;
  8066. }
  8067. let (start, len) = shadow.span();
  8068. let (start, len) = (start as usize, len as usize);
  8069. // Often the range of the time before, as a list's is.
  8070. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  8071. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  8072. ranges.push((shadow.clone(), start + from, n));
  8073. }
  8074. if ranges.is_empty() {
  8075. continue;
  8076. }
  8077. let flushes = 1 + random.below(3);
  8078. submission(&ranges, flushes);
  8079. for (shadow, at, n) in &ranges {
  8080. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  8081. let start = shadow.span().0 as usize;
  8082. let same = unsafe {
  8083. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  8084. };
  8085. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  8086. }
  8087. }
  8088. }
  8089. /// A copy in the card's memory, with the card's side and the sends to it
  8090. /// played by the test.
  8091. struct Carded {
  8092. shadow: Arc<Shadow>,
  8093. data: usize,
  8094. start: usize,
  8095. len: usize,
  8096. /// The last send, the last send every fetch to come is behind, and
  8097. /// the card's bytes: the queue's order is the order it is locked in.
  8098. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  8099. /// Whether a flight that writes it has not landed.
  8100. flying: std::sync::atomic::AtomicBool,
  8101. /// The dword of each eight its shaders write.
  8102. class: usize,
  8103. }
  8104. impl Carded {
  8105. fn new(start: usize, len: usize, class: usize) -> Carded {
  8106. let data = memory(len);
  8107. Carded {
  8108. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  8109. data: data as usize,
  8110. start,
  8111. len,
  8112. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  8113. flying: std::sync::atomic::AtomicBool::new(false),
  8114. class,
  8115. }
  8116. }
  8117. /// What changed on the CPU's side goes up.
  8118. fn send(&self) {
  8119. let mut card = self.card.lock().unwrap();
  8120. card.0 += 1;
  8121. let (number, merged) = (card.0, card.1);
  8122. for (a, b) in self.shadow.send_up(number, merged) {
  8123. // SAFETY: the copy's bytes; nothing writes those that are to
  8124. // go up.
  8125. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  8126. }
  8127. }
  8128. }
  8129. /// Everything at once: the title writes its memory on two threads, the
  8130. /// submitting thread puts its bytes in under shader writes
  8131. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  8132. /// the card's memory, one not), sends up what changed and declares what
  8133. /// the next flight's shaders write, and what flights wrote is landed
  8134. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  8135. /// still and the copies are refreshed once more, each of them, and the
  8136. /// card's side of those that have one, hold what title memory holds, and
  8137. /// title memory what was written last.
  8138. ///
  8139. /// Into the first copy shaders write besides through a view nobody
  8140. /// declared, words the title does not write: nothing that goes up ever
  8141. /// puts an older value over those.
  8142. ///
  8143. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  8144. /// only takes the block out of the guards' clean ones and leaves its bit,
  8145. /// or if a fault leaves the bit; in some thousand rounds,
  8146. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  8147. #[test]
  8148. fn landings_title_writes_and_light_refreshes_at_once() {
  8149. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  8150. assert!(crate::safecopy::on());
  8151. const LEN: usize = 24 * PAGE;
  8152. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  8153. let region = title(LEN, true);
  8154. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  8155. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  8156. let plain = {
  8157. let (start, len) = (region + 700, LEN - 9000);
  8158. let data = memory(len);
  8159. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  8160. };
  8161. // What was last written so, by offset.
  8162. let mut undeclared = std::collections::HashMap::new();
  8163. let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0");
  8164. let stop = AtomicBool::new(false);
  8165. // Also when an assertion fails on one of the threads.
  8166. struct Stop<'a>(&'a AtomicBool);
  8167. impl Drop for Stop<'_> {
  8168. fn drop(&mut self) {
  8169. self.0.store(true, Ordering::Relaxed);
  8170. }
  8171. }
  8172. // Held shared by who writes title memory, alone while it is looked at.
  8173. let still = std::sync::RwLock::new(());
  8174. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  8175. std::thread::scope(|s| {
  8176. for t in 0..2usize {
  8177. let (stop, still) = (&stop, &still);
  8178. s.spawn(move || {
  8179. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  8180. let mut value = 0u32;
  8181. while !stop.load(Ordering::Relaxed) {
  8182. {
  8183. let _moving = still.read().unwrap();
  8184. for _ in 0..3 {
  8185. value += 1;
  8186. // Of each eight dwords, one a thread.
  8187. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  8188. dword(at).store(value, Ordering::Relaxed);
  8189. }
  8190. }
  8191. std::thread::sleep(std::time::Duration::from_micros(20));
  8192. }
  8193. });
  8194. }
  8195. // Lands flights.
  8196. {
  8197. let (carded, stop) = (&carded, &stop);
  8198. s.spawn(move || {
  8199. let _stop = Stop(stop);
  8200. while let Ok((which, ranges, value)) = flights.recv() {
  8201. let c = &carded[which];
  8202. // Fetched: the card's bytes, behind every send so far.
  8203. let (after, now) = {
  8204. let card = c.card.lock().unwrap();
  8205. (card.0, card.2.clone())
  8206. };
  8207. // By piece: 64 KiB of title memory.
  8208. let mut pieces = Vec::new();
  8209. for &(from, to) in &ranges {
  8210. let mut at = from;
  8211. while at < to {
  8212. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  8213. pieces.push((at, next, now.as_ptr() as usize + at));
  8214. at = next;
  8215. }
  8216. }
  8217. let parts: Vec<_> = pieces.chunks(3).collect();
  8218. crate::land::each(parts.len(), &|i| {
  8219. let mut notes = crate::land::Notes::default();
  8220. // SAFETY: the bytes of `now`; each piece once.
  8221. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  8222. notes.flush();
  8223. });
  8224. for &(from, to) in &ranges {
  8225. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8226. // (The next fetch may have brought more.)
  8227. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  8228. }
  8229. }
  8230. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  8231. c.shadow.copy_back_done(&done);
  8232. c.card.lock().unwrap().1 = after;
  8233. c.flying.store(false, Ordering::Release);
  8234. }
  8235. });
  8236. }
  8237. let _stop = Stop(&stop);
  8238. let mut random = Random(0xABCD_EF01_2345_6789);
  8239. let check = |round: usize, random: &mut Random, quiet: bool| {
  8240. for c in &carded {
  8241. if c.shadow.writes_pending() {
  8242. let mut runs = usize::MAX;
  8243. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  8244. }
  8245. }
  8246. let mut ranges = Vec::new();
  8247. for (shadow, start, len) in
  8248. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  8249. {
  8250. // All of it, or a part; often the same part.
  8251. let (from, n) = match random.below(3) {
  8252. _ if quiet => (0, len),
  8253. 0 => (0, len),
  8254. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  8255. _ => {
  8256. let from = random.below(len / 4) * 4;
  8257. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  8258. }
  8259. };
  8260. ranges.push((shadow.clone(), start + from, n));
  8261. }
  8262. submission(&ranges, 1 + random.below(3));
  8263. carded.iter().for_each(Carded::send);
  8264. };
  8265. let mut value = 1u32;
  8266. for round in 0..rounds {
  8267. check(round, &mut random, false);
  8268. if exact {
  8269. let c = &carded[0];
  8270. let mut card = c.card.lock().unwrap();
  8271. for _ in 0..40 {
  8272. value += 1;
  8273. let at = random.below(LEN / 32) * 32 + 4 * 6;
  8274. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8275. undeclared.insert(at, value);
  8276. }
  8277. }
  8278. // The flight of this submission: its shaders' writes.
  8279. for (which, c) in carded.iter().enumerate() {
  8280. if c.flying.swap(true, Ordering::Acquire) {
  8281. continue;
  8282. }
  8283. value += 1;
  8284. let mut ranges: Vec<(usize, usize)> = Vec::new();
  8285. let first = random.below(6) * PAGE / 2;
  8286. for k in 0..2 {
  8287. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  8288. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  8289. if from < to {
  8290. ranges.push((from, to));
  8291. }
  8292. }
  8293. for &(from, to) in &ranges {
  8294. c.shadow.writing(c.start + from, to - from);
  8295. }
  8296. {
  8297. let mut card = c.card.lock().unwrap();
  8298. for &(from, to) in &ranges {
  8299. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8300. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8301. }
  8302. }
  8303. }
  8304. fly.send((which, ranges, value)).unwrap();
  8305. }
  8306. if round % 20 != 19 {
  8307. continue;
  8308. }
  8309. // Still: no flight in the air, no title write.
  8310. let _still = still.write().unwrap();
  8311. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  8312. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  8313. std::thread::yield_now();
  8314. }
  8315. check(round, &mut random, true);
  8316. // SAFETY: the test's own memory, written by nobody now.
  8317. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  8318. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  8319. for c in &carded {
  8320. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  8321. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  8322. let card = c.card.lock().unwrap();
  8323. let mut side = card.2.clone();
  8324. if c.class == carded[0].class {
  8325. // (They may have been landed meanwhile, by a flight
  8326. // that declared their range, and may not.)
  8327. for (&at, &value) in &undeclared {
  8328. let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
  8329. assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
  8330. side[at..at + 4].copy_from_slice(&there[at..at + 4]);
  8331. }
  8332. }
  8333. assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
  8334. }
  8335. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  8336. }
  8337. drop(fly);
  8338. });
  8339. }
  8340. /// The title's bytes put in under shader writes, for a copy of 174 MB
  8341. /// whose shader writes were declared as 40 ranges that overlap, with 12
  8342. /// pages written since. Run with `--ignored --nocapture`, and with
  8343. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8344. #[test]
  8345. #[ignore]
  8346. fn bytes_under_overlapping_ranges() {
  8347. const BIG: usize = 174 << 20;
  8348. let big = title(BIG, true);
  8349. // SAFETY (both): the test's own memory.
  8350. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  8351. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8352. copy.update(big, BIG);
  8353. copy.take_dirty();
  8354. for i in 0..40 {
  8355. copy.writing(big + i * 5920, BIG - i * 5920);
  8356. }
  8357. let mut best = f64::MAX;
  8358. for round in 0..30 {
  8359. for i in 0..12 {
  8360. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  8361. }
  8362. let started = std::time::Instant::now();
  8363. let mut runs = usize::MAX;
  8364. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  8365. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  8366. copy.take_dirty();
  8367. }
  8368. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  8369. }
  8370. /// A range nothing wrote is known to be as it was, at its ends too, and
  8371. /// is so no more once something wrote it.
  8372. #[test]
  8373. fn unchanged_ranges_are_known() {
  8374. for view in [false, true] {
  8375. let region = title(8 * PAGE, view);
  8376. // (A page read for the first time counts as written.)
  8377. // SAFETY: the test's own memory.
  8378. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  8379. let data = memory(8 * PAGE);
  8380. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  8381. // Ends in the middle of pages.
  8382. let (at, len) = (region + 500, 5 * PAGE);
  8383. let look = |expected: bool, what: &str| {
  8384. // The submission's one asking, which takes two ranges. (Again
  8385. // if a submission of another test ended it.)
  8386. let mut known = false;
  8387. for _ in 0..100 {
  8388. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  8389. known = copy.nothing_new(at, len);
  8390. if known || !expected {
  8391. break;
  8392. }
  8393. }
  8394. assert_eq!(known, expected, "view {view}: {what}");
  8395. let copied = copy.update(at, len);
  8396. crate::watch::ask_once_end();
  8397. copied
  8398. };
  8399. assert_eq!(look(false, "never taken"), len);
  8400. assert_eq!(look(true, "taken"), 0);
  8401. assert_eq!(look(true, "taken"), 0);
  8402. // SAFETY: the test's own memory.
  8403. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  8404. assert_eq!(look(false, "written at its end"), PAGE - 500);
  8405. assert_eq!(look(true, "taken again"), 0);
  8406. // Outside the range, on its last page.
  8407. // SAFETY: as above.
  8408. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  8409. assert_eq!(look(false, "written on its last page"), 500);
  8410. // A longer range was never taken whole.
  8411. assert!(!copy.nothing_new(region, 6 * PAGE));
  8412. }
  8413. }
  8414. /// Of a copy in the card's memory only the dwords title memory changed go
  8415. /// up, and none beside them, not even between two in 64 bytes; a page
  8416. /// never taken goes up whole.
  8417. #[test]
  8418. fn only_what_differs_goes_up() {
  8419. let region = title(4 * PAGE, true);
  8420. let data = memory(4 * PAGE);
  8421. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  8422. copy.update(region, 4 * PAGE);
  8423. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  8424. // What the relay does: shader writes into title memory, and into the
  8425. // CPU's side.
  8426. crate::watch::landing(region + PAGE + 640, 64);
  8427. // SAFETY: the test's own memory.
  8428. unsafe {
  8429. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  8430. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  8431. }
  8432. copy.update(region, 4 * PAGE);
  8433. let again = copy.take_dirty();
  8434. // SAFETY: as above.
  8435. unsafe {
  8436. ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
  8437. ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
  8438. ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
  8439. // The value that was there.
  8440. ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
  8441. }
  8442. copy.update(region, 4 * PAGE);
  8443. let written = copy.take_dirty();
  8444. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") {
  8445. assert_eq!(again, []);
  8446. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
  8447. } else {
  8448. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  8449. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  8450. }
  8451. // SAFETY: as above.
  8452. assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
  8453. }
  8454. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  8455. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  8456. /// big copy that 55 landed pieces and 9 title writes opened, while a
  8457. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  8458. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8459. #[test]
  8460. #[ignore]
  8461. fn frame_of_refreshes() {
  8462. let mut random = Random(0x9876_5432_1234_5671);
  8463. const EACH: usize = 224 << 10;
  8464. const BIG: usize = 174 << 20;
  8465. let watched = title(3000 * EACH, false);
  8466. // `VICTORY_BENCH_HOLES=0`: views without holes.
  8467. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  8468. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  8469. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  8470. let big = title(BIG, true);
  8471. // SAFETY: the test's own memory.
  8472. unsafe {
  8473. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  8474. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  8475. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  8476. }
  8477. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  8478. }
  8479. let mut small = Vec::new();
  8480. for i in 0..4400 {
  8481. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  8482. let data = memory(EACH);
  8483. // The range views read, not all of the copy.
  8484. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  8485. }
  8486. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  8487. // The same memory, as another copy: what is landed is landed through
  8488. // it, and the refreshes are of the first.
  8489. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8490. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  8491. let (mut sum, mut landing) = (0.0, 0.0);
  8492. const FRAMES: usize = 12;
  8493. for frame in 0..FRAMES {
  8494. let mut took = [0f64; 2];
  8495. for i in 0..30 {
  8496. // The title's writes, and the relay's beside the submission.
  8497. for _ in 0..9 {
  8498. let at = views + random.below(1400 * EACH / 8) * 8;
  8499. if there(at) {
  8500. // SAFETY: the test's own memory.
  8501. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8502. }
  8503. }
  8504. for _ in 0..60 {
  8505. let at = watched + random.below(3000 * EACH / 8) * 8;
  8506. // SAFETY: the test's own memory.
  8507. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8508. }
  8509. let first = random.below(BIG / PAGE - 60);
  8510. let lands = lands.clone();
  8511. let land = std::thread::spawn(move || {
  8512. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  8513. let started = std::time::Instant::now();
  8514. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  8515. let pieces: Vec<_> =
  8516. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  8517. let mut notes = crate::land::Notes::default();
  8518. // SAFETY: the bytes of `now`; nothing else lands here.
  8519. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  8520. notes.flush();
  8521. }
  8522. started.elapsed().as_secs_f64() * 1e3
  8523. });
  8524. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  8525. small.iter().cloned().chain([heap.clone()]).collect()
  8526. } else {
  8527. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  8528. };
  8529. let started = std::time::Instant::now();
  8530. submission(&ranges, 3);
  8531. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  8532. let put = land.join().unwrap();
  8533. if frame >= 2 {
  8534. landing += put;
  8535. }
  8536. heap.0.take_dirty();
  8537. }
  8538. if frame >= 2 {
  8539. sum += took[0] + took[1];
  8540. for k in 0..2 {
  8541. best[k] = best[k].min(took[k]);
  8542. asking[k] += took[k];
  8543. }
  8544. }
  8545. }
  8546. println!(
  8547. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  8548. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  8549. crate::watch::light(),
  8550. sum / (FRAMES - 2) as f64,
  8551. asking[0] / (FRAMES - 2) as f64,
  8552. best[0],
  8553. asking[1] / (FRAMES - 2) as f64,
  8554. best[1],
  8555. landing / (FRAMES - 2) as f64,
  8556. );
  8557. #[cfg(feature = "diagnostics")]
  8558. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  8559. }
  8560. }
  8561. #[cfg(test)]
  8562. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  8563. use super::Batch;
  8564. use std::sync::Arc;
  8565. #[test]
  8566. fn a_texture_is_checked_once_per_submission() {
  8567. let mut batch = Batch::default();
  8568. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  8569. // The first list sampling each texture checks it ...
  8570. assert!(batch.texture_due(&a));
  8571. assert!(batch.texture_due(&b));
  8572. // ... later lists of the same submission do not.
  8573. assert!(!batch.texture_due(&a));
  8574. assert!(!batch.texture_due(&a.clone()));
  8575. assert!(!batch.texture_due(&b));
  8576. }
  8577. #[test]
  8578. fn title_writes_make_textures_due_again() {
  8579. let mut batch = Batch::default();
  8580. let a = Arc::new(1u32);
  8581. assert!(batch.texture_due(&a));
  8582. assert!(!batch.texture_due(&a));
  8583. // A copy into title memory or work that may write it may have
  8584. // changed the texture's memory.
  8585. batch.title_written();
  8586. assert!(batch.texture_due(&a));
  8587. assert!(!batch.texture_due(&a));
  8588. // A fresh submission starts over.
  8589. let mut next = Batch::default();
  8590. assert!(next.texture_due(&a));
  8591. }
  8592. /// The hashing a submission does for textures in physical-page memory,
  8593. /// with every list checking the textures it samples (before) and with
  8594. /// each checked once (after). Run with
  8595. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  8596. #[test]
  8597. #[ignore = "benchmark"]
  8598. fn texture_checks_per_submission() {
  8599. const TEXTURES: usize = 48;
  8600. const SIZE: usize = 4 << 20;
  8601. const LISTS: usize = 12;
  8602. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  8603. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  8604. .collect();
  8605. let submit = |dedupe: bool| {
  8606. let mut batch = Batch::default();
  8607. let mut hashed = 0usize;
  8608. let started = std::time::Instant::now();
  8609. for _ in 0..LISTS {
  8610. for t in &textures {
  8611. if !dedupe || batch.texture_due(t) {
  8612. std::hint::black_box(blake3::hash(t));
  8613. hashed += 1;
  8614. }
  8615. }
  8616. }
  8617. (started.elapsed(), hashed)
  8618. };
  8619. submit(false); // warm up
  8620. let (before, n_before) = submit(false);
  8621. let (after, n_after) = submit(true);
  8622. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  8623. println!(
  8624. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  8625. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  8626. SIZE >> 20,
  8627. before.as_secs_f64() / after.as_secs_f64()
  8628. );
  8629. }
  8630. #[test]
  8631. fn vram_idle_ms_scales_with_pressure() {
  8632. let vram_idle_ms = |memory| super::vram_idle_for(memory, false);
  8633. let keeps = |memory| super::vram_idle_for(memory, true);
  8634. let gib = 1024 * 1024 * 1024;
  8635. assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000);
  8636. assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000);
  8637. assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500);
  8638. assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000);
  8639. assert_eq!(keeps(None), 5_000);
  8640. // Normal (< 75%)
  8641. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  8642. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  8643. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  8644. // Moderate (75%..85%)
  8645. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  8646. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  8647. // High (>= 85%, including over-budget)
  8648. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  8649. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  8650. // Missing or zero budget falls back to normal
  8651. assert_eq!(vram_idle_ms(None), 5_000);
  8652. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  8653. }
  8654. #[test]
  8655. fn ram_idle_ms_scales_with_pressure() {
  8656. use super::ram_idle_ms;
  8657. let gib = 1024 * 1024 * 1024;
  8658. // Normal (>= 4 GiB)
  8659. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  8660. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  8661. // Moderate (2 GiB..4 GiB)
  8662. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  8663. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  8664. // High (< 2 GiB)
  8665. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  8666. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  8667. // Missing falls back to normal
  8668. assert_eq!(ram_idle_ms(None), 10_000);
  8669. }
  8670. }