host.rs 297 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920
  1. //! The host GPU: one D3D12 device and direct queue (decision 0007), and a
  2. //! window to present on.
  3. //!
  4. //! shortcut: every submission is waited for, so CPU and GPU never overlap
  5. //! (unless `VICTORY_LATE_WAIT=1`, see [`late`]);
  6. //! overlap them with per-submission fences once more than clears run.
  7. use std::sync::atomic::{AtomicU32, Ordering};
  8. use std::sync::{Mutex, OnceLock};
  9. use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
  10. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  11. use windows::Win32::Graphics::Direct3D12::*;
  12. use windows::Win32::Graphics::Dxgi::Common::*;
  13. use windows::Win32::Graphics::Dxgi::*;
  14. use windows::Win32::System::LibraryLoader::GetModuleHandleW;
  15. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  16. use windows::Win32::UI::WindowsAndMessaging::*;
  17. use windows::core::{Interface, PCWSTR, w};
  18. /// Resource states without the console's own bits (compression hints from
  19. /// bit 25 up), which the host rejects.
  20. pub(crate) fn pc_state(state: u32) -> u32 {
  21. state & 0x01ff_ffff
  22. }
  23. /// A console state as a host texture state: PC bits only, and none of the
  24. /// buffer-only ones the console allows on textures (vertex, constant and
  25. /// index buffer, stream out, indirect arguments, as in "generic read").
  26. pub(crate) fn texture_state(state: u32) -> u32 {
  27. const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
  28. pc_state(state) & !BUFFER_ONLY
  29. }
  30. /// Render target views live only until their command is recorded, so a
  31. /// ring of host descriptors is enough.
  32. const RTV_RING: u32 = 1024;
  33. pub(crate) struct Host {
  34. pub(crate) device: ID3D12Device,
  35. queue: ID3D12CommandQueue,
  36. fence: ID3D12Fence,
  37. /// The last value signalled on `fence`, behind the submission lock.
  38. submitted: Mutex<u64>,
  39. event: HANDLE,
  40. rtvs: ID3D12DescriptorHeap,
  41. rtv_size: u32,
  42. /// A ring of depth views, used as `rtvs`.
  43. dsvs: ID3D12DescriptorHeap,
  44. dsv_size: u32,
  45. next_dsv: AtomicU32,
  46. /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug
  47. /// layer's messages.
  48. messages: Option<ID3D12InfoQueue>,
  49. next_rtv: AtomicU32,
  50. presenter: Mutex<Option<Presenter>>,
  51. /// The adapter the device is on, for its memory budget
  52. /// ([`Host::video_memory`]); `None` if the system does not name it.
  53. adapter: Option<IDXGIAdapter3>,
  54. }
  55. // SAFETY: D3D12 devices, queues, fences and descriptor heaps are
  56. // free-threaded; the event handle is only waited on under `submitted`.
  57. unsafe impl Send for Host {}
  58. // SAFETY: as above.
  59. unsafe impl Sync for Host {}
  60. /// Host objects the title let go of while a submission may still use them
  61. /// (a texture its descriptors name, a descriptor slot's old resource), by
  62. /// the submission count they wait for. The title's descriptor writes and
  63. /// releases reach the host at once, from its own threads, while the host
  64. /// runs a submission: freeing there is a GPU page fault on the freed
  65. /// texture (a device hang).
  66. static RETIRED: Mutex<Vec<(u64, Retired)>> = Mutex::new(Vec::new());
  67. /// Submissions started and finished (waited for).
  68. static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  69. static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  70. /// A retired object, dropped on whatever thread finishes the submission.
  71. struct Retired(#[allow(dead_code)] Box<dyn std::any::Any>);
  72. // SAFETY: what is retired is D3D12 objects (free-threaded) and the
  73. // reference-counted wrappers holding them, dropped once.
  74. unsafe impl Send for Retired {}
  75. /// Milliseconds since the first call.
  76. pub(crate) fn now_ms() -> u64 {
  77. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  78. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  79. }
  80. /// This moment, for telling later how long ago it was ([`long_ago`]): the
  81. /// frames begun so far (high half, `crate::frame::current`) and tenths of a
  82. /// second since the start. Host copies of title memory, staging buffers and
  83. /// host textures note when they were last used with it.
  84. pub(crate) fn moment() -> u64 {
  85. (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff)
  86. }
  87. /// Whether `moment` lies at least `ms` milliseconds and `frames` frames
  88. /// back. Both: at seconds per frame, what every frame uses is not touched
  89. /// for seconds, and at many frames per second not for many frames. (A title
  90. /// that never waits for frames has no frame count: nothing is then idle.)
  91. pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
  92. let now = self::moment();
  93. let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
  94. (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
  95. }
  96. /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
  97. pub(crate) fn available_physical_ram() -> Option<u64> {
  98. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  99. // SAFETY: plain data the call fills in.
  100. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  101. m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
  102. // SAFETY: a sized structure.
  103. let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
  104. ok.then_some(m.ullAvailPhys)
  105. }
  106. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  107. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  108. /// handles not yet recorded into a list or slot remain protected.
  109. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  110. const NORMAL_MS: u64 = 5_000;
  111. const MODERATE_MS: u64 = 2_500;
  112. const HIGH_MS: u64 = 1_000;
  113. let Some([budget, used, ..]) = video_memory else {
  114. return NORMAL_MS;
  115. };
  116. if budget == 0 {
  117. return NORMAL_MS;
  118. }
  119. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  120. if used_pct >= 85 {
  121. HIGH_MS
  122. } else if used_pct >= 75 {
  123. MODERATE_MS
  124. } else {
  125. NORMAL_MS
  126. }
  127. }
  128. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  129. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  130. /// when free physical RAM is low. Never returns less than 2,000 ms.
  131. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  132. const GIB: u64 = 1024 * 1024 * 1024;
  133. const NORMAL_MS: u64 = 10_000;
  134. const MODERATE_MS: u64 = 5_000;
  135. const HIGH_MS: u64 = 2_000;
  136. let Some(avail) = avail_phys else {
  137. return NORMAL_MS;
  138. };
  139. if avail < 2 * GIB {
  140. HIGH_MS
  141. } else if avail < 4 * GIB {
  142. MODERATE_MS
  143. } else {
  144. NORMAL_MS
  145. }
  146. }
  147. /// How many references are held on a host object (its COM count): ours
  148. /// all, since the host's views and commands hold none. A buffer or texture
  149. /// with one is held by its owner alone: no descriptor slot keeps it
  150. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  151. pub(crate) fn references(object: &impl Interface) -> u32 {
  152. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  153. let raw = object.as_raw();
  154. // SAFETY: a live COM object, whose first three methods are those of
  155. // `IUnknown` (query, add a reference, release one); the pair leaves the
  156. // count as it was, and the release returns it. The first is not called.
  157. unsafe {
  158. let methods = *raw.cast::<*const [Method; 3]>();
  159. ((*methods)[1])(raw);
  160. ((*methods)[2])(raw)
  161. }
  162. }
  163. /// Once a second, before a submission starts: lets go of what nothing
  164. /// names any more (copies of windows of title memory, staging buffers,
  165. /// host copies of textures the title fills).
  166. /// `VICTORY_SWEEP=0` keeps everything, as before.
  167. fn sweep() {
  168. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  169. crate::inplace::tick();
  170. static ON: OnceLock<bool> = OnceLock::new();
  171. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  172. return;
  173. }
  174. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  175. let now = now_ms();
  176. let last = LAST.load(Ordering::Relaxed);
  177. if now < last + 1000
  178. || LAST
  179. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  180. .is_err()
  181. {
  182. return;
  183. }
  184. crate::pipeline::trim_library();
  185. crate::shadow::let_go_idle();
  186. crate::texture::let_go_idle();
  187. crate::resource::let_go_idle();
  188. }
  189. /// Drops `object` once every submission running now has finished: at once
  190. /// if none is.
  191. pub(crate) fn retire<T: 'static>(object: T) {
  192. let started = STARTED.load(Ordering::Acquire);
  193. if started <= FINISHED.load(Ordering::Acquire) {
  194. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  195. drop(object);
  196. return;
  197. }
  198. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  199. RETIRED
  200. .lock()
  201. .unwrap_or_else(|e| e.into_inner())
  202. .push((started, Retired(Box::new(object))));
  203. }
  204. /// Drops what waited for submissions up to `finished`.
  205. fn bury(finished: u64) {
  206. let done: Vec<(u64, Retired)> = {
  207. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  208. if retired.is_empty() {
  209. return;
  210. }
  211. let (done, keep) = std::mem::take(&mut *retired)
  212. .into_iter()
  213. .partition(|(at, _)| *at <= finished);
  214. *retired = keep;
  215. done
  216. };
  217. drop(done);
  218. }
  219. /// Objects [`retire`] dropped at once (no submission was running) and
  220. /// kept until a running submission finished, since the start.
  221. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  222. /// What the layer did to the host's objects lately, newest last (sweeps
  223. /// that let host copies go, pipeline library calls, saves and trims): said
  224. /// once when the host device is removed ([`log_removal_context`]), with
  225. /// what the submitting thread and the pipeline workers were doing at that
  226. /// moment. A device the driver removes "internally" names no command, and
  227. /// the pass that happens to notice first names only the view it was at:
  228. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  229. /// pipeline library call that no line of the log tied to them.
  230. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  231. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  232. /// The entries kept.
  233. const TRAIL_MOST: usize = 96;
  234. fn trail_on() -> bool {
  235. static ON: OnceLock<bool> = OnceLock::new();
  236. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  237. }
  238. /// Microseconds since the first call.
  239. pub(crate) fn now_us() -> u64 {
  240. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  241. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  242. }
  243. /// The calling thread, as the log's other lines name threads.
  244. pub(crate) fn thread_id() -> u32 {
  245. // SAFETY: a plain query.
  246. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  247. }
  248. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  249. /// run when the trail is kept.
  250. pub(crate) fn trail(what: impl FnOnce() -> String) {
  251. if !trail_on() {
  252. return;
  253. }
  254. let entry = (now_us(), thread_id(), what());
  255. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  256. if trail.len() >= TRAIL_MOST {
  257. trail.pop_front();
  258. }
  259. trail.push_back(entry);
  260. }
  261. /// What the submitting thread is doing (0 nothing: between submissions,
  262. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  263. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  264. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  265. fn submitting(phase: u64, lists: usize) {
  266. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  267. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  268. SUBMITTING[0].store(phase, Ordering::Relaxed);
  269. }
  270. /// What was going on when the host device went: whether a submission was
  271. /// on the card, the pipeline library's state and the calls running in it,
  272. /// and the trail.
  273. pub(crate) fn removal_context() -> String {
  274. use std::fmt::Write;
  275. let now = now_us();
  276. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  277. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  278. 0 => "between submissions (nothing of ours was running on the card)",
  279. 1 => "preparing a submission (nothing of ours was running on the card)",
  280. 2 => "waiting for the card to run a submission",
  281. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  282. };
  283. let mut text = format!(
  284. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  285. SUBMITTING[1].load(Ordering::Relaxed),
  286. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  287. crate::pipeline::library_removal_note(),
  288. RETIREMENTS[0].load(Ordering::Relaxed),
  289. RETIREMENTS[1].load(Ordering::Relaxed),
  290. STARTED.load(Ordering::Relaxed),
  291. FINISHED.load(Ordering::Relaxed),
  292. );
  293. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  294. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  295. for (at, thread, what) in trail.iter() {
  296. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  297. }
  298. text
  299. }
  300. /// Says [`removal_context`] in the log, once: called by whoever finds the
  301. /// host device removed.
  302. pub(crate) fn log_removal_context() {
  303. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  304. if !trail_on() || SAID.swap(true, Ordering::Relaxed) {
  305. return;
  306. }
  307. tracing::error!("when the host device went: {}", removal_context());
  308. }
  309. /// Time spent in submissions since the last frame-rate line, in
  310. /// microseconds: preparing them on the CPU (title memory copies, texture
  311. /// detiling), then waiting for the GPU.
  312. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  313. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  314. /// After submissions: shader-written ranges compared and copied back into
  315. /// title memory (microseconds, bytes that differed), since the last
  316. /// frame-rate line.
  317. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  318. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  319. /// The card's clock, for the frame line of every run, in microseconds since
  320. /// the last one: how long the card had nothing of ours queued; how much of
  321. /// that while the thread that holds the submission lock was working (the
  322. /// card idle behind us: preparing and copying back are done with the card
  323. /// standing); and how long that thread stood waiting for the card.
  324. ///
  325. /// Every send of lists to the queue is followed by a signal on a fence of
  326. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  327. /// the newest signal and notes the moment the card reached it with nothing
  328. /// newer sent; the next send ends that idle stretch.
  329. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  330. /// Of the thread that holds the submission lock: the microseconds it has
  331. /// worked so far (preparing, copying back; not its waits for the card), and
  332. /// since when it works now ([`now_us`] plus one; 0: it does not).
  333. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  334. /// The thread that holds the submission lock starts (`on`) or stops
  335. /// working; whether it worked until now.
  336. fn working(on: bool) -> bool {
  337. let now = now_us() + 1;
  338. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  339. if since != 0 {
  340. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  341. }
  342. since != 0
  343. }
  344. /// [`WORKING`] as of now: microseconds worked so far.
  345. fn worked() -> u64 {
  346. let since = WORKING[1].load(Ordering::Relaxed);
  347. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  348. WORKING[0].load(Ordering::Relaxed) + now
  349. }
  350. /// The thread that holds the submission lock stood waiting for the card
  351. /// from `since` until now ([`CARD_CLOCK_US`]).
  352. fn stood(since: std::time::Instant) {
  353. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  354. }
  355. /// What [`CARD_CLOCK_US`] is measured with.
  356. struct CardClock {
  357. fence: ID3D12Fence,
  358. /// Signals sent so far; and, while the card has reached the last of
  359. /// them, since when and what [`worked`] said then.
  360. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  361. sent: std::sync::Condvar,
  362. }
  363. // SAFETY: a fence (free-threaded) behind a lock.
  364. unsafe impl Send for CardClock {}
  365. // SAFETY: as above.
  366. unsafe impl Sync for CardClock {}
  367. /// The clock's thread: waits for the newest signal sent and notes when the
  368. /// card got there with nothing newer behind it.
  369. fn card_clock_watch(clock: &'static CardClock) {
  370. // SAFETY: a plain event of our own.
  371. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  372. return;
  373. };
  374. let mut seen = 0;
  375. loop {
  376. let target = {
  377. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  378. while state.0 == seen {
  379. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  380. }
  381. state.0
  382. };
  383. // SAFETY: the clock's fence and this thread's event.
  384. unsafe {
  385. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  386. WaitForSingleObject(event, INFINITE);
  387. }
  388. }
  389. seen = target;
  390. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  391. if state.0 == target && state.1.is_none() {
  392. state.1 = Some((std::time::Instant::now(), worked()));
  393. }
  394. }
  395. }
  396. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  397. /// frame's time.
  398. fn card_clock_line(frames: f64, ms: f64) {
  399. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  400. tracing::info!(
  401. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  402. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  403. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  404. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  405. );
  406. }
  407. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  408. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  409. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  410. std::sync::atomic::AtomicU64::new(0),
  411. std::sync::atomic::AtomicU64::new(0),
  412. std::sync::atomic::AtomicU64::new(0),
  413. std::sync::atomic::AtomicU64::new(0),
  414. ];
  415. /// Host buffers made since the start, as (count, bytes): in the upload heap
  416. /// (staging, list scratch), shared with the processor (host copies of title
  417. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  418. /// For the memory line: against what is alive, they show what was let go.
  419. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  420. /// What of that is alive now, for the memory line (`MADE` counts what was
  421. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  422. /// and nothing said how many were alive): host lists; the lists' scratch
  423. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  424. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  425. /// instead of made, since the start; and the lists' other upload buffers
  426. /// (texture data copied from buffers, scratch too big for a chunk) and
  427. /// their bytes.
  428. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  429. /// About host lists, for the memory line: lists made by the host since the
  430. /// start; preludes made (a list's second allocator and list, made when it
  431. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  432. /// bytes the process's private memory grew by while lists were being made
  433. /// (what a list costs: host objects with the driver's command memory; 631
  434. /// lists were alive in run 65, each with a prelude it may never use).
  435. /// Then the lists alive that were never reset since they were made: the
  436. /// host sides of title lists the title made and has not used (a host list
  437. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  438. /// makes at its start).
  439. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  440. /// The process's private bytes (diagnostics: around the making of lists).
  441. #[cfg(feature = "diagnostics")]
  442. fn private_bytes() -> u64 {
  443. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  444. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  445. let mut c = PROCESS_MEMORY_COUNTERS {
  446. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  447. ..Default::default()
  448. };
  449. // SAFETY: our own process and a sized structure.
  450. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  451. c.PagefileUsage as u64
  452. }
  453. /// What the runtime does when the host GPU fails for good: report it like a
  454. /// crash and end the run. The console has no such state, and carrying on
  455. /// draws nothing at seconds per frame.
  456. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  457. /// Sets what a host GPU failure does (the runtime's crash report).
  458. pub fn on_failure(report: fn(&str) -> !) {
  459. let _ = ON_FAILURE.set(report);
  460. }
  461. /// Ends the run on a host GPU failure: what failed, the removal reason and
  462. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  463. /// diagnostics build names the command).
  464. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  465. let mut text = what.to_string();
  466. if let Some(host) = host() {
  467. // SAFETY: a plain query.
  468. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  469. text.push_str(&format!("; device removed: {e}"));
  470. log_removal_context();
  471. }
  472. match host.log_messages() {
  473. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  474. None if host.messages.is_none() => text.push_str(
  475. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  476. ),
  477. None => {}
  478. }
  479. }
  480. tracing::error!("{text}");
  481. // Tests have no log: the reason goes to their output.
  482. #[cfg(test)]
  483. eprintln!("host GPU failure: {text}");
  484. match ON_FAILURE.get() {
  485. Some(report) => report(&text),
  486. None => std::process::abort(),
  487. }
  488. }
  489. /// The host GPU, created on first use; `None` without one (a run then
  490. /// behaves as before: nothing executes).
  491. pub(crate) fn host() -> Option<&'static Host> {
  492. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  493. HOST.get_or_init(|| match create() {
  494. Ok(host) => Some(host),
  495. Err(e) => {
  496. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  497. None
  498. }
  499. })
  500. .as_ref()
  501. }
  502. fn create() -> windows::core::Result<Host> {
  503. // SAFETY: plain D3D12 object creation with valid descriptions.
  504. unsafe {
  505. // The debug layer only in builds with diagnostics.
  506. let debug =
  507. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some();
  508. if debug {
  509. let mut layer: Option<ID3D12Debug> = None;
  510. match D3D12GetDebugInterface(&mut layer) {
  511. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  512. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  513. }
  514. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  515. // descriptor heap indices and the like become messages naming
  516. // the command instead of page faults. Without state tracking
  517. // (directly indexed textures are not transitioned).
  518. if std::env::var_os("VICTORY_D3D12_GBV").is_some()
  519. && let Some(l) = &layer
  520. {
  521. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  522. d1.SetEnableGPUBasedValidation(true);
  523. }
  524. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  525. d2.SetGPUBasedValidationFlags(
  526. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  527. );
  528. }
  529. tracing::info!("GPU-based validation on");
  530. }
  531. }
  532. // Diagnostics: device-removed data (the command that faulted, the
  533. // faulting address), read when the device is removed.
  534. if dred_on() {
  535. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  536. if D3D12GetDebugInterface(&mut dred).is_ok()
  537. && let Some(dred) = dred
  538. {
  539. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  540. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  541. }
  542. }
  543. let mut device: Option<ID3D12Device> = None;
  544. // Diagnostics: the software adapter, on which a shader's wild access
  545. // is an access violation in this process (a crash report with the
  546. // address and instruction) instead of a GPU fault and driver reset.
  547. if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() {
  548. let adapter = warp_adapter()?;
  549. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  550. tracing::info!("host device on the software adapter (WARP)");
  551. } else {
  552. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  553. }
  554. let device = device.ok_or_else(windows::core::Error::empty)?;
  555. // Before anything is made with it (`VICTORY_RECORD`).
  556. #[cfg(feature = "diagnostics")]
  557. crate::replay::record::from_env(&device);
  558. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  559. // driver compiling shaders again on the "D3D Background Thread"s,
  560. // for minutes after pipelines were made or loaded) is switched off.
  561. // An experiment: while those threads ran, the same shot took
  562. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  563. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  564. // whether the card is slower with the shaders it then keeps is not
  565. // known.
  566. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  567. && let Ok(device6) = device.cast::<ID3D12Device6>()
  568. {
  569. let set = device6.SetBackgroundProcessingMode(
  570. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  571. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  572. None,
  573. None,
  574. );
  575. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  576. }
  577. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  578. // cross-lane code stays in 32-lane halves translated for waves of 32
  579. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  580. if device
  581. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  582. .is_ok()
  583. {
  584. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  585. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  586. }
  587. let messages = debug
  588. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  589. .flatten();
  590. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  591. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  592. ..Default::default()
  593. })?;
  594. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  595. let event = CreateEventW(None, false, false, None)?;
  596. let rtvs: ID3D12DescriptorHeap =
  597. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  598. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  599. NumDescriptors: RTV_RING,
  600. ..Default::default()
  601. })?;
  602. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  603. let dsvs: ID3D12DescriptorHeap =
  604. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  605. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  606. NumDescriptors: RTV_RING,
  607. ..Default::default()
  608. })?;
  609. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  610. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  611. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  612. .ok();
  613. tracing::info!("host D3D12 device ready");
  614. Ok(Host {
  615. device,
  616. queue,
  617. fence,
  618. submitted: Mutex::new(0),
  619. event,
  620. rtvs,
  621. rtv_size,
  622. dsvs,
  623. dsv_size,
  624. next_dsv: AtomicU32::new(0),
  625. messages,
  626. next_rtv: AtomicU32::new(0),
  627. presenter: Mutex::new(None),
  628. adapter,
  629. })
  630. }
  631. }
  632. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  633. /// Reject it before creating a device in diagnostics' software-only mode.
  634. fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  635. // SAFETY: plain DXGI adapter queries.
  636. unsafe {
  637. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  638. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  639. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  640. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  641. tracing::warn!(
  642. vendor = format_args!("{:#x}", desc.VendorId),
  643. flags = format_args!("{:#x}", desc.Flags),
  644. "DXGI did not identify the WARP adapter as software; refusing device"
  645. );
  646. return Err(windows::core::Error::from_hresult(
  647. windows::Win32::Foundation::E_FAIL,
  648. ));
  649. }
  650. Ok(adapter)
  651. }
  652. }
  653. #[cfg(test)]
  654. mod tests {
  655. #[test]
  656. fn sparse_copies_preserve_islands_and_observe_remaps() {
  657. use windows_sys::Win32::System::Memory::*;
  658. const N: usize = 5 << 16;
  659. // SAFETY: we reserve a private region, commit selected pages inside it,
  660. // and only directly access the pages while they are writable.
  661. unsafe {
  662. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  663. assert!(!base.is_null());
  664. let mut expected = vec![0; N];
  665. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  666. let at = base.add(offset);
  667. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  668. at.write_bytes(value, 4096);
  669. expected[offset..offset + 4096].fill(value);
  670. }
  671. for remap in [false, true] {
  672. if remap {
  673. let mut old = 0;
  674. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  675. expected[..4096].fill(0);
  676. let at = base.add(1 << 16);
  677. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  678. at.write_bytes(0xc7, 4096);
  679. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  680. }
  681. let mut out = vec![0xee; N];
  682. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  683. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  684. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  685. }
  686. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  687. }
  688. }
  689. use super::*;
  690. #[test]
  691. fn warp_adapter_accepts_only_software() {
  692. // This probes DXGI without creating a D3D12 device or running a title.
  693. // SAFETY: plain DXGI adapter queries.
  694. let raw = unsafe {
  695. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  696. else {
  697. return;
  698. };
  699. factory.EnumWarpAdapter::<IDXGIAdapter>()
  700. };
  701. let Ok(raw) = raw else { return };
  702. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  703. // IDXGIAdapter1; `raw` owns that interface.
  704. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  705. eprintln!(
  706. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  707. desc.VendorId, desc.Flags
  708. );
  709. assert_eq!(
  710. warp_adapter().is_ok(),
  711. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  712. );
  713. }
  714. }
  715. /// A host command list and its allocator, always used together.
  716. pub(crate) struct HostList {
  717. allocator: ID3D12CommandAllocator,
  718. pub(crate) list: ID3D12GraphicsCommandList,
  719. /// Work for submission time, in recorded order.
  720. deferred: Mutex<Deferred>,
  721. /// Upload memory for data the list's draws make (expanded vertices),
  722. /// reused after a reset.
  723. scratch: Mutex<Scratch>,
  724. /// Host texture states the list assumes, by host copy: at its start and
  725. /// at its end. Lists are recorded on many threads and run in submission
  726. /// order, so the transitions from a texture's real state are made at
  727. /// submission, in `prelude`. Holding the copies keeps every texture the
  728. /// list names alive until it is reset, even if the title releases the
  729. /// resource first.
  730. states: Mutex<States>,
  731. /// What the list does with depth textures that have a colour twin, by
  732. /// twin ([`TwinUse`]).
  733. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  734. /// The list that runs those transitions just before this one, made
  735. /// when the list first has such transitions ([`lazy_prelude`]).
  736. prelude: OnceLock<Option<Prelude>>,
  737. /// The pipelines the list binds, for reports of slow submissions.
  738. pipelines: Mutex<std::collections::BTreeSet<String>>,
  739. /// The work its indirect executions may still do (`indirect`): a
  740. /// shader-writable word, zeroed when the list is submitted, and after
  741. /// it what the clamp notes about mesh records. In memory the CPU maps.
  742. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  743. /// The same words in the card's own memory ([`card_budget`]), which the
  744. /// clamp uses instead when there is one: zeroed in the list before its
  745. /// first clamp, its notes copied to `budget` when the list closes.
  746. card_budget: OnceLock<Option<ID3D12Resource>>,
  747. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  748. /// grown to the largest indirect execution recorded on the list.
  749. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  750. /// Counts the list in [`ALIVE`] while it lives.
  751. _alive: Counted,
  752. /// The texts of the markers `note_op` set, in order (for device-removed
  753. /// data without marker texts), with the host GPU range a copy reads.
  754. #[cfg(feature = "diagnostics")]
  755. notes: Mutex<Vec<Note>>,
  756. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  757. /// and at the end, and where they are read back.
  758. #[cfg(feature = "diagnostics")]
  759. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  760. }
  761. /// A list's prelude: an allocator and a closed list.
  762. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  763. /// Whether a host list's prelude is made when the list first needs one. A
  764. /// prelude runs the texture transitions and twin copies a list needs before
  765. /// it; lists that name no texture never have one, and every host list was
  766. /// made with one all the same: twice the host objects per list, for the
  767. /// title's 630 lists and for every list made anew.
  768. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  769. fn lazy_prelude() -> bool {
  770. static ON: OnceLock<bool> = OnceLock::new();
  771. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  772. }
  773. /// Timestamps per list (diagnostics); commands past them are not timed.
  774. #[cfg(feature = "diagnostics")]
  775. const STAMPS: u32 = 4096;
  776. /// A marker's text and the host range its command reads (diagnostics).
  777. #[cfg(feature = "diagnostics")]
  778. type Note = (String, Option<(u64, u64)>);
  779. type States = std::collections::HashMap<
  780. usize,
  781. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  782. >;
  783. /// What a list does with a depth texture that has a colour twin
  784. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  785. /// in submission order, so a list cannot know which side an earlier list
  786. /// leaves behind: it notes which sides it uses as it finds them, and its
  787. /// prelude copies one side into the other at submission if that side is
  788. /// behind then. From its first use of a side on, the list knows.
  789. struct TwinUse {
  790. /// The depth texture (the title resource's host copy) and its twin.
  791. depth: std::sync::Arc<crate::resource::HostTexture>,
  792. twin: std::sync::Arc<crate::resource::Twin>,
  793. /// The sides (depth texture, twin) the list uses as it finds them.
  794. needs: [bool; 2],
  795. /// Whether each side lacks what the other was written last, where the
  796. /// list is now; `None`: as the list found it.
  797. behind: [Option<bool>; 2],
  798. /// The draw or dispatch being prepared writes the twin.
  799. writing: bool,
  800. /// The depth plane's twin holds what the plane lacks although the list
  801. /// copied the twins since: the plane's pass waits for the list's close.
  802. late: bool,
  803. }
  804. /// The pass that draws the twin of a depth plane into the plane: one
  805. /// triangle over each mip of each slice, its pixel shader writing the
  806. /// twin's texel as the depth, with the depth test "always" and no stencil
  807. /// (the stencil plane is copied through a buffer and not touched here).
  808. ///
  809. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  810. /// the step times the float nearest 1/65535 (0x37800080). That is how
  811. /// The title's tiled lighting computes the depth of the
  812. /// rectangles it then draws with the test "equal", one class of materials
  813. /// a draw (all six of its vertex shaders multiply the class number by that
  814. /// constant), so the pass and the draw give the host the same float, and
  815. /// the host turns the same float into the same 24 bits. The step divided
  816. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  817. /// and lands in another 24-bit step for 127 of them (none under 385).
  818. const PLANE_CORNERS: &str = r#"
  819. float4 corner(uint i : SV_VertexID) : SV_Position {
  820. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  821. }
  822. "#;
  823. const PLANE_STEPS: &str = r#"
  824. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  825. Texture2DArray<uint> twin : register(t0);
  826. [RootSignature(RS)]
  827. float plane(float4 p : SV_Position) : SV_Depth {
  828. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  829. }
  830. "#;
  831. const PLANE_FLOATS: &str = r#"
  832. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  833. Texture2DArray<float> twin : register(t0);
  834. [RootSignature(RS)]
  835. float plane(float4 p : SV_Position) : SV_Depth {
  836. return twin.Load(int4(int2(p.xy), 0, 0));
  837. }
  838. "#;
  839. /// Views of twins the pass reads, in a heap of ours used as a ring.
  840. /// shortcut: a view must last until its list has run; with one or two
  841. /// passes a frame the ring is far from coming round.
  842. const PLANE_VIEWS: u32 = 256;
  843. /// What the pass draws with: the heap of its views of twins, and per kind
  844. /// of twin (16-bit steps or floats) and depth format the root signature
  845. /// and pipeline, made when first needed (`None`: the host refused).
  846. struct PlanePass {
  847. views: ID3D12DescriptorHeap,
  848. cpu: usize,
  849. gpu: u64,
  850. step: u32,
  851. next: AtomicU32,
  852. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  853. }
  854. /// The pass's root signature and pipeline for one kind of twin and one
  855. /// depth format.
  856. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  857. // SAFETY: D3D12 objects are free-threaded.
  858. unsafe impl Send for PlanePass {}
  859. // SAFETY: as above.
  860. unsafe impl Sync for PlanePass {}
  861. fn plane_pass() -> Option<&'static PlanePass> {
  862. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  863. PASS.get_or_init(|| {
  864. let host = host()?;
  865. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  866. // SAFETY: plain heap creation and queries.
  867. unsafe {
  868. let views: ID3D12DescriptorHeap = host
  869. .device
  870. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  871. Type: kind,
  872. NumDescriptors: PLANE_VIEWS,
  873. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  874. NodeMask: 0,
  875. })
  876. .ok()?;
  877. Some(PlanePass {
  878. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  879. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  880. step: host.device.GetDescriptorHandleIncrementSize(kind),
  881. views,
  882. next: AtomicU32::new(0),
  883. made: Mutex::default(),
  884. })
  885. }
  886. })
  887. .as_ref()
  888. }
  889. /// Compiles function `entry` of `source` for `target` with the system's
  890. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  891. pub(crate) fn compile(
  892. source: &str,
  893. entry: windows::core::PCSTR,
  894. target: windows::core::PCSTR,
  895. ) -> windows::core::Result<Vec<u8>> {
  896. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  897. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  898. let mut code: Option<ID3DBlob> = None;
  899. let mut errors: Option<ID3DBlob> = None;
  900. // SAFETY: the source and names live through the call; out pointers ours.
  901. let compiled = unsafe {
  902. D3DCompile(
  903. source.as_ptr().cast(),
  904. source.len(),
  905. windows::core::s!("victory"),
  906. None,
  907. None,
  908. entry,
  909. target,
  910. 0,
  911. 0,
  912. &mut code,
  913. Some(&mut errors),
  914. )
  915. };
  916. if let Err(e) = compiled {
  917. if let Some(errors) = errors {
  918. // SAFETY: the blob's own bytes.
  919. let text = unsafe {
  920. std::slice::from_raw_parts(
  921. errors.GetBufferPointer().cast::<u8>(),
  922. errors.GetBufferSize(),
  923. )
  924. };
  925. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  926. }
  927. return Err(e);
  928. }
  929. let code = code.ok_or_else(windows::core::Error::empty)?;
  930. // SAFETY: the blob's own bytes.
  931. let bytes = unsafe {
  932. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  933. };
  934. Ok(bytes.to_vec())
  935. }
  936. impl PlanePass {
  937. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  938. /// or of floats and the depth format `format`.
  939. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  940. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  941. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  942. return pipeline.clone();
  943. }
  944. let pipeline = match Self::make(steps, format) {
  945. Ok(pipeline) => Some(pipeline),
  946. Err(e) => {
  947. tracing::warn!(
  948. error = %e,
  949. steps,
  950. format = format.0,
  951. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  952. );
  953. None
  954. }
  955. };
  956. made.push((steps, format.0, pipeline.clone()));
  957. pipeline
  958. }
  959. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  960. use windows::core::s;
  961. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  962. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  963. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  964. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  965. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  966. pShaderBytecode: bytes.as_ptr().cast(),
  967. BytecodeLength: bytes.len(),
  968. };
  969. // SAFETY: the root signature is inside the pixel shader; the
  970. // description points at live data and never releases its pointer.
  971. unsafe {
  972. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  973. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  974. pRootSignature: std::mem::transmute_copy(&root),
  975. VS: code(&vs[..]),
  976. PS: code(&ps[..]),
  977. SampleMask: u32::MAX,
  978. RasterizerState: D3D12_RASTERIZER_DESC {
  979. FillMode: D3D12_FILL_MODE_SOLID,
  980. CullMode: D3D12_CULL_MODE_NONE,
  981. DepthClipEnable: true.into(),
  982. ..Default::default()
  983. },
  984. // Every texel is written; stencil stays off.
  985. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  986. DepthEnable: true.into(),
  987. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  988. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  989. ..Default::default()
  990. },
  991. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  992. DSVFormat: format,
  993. SampleDesc: DXGI_SAMPLE_DESC {
  994. Count: 1,
  995. Quality: 0,
  996. },
  997. ..Default::default()
  998. };
  999. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1000. Ok((root, pipeline))
  1001. }
  1002. }
  1003. }
  1004. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1005. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1006. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1007. /// heap, graphics root signature, pipeline, depth target, viewport,
  1008. /// scissor and topology and puts none of them back: it is for a list that
  1009. /// records nothing of the title's after it.
  1010. fn record_plane_pass(
  1011. list: &ID3D12GraphicsCommandList,
  1012. depth: &ID3D12Resource,
  1013. plane: &ID3D12Resource,
  1014. ) {
  1015. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1016. return;
  1017. };
  1018. // SAFETY: live resources.
  1019. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1020. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1021. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1022. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1023. let steps = twin.Format.0 == 53;
  1024. let format = DXGI_FORMAT(match of.Format.0 {
  1025. 44 => 45,
  1026. 19 => 20,
  1027. typed => typed,
  1028. });
  1029. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1030. return;
  1031. };
  1032. for slice in 0..u32::from(of.DepthOrArraySize) {
  1033. for mip in 0..u32::from(of.MipLevels) {
  1034. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1035. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1036. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1037. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1038. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1039. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1040. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1041. MostDetailedMip: mip,
  1042. MipLevels: 1,
  1043. FirstArraySlice: slice,
  1044. ArraySize: 1,
  1045. ..Default::default()
  1046. },
  1047. },
  1048. };
  1049. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1050. Format: format,
  1051. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1052. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1053. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1054. MipSlice: mip,
  1055. FirstArraySlice: slice,
  1056. ArraySize: 1,
  1057. },
  1058. },
  1059. ..Default::default()
  1060. };
  1061. let target = host.dsv(depth, Some(&target));
  1062. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1063. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1064. ptr: pass.cpu + (slot * pass.step) as usize,
  1065. };
  1066. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1067. ptr: pass.gpu + u64::from(slot * pass.step),
  1068. };
  1069. // SAFETY: an open list; a slot of our heap; live resources and
  1070. // objects (the pass's own live as long as the process).
  1071. unsafe {
  1072. host.device
  1073. .CreateShaderResourceView(plane, Some(&view), cpu);
  1074. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1075. list.SetGraphicsRootSignature(&root);
  1076. list.SetPipelineState(&pipeline);
  1077. list.SetGraphicsRootDescriptorTable(0, gpu);
  1078. list.OMSetRenderTargets(0, None, false, Some(&target));
  1079. list.RSSetViewports(&[D3D12_VIEWPORT {
  1080. TopLeftX: 0.0,
  1081. TopLeftY: 0.0,
  1082. Width: width as f32,
  1083. Height: height as f32,
  1084. MinDepth: 0.0,
  1085. MaxDepth: 1.0,
  1086. }]);
  1087. list.RSSetScissorRects(&[RECT {
  1088. left: 0,
  1089. top: 0,
  1090. right: width as i32,
  1091. bottom: height as i32,
  1092. }]);
  1093. list.IASetPrimitiveTopology(
  1094. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1095. );
  1096. list.DrawInstanced(3, 1, 0, 0);
  1097. }
  1098. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1099. }
  1100. }
  1101. }
  1102. /// Records into `list` the copy of a depth texture into its colour twin
  1103. /// (`colour`) or of the twin into the depth texture, both already in their
  1104. /// copy states: whole textures of one size in one format family, which the
  1105. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1106. /// alone, through the twin's buffer.
  1107. fn record_twin_copy(
  1108. list: &ID3D12GraphicsCommandList,
  1109. depth: &ID3D12Resource,
  1110. twin: &crate::resource::Twin,
  1111. colour: bool,
  1112. ) {
  1113. let (from, to) = if colour {
  1114. (depth, &twin.colour.texture)
  1115. } else {
  1116. (&twin.colour.texture, depth)
  1117. };
  1118. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1119. // shortcut: the depth plane's twin is not given the plane (that is a
  1120. // pass the other way: the plane read by a shader, the twin as its
  1121. // target). The twin then lacks what draws and clears wrote to the
  1122. // plane since shaders last wrote the twin. In the title
  1123. // nothing writes that plane but the twin's pass (its 192 draws against
  1124. // it only test, run 29), so the twin lacks nothing. Counted.
  1125. if colour && twin.plane.is_some() {
  1126. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1127. }
  1128. let Some(through) = &twin.through else {
  1129. // SAFETY: an open list and two live textures.
  1130. unsafe { list.CopyResource(to, from) };
  1131. return;
  1132. };
  1133. // A stencil plane and its twin: each mip and slice of the plane goes
  1134. // into the buffer, laid out as the host lays the plane out for copies,
  1135. // and from the buffer into the other texture, whole subresources both
  1136. // times. In the depth texture the stencil plane's subresources follow
  1137. // the depth plane's; the twin has the one plane.
  1138. let Some(host) = host() else { return };
  1139. // SAFETY: a live texture.
  1140. let of = unsafe { depth.GetDesc() };
  1141. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1142. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1143. // SAFETY: a plain query writing `planes` footprints.
  1144. unsafe {
  1145. host.device.GetCopyableFootprints(
  1146. &of,
  1147. planes,
  1148. planes,
  1149. 0,
  1150. Some(rows.as_mut_ptr()),
  1151. None,
  1152. None,
  1153. None,
  1154. );
  1155. }
  1156. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1157. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1158. // SAFETY: a borrowed pointer the location never releases.
  1159. pResource: unsafe { std::mem::transmute_copy(texture) },
  1160. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1161. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1162. SubresourceIndex: index,
  1163. },
  1164. };
  1165. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1166. // SAFETY: as above.
  1167. pResource: unsafe { std::mem::transmute_copy(through) },
  1168. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1169. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1170. PlacedFootprint: *row,
  1171. },
  1172. };
  1173. let (common, source, dest) = (
  1174. D3D12_RESOURCE_STATE_COMMON,
  1175. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1176. D3D12_RESOURCE_STATE_COPY_DEST,
  1177. );
  1178. // SAFETY: an open list and live resources; the buffer was made as big
  1179. // as these footprints, and rests in the common state between copies.
  1180. unsafe {
  1181. list.ResourceBarrier(&[transition(through, common, dest)]);
  1182. for (i, row) in rows.iter().enumerate() {
  1183. let index = first_from + i as u32;
  1184. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1185. }
  1186. list.ResourceBarrier(&[transition(through, dest, source)]);
  1187. for (i, row) in rows.iter().enumerate() {
  1188. let index = first_to + i as u32;
  1189. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1190. }
  1191. list.ResourceBarrier(&[transition(through, source, common)]);
  1192. }
  1193. }
  1194. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1195. /// builds).
  1196. pub(crate) fn dred_on() -> bool {
  1197. static ON: OnceLock<bool> = OnceLock::new();
  1198. *ON.get_or_init(|| {
  1199. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some()
  1200. })
  1201. }
  1202. /// Indirect mesh dispatches since the last frame line: the largest group
  1203. /// count a record asked for, and the groups asked in all (from the lists'
  1204. /// budget buffers, a run late).
  1205. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1206. /// Whether a list's indirect-work budget lives in the card's own memory
  1207. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1208. /// before). The clamp charges it with atomics, at least two in a row for
  1209. /// every clamp; in mapped memory on a card of its own each of them
  1210. /// crosses the bus.
  1211. fn card_budget() -> bool {
  1212. static ON: OnceLock<bool> = OnceLock::new();
  1213. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1214. }
  1215. /// Whether each list of a submission runs and is timed on its own, slow
  1216. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1217. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1218. #[cfg(feature = "diagnostics")]
  1219. fn timing() -> bool {
  1220. static ON: OnceLock<bool> = OnceLock::new();
  1221. *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some())
  1222. }
  1223. /// Names a host object for the device-removed report, which names the
  1224. /// allocations a page fault hit (only with device-removed data on), or for
  1225. /// the frame recorder (`VICTORY_RECORD`).
  1226. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1227. #[cfg(feature = "diagnostics")]
  1228. if crate::replay::record::on() {
  1229. let text = text();
  1230. crate::replay::record::name(object, &text);
  1231. if dred_on()
  1232. && let Ok(object) = object.cast::<ID3D12Object>()
  1233. {
  1234. // SAFETY: a plain call on a live object.
  1235. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1236. }
  1237. return;
  1238. }
  1239. if dred_on()
  1240. && let Ok(object) = object.cast::<ID3D12Object>()
  1241. {
  1242. // SAFETY: a plain call on a live object.
  1243. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1244. }
  1245. }
  1246. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1247. /// [`LISTS`]`[3]` until it is first reset.
  1248. struct Counted {
  1249. /// Not reset since it was made.
  1250. fresh: std::sync::atomic::AtomicBool,
  1251. }
  1252. impl Counted {
  1253. fn new() -> Counted {
  1254. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1255. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1256. Counted {
  1257. fresh: std::sync::atomic::AtomicBool::new(true),
  1258. }
  1259. }
  1260. /// The list is reset: it is in use.
  1261. fn used(&self) {
  1262. if self.fresh.swap(false, Ordering::Relaxed) {
  1263. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1264. }
  1265. }
  1266. }
  1267. impl Drop for Counted {
  1268. fn drop(&mut self) {
  1269. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1270. self.used();
  1271. }
  1272. }
  1273. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1274. /// mapping and its host GPU address.
  1275. struct Chunk {
  1276. _buffer: ID3D12Resource,
  1277. data: usize,
  1278. gpu: u64,
  1279. }
  1280. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1281. // written only by the list that holds the chunk.
  1282. unsafe impl Send for Chunk {}
  1283. /// Upload chunks handed out front to back: the chunks (each with its
  1284. /// bytes), the one in use and the bytes used in it.
  1285. #[derive(Default)]
  1286. struct Scratch {
  1287. chunks: Vec<(Chunk, u64)>,
  1288. current: usize,
  1289. used: u64,
  1290. }
  1291. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1292. unsafe impl Send for Scratch {}
  1293. impl Drop for Scratch {
  1294. fn drop(&mut self) {
  1295. give_chunks(std::mem::take(&mut self.chunks));
  1296. }
  1297. }
  1298. const SCRATCH_CHUNK: u64 = 4 << 20;
  1299. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1300. /// lists put a few constants or a rectangle's corners there, and every
  1301. /// list that did took 4 MiB of the PC's memory for it.
  1302. const SCRATCH_FIRST: u64 = 256 << 10;
  1303. /// The most bytes of chunks kept while no list holds them.
  1304. const SPARE_MOST: u64 = 128 << 20;
  1305. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1306. /// first needs one, a small one first, and gives all of them back when it
  1307. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1308. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1309. /// host lists of held submissions, which live for one submission, each
  1310. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1311. /// freed per frame of gameplay (run 60).
  1312. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1313. fn scratch_pool() -> bool {
  1314. static ON: OnceLock<bool> = OnceLock::new();
  1315. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1316. }
  1317. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1318. /// for one of the same size.
  1319. struct Spare<T> {
  1320. kept: Vec<(T, u64)>,
  1321. bytes: u64,
  1322. }
  1323. impl<T> Spare<T> {
  1324. const fn new() -> Self {
  1325. Spare { kept: Vec::new(), bytes: 0 }
  1326. }
  1327. /// A kept thing of `size` bytes, the one given last.
  1328. fn take(&mut self, size: u64) -> Option<T> {
  1329. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1330. self.bytes -= size;
  1331. Some(self.kept.remove(at).0)
  1332. }
  1333. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1334. /// `most`: then it comes back.
  1335. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1336. if self.bytes + size > most {
  1337. return Some(thing);
  1338. }
  1339. self.bytes += size;
  1340. self.kept.push((thing, size));
  1341. None
  1342. }
  1343. }
  1344. /// Scratch chunks no list holds.
  1345. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1346. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1347. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1348. if scratch_pool()
  1349. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1350. {
  1351. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1352. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1353. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1354. return Some(chunk);
  1355. }
  1356. let (buffer, data) = host.upload_buffer(size)?;
  1357. name(&buffer, || "list scratch".into());
  1358. // SAFETY: a live buffer.
  1359. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  1360. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1361. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1362. Some(Chunk {
  1363. _buffer: buffer,
  1364. data: data as usize,
  1365. gpu,
  1366. })
  1367. }
  1368. /// A list is done with `chunks` (it was reset after its submissions ran,
  1369. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1370. /// without the pool.
  1371. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1372. if chunks.is_empty() {
  1373. return;
  1374. }
  1375. let mut freed = Vec::new();
  1376. {
  1377. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1378. for (chunk, size) in chunks {
  1379. let back = if scratch_pool() {
  1380. spare.give(chunk, size, SPARE_MOST)
  1381. } else {
  1382. Some(chunk)
  1383. };
  1384. match back {
  1385. None => {
  1386. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1387. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1388. }
  1389. Some(chunk) => {
  1390. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1391. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1392. freed.push(chunk);
  1393. }
  1394. }
  1395. }
  1396. }
  1397. // Freed outside the lock.
  1398. drop(freed);
  1399. }
  1400. /// What the host keeps for copies in the card's own memory
  1401. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1402. struct CardWork {
  1403. /// Before a submission's lists: what changed on the copies' CPU side
  1404. /// goes to their card side. Those not in use: a plan takes one and
  1405. /// gives it back when its submission has run (`Host::card_done`), so
  1406. /// that submissions sent ahead ([`late`]) each have their own.
  1407. sync: Vec<Prelude>,
  1408. /// After them, in the same submission: the compare of the declared
  1409. /// ranges with their bytes from before. As `sync`.
  1410. check: Vec<Prelude>,
  1411. /// After it ran: the pieces that differ come down.
  1412. fetch: Prelude,
  1413. root: ID3D12RootSignature,
  1414. pso: ID3D12PipelineState,
  1415. /// One dword per piece compared, set where the piece differs: PC
  1416. /// memory, mapped (buffer, mapping, bytes).
  1417. differs: (ID3D12Resource, usize, u64),
  1418. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1419. fetched: Option<(ID3D12Resource, usize, u64)>,
  1420. /// The dwords of `differs` taken by plans whose results were not read
  1421. /// yet.
  1422. taken: u32,
  1423. /// Plans made and not done with (`Host::card_done`).
  1424. out: u32,
  1425. }
  1426. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1427. // under the submission lock.
  1428. unsafe impl Send for CardWork {}
  1429. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1430. /// The compare of a declared range of a copy in the card's memory with
  1431. /// its bytes from before, one thread per 64 KiB piece (cut at multiples of
  1432. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1433. /// gets a dword per piece, 1 where a byte differs. The offsets are widened
  1434. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1435. /// byte just outside the range costs a fetch that finds nothing.
  1436. pub(crate) const CARD_COMPARE: &str = r#"
  1437. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1438. cbuffer Span : register(b0) {
  1439. uint first; // the first piece
  1440. uint skew; // where the copy starts in its piece 0
  1441. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1442. uint pieces;
  1443. uint out_at; // the first piece's dword in `differs`, in bytes
  1444. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1445. };
  1446. ByteAddressBuffer now : register(t0);
  1447. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1448. // last sent up (or hashed whole, the first time).
  1449. RWByteAddressBuffer hashes : register(u0);
  1450. RWByteAddressBuffer differs : register(u1);
  1451. [RootSignature(RS)]
  1452. [numthreads(64, 1, 1)]
  1453. void main(uint3 id : SV_DispatchThreadID) {
  1454. if (id.x >= pieces) return;
  1455. uint piece = first + id.x;
  1456. uint lo = piece * 65536u;
  1457. lo = lo > skew ? lo - skew : 0u;
  1458. uint hi = min((piece + 1u) * 65536u - skew, size);
  1459. lo = lo & ~15u;
  1460. hi = (hi + 15u) & ~15u;
  1461. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu);
  1462. [loop]
  1463. for (uint at = lo; at < hi; at += 16u) {
  1464. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1465. h = h.yzwx ^ (h >> 15);
  1466. }
  1467. if (compare != 0u) {
  1468. differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u);
  1469. // With the copy-back on its own thread: the next compare of the
  1470. // piece finds what is written from here on.
  1471. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1472. } else {
  1473. hashes.Store4(piece * 16u, h);
  1474. }
  1475. }
  1476. "#;
  1477. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1478. /// the card's memory are hashed in runs of pieces that touch, each piece
  1479. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1480. /// per range sent up.
  1481. ///
  1482. /// These passes are ours, they run on the card before every submission's
  1483. /// lists, and no timing so far names them: each walks its 64 KiB pieces
  1484. /// 16 bytes at a time, 4,096 steps one after the other, so a pass takes
  1485. /// the time of one piece however few its pieces are. Run 102 sent up 514
  1486. /// ranges a frame: 514 such passes. The same pieces are hashed either way;
  1487. /// a piece hashed when it need not be, or not hashed when it should, costs
  1488. /// a fetch that finds nothing and loses no shader write.
  1489. fn rehash_runs() -> bool {
  1490. static ON: OnceLock<bool> = OnceLock::new();
  1491. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1492. }
  1493. /// Since the last frame-rate line, of our own passes over copies in the
  1494. /// card's memory: hash passes after ranges were sent up, the pieces they
  1495. /// hashed, and compare passes after the lists.
  1496. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1497. /// Whether what shaders wrote to copies in the card's memory is merged
  1498. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1499. /// default). The pieces the card's compare found differing come down in
  1500. /// one fetch and were then merged one after the other on the thread that
  1501. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1502. /// with the copy's CPU side byte by byte and put into title memory through
  1503. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1504. /// so eight threads take an eighth of them each.
  1505. fn wide_merge() -> bool {
  1506. static ON: OnceLock<bool> = OnceLock::new();
  1507. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1508. }
  1509. /// One declared range of a copy in the card's memory, in a submission.
  1510. struct CardRange {
  1511. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1512. /// As declared (title addresses), for the statistics.
  1513. declared: (usize, usize),
  1514. span: crate::shadow::CardSpan,
  1515. /// Its first piece's dword in the compare's results.
  1516. at: u32,
  1517. /// Whether the card compares it; else every piece is fetched.
  1518. compared: bool,
  1519. }
  1520. /// What a submission does for copies in the card's memory.
  1521. struct CardPlan {
  1522. ranges: Vec<CardRange>,
  1523. /// The compare, run after the submission's lists.
  1524. check: Option<ID3D12CommandList>,
  1525. /// The copies whose card side was brought up to date, alive until the
  1526. /// submission has run.
  1527. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1528. /// The lists of ours the plan recorded (whether the compare, the
  1529. /// list), given back by `Host::card_done`.
  1530. lists: Vec<(bool, Prelude)>,
  1531. /// With [`relay`]: the number of the send to copies in the card's memory
  1532. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1533. sent_as: u64,
  1534. }
  1535. /// One piece of submission-time work, in recorded order.
  1536. enum Step {
  1537. /// A copy into title memory (destination, source, bytes): the title's
  1538. /// buffer copies, which later refreshes must see.
  1539. Copy(usize, usize, usize),
  1540. /// A copy of title memory into the list's own upload memory.
  1541. Fill(usize, usize, usize),
  1542. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1543. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1544. /// intervenes.
  1545. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1546. /// Work that may write title memory.
  1547. Run(Box<dyn Fn() + Send>),
  1548. /// Work that writes host memory only.
  1549. Host(Box<dyn Fn() + Send>),
  1550. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1551. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1552. /// Brings a texture's staging buffer up to date: once per submission,
  1553. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1554. Texture(std::sync::Arc<crate::texture::Staging>),
  1555. }
  1556. /// What a list does on the CPU when it is submitted: copies between host
  1557. /// memory regions (title buffers, upload buffers and buffer copies), and
  1558. /// the upload buffers its GPU commands read, kept until the list is reset.
  1559. #[derive(Default)]
  1560. struct Deferred {
  1561. /// Destination, source, bytes.
  1562. copies: Vec<Step>,
  1563. uploads: Vec<ID3D12Resource>,
  1564. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1565. upload_bytes: u64,
  1566. /// Host objects the list's commands name (pipelines, root signatures,
  1567. /// descriptor heaps): the title may release its objects before it
  1568. /// submits the list.
  1569. kept: Vec<windows::core::IUnknown>,
  1570. /// Buffer ranges refreshed since the last title copy (host copy,
  1571. /// address, bytes): refreshing them again would find the same bytes.
  1572. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1573. /// Textures whose contents the list brings up to date.
  1574. textures: std::collections::HashSet<usize>,
  1575. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1576. /// bytes.
  1577. writes: Vec<(usize, crate::queue::Written, usize)>,
  1578. /// Textures read back (texture to buffer copies), done once the list
  1579. /// has run: the host buffer the list copies the texels into, the title
  1580. /// memory they go to, the bytes of a row, the rows, the title's row
  1581. /// pitch.
  1582. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1583. /// Whether the indirect-work budget is zeroed for this recording (a
  1584. /// step on the CPU, or in the list for the card's copy).
  1585. budget_zeroed: bool,
  1586. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1587. /// interface pointer) that a clamp in this recording left readable as
  1588. /// indirect arguments; 0 if none. It stays readable until the next
  1589. /// clamp into it ([`HostList::indirect_state`]).
  1590. indirect_readable: usize,
  1591. }
  1592. impl Deferred {
  1593. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1594. /// reset.
  1595. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1596. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1597. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1598. self.upload_bytes += size;
  1599. self.uploads.push(buffer);
  1600. }
  1601. }
  1602. impl Drop for Deferred {
  1603. fn drop(&mut self) {
  1604. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1605. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1606. }
  1607. }
  1608. /// Whether a queue's submissions go to the card without a wait for each
  1609. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1610. /// waits for every list on its own).
  1611. ///
  1612. /// Every submission was prepared, sent, waited for and copied back before
  1613. /// the next one was looked at, so the card stood idle while we prepared
  1614. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1615. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1616. /// other, on the one thread that submits.
  1617. ///
  1618. /// With the switch a queue's submission is sent and joins a line of
  1619. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1620. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1621. /// for the card, what their shaders wrote copied back once per byte, then
  1622. /// their bottom-of-pipe writes and the fence signals behind them, in
  1623. /// order) at the next point where the title, or our own preparing, can
  1624. /// observe what they do. Those points, exactly:
  1625. ///
  1626. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1627. /// read-back or map of a texture, a clear or upload run at once;
  1628. /// 2. the next submission reads title memory that a flight's shaders may
  1629. /// write: a title buffer copy, a fill of upload memory, a texture's
  1630. /// memory, any step that runs code of ours on title memory
  1631. /// ([`late_blocked`]);
  1632. /// 3. the next submission refreshes a range of a host copy that a flight's
  1633. /// shaders may write, and the title wrote a page of it since it was last
  1634. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1635. /// alone until the flight's writes are back, as it always did within a
  1636. /// submission;
  1637. /// 4. a queue stands at a wait for a memory value that no flight's
  1638. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1639. /// write ([`late_met`]);
  1640. /// 5. the title blocks on a fence without an event;
  1641. /// 6. the card has run every flight (a thread of ours waits for that:
  1642. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1643. ///
  1644. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1645. /// when the card has really run the work, later than before and never
  1646. /// earlier; a fence signalled on a queue while flights are in the air is
  1647. /// set behind them. A wait for a memory value that a flight's
  1648. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1649. /// the card behind that flight, which is the order the wait asks for.
  1650. ///
  1651. /// What it assumes beyond today: memory the title rewrites between two of
  1652. /// its submissions, without waiting for the first, may be seen by the
  1653. /// first's shaders (as on the console, where the card reads title memory
  1654. /// when it runs, not when the list is submitted).
  1655. pub(crate) fn late() -> bool {
  1656. late_stage() > 0
  1657. }
  1658. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1659. fn late_stage() -> u8 {
  1660. static STAGE: OnceLock<u8> = OnceLock::new();
  1661. *STAGE.get_or_init(|| {
  1662. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1663. return 0;
  1664. }
  1665. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1666. Ok("1") => 1,
  1667. Ok("2") => 2,
  1668. Ok("3") => 3,
  1669. // The relay alone: on top of stage 3.
  1670. Err(_) if crate::shadow::relay() => 3,
  1671. _ => 0,
  1672. }
  1673. })
  1674. }
  1675. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1676. /// longer a point. Where the title wrote a page that lies in a range a
  1677. /// flight's shaders may write, the bytes the title changed are found (the
  1678. /// page as it is now against what the copy held when the flight was
  1679. /// prepared) and put into the copy, and only those: what the flight's
  1680. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1681. /// flights are settled for it only where that cannot be done: memory that
  1682. /// is not write-watched, or a copy in the card's memory with more changed
  1683. /// runs than a submission should send up one by one.
  1684. ///
  1685. /// In run 92 (stage 1) this point settled the flights five times a frame
  1686. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1687. /// frame of waiting were left of 200.
  1688. ///
  1689. /// What differs from settling first: a byte both the title and a flight's
  1690. /// shader wrote is the title's if the shader wrote it first, the shader's
  1691. /// if it wrote it afterwards; settled first it was always the shader's.
  1692. /// The title writing a byte a shader of its own is writing is a race on
  1693. /// the console too.
  1694. fn late_exact() -> bool {
  1695. late_stage() > 1
  1696. }
  1697. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1698. /// no longer a point where flights are settled). The copy to the back
  1699. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1700. /// its own for each present in the air) and the swap chain is told to
  1701. /// present behind it; the queue's call returns, and the card finishes the
  1702. /// frame while the title records the next one. What the title is told
  1703. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1704. /// has run it, by the settling thread.
  1705. ///
  1706. /// What is left out with it: the look whether the presented frame is black
  1707. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1708. /// or listed is presented the old way. Once every second and a half a
  1709. /// submission settles the flights all the same, for the sweep that lets
  1710. /// idle host objects go (it needs nothing in the air).
  1711. pub(crate) fn late_free_present() -> bool {
  1712. late_stage() > 2
  1713. }
  1714. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1715. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1716. /// and is off with it, in the timing run and with kept snapshots).
  1717. ///
  1718. /// With [`late`] alone every settle does three things on the thread that
  1719. /// holds the submission lock: it waits for everything in the air, copies
  1720. /// back with the card standing, and only then goes on preparing. The frame
  1721. /// stays a relay: the card works about 242 ms of it and one thread
  1722. /// prepares, waits and copies back for about 220.
  1723. ///
  1724. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1725. /// soon as the card has run them, in the order they were sent and without
  1726. /// the submission lock: it fetches and merges what their shaders wrote to
  1727. /// copies in the card's memory, compares and merges the other copies,
  1728. /// frees the flights' ranges, and then does their read-backs, their
  1729. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1730. /// order. The submitting thread meanwhile prepares and sends the next
  1731. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  1732. /// that thread has landed everything in the air, at the same points as
  1733. /// before (the list in [`late`]), so whoever can observe title memory, a
  1734. /// fence or a present still does so only after the flights before it are
  1735. /// merged.
  1736. ///
  1737. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  1738. /// flight; a merge that never stores into memory the card may be writing;
  1739. /// sends to card copies numbered) and here: flights land in the order of
  1740. /// [`LINE`] by one thread, so a later flight's results never reach title
  1741. /// memory before an earlier flight's; the compare on the card stores the
  1742. /// hash it made, so each flight's compare flags exactly what changed since
  1743. /// the compare before it, however late the pieces are fetched; the fetch
  1744. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  1745. /// title bytes the card had received when it ran.
  1746. pub(crate) fn relay() -> bool {
  1747. static ON: OnceLock<bool> = OnceLock::new();
  1748. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  1749. }
  1750. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  1751. /// title memory a flight's shaders may write (a title buffer copy, a fill
  1752. /// of upload memory, a texture) waits only until the flights that declared
  1753. /// that memory have landed, not for everything in the air; and at
  1754. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  1755. /// both wait for everything.
  1756. fn relay_exact() -> bool {
  1757. static ON: OnceLock<bool> = OnceLock::new();
  1758. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_some_and(|v| v == "2"))
  1759. }
  1760. /// Whether the pieces the relay fetches from the card's memory come over the
  1761. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  1762. /// draws.
  1763. ///
  1764. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  1765. /// and with the relay that is most of a frame: the thread that lands flights
  1766. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  1767. /// a few milliseconds of copying, and everything that waits for a landing
  1768. /// (the title's fences, reads of memory flights may write) waited with it.
  1769. ///
  1770. /// What changes: the fetch runs when its flights are done and beside later
  1771. /// submissions, so of the sends of title bytes it is only known to have run
  1772. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  1773. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  1774. /// the title's, newer than what the flights wrote. A later flight's bytes
  1775. /// may be in what is fetched, as before.
  1776. fn relay_copy() -> bool {
  1777. static ON: OnceLock<bool> = OnceLock::new();
  1778. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  1779. }
  1780. /// Told when something joins [`LINE`], for the thread that lands flights
  1781. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  1782. /// what queues hold.
  1783. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  1784. /// Told when flights have landed ([`relay`]): who waits for that looks
  1785. /// again.
  1786. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  1787. /// With [`relay`], the order of what we put on the queue: the number of
  1788. /// sends of changed ranges to copies in the card's memory so far
  1789. /// (`Host::card_before`). Held from the taking of the ranges until their
  1790. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  1791. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  1792. /// later one.
  1793. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  1794. /// Since the last frame-rate line, of the thread that lands flights
  1795. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  1796. /// card with nothing to land, microseconds it waited for fetches of card
  1797. /// copies' pieces, microseconds of landing in all.
  1798. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  1799. /// Of the line's things in order (a flight: the value signalled on the
  1800. /// host's fence behind it; a write or a signal behind a flight: `None`):
  1801. /// how many, from the front, can be landed when the card has reached
  1802. /// `completed`: everything ahead of the first flight it has not run. A
  1803. /// later flight never lands before an earlier one, and what follows a
  1804. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  1805. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  1806. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  1807. }
  1808. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  1809. /// holds, for every piece of every range of the plan, the copy, the
  1810. /// piece's number in the copy and whether the compare flagged it there (or
  1811. /// did not run). The pieces to fetch, under whichever range: all of them
  1812. /// flagged under any. Two ranges of a plan may hold parts of the same
  1813. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  1814. /// the hash, so the second of them may find it stored already and not
  1815. /// flag it.
  1816. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> std::collections::HashSet<(usize, u32)> {
  1817. flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect()
  1818. }
  1819. #[cfg(test)]
  1820. mod relay_tests {
  1821. use super::{flagged_pieces, landable};
  1822. /// Two flights and what follows each: nothing of the second lands
  1823. /// before the card has run it, and nothing behind a flight lands
  1824. /// before the flight.
  1825. #[test]
  1826. fn flights_land_in_the_order_they_were_sent() {
  1827. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  1828. let line = [Some(5), None, None, Some(6), None];
  1829. assert_eq!(landable(&line, 4), 0);
  1830. assert_eq!(landable(&line, 5), 3);
  1831. assert_eq!(landable(&line, 6), 5);
  1832. assert_eq!(landable(&line, u64::MAX), 5);
  1833. // Signals with no flight ahead land at once; behind one they wait.
  1834. assert_eq!(landable(&[None, None], 0), 2);
  1835. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  1836. assert_eq!(landable(&[], 3), 0);
  1837. // After the first three landed, the rest when its turn comes.
  1838. assert_eq!(landable(&line[3..], 5), 0);
  1839. assert_eq!(landable(&line[3..], 6), 2);
  1840. }
  1841. /// A piece flagged under one range of a plan is fetched under every
  1842. /// range that holds a part of it; pieces of other copies are not.
  1843. #[test]
  1844. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  1845. let (a, b) = (0x1000usize, 0x2000usize);
  1846. // Copy a: piece 3 under two ranges, flagged under the first only;
  1847. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  1848. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  1849. let fetch = flagged_pieces(&flags);
  1850. assert!(fetch.contains(&(a, 3)));
  1851. assert!(!fetch.contains(&(a, 4)));
  1852. assert!(!fetch.contains(&(b, 3)));
  1853. assert!(fetch.contains(&(b, 9)));
  1854. assert_eq!(fetch.len(), 2);
  1855. }
  1856. }
  1857. /// The most host lists in the air before the flights are settled
  1858. /// (`VICTORY_LATE_WAIT_LISTS`, 128; 32 settled the flights three times a
  1859. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  1860. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  1861. /// descriptor slots, upload
  1862. /// memory and scratch chunks are held until then, and a frame's lists held
  1863. /// all at once ran the slots out before (run 45).
  1864. fn late_most() -> usize {
  1865. static MOST: OnceLock<usize> = OnceLock::new();
  1866. *MOST.get_or_init(|| {
  1867. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(128).max(1)
  1868. })
  1869. }
  1870. /// Whether a submission with bottom-of-pipe writes may fly
  1871. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  1872. /// the title is told at once, as before; for telling a title that polls
  1873. /// such a value from one that does not).
  1874. fn late_writes() -> bool {
  1875. static ON: OnceLock<bool> = OnceLock::new();
  1876. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  1877. }
  1878. /// Per host copy, the ranges a submission's shaders may write, as declared
  1879. /// (address, end).
  1880. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  1881. /// What [`Host::submit`] hands back for a submission it sent and did not
  1882. /// wait for.
  1883. struct Sent {
  1884. /// Its number among the submissions started.
  1885. number: u64,
  1886. card: Option<CardPlan>,
  1887. back: Vec<Declared>,
  1888. /// Its bottom-of-pipe writes.
  1889. writes: Vec<(usize, crate::queue::Written, usize)>,
  1890. }
  1891. /// A submission on the card that has not been waited for ([`late`]): its
  1892. /// host lists, taken from the title's (which it may reset meanwhile), and
  1893. /// what is to be done once it has run.
  1894. struct Flight {
  1895. number: u64,
  1896. /// The value signalled on the host's fence behind it.
  1897. fence: u64,
  1898. lists: Vec<crate::list::Detached>,
  1899. order: Vec<usize>,
  1900. card: Option<CardPlan>,
  1901. back: Vec<Declared>,
  1902. }
  1903. /// One thing in the line of what waits for the card, in order.
  1904. enum Late {
  1905. Run(Flight),
  1906. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  1907. Write(usize, crate::queue::Written, usize),
  1908. /// A fence (its address) signalled behind the flights before it.
  1909. Signal(usize, u64),
  1910. }
  1911. struct Line {
  1912. line: Vec<Late>,
  1913. /// The title memory the flights' shaders may write (address, end), in
  1914. /// order and joined.
  1915. written: Vec<(usize, usize)>,
  1916. /// Host lists in the flights.
  1917. lists: usize,
  1918. /// The value signalled on the host's fence behind the last flight.
  1919. target: u64,
  1920. /// A settle has taken the line and is not done: a signal still goes
  1921. /// behind it.
  1922. settling: bool,
  1923. /// Something was settled away from a queue's own calls: the helper
  1924. /// thread looks at what queues hold.
  1925. poke: bool,
  1926. /// Host lists of settled flights, reset and given back outside the
  1927. /// submission lock ([`land`]: a settle may run under a caller's own
  1928. /// locks).
  1929. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  1930. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  1931. /// landed (taken out of `line`, not done yet), for [`late_met`].
  1932. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  1933. }
  1934. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  1935. // into; touched under the lock.
  1936. unsafe impl Send for Line {}
  1937. static LINE: Mutex<Line> = Mutex::new(Line {
  1938. line: Vec::new(),
  1939. written: Vec::new(),
  1940. lists: 0,
  1941. target: 0,
  1942. settling: false,
  1943. poke: false,
  1944. landed: Vec::new(),
  1945. in_hand: Vec::new(),
  1946. });
  1947. /// Told when a flight joins [`LINE`] or it is poked.
  1948. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  1949. fn line() -> std::sync::MutexGuard<'static, Line> {
  1950. LINE.lock().unwrap_or_else(|e| e.into_inner())
  1951. }
  1952. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  1953. const WHY_SYNC: usize = 2;
  1954. const WHY_CARD_DONE: usize = 3;
  1955. const WHY_VALUE: usize = 4;
  1956. const WHY_STALE: usize = 5;
  1957. const WHY_READ: usize = 6;
  1958. const WHY_RUN: usize = 7;
  1959. const WHY_MOST: usize = 8;
  1960. const WHY_WRITES: usize = 9;
  1961. const WHY_FENCE: usize = 10;
  1962. /// Since the last frame-rate line: submissions sent without a wait;
  1963. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  1964. /// microseconds settles waited for the card; value waits met by a flight's
  1965. /// bottom-of-pipe write; fence signals set behind flights.
  1966. /// Then: the settles for title memory read, by what read it (a buffer
  1967. /// copy, a fill of upload memory, a texture).
  1968. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  1969. /// Since the last frame-rate line: the microseconds settles waited for the
  1970. /// card, by why they settled (the `WHY_` places).
  1971. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  1972. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  1973. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  1974. if from >= to {
  1975. return false;
  1976. }
  1977. let at = ranges.partition_point(|r| r.1 <= from);
  1978. ranges.get(at).is_some_and(|r| r.0 < to)
  1979. }
  1980. /// `ranges` with `more`, in order, joined where they overlap or touch.
  1981. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  1982. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  1983. ranges.sort_unstable();
  1984. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  1985. for &(from, to) in ranges.iter() {
  1986. match out.last_mut() {
  1987. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  1988. _ => out.push((from, to)),
  1989. }
  1990. }
  1991. *ranges = out;
  1992. }
  1993. /// Whether anything is in the air.
  1994. fn flying() -> bool {
  1995. if !late() {
  1996. return false;
  1997. }
  1998. let line = line();
  1999. // (With the relay: also while flights are being landed.)
  2000. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2001. }
  2002. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2003. /// before they are settled, if so. Preparing reads title memory on the
  2004. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2005. /// runs steps of ours that may read or write it anywhere; what the
  2006. /// flights' shaders write is not there yet.
  2007. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2008. let written = {
  2009. let line = line();
  2010. if line.written.is_empty() {
  2011. return None;
  2012. }
  2013. line.written.clone()
  2014. };
  2015. blocked_by(&written, runs, true)
  2016. }
  2017. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2018. /// flights when the title itself wrote the memory since they were given it
  2019. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2020. ///
  2021. /// The title's 174 MB heap is declared written as a whole (a root view has
  2022. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2023. /// bytes a frame, at a new place each time, waited for every flight's
  2024. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2025. /// named). The title writes those bytes just before the draw that reads
  2026. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2027. ///
  2028. /// Or no shader's write went into that page in the last 600 frames
  2029. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2030. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2031. /// before the page was taken.
  2032. ///
  2033. /// What can go wrong: a constant a flight's shader really writes, in a
  2034. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2035. /// for the first time, is read as it was before that flight.
  2036. fn fill_is_titles(src: usize, len: usize) -> bool {
  2037. const SMALL: usize = 64 << 10;
  2038. static ON: OnceLock<bool> = OnceLock::new();
  2039. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2040. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2041. }
  2042. /// Diagnostics: the reads that made a submission wait for flights: what
  2043. /// kind, where, how much, and the declared write it lies in; how often and
  2044. /// how long the wait was.
  2045. #[cfg(feature = "diagnostics")]
  2046. type Blame = std::collections::HashMap<(&'static str, usize, usize, usize, usize), (u64, u64)>;
  2047. #[cfg(feature = "diagnostics")]
  2048. static BLAME: Mutex<Option<Blame>> = Mutex::new(None);
  2049. #[cfg(feature = "diagnostics")]
  2050. static BLAMED: Mutex<Option<(&'static str, usize, usize, usize, usize)>> = Mutex::new(None);
  2051. #[cfg(feature = "diagnostics")]
  2052. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2053. let i = written.partition_point(|r| r.1 <= at);
  2054. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2055. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = Some((kind, at, len, from, to - from));
  2056. }
  2057. /// The wait for what [`blame`] last named took `us`.
  2058. #[cfg(feature = "diagnostics")]
  2059. fn blamed(us: u64) {
  2060. if let Some(key) = BLAMED.lock().unwrap_or_else(|e| e.into_inner()).take() {
  2061. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2062. let e = all.get_or_insert_with(Default::default).entry(key).or_insert((0, 0));
  2063. e.0 += 1;
  2064. e.1 += us;
  2065. }
  2066. }
  2067. #[cfg(feature = "diagnostics")]
  2068. fn log_blame(frames: f64) {
  2069. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2070. let mut all: Vec<_> = all.into_iter().collect();
  2071. all.sort_unstable_by_key(|(_, (_, us))| std::cmp::Reverse(*us));
  2072. for ((kind, at, len, from, size), (n, us)) in all.into_iter().take(8) {
  2073. tracing::info!(
  2074. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} {at:#x}+{len:#x}, in shader writes declared over {from:#x}+{size:#x}",
  2075. us as f64 / 1e3 / frames,
  2076. n as f64 / frames
  2077. );
  2078. }
  2079. }
  2080. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2081. /// may write (in order, joined); `count` whether the kind of read is
  2082. /// counted for the frame line.
  2083. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2084. if written.is_empty() {
  2085. return None;
  2086. }
  2087. for list in runs {
  2088. for step in &list.deferred().copies {
  2089. match step {
  2090. &Step::Copy(dst, src, len) => {
  2091. let read = touches(written, src, src + len) && !fill_is_titles(src, len);
  2092. if read || touches(written, dst, dst + len) {
  2093. if count {
  2094. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2095. #[cfg(feature = "diagnostics")]
  2096. if read {
  2097. blame("a buffer copy's source", written, src, len);
  2098. } else {
  2099. blame("a buffer copy's destination", written, dst, len);
  2100. }
  2101. }
  2102. return Some(WHY_READ);
  2103. }
  2104. }
  2105. &Step::Fill(_, src, len) => {
  2106. if touches(written, src, src + len) && !fill_is_titles(src, len) {
  2107. if count {
  2108. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2109. #[cfg(feature = "diagnostics")]
  2110. blame("a fill of upload memory", written, src, len);
  2111. }
  2112. return Some(WHY_READ);
  2113. }
  2114. }
  2115. Step::Texture(staging) => {
  2116. let (at, len) = staging.memory();
  2117. if touches(written, at, at + len) {
  2118. if count {
  2119. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2120. #[cfg(feature = "diagnostics")]
  2121. blame("a texture", written, at, len);
  2122. }
  2123. return Some(WHY_READ);
  2124. }
  2125. }
  2126. Step::Run(_) => return Some(WHY_RUN),
  2127. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(_) => {}
  2128. }
  2129. }
  2130. }
  2131. None
  2132. }
  2133. /// With flights in the air, after the submission's write-watch asking:
  2134. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2135. /// may write and that the title wrote since it was last copied. The
  2136. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2137. /// the title's bytes there would reach the card a submission late.
  2138. fn stale_under_flights(runs: &[&HostList]) -> bool {
  2139. use std::sync::Arc;
  2140. // Per copy, the span of what is refreshed (a flush brings that much
  2141. // up to date at most).
  2142. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2143. for list in runs {
  2144. for step in &list.deferred().copies {
  2145. if let Step::Refresh(shadow, address, len) = step
  2146. && shadow.writes_pending()
  2147. {
  2148. match spans.iter_mut().find(|s| Arc::ptr_eq(&s.0, shadow)) {
  2149. Some(s) => (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len)),
  2150. None => spans.push((shadow.clone(), *address, *address + *len)),
  2151. }
  2152. }
  2153. }
  2154. }
  2155. if late_exact() {
  2156. // The title's bytes are put in beside the flights' writes; a
  2157. // settle is still due where that could not be done. At most this
  2158. // many changed runs go up to copies in the card's memory, each a
  2159. // copy of its own there.
  2160. let mut runs_left = 512;
  2161. return spans.iter().any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2162. }
  2163. spans.iter().any(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from))
  2164. }
  2165. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2166. /// air, if there are any, and is set when they are settled. Whether it
  2167. /// did; if not the caller sets the fence now.
  2168. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2169. if !late() {
  2170. return false;
  2171. }
  2172. let mut line = line();
  2173. if line.line.is_empty() && !line.settling {
  2174. return false;
  2175. }
  2176. line.line.push(Late::Signal(fence, value));
  2177. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2178. drop(line);
  2179. // A signal alone (behind a settle under way) has no flight to wake
  2180. // the helper thread for it.
  2181. LINE_MOVED.notify_one();
  2182. RELAY_MOVED.notify_one();
  2183. true
  2184. }
  2185. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2186. /// whether it is met once the flights in the air have run. A flight's
  2187. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2188. /// for the card: the part behind the wait goes to the card behind that
  2189. /// flight, which is the order the wait asks for. If the flights may write
  2190. /// the value in a way not known here (shaders, a timestamp, another
  2191. /// width), they are settled and memory is asked again.
  2192. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2193. let (address, bytes) = wait.place();
  2194. {
  2195. let line = line();
  2196. if line.line.is_empty() && line.in_hand.is_empty() {
  2197. return false;
  2198. }
  2199. let mut unsure = touches(&line.written, address, address + bytes);
  2200. // (With the relay: first the writes of flights being landed.)
  2201. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2202. Late::Write(at, what, n) => Some((at, what, n)),
  2203. _ => None,
  2204. }));
  2205. for (at, what, n) in writes {
  2206. if *at >= address + bytes || address >= *at + *n {
  2207. continue;
  2208. }
  2209. match what {
  2210. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2211. if wait.holds_for(*v) {
  2212. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2213. return true;
  2214. }
  2215. }
  2216. _ => unsure = true,
  2217. }
  2218. }
  2219. if !unsure {
  2220. return false;
  2221. }
  2222. }
  2223. settle_now(WHY_VALUE);
  2224. wait.met()
  2225. }
  2226. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2227. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2228. pub(crate) fn settle_now(why: usize) {
  2229. if !late() {
  2230. return;
  2231. }
  2232. let Some(host) = host() else {
  2233. return;
  2234. };
  2235. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2236. host.settle(&mut submitted, why);
  2237. }
  2238. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2239. pub(crate) fn settle_for_present() {
  2240. settle_now(WHY_SYNC);
  2241. }
  2242. pub(crate) fn settle_for_fence() {
  2243. settle_now(WHY_FENCE);
  2244. }
  2245. /// Resets the host lists of settled flights and keeps them for reuse, as
  2246. /// a queue does for the lists it ran (`crate::list::recycle`).
  2247. fn land() {
  2248. let landed = std::mem::take(&mut line().landed);
  2249. for (lists, order) in landed {
  2250. crate::list::recycle(lists, &order);
  2251. }
  2252. }
  2253. /// The thread that settles the flights once the card has run them all
  2254. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2255. /// at the next call that settles, and a title thread that polls such a
  2256. /// value while the submitting thread waits for that thread would never
  2257. /// see it.
  2258. fn late_helper() {
  2259. let Some(host) = host() else {
  2260. return;
  2261. };
  2262. // SAFETY: a plain event of our own.
  2263. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2264. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2265. return;
  2266. };
  2267. loop {
  2268. let target = {
  2269. let mut line = line();
  2270. loop {
  2271. if line.poke {
  2272. line.poke = false;
  2273. break None;
  2274. }
  2275. // (With the relay the flights are another thread's.)
  2276. if !relay() && !line.line.is_empty() && !line.settling {
  2277. break Some(line.target);
  2278. }
  2279. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2280. }
  2281. };
  2282. let Some(target) = target else {
  2283. land();
  2284. crate::queue::release_held(false);
  2285. continue;
  2286. };
  2287. // The card first, without the submission lock: the submitting
  2288. // thread prepares and sends meanwhile.
  2289. // SAFETY: our fence and event.
  2290. unsafe {
  2291. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2292. WaitForSingleObject(event, INFINITE);
  2293. }
  2294. }
  2295. {
  2296. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2297. // Something newer went up meanwhile: the card is waited for
  2298. // again, the submitting thread is not held up for it.
  2299. if line().target != target {
  2300. continue;
  2301. }
  2302. host.settle(&mut submitted, WHY_CARD_DONE);
  2303. }
  2304. land();
  2305. crate::queue::release_held(false);
  2306. }
  2307. }
  2308. /// Starts the threads of [`late`], once: the one that settles flights when
  2309. /// the card has run them and looks at what queues hold, and with [`relay`]
  2310. /// the one that lands flights.
  2311. fn late_threads() {
  2312. static HELPER: std::sync::Once = std::sync::Once::new();
  2313. HELPER.call_once(|| {
  2314. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2315. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2316. }
  2317. tracing::info!(
  2318. most = late_most(),
  2319. writes = late_writes(),
  2320. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2321. );
  2322. if relay() {
  2323. // Without it nothing would ever land.
  2324. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2325. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2326. }
  2327. tracing::info!(
  2328. exact = relay_exact(),
  2329. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2330. );
  2331. }
  2332. });
  2333. }
  2334. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2335. /// time flights have landed. Counted as a settle for `why`, and its time
  2336. /// as waiting for the card. The caller may hold the submission lock: the
  2337. /// thread that lands flights never takes it.
  2338. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2339. let mut line = line();
  2340. if done(&line) {
  2341. return;
  2342. }
  2343. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2344. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2345. let was_working = working(false);
  2346. let waiting = std::time::Instant::now();
  2347. while !done(&line) {
  2348. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2349. }
  2350. drop(line);
  2351. stood(waiting);
  2352. working(was_working);
  2353. let us = waiting.elapsed().as_micros() as u64;
  2354. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2355. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2356. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2357. #[cfg(feature = "diagnostics")]
  2358. blamed(us);
  2359. }
  2360. /// What the thread that lands flights fetches card copies' pieces with
  2361. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2362. /// behind the submission lock), and the memory the pieces come down to.
  2363. struct RelayFetch {
  2364. list: Prelude,
  2365. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2366. queue: Option<ID3D12CommandQueue>,
  2367. fence: ID3D12Fence,
  2368. event: HANDLE,
  2369. /// The last value signalled on `fence`.
  2370. sent: u64,
  2371. /// Buffer, mapping, bytes.
  2372. buffer: Option<(ID3D12Resource, usize, u64)>,
  2373. }
  2374. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2375. /// the first flights of the line it takes them, with what follows them,
  2376. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2377. /// the card, or for a flight. It takes neither the submission lock nor
  2378. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2379. /// lists and looking at what queues hold are left to [`late_helper`].
  2380. fn relay_worker() {
  2381. let Some(host) = host() else {
  2382. return;
  2383. };
  2384. // SAFETY: a plain event of our own.
  2385. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2386. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2387. };
  2388. let mut fetch: Option<RelayFetch> = None;
  2389. loop {
  2390. let next = {
  2391. let mut line = line();
  2392. loop {
  2393. if line.line.is_empty() {
  2394. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2395. continue;
  2396. }
  2397. let fences: Vec<Option<u64>> = line
  2398. .line
  2399. .iter()
  2400. .map(|l| match l {
  2401. Late::Run(flight) => Some(flight.fence),
  2402. _ => None,
  2403. })
  2404. .collect();
  2405. // SAFETY: a plain query.
  2406. let completed = unsafe { host.fence.GetCompletedValue() };
  2407. let n = landable(&fences, completed);
  2408. if n == 0 {
  2409. // The first thing is a flight the card has not run.
  2410. break Err(fences[0].unwrap_or(0));
  2411. }
  2412. line.settling = true;
  2413. let items: Vec<Late> = line.line.drain(..n).collect();
  2414. line.in_hand = items
  2415. .iter()
  2416. .filter_map(|l| match l {
  2417. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2418. _ => None,
  2419. })
  2420. .collect();
  2421. break Ok(items);
  2422. }
  2423. };
  2424. match next {
  2425. Ok(items) => host.relay_land(items, &mut fetch),
  2426. Err(target) => {
  2427. let waiting = std::time::Instant::now();
  2428. // SAFETY: the host's fence and this thread's event.
  2429. let waited = unsafe {
  2430. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2431. WaitForSingleObject(event, INFINITE);
  2432. })
  2433. };
  2434. if waited.is_err() {
  2435. std::thread::sleep(std::time::Duration::from_millis(1));
  2436. }
  2437. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2438. }
  2439. }
  2440. }
  2441. }
  2442. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2443. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2444. /// once, the pieces that differ found on several threads; but the merge is
  2445. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2446. /// are not done with here (each flight's are, afterwards).
  2447. fn relay_hand_back(back: &[Declared]) {
  2448. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2449. for (shadow, declared) in back {
  2450. if shadow.carded() {
  2451. continue;
  2452. }
  2453. let mut spans: Vec<(usize, usize)> = Vec::new();
  2454. join_ranges(&mut spans, declared.iter().copied());
  2455. for &(from, to) in &spans {
  2456. shadow.relay_compared(from, to - from);
  2457. }
  2458. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2459. }
  2460. if work.is_empty() {
  2461. return;
  2462. }
  2463. #[cfg(feature = "diagnostics")]
  2464. let scanning = std::time::Instant::now();
  2465. // Looked through without a lock: a piece that changes meanwhile (a
  2466. // later flight writing, the title's bytes going in) is found now or by
  2467. // that flight's landing, and the merge looks again under the lock.
  2468. let found = crate::shadow::find_all(&work);
  2469. #[cfg(feature = "diagnostics")]
  2470. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2471. let (mut now, mut title) = (Vec::new(), Vec::new());
  2472. for ((shadow, from, to), found) in work.iter().zip(found) {
  2473. let mut written = 0;
  2474. for (at, n) in found {
  2475. written += shadow.relay_merge(at, n, &mut now, &mut title);
  2476. }
  2477. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  2478. #[cfg(feature = "diagnostics")]
  2479. crate::copystat::compared(*from, to - from, written);
  2480. let _ = (from, to);
  2481. }
  2482. }
  2483. /// For the frame-rate line, with [`late`]: what the line of flights did
  2484. /// per frame since the last one.
  2485. fn late_line(frames: f64) {
  2486. if !late() {
  2487. return;
  2488. }
  2489. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2490. tracing::info!(
  2491. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2492. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2493. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2494. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2495. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2496. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2497. s[0],
  2498. s[1],
  2499. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2500. s[12] / 1000.0,
  2501. s[WHY_SYNC],
  2502. s[WHY_CARD_DONE],
  2503. s[WHY_VALUE],
  2504. s[WHY_STALE],
  2505. s[WHY_READ],
  2506. s[15],
  2507. s[16],
  2508. s[17],
  2509. s[WHY_RUN],
  2510. late_most(),
  2511. s[WHY_MOST],
  2512. s[WHY_WRITES],
  2513. s[WHY_FENCE],
  2514. s[13],
  2515. s[14],
  2516. );
  2517. {
  2518. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2519. tracing::info!(
  2520. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2521. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2522. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2523. w[WHY_SYNC],
  2524. w[WHY_CARD_DONE],
  2525. w[WHY_VALUE],
  2526. w[WHY_STALE],
  2527. w[WHY_READ],
  2528. w[WHY_RUN],
  2529. w[WHY_MOST],
  2530. w[WHY_WRITES],
  2531. w[WHY_FENCE],
  2532. );
  2533. }
  2534. if relay() {
  2535. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2536. tracing::info!(
  2537. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2538. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2539. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2540. \"settles\" above are waits of other threads for it)",
  2541. r[1],
  2542. r[0],
  2543. r[2] / 1000.0,
  2544. r[3] / 1000.0,
  2545. r[4] / 1000.0,
  2546. );
  2547. }
  2548. if late_exact() {
  2549. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  2550. tracing::info!(
  2551. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  2552. {runs:.0} changed runs, {:.2} MB",
  2553. bytes / (1 << 20) as f64
  2554. );
  2555. }
  2556. }
  2557. #[cfg(test)]
  2558. mod late_tests {
  2559. use super::{continues, join_ranges, touches};
  2560. /// Copies join only when both ends continue and the whole does not
  2561. /// overlap itself.
  2562. #[test]
  2563. fn copies_join_only_end_to_end_and_apart() {
  2564. // (destination, source, bytes)
  2565. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  2566. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  2567. // A gap, or only one side continues.
  2568. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  2569. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  2570. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  2571. // Together they would overlap: the second reads what the first wrote.
  2572. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  2573. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  2574. // They touch without overlapping.
  2575. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  2576. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  2577. }
  2578. /// Ranges are found by what they hold, not by where they start, and a
  2579. /// range that only touches another's end does not touch it.
  2580. #[test]
  2581. fn ranges_touch_where_they_overlap() {
  2582. let mut ranges = Vec::new();
  2583. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  2584. assert_eq!(ranges, [(10, 25), (40, 60)]);
  2585. join_ranges(&mut ranges, [(25, 40)]);
  2586. assert_eq!(ranges, [(10, 60)]);
  2587. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  2588. for (from, to, hit) in [
  2589. (0, 10, false),
  2590. (0, 11, true),
  2591. (24, 25, true),
  2592. (25, 40, false),
  2593. (25, 41, true),
  2594. (59, 200, true),
  2595. (60, 100, false),
  2596. (100, 101, true),
  2597. (101, 500, false),
  2598. (30, 30, false),
  2599. (50, 50, false),
  2600. ] {
  2601. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  2602. }
  2603. assert!(!touches(&[], 0, usize::MAX));
  2604. }
  2605. }
  2606. /// Whether a title buffer copy that continues the one recorded before it
  2607. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  2608. /// default).
  2609. ///
  2610. /// Each copy is done at submission through the kernel, which reports a
  2611. /// page that is not there instead of faulting (`copy_mapped`), tells the
  2612. /// write watch and the guards, and ends the refreshes gathered so far: a
  2613. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  2614. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  2615. /// continue the one before is counted either way and said on its own line
  2616. /// with the frame rate; the switch is worth that many kernel calls.
  2617. ///
  2618. /// Joined, the same bytes move: [`continues`] joins only copies whose
  2619. /// ranges, taken together, do not overlap, and nothing is recorded between
  2620. /// two steps that follow each other. What differs: a page that is not
  2621. /// mapped now fails the joined copy as a whole (it then goes page by page,
  2622. /// zeros for what cannot be read, as a single copy does), where before
  2623. /// only the copy that held it did.
  2624. fn join_copies() -> bool {
  2625. static ON: OnceLock<bool> = OnceLock::new();
  2626. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  2627. }
  2628. /// Since the last frame-rate line: title buffer copies recorded, and those
  2629. /// that continue the one before ([`join_copies`]).
  2630. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  2631. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  2632. /// where `last` ended, source and destination both, and the two as one do
  2633. /// not overlap (source over destination): then one copy of both moves the
  2634. /// bytes the two would move in turn.
  2635. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  2636. let ((d, s, n), (dst, src, len)) = (last, next);
  2637. let Some(all) = n.checked_add(len) else {
  2638. return false;
  2639. };
  2640. d.checked_add(n) == Some(dst)
  2641. && s.checked_add(n) == Some(src)
  2642. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  2643. }
  2644. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  2645. /// One list's lock at a time: a submission may name a list twice.
  2646. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  2647. let mut back: Vec<Declared> = Vec::new();
  2648. for list in runs {
  2649. for step in &list.deferred().copies {
  2650. if let Step::GpuWrite(shadow, address, len) = step {
  2651. let range = (*address, *address + *len);
  2652. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  2653. Some((_, ranges)) => {
  2654. if !ranges.contains(&range) {
  2655. ranges.push(range);
  2656. }
  2657. }
  2658. None => back.push((shadow.clone(), vec![range])),
  2659. }
  2660. }
  2661. }
  2662. }
  2663. back
  2664. }
  2665. /// After `list` has run: the texels its read-backs copied into host
  2666. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  2667. ///
  2668. /// A submission that is waited for did this itself. One sent ahead
  2669. /// ([`late`]) did not, at any stage: the flights' lists were settled
  2670. /// without it, so the title read a buffer nobody wrote, as before read-backs
  2671. /// were made (the exposure metering's two small float targets, every frame).
  2672. fn read_backs(list: &HostList) {
  2673. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  2674. let mut data = std::ptr::null_mut();
  2675. // SAFETY: a read-back buffer of ours, written by the list that has
  2676. // run; the title's destination holds every row (checked when the
  2677. // copy was recorded).
  2678. unsafe {
  2679. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  2680. let from = data.cast::<u8>().cast_const();
  2681. for line in 0..*rows {
  2682. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  2683. }
  2684. buffer.Unmap(0, None);
  2685. }
  2686. }
  2687. }
  2688. }
  2689. /// After the card ran what declared `back`: what shaders wrote there goes
  2690. /// into title memory, and the ranges are done with.
  2691. fn hand_back(back: &[Declared]) {
  2692. if crate::shadow::wide_back() {
  2693. // Every range first (the pieces that differ, found on several
  2694. // threads), then the merges, in order, as below.
  2695. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2696. for (shadow, declared) in back {
  2697. if shadow.carded() {
  2698. continue;
  2699. }
  2700. let mut sorted = declared.clone();
  2701. sorted.sort_unstable();
  2702. let mut spans: Vec<(usize, usize)> = Vec::new();
  2703. for (from, to) in sorted {
  2704. match spans.last_mut() {
  2705. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2706. _ => spans.push((from, to)),
  2707. }
  2708. }
  2709. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2710. }
  2711. #[cfg(feature = "diagnostics")]
  2712. let scanning = std::time::Instant::now();
  2713. let found = crate::shadow::find_all(&work);
  2714. #[cfg(feature = "diagnostics")]
  2715. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2716. for ((shadow, from, to), found) in work.iter().zip(found) {
  2717. let written = shadow.copy_back_with(*from, to - from, Some(found));
  2718. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  2719. #[cfg(feature = "diagnostics")]
  2720. crate::copystat::compared(*from, to - from, written);
  2721. }
  2722. for (shadow, declared) in back {
  2723. shadow.copy_back_done(declared);
  2724. }
  2725. return;
  2726. }
  2727. for (shadow, declared) in back {
  2728. if shadow.carded() {
  2729. // Done before (`Host::card_back`).
  2730. shadow.copy_back_done(declared);
  2731. continue;
  2732. }
  2733. // Each byte compared once: the world declares dozens of views
  2734. // of its 174 MB heap that overlap almost entirely, and comparing
  2735. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  2736. // MB shaders wrote. Only ranges that overlap or touch are
  2737. // joined: what lies between two was not given to shaders (the
  2738. // snapshot does not hold it).
  2739. let mut sorted = declared.clone();
  2740. sorted.sort_unstable();
  2741. let mut spans: Vec<(usize, usize)> = Vec::new();
  2742. for (from, to) in sorted {
  2743. match spans.last_mut() {
  2744. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2745. _ => spans.push((from, to)),
  2746. }
  2747. }
  2748. for (from, to) in spans {
  2749. let written = shadow.copy_back(from, to - from);
  2750. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  2751. #[cfg(feature = "diagnostics")]
  2752. crate::copystat::compared(from, to - from, written);
  2753. }
  2754. shadow.copy_back_done(declared);
  2755. }
  2756. }
  2757. impl Host {
  2758. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  2759. /// mesh shaders need both); logged once.
  2760. pub(crate) fn mesh_shaders(&self) -> bool {
  2761. static MESH: OnceLock<bool> = OnceLock::new();
  2762. *MESH.get_or_init(|| {
  2763. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  2764. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  2765. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  2766. };
  2767. // SAFETY: each query writes its own structure of the given size.
  2768. let ok = unsafe {
  2769. self.device
  2770. .CheckFeatureSupport(
  2771. D3D12_FEATURE_D3D12_OPTIONS7,
  2772. (&raw mut options).cast(),
  2773. size_of_val(&options) as u32,
  2774. )
  2775. .is_ok()
  2776. && self
  2777. .device
  2778. .CheckFeatureSupport(
  2779. D3D12_FEATURE_SHADER_MODEL,
  2780. (&raw mut model).cast(),
  2781. size_of_val(&model) as u32,
  2782. )
  2783. .is_ok()
  2784. };
  2785. let mesh = ok
  2786. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  2787. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  2788. tracing::info!(mesh, "host mesh shader support");
  2789. mesh
  2790. })
  2791. }
  2792. /// A new list, open for recording.
  2793. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  2794. #[cfg(feature = "diagnostics")]
  2795. let started = std::time::Instant::now();
  2796. #[cfg(feature = "diagnostics")]
  2797. let before = private_bytes();
  2798. let list = self.make_list();
  2799. LISTS[0].fetch_add(1, Ordering::Relaxed);
  2800. // (May shrink while a list is made, on another thread's account:
  2801. // added as it is, the sum is what counts.)
  2802. #[cfg(feature = "diagnostics")]
  2803. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  2804. #[cfg(feature = "diagnostics")]
  2805. {
  2806. use crate::copystat::{C, add};
  2807. add(C::HostLists, 1);
  2808. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  2809. }
  2810. list
  2811. }
  2812. /// An allocator and a closed list for a prelude.
  2813. fn make_prelude(&self) -> Option<Prelude> {
  2814. // SAFETY: plain object creation.
  2815. let made: windows::core::Result<Prelude> = unsafe {
  2816. (|| {
  2817. let allocator: ID3D12CommandAllocator =
  2818. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  2819. let list: ID3D12GraphicsCommandList =
  2820. self.device
  2821. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  2822. list.Close()?;
  2823. Ok((allocator, list))
  2824. })()
  2825. };
  2826. LISTS[1].fetch_add(1, Ordering::Relaxed);
  2827. match made {
  2828. Ok(prelude) => Some(prelude),
  2829. Err(e) => {
  2830. tracing::warn!(error = %e, "no host list for a prelude");
  2831. None
  2832. }
  2833. }
  2834. }
  2835. fn make_list(&self) -> windows::core::Result<HostList> {
  2836. // SAFETY: plain object creation.
  2837. unsafe {
  2838. let allocator: ID3D12CommandAllocator = self
  2839. .device
  2840. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  2841. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  2842. 0,
  2843. D3D12_COMMAND_LIST_TYPE_DIRECT,
  2844. &allocator,
  2845. None,
  2846. )?;
  2847. let prelude = OnceLock::new();
  2848. if !lazy_prelude() {
  2849. let _ = prelude.set(self.make_prelude());
  2850. }
  2851. Ok(HostList {
  2852. allocator,
  2853. list,
  2854. deferred: Mutex::default(),
  2855. scratch: Mutex::default(),
  2856. states: Mutex::default(),
  2857. twins: Mutex::default(),
  2858. prelude,
  2859. pipelines: Mutex::default(),
  2860. budget: OnceLock::new(),
  2861. card_budget: OnceLock::new(),
  2862. indirect_args: Mutex::default(),
  2863. _alive: Counted::new(),
  2864. #[cfg(feature = "diagnostics")]
  2865. notes: Mutex::default(),
  2866. #[cfg(feature = "diagnostics")]
  2867. stamps: OnceLock::new(),
  2868. })
  2869. }
  2870. }
  2871. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  2872. fn card_clock(&self) -> Option<&'static CardClock> {
  2873. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  2874. static WATCH: std::sync::Once = std::sync::Once::new();
  2875. let clock = CLOCK
  2876. .get_or_init(|| {
  2877. // SAFETY: a plain fence on our device.
  2878. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  2879. Some(CardClock {
  2880. fence,
  2881. state: Mutex::new((0, None)),
  2882. sent: std::sync::Condvar::new(),
  2883. })
  2884. })
  2885. .as_ref()?;
  2886. WATCH.call_once(|| {
  2887. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  2888. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  2889. }
  2890. });
  2891. Some(clock)
  2892. }
  2893. /// Lists of ours just went to the queue: the clock's signal goes
  2894. /// behind them, and an idle stretch of the card, if one was under way,
  2895. /// ends here ([`CARD_CLOCK_US`]).
  2896. fn card_sent(&self) {
  2897. let Some(clock) = self.card_clock() else {
  2898. return;
  2899. };
  2900. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  2901. state.0 += 1;
  2902. // SAFETY: our queue and the clock's fence.
  2903. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  2904. if let Some((since, worked_then)) = state.1.take() {
  2905. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  2906. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  2907. }
  2908. drop(state);
  2909. clock.sent.notify_one();
  2910. }
  2911. /// Whether the host has what copies in the card's memory need (three
  2912. /// lists and the compare); made at the first ask. A copy goes to the
  2913. /// card's memory only if it has.
  2914. pub(crate) fn card_ready(&self) -> bool {
  2915. static READY: OnceLock<bool> = OnceLock::new();
  2916. *READY.get_or_init(|| match self.make_card_work() {
  2917. Ok(work) => {
  2918. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  2919. true
  2920. }
  2921. Err(e) => {
  2922. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  2923. false
  2924. }
  2925. })
  2926. }
  2927. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  2928. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  2929. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  2930. let mut code: Option<ID3DBlob> = None;
  2931. // SAFETY: the source and names live through the call; the out
  2932. // pointer is ours.
  2933. unsafe {
  2934. D3DCompile(
  2935. CARD_COMPARE.as_ptr().cast(),
  2936. CARD_COMPARE.len(),
  2937. windows::core::s!("card compare"),
  2938. None,
  2939. None,
  2940. windows::core::s!("main"),
  2941. windows::core::s!("cs_5_1"),
  2942. 0,
  2943. 0,
  2944. &mut code,
  2945. None,
  2946. )?;
  2947. }
  2948. let code = code.ok_or_else(windows::core::Error::empty)?;
  2949. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  2950. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  2951. // in one submission.
  2952. const RESULTS: u64 = 1 << 20;
  2953. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  2954. name(&differs, || "card compare results".into());
  2955. // SAFETY: the blob's own bytes; the root signature is inside the
  2956. // shader.
  2957. unsafe {
  2958. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  2959. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  2960. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  2961. pRootSignature: std::mem::transmute_copy(&root),
  2962. CS: D3D12_SHADER_BYTECODE {
  2963. pShaderBytecode: bytes.as_ptr().cast(),
  2964. BytecodeLength: bytes.len(),
  2965. },
  2966. ..Default::default()
  2967. })?;
  2968. #[cfg(feature = "diagnostics")]
  2969. name(&pso, || crate::replay::play::COMPARE.into());
  2970. Ok(CardWork {
  2971. sync: vec![list()?],
  2972. check: vec![list()?],
  2973. fetch: list()?,
  2974. root,
  2975. pso,
  2976. differs: (differs, data as usize, RESULTS),
  2977. fetched: None,
  2978. taken: 0,
  2979. out: 0,
  2980. })
  2981. }
  2982. }
  2983. /// Before a submission's lists run, for copies in the card's memory
  2984. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  2985. /// the last submission goes to their card side (a list of ours, run
  2986. /// now; the submission's lists follow it on the queue), and the ranges
  2987. /// this submission's shaders may write get a compare to run after its
  2988. /// lists. `None` if there is nothing to do.
  2989. ///
  2990. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  2991. /// then stores the hashes it makes (see [`flagged_pieces`] and
  2992. /// `relay`).
  2993. fn card_before(&self, runs: &[&HostList], flown: bool) -> Option<CardPlan> {
  2994. use std::sync::Arc;
  2995. if !crate::shadow::cards() {
  2996. return None;
  2997. }
  2998. // The ranges this submission's shaders may write, per copy.
  2999. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3000. for list in runs {
  3001. for step in &list.deferred().copies {
  3002. if let Step::GpuWrite(shadow, address, len) = step
  3003. && shadow.carded()
  3004. {
  3005. let range = (*address, *address + *len);
  3006. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3007. Some((_, ranges)) => {
  3008. if !ranges.contains(&range) {
  3009. ranges.push(range);
  3010. }
  3011. }
  3012. None => declared.push((shadow.clone(), vec![range])),
  3013. }
  3014. }
  3015. }
  3016. }
  3017. // With the relay: the order of the queue is held from here until
  3018. // what is taken is on the queue, and the taking is numbered.
  3019. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3020. let sent_as = match order.as_mut() {
  3021. Some(order) => {
  3022. **order += 1;
  3023. **order
  3024. }
  3025. None => 0,
  3026. };
  3027. let mut dirty = crate::shadow::card_dirty(sent_as);
  3028. if declared.is_empty() && dirty.is_empty() {
  3029. return None;
  3030. }
  3031. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3032. let work = work.as_mut()?;
  3033. // A copy whose shader writes are declared for the first time gets
  3034. // its bytes from before, whole.
  3035. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3036. for (shadow, _) in &declared {
  3037. if shadow.card_make_before(|size| {
  3038. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3039. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3040. Some(before)
  3041. }) {
  3042. whole.push(shadow.clone());
  3043. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3044. dirty.push((shadow.clone(), Vec::new()));
  3045. }
  3046. }
  3047. }
  3048. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3049. if !dirty.is_empty() {
  3050. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3051. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3052. };
  3053. let (allocator, list) = &sync;
  3054. // SAFETY: the list's last run finished (it ran ahead of a
  3055. // submission that was waited for, and came back after that);
  3056. // live buffers, and the ranges lie in them.
  3057. let recorded = unsafe {
  3058. (|| -> windows::core::Result<()> {
  3059. allocator.Reset()?;
  3060. list.Reset(allocator, None)?;
  3061. for (shadow, ranges) in &dirty {
  3062. let Some((staging, before, size)) = shadow.card_sides() else {
  3063. continue;
  3064. };
  3065. for &(a, b) in ranges {
  3066. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3067. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3068. }
  3069. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3070. let Some(before) = before else {
  3071. continue;
  3072. };
  3073. // No twin (it cost the card the copy's size again,
  3074. // 399 MB in run 75): `before` holds a 128-bit hash
  3075. // of each 64 KiB piece. The pieces just sent up are
  3076. // hashed again, all of them the first time; the
  3077. // compare after the lists hashes the declared
  3078. // pieces and flags those whose hash is another.
  3079. if !ranges.is_empty() {
  3080. list.ResourceBarrier(&[transition(
  3081. &shadow.buffer,
  3082. D3D12_RESOURCE_STATE_COPY_DEST,
  3083. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3084. )]);
  3085. }
  3086. list.SetComputeRootSignature(&work.root);
  3087. list.SetPipelineState(&work.pso);
  3088. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3089. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3090. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3091. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3092. vec![shadow.card_run(0, usize::MAX)]
  3093. } else {
  3094. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3095. };
  3096. // The same pieces in fewer passes (`rehash_runs`).
  3097. let runs = if rehash_runs() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3098. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3099. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3100. for run in runs {
  3101. let constants = [run.first, run.skew, size as u32, run.pieces, 0, 0];
  3102. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  3103. list.Dispatch(run.pieces.div_ceil(64), 1, 1);
  3104. }
  3105. }
  3106. list.Close()?;
  3107. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3108. Ok(())
  3109. })()
  3110. };
  3111. if let Err(e) = recorded {
  3112. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3113. }
  3114. used.push((false, sync));
  3115. }
  3116. drop(order);
  3117. let mut plan = CardPlan {
  3118. ranges: Vec::new(),
  3119. check: None,
  3120. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3121. lists: used,
  3122. sent_as,
  3123. };
  3124. // Each byte once, as the copy-back joins the declared ranges. The
  3125. // results go behind those of plans still in the air.
  3126. let mut at = work.taken;
  3127. for (shadow, ranges) in &declared {
  3128. let mut sorted = ranges.clone();
  3129. sorted.sort_unstable();
  3130. let mut spans: Vec<(usize, usize)> = Vec::new();
  3131. for (from, to) in sorted {
  3132. match spans.last_mut() {
  3133. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3134. _ => spans.push((from, to)),
  3135. }
  3136. }
  3137. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3138. for (from, to) in spans {
  3139. let Some(span) = shadow.card_span(from, to) else {
  3140. continue;
  3141. };
  3142. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3143. plan.ranges.push(CardRange {
  3144. shadow: shadow.clone(),
  3145. declared: (from, to),
  3146. span,
  3147. at,
  3148. compared,
  3149. });
  3150. if compared {
  3151. at += span.pieces;
  3152. }
  3153. }
  3154. }
  3155. work.taken = at;
  3156. if plan.ranges.iter().any(|r| r.compared) {
  3157. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3158. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3159. };
  3160. let (allocator, list) = &check;
  3161. // SAFETY: the list's last run finished (its submission was
  3162. // waited for, and it came back after that); live buffers; the
  3163. // compare's own root signature.
  3164. let recorded = unsafe {
  3165. (|| -> windows::core::Result<ID3D12CommandList> {
  3166. allocator.Reset()?;
  3167. list.Reset(allocator, None)?;
  3168. // What the submission's shaders wrote, first.
  3169. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3170. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3171. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3172. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3173. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3174. pResource: std::mem::ManuallyDrop::new(None),
  3175. }),
  3176. },
  3177. }]);
  3178. list.SetComputeRootSignature(&work.root);
  3179. list.SetPipelineState(&work.pso);
  3180. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3181. for r in plan.ranges.iter().filter(|r| r.compared) {
  3182. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3183. continue;
  3184. };
  3185. let constants = [r.span.first, r.span.skew, size as u32, r.span.pieces, r.at * 4, if flown { 2 } else { 1 }];
  3186. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  3187. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3188. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3189. list.Dispatch(r.span.pieces.div_ceil(64), 1, 1);
  3190. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3191. }
  3192. list.Close()?;
  3193. list.cast()
  3194. })()
  3195. };
  3196. match recorded {
  3197. Ok(list) => plan.check = Some(list),
  3198. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3199. }
  3200. plan.lists.push((true, check));
  3201. }
  3202. work.out += 1;
  3203. Some(plan)
  3204. }
  3205. /// With [`relay`]: whether the compare's result area is half taken by
  3206. /// plans in the air. It starts from the beginning only when no plan is
  3207. /// out, so the caller lets the flights land first.
  3208. fn card_results_low(&self) -> bool {
  3209. CARD_WORK
  3210. .lock()
  3211. .unwrap_or_else(|e| e.into_inner())
  3212. .as_ref()
  3213. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3214. }
  3215. /// The plan's submission has run and its results were read
  3216. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3217. /// when nothing of ours is on the card, so the compare's results start
  3218. /// from the beginning again.
  3219. fn card_done(&self, plan: CardPlan) {
  3220. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3221. let Some(work) = work.as_mut() else {
  3222. return;
  3223. };
  3224. for (check, list) in plan.lists {
  3225. if check { work.check.push(list) } else { work.sync.push(list) }
  3226. }
  3227. work.out = work.out.saturating_sub(1);
  3228. // With the relay other plans may be on the card, their results
  3229. // not read yet: the area starts again only when none is out.
  3230. if !relay() || work.out == 0 {
  3231. work.taken = 0;
  3232. }
  3233. }
  3234. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3235. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3236. // SAFETY: plain object creation.
  3237. let copying = relay_copy().then(|| unsafe {
  3238. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3239. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3240. let list: ID3D12GraphicsCommandList =
  3241. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3242. list.Close()?;
  3243. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3244. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3245. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3246. ..Default::default()
  3247. })?;
  3248. Ok(((allocator, list), queue))
  3249. })()
  3250. });
  3251. let (list, queue) = match copying {
  3252. Some(Ok((list, queue))) => (list, Some(queue)),
  3253. Some(Err(e)) => {
  3254. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3255. (self.make_prelude()?, None)
  3256. }
  3257. None => (self.make_prelude()?, None),
  3258. };
  3259. // SAFETY: plain objects of our own.
  3260. unsafe {
  3261. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3262. let event = CreateEventW(None, false, false, None).ok()?;
  3263. Some(RelayFetch {
  3264. list,
  3265. queue,
  3266. fence,
  3267. event,
  3268. sent: 0,
  3269. buffer: None,
  3270. })
  3271. }
  3272. }
  3273. /// [`relay`], on the thread that lands flights: for the plans of the
  3274. /// flights being landed (the card has run them), the pieces their
  3275. /// compares flagged are fetched, once each, with a list and a wait of
  3276. /// this thread's own, and what shaders wrote in them goes into title
  3277. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3278. /// no submission lock; a piece flagged under one range of a plan is
  3279. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3280. /// whatever was sent meanwhile, so it may bring a later flight's
  3281. /// bytes, which that flight's landing then finds merged already; and
  3282. /// nothing is sent back up.
  3283. fn relay_card_back(&self, plans: &[&CardPlan], fetch: &mut Option<RelayFetch>) {
  3284. let differs = {
  3285. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3286. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3287. };
  3288. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3289. let mut total = 0u64;
  3290. if let Some((differs, dwords)) = differs {
  3291. // SAFETY: the mapping of the results. The compares of these
  3292. // plans have run, and their dwords are given to no other plan
  3293. // before these are done with (`card_done`).
  3294. let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) };
  3295. let mut seen = std::collections::HashSet::new();
  3296. for plan in plans {
  3297. let flags: Vec<(usize, u32, bool)> = plan
  3298. .ranges
  3299. .iter()
  3300. .flat_map(|r| {
  3301. (0..r.span.pieces).map(move |p| {
  3302. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| d != 0);
  3303. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, flagged)
  3304. })
  3305. })
  3306. .collect();
  3307. let fetched = flagged_pieces(&flags);
  3308. for r in &plan.ranges {
  3309. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3310. for p in 0..r.span.pieces {
  3311. if !fetched.contains(&(copy, r.span.first + p)) {
  3312. continue;
  3313. }
  3314. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3315. if lo < hi && seen.insert((copy, lo, hi)) {
  3316. pieces.push((r.shadow.clone(), lo, hi, total));
  3317. total += (hi - lo) as u64;
  3318. }
  3319. }
  3320. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3321. }
  3322. }
  3323. }
  3324. if fetch.is_none() {
  3325. *fetch = self.make_relay_fetch();
  3326. }
  3327. // The sends these flights ran behind, all a fetch on the copy queue
  3328. // is known to have run behind.
  3329. let behind = plans.iter().map(|p| p.sent_as).max().unwrap_or(0);
  3330. if pieces.is_empty() {
  3331. // Nothing to fetch: every send so far is older than the next
  3332. // fetch, if that goes to the queue the sends went to.
  3333. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  3334. true => behind,
  3335. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  3336. };
  3337. crate::shadow::relay_fetched(after);
  3338. return;
  3339. }
  3340. let Some(f) = fetch.as_mut() else {
  3341. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  3342. };
  3343. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  3344. let size = total.next_multiple_of(16 << 20);
  3345. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3346. }
  3347. let Some((buffer, data, _)) = f.buffer.clone() else {
  3348. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  3349. };
  3350. f.sent += 1;
  3351. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  3352. let copy_queue = f.queue.clone();
  3353. let waiting = std::time::Instant::now();
  3354. // SAFETY: the list's last run was waited for by this thread; live
  3355. // buffers (the copies are held by the plans); the fence and the
  3356. // event are this thread's.
  3357. let ran = unsafe {
  3358. (|| -> windows::core::Result<u64> {
  3359. allocator.Reset()?;
  3360. list.Reset(&allocator, None)?;
  3361. for (shadow, lo, hi, at) in &pieces {
  3362. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  3363. }
  3364. list.Close()?;
  3365. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  3366. if let Some(queue) = &copy_queue {
  3367. queue.ExecuteCommandLists(&lists);
  3368. queue.Signal(&fence, sent)?;
  3369. fence.SetEventOnCompletion(sent, event)?;
  3370. WaitForSingleObject(event, INFINITE);
  3371. return Ok(behind);
  3372. }
  3373. // In the order of the queue: the sends of title bytes so
  3374. // far are ahead of this fetch, every later one behind it.
  3375. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  3376. self.queue.ExecuteCommandLists(&lists);
  3377. let after = *order;
  3378. drop(order);
  3379. self.card_sent();
  3380. self.queue.Signal(&fence, sent)?;
  3381. fence.SetEventOnCompletion(sent, event)?;
  3382. WaitForSingleObject(event, INFINITE);
  3383. Ok(after)
  3384. })()
  3385. };
  3386. let after = match ran {
  3387. Ok(after) => after,
  3388. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  3389. };
  3390. let us = waiting.elapsed().as_micros() as u64;
  3391. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  3392. {
  3393. use crate::shadow::CARD_STATS;
  3394. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  3395. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  3396. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  3397. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  3398. }
  3399. let mut title = Vec::new();
  3400. let mut written = 0;
  3401. for (shadow, lo, hi, at) in &pieces {
  3402. // SAFETY: the mapping of the fetched bytes, `total` of them;
  3403. // the copy into it has run.
  3404. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  3405. written += shadow.card_merge_relay(*lo, gpu, after, &mut title);
  3406. }
  3407. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3408. // Sends up to `after` are of no use to any later merge.
  3409. crate::shadow::relay_fetched(after);
  3410. }
  3411. /// [`relay`], on the thread that lands flights: `items` are the first
  3412. /// things of the line, flights the card has run and what follows them.
  3413. /// What their shaders wrote goes into title memory (copies in the
  3414. /// card's memory first, then the others, each byte once whichever
  3415. /// flights declared it); then every flight's ranges are done with;
  3416. /// then, in the line's order, each flight's read-backs, its
  3417. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  3418. /// is complete before the title is told anything.
  3419. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  3420. let landing = std::time::Instant::now();
  3421. {
  3422. let flights: Vec<&Flight> = items
  3423. .iter()
  3424. .filter_map(|l| match l {
  3425. Late::Run(flight) => Some(flight),
  3426. _ => None,
  3427. })
  3428. .collect();
  3429. if !flights.is_empty() {
  3430. // SAFETY: a plain query.
  3431. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  3432. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  3433. fail(format_args!(
  3434. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  3435. flights.len(),
  3436. runs.len(),
  3437. self.removal_data(&runs),
  3438. last_notes(&runs)
  3439. ));
  3440. }
  3441. let plans: Vec<&CardPlan> = flights.iter().filter_map(|f| f.card.as_ref()).collect();
  3442. self.relay_card_back(&plans, fetch);
  3443. let mut back: Vec<Declared> = Vec::new();
  3444. for flight in &flights {
  3445. for (shadow, ranges) in &flight.back {
  3446. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  3447. Some((_, all)) => {
  3448. for range in ranges {
  3449. if !all.contains(range) {
  3450. all.push(*range);
  3451. }
  3452. }
  3453. }
  3454. None => back.push((shadow.clone(), ranges.clone())),
  3455. }
  3456. }
  3457. }
  3458. relay_hand_back(&back);
  3459. // Only now, and flight by flight: a range another flight
  3460. // in the air declared too stays closed to refreshes.
  3461. for flight in &flights {
  3462. for (shadow, ranges) in &flight.back {
  3463. shadow.copy_back_done(ranges);
  3464. }
  3465. }
  3466. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  3467. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  3468. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  3469. }
  3470. }
  3471. // In the order given: what tells the title the card is done.
  3472. let mut last = 0;
  3473. let mut landed = Vec::new();
  3474. for item in items {
  3475. match item {
  3476. Late::Run(flight) => {
  3477. last = flight.number;
  3478. for &i in &flight.order {
  3479. read_backs(flight.lists[i].host());
  3480. }
  3481. if let Some(card) = flight.card {
  3482. self.card_done(card);
  3483. }
  3484. landed.push((flight.lists, flight.order));
  3485. }
  3486. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  3487. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  3488. }
  3489. }
  3490. if last > 0 {
  3491. FINISHED.store(last, Ordering::Release);
  3492. bury(last);
  3493. }
  3494. self.log_messages();
  3495. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  3496. {
  3497. let mut line = line();
  3498. let Line {
  3499. line: items,
  3500. written,
  3501. lists,
  3502. settling,
  3503. poke,
  3504. landed: kept,
  3505. in_hand,
  3506. ..
  3507. } = &mut *line;
  3508. kept.extend(landed);
  3509. in_hand.clear();
  3510. // What is still in the air, from the flights that are.
  3511. written.clear();
  3512. *lists = 0;
  3513. let mut ranges = Vec::new();
  3514. for item in items.iter() {
  3515. if let Late::Run(flight) = item {
  3516. *lists += flight.order.len().max(1);
  3517. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  3518. }
  3519. }
  3520. join_ranges(written, ranges);
  3521. *settling = false;
  3522. // The landed lists are reset, and what queues hold looked at,
  3523. // by the helper thread (they take locks a waiter may hold).
  3524. *poke = true;
  3525. }
  3526. LINE_MOVED.notify_all();
  3527. LINE_LANDED.notify_all();
  3528. }
  3529. /// After a submission ran, for copies in the card's memory: the pieces
  3530. /// of the declared ranges that the compare found differing (all of a
  3531. /// range it did not compare) are fetched, with one more wait for the
  3532. /// card, and what shaders wrote in them goes into title memory.
  3533. /// `submitted` is the last value signalled on the fence. `seen` holds
  3534. /// the pieces fetched already since the card was last waited for
  3535. /// (several submissions settled together name the same ones).
  3536. fn card_back(
  3537. &self,
  3538. plan: &CardPlan,
  3539. submitted: &mut u64,
  3540. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  3541. ) {
  3542. if plan.ranges.is_empty() {
  3543. return;
  3544. }
  3545. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3546. let Some(work) = work.as_mut() else {
  3547. return;
  3548. };
  3549. // SAFETY: the mapping of the results, which the compare (it has
  3550. // run) wrote.
  3551. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  3552. // The pieces to fetch: the range, the offsets in its copy, and
  3553. // where the bytes come down.
  3554. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  3555. let mut total = 0u64;
  3556. for (i, r) in plan.ranges.iter().enumerate() {
  3557. for p in 0..r.span.pieces {
  3558. if r.compared && differs[(r.at + p) as usize] == 0 {
  3559. continue;
  3560. }
  3561. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3562. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  3563. pieces.push((i, lo, hi, total));
  3564. total += (hi - lo) as u64;
  3565. }
  3566. }
  3567. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3568. }
  3569. let mut written = vec![0usize; plan.ranges.len()];
  3570. if !pieces.is_empty() {
  3571. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  3572. let size = total.next_multiple_of(16 << 20);
  3573. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3574. }
  3575. let Some((fetched, data, _)) = &work.fetched else {
  3576. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  3577. };
  3578. let waiting = std::time::Instant::now();
  3579. let (allocator, list) = &work.fetch;
  3580. // SAFETY: the list's last run was waited for; live buffers; the
  3581. // fence and event are ours, under the submission lock.
  3582. let ran = unsafe {
  3583. (|| -> windows::core::Result<()> {
  3584. allocator.Reset()?;
  3585. list.Reset(allocator, None)?;
  3586. for &(i, lo, hi, at) in &pieces {
  3587. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  3588. }
  3589. list.Close()?;
  3590. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3591. self.card_sent();
  3592. *submitted += 1;
  3593. self.queue.Signal(&self.fence, *submitted)?;
  3594. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  3595. let was_working = working(false);
  3596. WaitForSingleObject(self.event, INFINITE);
  3597. stood(waiting);
  3598. working(was_working);
  3599. Ok(())
  3600. })()
  3601. };
  3602. if let Err(e) = ran {
  3603. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  3604. }
  3605. {
  3606. use crate::shadow::CARD_STATS;
  3607. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  3608. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  3609. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  3610. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  3611. }
  3612. if wide_merge() && pieces.len() >= 8 {
  3613. // The pieces are apart from one another (each its own bytes
  3614. // of its copy and of title memory): several at a time.
  3615. let fetched = *data;
  3616. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  3617. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  3618. let each = pieces.len().div_ceil(8);
  3619. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  3620. .chunks(each)
  3621. .map(|chunk| {
  3622. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  3623. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  3624. let counts = counts.clone();
  3625. Box::new(move || {
  3626. let mut title = Vec::new();
  3627. for (shadow, i, lo, hi, at) in chunk {
  3628. // SAFETY: the mapping of the fetched bytes;
  3629. // the copy into it has run, and the caller
  3630. // waits for this job.
  3631. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  3632. counts[i].fetch_add(shadow.card_merge(lo, gpu, &mut title), Ordering::Relaxed);
  3633. }
  3634. }) as Box<dyn FnOnce() + Send>
  3635. })
  3636. .collect();
  3637. crate::shadow::wide_run(jobs);
  3638. for (written, count) in written.iter_mut().zip(counts.iter()) {
  3639. *written += count.load(Ordering::Relaxed);
  3640. }
  3641. } else {
  3642. let mut title = Vec::new();
  3643. for &(i, lo, hi, at) in &pieces {
  3644. // SAFETY: the mapping of the fetched bytes, `total` of
  3645. // them; the copy into it has run.
  3646. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  3647. written[i] += plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  3648. }
  3649. }
  3650. }
  3651. for (r, written) in plan.ranges.iter().zip(written) {
  3652. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3653. let (from, to) = r.declared;
  3654. #[cfg(feature = "diagnostics")]
  3655. crate::copystat::compared(from, to - from, written);
  3656. let _ = (from, to);
  3657. }
  3658. }
  3659. /// Runs closed lists and waits for them, and with [`late`] for
  3660. /// everything sent to the card before them, which is settled first.
  3661. pub(crate) fn execute(&self, runs: &[&HostList]) {
  3662. let _ = self.submit(runs, false);
  3663. }
  3664. /// A queue's submission with [`late`]: the host lists `lists`, taken
  3665. /// from the title's, go to the card in `order` and are not waited for.
  3666. /// They join the line of flights and are settled, with the others in
  3667. /// the air, at the next point where what they do can be observed
  3668. /// ([`late`] lists those points); their host lists are reset and kept
  3669. /// for reuse then, as a queue does for the lists it ran.
  3670. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  3671. if order.is_empty() {
  3672. crate::list::recycle(lists, &order);
  3673. return;
  3674. }
  3675. late_threads();
  3676. let sent = {
  3677. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  3678. self.submit(&runs, true)
  3679. };
  3680. let Some((mut submitted, sent)) = sent else {
  3681. // (Not reached: a submission sent ahead always comes back.)
  3682. crate::list::recycle(lists, &order);
  3683. return;
  3684. };
  3685. let told = !sent.writes.is_empty();
  3686. let most = {
  3687. let mut line = line();
  3688. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  3689. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  3690. *flying += order.len();
  3691. *target = *submitted;
  3692. items.push(Late::Run(Flight {
  3693. number: sent.number,
  3694. fence: *target,
  3695. lists,
  3696. order,
  3697. card: sent.card,
  3698. back: sent.back,
  3699. }));
  3700. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  3701. *flying >= late_most()
  3702. };
  3703. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  3704. RELAY_MOVED.notify_one();
  3705. if told && !late_writes() {
  3706. self.settle(&mut submitted, WHY_WRITES);
  3707. } else if most && relay_exact() {
  3708. // Until there are fewer, not until there are none.
  3709. relay_wait(WHY_MOST, |line| line.lists < late_most());
  3710. } else if most {
  3711. self.settle(&mut submitted, WHY_MOST);
  3712. } else {
  3713. LINE_MOVED.notify_one();
  3714. }
  3715. drop(submitted);
  3716. land();
  3717. }
  3718. /// Sends `list`, a closed list of ours (the present's copy), as a
  3719. /// flight ([`late_free_present`]): not waited for, settled with the
  3720. /// others. The caller keeps the list and does not reset it before the
  3721. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  3722. /// it ran and was waited for after all.
  3723. fn execute_own(&self, list: &HostList) -> u64 {
  3724. late_threads();
  3725. let Some((submitted, sent)) = self.submit(&[list], true) else {
  3726. return 0;
  3727. };
  3728. let number = sent.number;
  3729. {
  3730. let mut line = line();
  3731. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  3732. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  3733. *flying += 1;
  3734. *target = *submitted;
  3735. items.push(Late::Run(Flight {
  3736. number,
  3737. fence: *target,
  3738. lists: Vec::new(),
  3739. order: Vec::new(),
  3740. card: sent.card,
  3741. back: sent.back,
  3742. }));
  3743. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  3744. }
  3745. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  3746. LINE_MOVED.notify_one();
  3747. RELAY_MOVED.notify_one();
  3748. drop(submitted);
  3749. number
  3750. }
  3751. /// Waits for the card to run every flight in the air ([`late`]) and
  3752. /// does what they left to do, as [`Host::execute`] does for one
  3753. /// submission after its wait: the pieces their shaders wrote in copies
  3754. /// in the card's memory are fetched and merged (each once), the ranges
  3755. /// they declared in the other copies are compared and copied back
  3756. /// (each byte once, whichever flights declared it), and then, in the
  3757. /// order they were given: their bottom-of-pipe writes and the fence
  3758. /// signals behind them. `submitted` is the submission lock's value;
  3759. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  3760. ///
  3761. /// Everything in the air is settled, never the first flights alone:
  3762. /// the merge writes the copies' CPU side, which a flight still on the
  3763. /// card may be writing too.
  3764. fn settle(&self, submitted: &mut u64, why: usize) {
  3765. if !late() {
  3766. return;
  3767. }
  3768. if relay() {
  3769. // Nothing is settled here: the thread that lands flights does
  3770. // it, in order, and this waits until nothing is in the air and
  3771. // nothing is being landed. Every point that settled before
  3772. // comes here, so each still sees title memory, fences and
  3773. // bottom-of-pipe values as after a settle.
  3774. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  3775. return;
  3776. }
  3777. let was_working = working(true);
  3778. let mut counted = false;
  3779. loop {
  3780. let items = {
  3781. let mut line = line();
  3782. if line.line.is_empty() {
  3783. line.settling = false;
  3784. break;
  3785. }
  3786. line.settling = true;
  3787. line.written.clear();
  3788. line.lists = 0;
  3789. std::mem::take(&mut line.line)
  3790. };
  3791. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  3792. if !counted {
  3793. counted = true;
  3794. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  3795. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  3796. }
  3797. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  3798. if flights > 0 {
  3799. submitting(2, flights);
  3800. let waiting = std::time::Instant::now();
  3801. // SAFETY: the fence and event are ours, under the
  3802. // submission lock; `submitted` is the last value signalled.
  3803. unsafe {
  3804. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  3805. Ok(()) => {
  3806. working(false);
  3807. WaitForSingleObject(self.event, INFINITE);
  3808. stood(waiting);
  3809. working(true);
  3810. }
  3811. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  3812. }
  3813. }
  3814. let gpu = waiting.elapsed();
  3815. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  3816. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  3817. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  3818. #[cfg(feature = "diagnostics")]
  3819. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  3820. format!("{flights} submissions sent ahead, settled together")
  3821. });
  3822. // SAFETY: a plain query.
  3823. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  3824. let runs: Vec<&HostList> = items
  3825. .iter()
  3826. .filter_map(|i| match i {
  3827. Late::Run(f) => Some(f),
  3828. _ => None,
  3829. })
  3830. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  3831. .collect();
  3832. fail(format_args!(
  3833. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  3834. runs.len(),
  3835. self.removal_data(&runs),
  3836. last_notes(&runs)
  3837. ));
  3838. }
  3839. submitting(3, flights);
  3840. let copying = std::time::Instant::now();
  3841. let mut seen = std::collections::HashSet::new();
  3842. let mut back: Vec<Declared> = Vec::new();
  3843. for item in &items {
  3844. let Late::Run(flight) = item else {
  3845. continue;
  3846. };
  3847. if let Some(card) = &flight.card {
  3848. self.card_back(card, submitted, &mut seen);
  3849. }
  3850. for (shadow, ranges) in &flight.back {
  3851. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  3852. Some((_, all)) => {
  3853. for range in ranges {
  3854. if !all.contains(range) {
  3855. all.push(*range);
  3856. }
  3857. }
  3858. }
  3859. None => back.push((shadow.clone(), ranges.clone())),
  3860. }
  3861. }
  3862. }
  3863. hand_back(&back);
  3864. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  3865. }
  3866. // In the order given: what tells the title the card is done.
  3867. let mut last = 0;
  3868. let mut landed = Vec::new();
  3869. for item in items {
  3870. match item {
  3871. Late::Run(flight) => {
  3872. last = flight.number;
  3873. for &i in &flight.order {
  3874. read_backs(flight.lists[i].host());
  3875. }
  3876. if let Some(card) = flight.card {
  3877. self.card_done(card);
  3878. }
  3879. landed.push((flight.lists, flight.order));
  3880. }
  3881. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  3882. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  3883. }
  3884. }
  3885. if last > 0 {
  3886. FINISHED.store(last, Ordering::Release);
  3887. bury(last);
  3888. }
  3889. line().landed.extend(landed);
  3890. }
  3891. if counted {
  3892. self.log_messages();
  3893. submitting(0, 0);
  3894. // What was settled may be what a queue stands at, and the
  3895. // caller may not be one that looks (a read-back, a present).
  3896. if why != WHY_CARD_DONE {
  3897. line().poke = true;
  3898. LINE_MOVED.notify_one();
  3899. }
  3900. }
  3901. working(was_working);
  3902. }
  3903. /// [`Host::execute`], or with `late` the first half of
  3904. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  3905. /// to be done once they have run comes back with the submission lock
  3906. /// still held.
  3907. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  3908. #[cfg(feature = "diagnostics")]
  3909. let called = std::time::Instant::now();
  3910. #[cfg(feature = "diagnostics")]
  3911. crate::copystat::submission_begins();
  3912. // One submission at a time from preparation to copy-back: snapshots
  3913. // and the ranges shaders write are per host copy, not per submission.
  3914. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  3915. let was_working = working(true);
  3916. submitting(1, runs.len());
  3917. // Flights in the air ([`late`]): a submission that is waited for
  3918. // settles them first, one sent ahead only if preparing it reads
  3919. // what they write.
  3920. if !late {
  3921. self.settle(&mut submitted, WHY_SYNC);
  3922. } else if let Some(why) = late_blocked(runs) {
  3923. if relay_exact() && why == WHY_READ {
  3924. // Only until the flights that may write what is read have
  3925. // landed: their copy-back's end, not the card's other work.
  3926. relay_wait(why, |line| blocked_by(&line.written, runs, false).is_none());
  3927. } else {
  3928. self.settle(&mut submitted, why);
  3929. }
  3930. }
  3931. let behind = late && flying();
  3932. // Before this submission counts as started: what the sweep lets go
  3933. // of is named by no list, and nothing runs now (behind flights the
  3934. // sweep waits for a submission that finds none in the air: there is
  3935. // one at every present).
  3936. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  3937. if !behind {
  3938. sweep();
  3939. SWEPT.store(now_ms(), Ordering::Relaxed);
  3940. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  3941. // With the present sent ahead nothing else brings a moment
  3942. // with nothing in the air: one is made for the sweep.
  3943. self.settle(&mut submitted, WHY_SYNC);
  3944. sweep();
  3945. SWEPT.store(now_ms(), Ordering::Relaxed);
  3946. }
  3947. let behind = late && flying();
  3948. // The slots that waited for a texture's host copy, before the
  3949. // lists that may read them run.
  3950. crate::descriptor::make_waiting();
  3951. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  3952. // The ranges shaders write are counted for it (with the relay).
  3953. crate::shadow::preparing(this_submission);
  3954. let started = std::time::Instant::now();
  3955. #[cfg(feature = "diagnostics")]
  3956. let lock = (started - called).as_micros() as u64;
  3957. #[cfg(feature = "diagnostics")]
  3958. crate::copystat::add(crate::copystat::C::Submissions, 1);
  3959. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  3960. // Where each run's lists start in `lists`.
  3961. let mut firsts = Vec::with_capacity(runs.len());
  3962. let mut batch = Batch::default();
  3963. // The time a settle of flights takes inside this preparing: the
  3964. // wait for the card and the copy-back have their own places on the
  3965. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  3966. let mut settled = std::time::Duration::ZERO;
  3967. // One write-watch asking for everything the submission refreshes
  3968. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  3969. if crate::watch::once() {
  3970. let mut spans: std::collections::HashMap<usize, (usize, usize)> = std::collections::HashMap::new();
  3971. for list in runs {
  3972. for step in &list.deferred().copies {
  3973. if let Step::Refresh(shadow, address, len) = step
  3974. && !shadow.unwatched()
  3975. {
  3976. let span = spans
  3977. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  3978. .or_insert((*address, *address + *len));
  3979. *span = (span.0.min(*address), span.1.max(*address + *len));
  3980. }
  3981. }
  3982. }
  3983. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  3984. crate::watch::ask_once(&ranges);
  3985. // Behind flights: the title wrote memory that a flight's shaders
  3986. // may write too, and this submission refreshes it. The flights
  3987. // are settled, and the asking made again: the copy-back wrote
  3988. // title memory, which other copies of it must see.
  3989. if behind && stale_under_flights(runs) {
  3990. let settling = std::time::Instant::now();
  3991. self.settle(&mut submitted, WHY_STALE);
  3992. settled += settling.elapsed();
  3993. crate::watch::ask_once(&ranges);
  3994. }
  3995. } else if behind && stale_under_flights(runs) {
  3996. let settling = std::time::Instant::now();
  3997. self.settle(&mut submitted, WHY_STALE);
  3998. settled += settling.elapsed();
  3999. }
  4000. for list in runs {
  4001. list.run_deferred(&mut batch);
  4002. firsts.push(lists.len());
  4003. if let Some(prelude) = list.prelude() {
  4004. lists.push(Some(prelude));
  4005. }
  4006. lists.push(list.list.cast().ok());
  4007. }
  4008. batch.flush();
  4009. crate::watch::ask_once_end();
  4010. // The snapshots of the ranges shaders may write, if they were left
  4011. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4012. // lists have not gone to the card.
  4013. {
  4014. #[cfg(feature = "diagnostics")]
  4015. let snapshots = std::time::Instant::now();
  4016. crate::shadow::take_snapshots();
  4017. #[cfg(feature = "diagnostics")]
  4018. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4019. }
  4020. // Copies in the card's memory: what changed on their CPU side goes
  4021. // up ahead of the lists, and a compare of what the shaders may
  4022. // write follows them in the same submission.
  4023. let flown = late && relay();
  4024. if flown && self.card_results_low() {
  4025. let settling = std::time::Instant::now();
  4026. self.settle(&mut submitted, WHY_MOST);
  4027. settled += settling.elapsed();
  4028. }
  4029. let card = self.card_before(runs, flown);
  4030. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4031. lists.push(Some(check));
  4032. }
  4033. let prepared = std::time::Instant::now();
  4034. if late {
  4035. *submitted += 1;
  4036. // SAFETY: closed lists; the fence is ours.
  4037. let signalled = unsafe {
  4038. self.queue.ExecuteCommandLists(&lists);
  4039. self.queue.Signal(&self.fence, *submitted)
  4040. };
  4041. self.card_sent();
  4042. if let Err(e) = signalled {
  4043. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4044. }
  4045. let back = declared_writes(runs);
  4046. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4047. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4048. submitting(0, 0);
  4049. #[cfg(feature = "diagnostics")]
  4050. crate::copystat::submission_ends(lock);
  4051. let sent = Sent {
  4052. number: this_submission,
  4053. card,
  4054. back,
  4055. writes,
  4056. };
  4057. working(was_working);
  4058. return Some((submitted, sent));
  4059. }
  4060. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4061. #[cfg(feature = "diagnostics")]
  4062. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4063. firsts
  4064. .iter()
  4065. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4066. .map(|(&a, &b)| &lists[a..b])
  4067. .collect()
  4068. } else {
  4069. vec![&lists[..]]
  4070. };
  4071. #[cfg(not(feature = "diagnostics"))]
  4072. let groups = [&lists[..]];
  4073. submitting(2, runs.len());
  4074. for (i, group) in groups.iter().enumerate() {
  4075. *submitted += 1;
  4076. let started = std::time::Instant::now();
  4077. // SAFETY: closed lists; the fence and event are ours.
  4078. unsafe {
  4079. self.queue.ExecuteCommandLists(group);
  4080. self.card_sent();
  4081. let waited = self
  4082. .queue
  4083. .Signal(&self.fence, *submitted)
  4084. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4085. match waited {
  4086. Ok(()) => {
  4087. working(false);
  4088. WaitForSingleObject(self.event, INFINITE);
  4089. stood(started);
  4090. working(true);
  4091. }
  4092. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4093. }
  4094. }
  4095. // With timing on each group is one of `runs` (and the compare
  4096. // of copies in the card's memory, with the last): every
  4097. // command's time on the card goes to the sums by pipeline.
  4098. #[cfg(feature = "diagnostics")]
  4099. if timing() {
  4100. // SAFETY: a plain query.
  4101. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4102. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4103. crate::copystat::command_took(&op, ms);
  4104. }
  4105. }
  4106. // A submission of one list was never named here (`groups.len()
  4107. // > 1` was the test): the two 50 ms lists of the gameplay
  4108. // frame, each a submission of its own, printed nothing.
  4109. #[cfg(feature = "diagnostics")]
  4110. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4111. // SAFETY: a plain query.
  4112. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4113. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4114. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4115. for (ms, op) in runs[i].slowest(frequency, 6) {
  4116. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4117. }
  4118. }
  4119. let _ = (i, started);
  4120. }
  4121. let _ = &firsts;
  4122. FINISHED.store(this_submission, Ordering::Release);
  4123. bury(this_submission);
  4124. let gpu = prepared.elapsed();
  4125. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4126. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4127. #[cfg(feature = "diagnostics")]
  4128. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4129. let pipelines: std::collections::BTreeSet<String> = runs
  4130. .iter()
  4131. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4132. .collect();
  4133. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  4134. text.chars().take(1200).collect()
  4135. });
  4136. // The host resets a device whose submission runs for about 2 s.
  4137. if gpu > std::time::Duration::from_millis(250) {
  4138. let pipelines: std::collections::BTreeSet<String> = runs
  4139. .iter()
  4140. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4141. .collect();
  4142. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  4143. }
  4144. // SAFETY: a plain query.
  4145. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4146. fail(format_args!(
  4147. "host GPU device removed after a submission of {} lists{}{}",
  4148. runs.len(),
  4149. self.removal_data(runs),
  4150. last_notes(runs)
  4151. ));
  4152. }
  4153. submitting(3, runs.len());
  4154. // What shaders wrote goes back before the bottom-of-pipe writes,
  4155. // which tell the title the GPU is done; each range once per
  4156. // submission, however many dispatches declared it (the world's
  4157. // passes declare the same big ranges dozens of times).
  4158. let copying = std::time::Instant::now();
  4159. // For copies in the card's memory the compare has run there: the
  4160. // pieces that differ are fetched and merged.
  4161. if let Some(card) = &card {
  4162. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  4163. }
  4164. let back = declared_writes(runs);
  4165. hand_back(&back);
  4166. if let Some(card) = card {
  4167. self.card_done(card);
  4168. }
  4169. #[cfg(feature = "diagnostics")]
  4170. if !back.is_empty() {
  4171. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  4172. }
  4173. // Nothing of this submission goes back to the title: no range of
  4174. // shader writes, no value written when it is done. The wait for
  4175. // such a one is only for order and for what the card still holds.
  4176. #[cfg(feature = "diagnostics")]
  4177. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  4178. use crate::copystat::{C, add};
  4179. add(C::NothingBack, 1);
  4180. add(C::NothingBackUs, gpu.as_micros() as u64);
  4181. }
  4182. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4183. for list in runs {
  4184. // Read backs first: a value written at the bottom of the pipe
  4185. // may be what tells the title that they are there.
  4186. read_backs(list);
  4187. for &(at, what, bytes) in &list.deferred().writes {
  4188. what.write(at as *mut u8, bytes);
  4189. }
  4190. }
  4191. self.log_messages();
  4192. submitting(0, 0);
  4193. #[cfg(feature = "diagnostics")]
  4194. crate::copystat::submission_ends(lock);
  4195. // With the relay: nothing is in the air now, so no fetch still to
  4196. // be merged is older than the sends to card copies so far, and
  4197. // their notes can go.
  4198. if relay() {
  4199. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  4200. }
  4201. working(was_working);
  4202. None
  4203. }
  4204. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  4205. /// it lies in (by the names we give them) or the title memory copy just
  4206. /// below it; for each list that did not finish, the command it stopped
  4207. /// at and what the draws and dispatches in flight there run (or, in
  4208. /// lists that never started, the pipelines they bind).
  4209. fn removal_data(&self, runs: &[&HostList]) -> String {
  4210. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  4211. return String::new();
  4212. };
  4213. let mut text = String::new();
  4214. let mut fault_va = None;
  4215. // SAFETY: the outputs are the runtime's, valid while the device
  4216. // lives; nodes are walked as linked, histories have their counts.
  4217. unsafe {
  4218. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  4219. && fault.PageFaultVA != 0
  4220. {
  4221. let va = fault.PageFaultVA;
  4222. fault_va = Some(va);
  4223. text.push_str(&format!("; page fault at {va:#x}"));
  4224. for (what, head) in [
  4225. ("inside", fault.pHeadExistingAllocationNode),
  4226. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  4227. ] {
  4228. let mut names = Vec::new();
  4229. let mut node = head;
  4230. while let Some(n) = node.as_ref()
  4231. && names.len() < 8
  4232. {
  4233. let name = if n.ObjectNameW.is_null() {
  4234. "unnamed".to_owned()
  4235. } else {
  4236. n.ObjectNameW.to_string().unwrap_or_default()
  4237. };
  4238. names.push(format!("{name} (type {})", n.AllocationType.0));
  4239. node = n.pNext;
  4240. }
  4241. if !names.is_empty() {
  4242. text.push_str(&format!("; {what} {names:?}"));
  4243. }
  4244. }
  4245. text.push_str(&crate::shadow::near(va));
  4246. text.push_str(&crate::descriptor::host::near_heaps(va));
  4247. }
  4248. // The plain output: the extended one (with marker texts) came
  4249. // back without stopped lists on this host.
  4250. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  4251. Ok(crumbs) => crumbs,
  4252. Err(e) => {
  4253. text.push_str(&format!("; no breadcrumbs ({e})"));
  4254. return text;
  4255. }
  4256. };
  4257. // Every list's progress (done/count), in the runtime's order.
  4258. let mut progress = Vec::new();
  4259. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  4260. while let Some(p) = node.as_ref() {
  4261. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4262. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  4263. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  4264. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  4265. node = p.pNext;
  4266. }
  4267. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  4268. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  4269. while let Some(p) = plain.as_ref() {
  4270. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4271. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  4272. let history =
  4273. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  4274. text.push_str(&format!(
  4275. "; a list stopped at command {done} of {} (op {})",
  4276. p.BreadcrumbCount, history[done as usize].0
  4277. ));
  4278. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  4279. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  4280. // The k-th marker command is the k-th note.
  4281. #[cfg(feature = "diagnostics")]
  4282. let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| {
  4283. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  4284. history
  4285. .iter()
  4286. .enumerate()
  4287. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  4288. .zip(notes.iter())
  4289. .map(|((at, _), (note, range))| {
  4290. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  4291. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  4292. })
  4293. .collect()
  4294. });
  4295. #[cfg(not(feature = "diagnostics"))]
  4296. let markers: Vec<(u32, String)> = Vec::new();
  4297. #[cfg(not(feature = "diagnostics"))]
  4298. let _ = fault_va;
  4299. if done > 0 {
  4300. text.push_str(&in_flight(history, &markers, done as usize));
  4301. } else if let Some(r) = run {
  4302. let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  4303. text.push_str(&format!(", its pipelines {pipelines:?}"));
  4304. }
  4305. }
  4306. plain = p.pNext;
  4307. }
  4308. }
  4309. text
  4310. }
  4311. /// Moves the debug layer's messages into our log; returns the first
  4312. /// error among them.
  4313. pub(crate) fn log_messages(&self) -> Option<String> {
  4314. let Some(queue) = &self.messages else {
  4315. return None;
  4316. };
  4317. let mut first_error = None;
  4318. // SAFETY: each message is read into a buffer of the size the queue
  4319. // reports, then the queue is emptied.
  4320. unsafe {
  4321. for i in 0..queue.GetNumStoredMessages() {
  4322. let mut size = 0;
  4323. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  4324. continue;
  4325. }
  4326. let mut buffer = vec![0u64; size.div_ceil(8)];
  4327. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  4328. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  4329. let m = &*message;
  4330. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  4331. let text = String::from_utf8_lossy(text);
  4332. let text = text.trim_end_matches('\0');
  4333. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  4334. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  4335. first_error = Some(text.to_owned());
  4336. }
  4337. }
  4338. }
  4339. queue.ClearStoredMessages();
  4340. }
  4341. first_error
  4342. }
  4343. /// A host render target view of `resource`, valid until it is recorded.
  4344. pub(crate) fn rtv(
  4345. &self,
  4346. resource: Option<&ID3D12Resource>,
  4347. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  4348. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4349. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4350. // SAFETY: a slot of our heap and a live resource, or none with a
  4351. // description (a typed null view).
  4352. unsafe {
  4353. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  4354. handle.ptr += (slot * self.rtv_size) as usize;
  4355. self.device
  4356. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  4357. handle
  4358. }
  4359. }
  4360. /// A host depth view of `resource`, valid until it is recorded.
  4361. pub(crate) fn dsv(
  4362. &self,
  4363. resource: &ID3D12Resource,
  4364. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  4365. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4366. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4367. // SAFETY: a slot of our heap and a live resource.
  4368. unsafe {
  4369. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  4370. handle.ptr += (slot * self.dsv_size) as usize;
  4371. self.device
  4372. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  4373. handle
  4374. }
  4375. }
  4376. }
  4377. impl HostList {
  4378. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  4379. #[cfg(feature = "diagnostics")]
  4380. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  4381. if !timing() {
  4382. return None;
  4383. }
  4384. self.stamps
  4385. .get_or_init(|| {
  4386. let device = &host()?.device;
  4387. let mut heap: Option<ID3D12QueryHeap> = None;
  4388. let mut back: Option<ID3D12Resource> = None;
  4389. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  4390. let desc = D3D12_RESOURCE_DESC {
  4391. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  4392. Width: u64::from(STAMPS) * 8,
  4393. Height: 1,
  4394. DepthOrArraySize: 1,
  4395. MipLevels: 1,
  4396. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  4397. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  4398. ..Default::default()
  4399. };
  4400. // SAFETY: plain object creation.
  4401. unsafe {
  4402. device
  4403. .CreateQueryHeap(
  4404. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  4405. &mut heap,
  4406. )
  4407. .ok()?;
  4408. device
  4409. .CreateCommittedResource(
  4410. &readback,
  4411. D3D12_HEAP_FLAG_NONE,
  4412. &desc,
  4413. D3D12_RESOURCE_STATE_COPY_DEST,
  4414. None,
  4415. &mut back,
  4416. )
  4417. .ok()?;
  4418. }
  4419. Some((heap?, back?))
  4420. })
  4421. .as_ref()
  4422. }
  4423. /// The noted commands that took longest on the GPU, longest first, as
  4424. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  4425. #[cfg(feature = "diagnostics")]
  4426. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  4427. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  4428. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  4429. return Vec::new();
  4430. };
  4431. let mut data = std::ptr::null_mut();
  4432. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  4433. // SAFETY: a read-back buffer the finished list resolved into.
  4434. let stamps: Vec<u64> = unsafe {
  4435. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  4436. return Vec::new();
  4437. }
  4438. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  4439. back.Unmap(0, None);
  4440. s
  4441. };
  4442. let mut times: Vec<(f64, String)> = (0..count)
  4443. .map(|i| {
  4444. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  4445. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  4446. })
  4447. .collect();
  4448. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  4449. times.truncate(n);
  4450. times
  4451. }
  4452. pub(crate) fn close(&self) {
  4453. self.twins_to_depth();
  4454. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  4455. if let Some((scratch, _)) = scratch {
  4456. self.indirect_common(&scratch);
  4457. }
  4458. self.card_budget_out();
  4459. #[cfg(feature = "diagnostics")]
  4460. if let Some((heap, back)) = self.stamps() {
  4461. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  4462. // SAFETY: an open list, our heap and read-back buffer.
  4463. unsafe {
  4464. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  4465. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  4466. }
  4467. }
  4468. // SAFETY: our list.
  4469. if let Err(e) = unsafe { self.list.Close() } {
  4470. fail(format_args!(
  4471. "a host command list did not close ({e}): a command recorded into it was invalid"
  4472. ));
  4473. }
  4474. }
  4475. /// Only after the list's last submission finished (every one is waited
  4476. /// for).
  4477. pub(crate) fn reset(&self) {
  4478. #[cfg(feature = "diagnostics")]
  4479. let started = std::time::Instant::now();
  4480. self._alive.used();
  4481. *self.deferred() = Deferred::default();
  4482. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  4483. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  4484. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  4485. #[cfg(feature = "diagnostics")]
  4486. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  4487. {
  4488. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  4489. (scratch.current, scratch.used) = (0, 0);
  4490. // Every submission of the list has run: nothing reads its
  4491. // scratch memory any more, and the next list to ask takes it.
  4492. if scratch_pool() {
  4493. give_chunks(std::mem::take(&mut scratch.chunks));
  4494. }
  4495. }
  4496. // SAFETY: the list is not executing.
  4497. let reset = unsafe {
  4498. self.allocator
  4499. .Reset()
  4500. .and_then(|()| self.list.Reset(&self.allocator, None))
  4501. };
  4502. if let Err(e) = reset {
  4503. fail(format_args!("a host command list did not reset ({e})"));
  4504. }
  4505. #[cfg(feature = "diagnostics")]
  4506. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  4507. }
  4508. /// Moves a title texture's host copy to `wanted` (a host state) in this
  4509. /// list: the host texture and the state it leaves, if that is a change.
  4510. /// The list's first use of a texture records nothing: its prelude brings
  4511. /// the texture there at submission.
  4512. pub(crate) fn transition(
  4513. &self,
  4514. resource: crate::object::This,
  4515. wanted: u32,
  4516. ) -> Option<(&'static ID3D12Resource, u32)> {
  4517. let texture = crate::resource::host_resource(resource)?;
  4518. let copy = crate::resource::host_copy(resource)?;
  4519. let wanted = legal_state(texture, wanted);
  4520. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  4521. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  4522. std::collections::hash_map::Entry::Vacant(v) => {
  4523. v.insert((wanted, wanted, copy));
  4524. None
  4525. }
  4526. std::collections::hash_map::Entry::Occupied(mut o) => {
  4527. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  4528. (before != wanted).then_some((texture, before))
  4529. }
  4530. }
  4531. }
  4532. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  4533. /// as [`HostList::transition`] does a title resource's host copy, and
  4534. /// records the barrier: for textures that are not a title resource's
  4535. /// host copy (colour twins) and for the copies between the two.
  4536. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  4537. let wanted = legal_state(&copy.texture, wanted);
  4538. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  4539. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  4540. std::collections::hash_map::Entry::Vacant(v) => {
  4541. v.insert((wanted, wanted, copy.clone()));
  4542. None
  4543. }
  4544. std::collections::hash_map::Entry::Occupied(mut o) => {
  4545. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  4546. (before != wanted).then_some(before)
  4547. }
  4548. };
  4549. drop(states);
  4550. if let Some(before) = before {
  4551. let barrier = transition(
  4552. &copy.texture,
  4553. D3D12_RESOURCE_STATES(before as i32),
  4554. D3D12_RESOURCE_STATES(wanted as i32),
  4555. );
  4556. // SAFETY: an open list and a live texture.
  4557. unsafe { self.list.ResourceBarrier(&[barrier]) };
  4558. }
  4559. }
  4560. /// A use of title texture `resource` about to be recorded, if it is a
  4561. /// depth texture with a colour twin (false if it is not): of the twin
  4562. /// (`colour`: unordered access) or of the depth texture (depth target,
  4563. /// clear, shader read, copy, resolve), writing it or only reading. The
  4564. /// side used is first brought up to date: by a copy recorded here if
  4565. /// this list wrote the other side since, by the list's prelude if the
  4566. /// list uses the side as it finds it. The twin is left in the
  4567. /// unordered access state; the caller moves the depth texture to the
  4568. /// state its use needs, as for any texture. A twin still ahead when the
  4569. /// list closes is copied then (`twins_to_depth`).
  4570. /// shortcut: every depth target bound for a draw counts as written
  4571. /// (also when the draw only tests), and every unordered access view a
  4572. /// shader names as written; views a shader picks from the heap by a
  4573. /// computed index are not seen here at all.
  4574. pub(crate) fn twin_use(
  4575. &self,
  4576. resource: crate::object::This,
  4577. colour: bool,
  4578. write: bool,
  4579. ) -> bool {
  4580. const UNORDERED_ACCESS: u32 = 0x8;
  4581. // Asked for every texture a draw reads: most have no twin.
  4582. let Some(twin) = crate::resource::twin(resource) else {
  4583. return false;
  4584. };
  4585. let Some(depth) = crate::resource::host_copy(resource) else {
  4586. return false;
  4587. };
  4588. let side = usize::from(colour);
  4589. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  4590. let u = twins
  4591. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  4592. .or_insert_with(|| TwinUse {
  4593. depth: depth.clone(),
  4594. twin: twin.clone(),
  4595. needs: [false; 2],
  4596. behind: [None; 2],
  4597. writing: false,
  4598. late: false,
  4599. });
  4600. let copy = match u.behind[side] {
  4601. Some(behind) => behind,
  4602. None => {
  4603. u.needs[side] = true;
  4604. false
  4605. }
  4606. };
  4607. u.behind[side] = Some(false);
  4608. match (write, colour) {
  4609. // Shaders write the twin when the draw or dispatch runs: what
  4610. // the same one reads of the depth texture is prepared before
  4611. // (`twins_written`).
  4612. (true, true) => u.writing = true,
  4613. (true, false) => u.behind[1] = Some(true),
  4614. (false, _) => {}
  4615. }
  4616. // shortcut: the depth plane's twin is not drawn into the plane
  4617. // here: the pass sets a pipeline and a target of ours, which a list
  4618. // still recording the title's commands cannot take. This use sees
  4619. // the plane as it was; the pass runs when the list closes
  4620. // (`twins_to_depth`). Counted.
  4621. if copy && !colour && twin.plane.is_some() {
  4622. u.late = true;
  4623. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  4624. }
  4625. drop(twins);
  4626. if copy {
  4627. self.twin_copy(&depth, &twin, colour);
  4628. } else if colour {
  4629. self.settle(&twin.colour, UNORDERED_ACCESS);
  4630. }
  4631. // The depth plane's twin is written through unordered access too.
  4632. if colour && let Some(plane) = &twin.plane {
  4633. self.settle(plane, UNORDERED_ACCESS);
  4634. }
  4635. true
  4636. }
  4637. /// Records the pass that draws the twin of the depth plane of `depth`
  4638. /// into the plane, if `twin` has one, with the moves to the states the
  4639. /// pass needs; the twin is left in the unordered access state. Only
  4640. /// for a list that records nothing of the title's afterwards
  4641. /// (`record_plane_pass`).
  4642. fn pass_plane(
  4643. &self,
  4644. depth: &std::sync::Arc<crate::resource::HostTexture>,
  4645. twin: &crate::resource::Twin,
  4646. ) {
  4647. const UNORDERED_ACCESS: u32 = 0x8;
  4648. const DEPTH_WRITE: u32 = 0x10;
  4649. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  4650. let Some(plane) = &twin.plane else { return };
  4651. self.settle(depth, DEPTH_WRITE);
  4652. self.settle(plane, PIXEL_SHADER_RESOURCE);
  4653. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  4654. self.settle(plane, UNORDERED_ACCESS);
  4655. }
  4656. /// Records the copy of a depth texture into its colour twin (`colour`)
  4657. /// or of the twin into the depth texture, with the moves to the copy
  4658. /// states. The twin is left in the unordered access state.
  4659. fn twin_copy(
  4660. &self,
  4661. depth: &std::sync::Arc<crate::resource::HostTexture>,
  4662. twin: &crate::resource::Twin,
  4663. colour: bool,
  4664. ) {
  4665. const UNORDERED_ACCESS: u32 = 0x8;
  4666. const COPY_DEST: u32 = 0x400;
  4667. const COPY_SOURCE: u32 = 0x800;
  4668. let (from, to) = if colour {
  4669. (depth, &twin.colour)
  4670. } else {
  4671. (&twin.colour, depth)
  4672. };
  4673. self.settle(from, COPY_SOURCE);
  4674. self.settle(to, COPY_DEST);
  4675. record_twin_copy(&self.list, &depth.texture, twin, colour);
  4676. self.settle(&twin.colour, UNORDERED_ACCESS);
  4677. }
  4678. /// Before the list closes: the depth textures whose twins it wrote last
  4679. /// are given what was written, and left readable by shaders. Shaders
  4680. /// that pick a view from the heap by a computed index are not seen by
  4681. /// `twin_use` and read the depth texture in lists that never name it
  4682. /// (in a captured frame of the title no table names a shadow
  4683. /// map for reading but the pass that fills the next one).
  4684. fn twins_to_depth(&self) {
  4685. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  4686. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  4687. let written: Vec<_> = twins
  4688. .values_mut()
  4689. .filter(|u| u.behind[0] == Some(true) || u.late)
  4690. .map(|u| {
  4691. // Not copied again if the list copied since the last write
  4692. // and only the depth plane's pass is left.
  4693. let copy = u.behind[0] == Some(true);
  4694. u.behind[0] = Some(false);
  4695. u.late = false;
  4696. (u.depth.clone(), u.twin.clone(), copy)
  4697. })
  4698. .collect();
  4699. drop(twins);
  4700. for (depth, twin, copy) in &written {
  4701. if *copy {
  4702. self.twin_copy(depth, twin, false);
  4703. }
  4704. // Nothing of the title's is recorded after this: the pass may
  4705. // leave its own pipeline and target set.
  4706. self.pass_plane(depth, twin);
  4707. self.settle(depth, SHADER_RESOURCE);
  4708. }
  4709. }
  4710. /// The draw or dispatch just prepared is recorded: the twins it writes
  4711. /// now hold what their depth textures lack.
  4712. pub(crate) fn twins_written(&self) {
  4713. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  4714. for u in twins.values_mut().filter(|u| u.writing) {
  4715. u.writing = false;
  4716. u.behind[0] = Some(true);
  4717. }
  4718. }
  4719. /// At submission: the list that moves each texture this list uses from
  4720. /// its real state to the one the list starts with; the textures' real
  4721. /// states become those the list ends with. For depth textures with a
  4722. /// colour twin it first copies the side the list uses as it finds it
  4723. /// from the other, if a list submitted earlier left it behind.
  4724. fn prelude(&self) -> Option<ID3D12CommandList> {
  4725. const COPY_DEST: u32 = 0x400;
  4726. const COPY_SOURCE: u32 = 0x800;
  4727. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  4728. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  4729. // The copies (depth texture, twin, whether into the twin); the
  4730. // sides are then as this list leaves them.
  4731. let mut syncs = Vec::new();
  4732. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  4733. for u in twins.values() {
  4734. let real = u.twin.behind.load(Ordering::Relaxed);
  4735. let mut behind = [real & 1 != 0, real & 2 != 0];
  4736. for side in [0, 1] {
  4737. if u.needs[side] && behind[side] {
  4738. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  4739. behind = [false; 2];
  4740. }
  4741. }
  4742. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  4743. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  4744. u.twin.behind.store(left, Ordering::Relaxed);
  4745. }
  4746. drop(twins);
  4747. // A copy runs with its textures in the copy states: each moves
  4748. // there from its real state, and from there to the state the list
  4749. // starts with (back to its real state if the list does not use it).
  4750. let mut to_copy = Vec::new();
  4751. let mut barriers = Vec::new();
  4752. let mut copying = std::collections::HashMap::new();
  4753. for (depth, twin, colour) in &syncs {
  4754. let (from, to) = if *colour {
  4755. (depth, &twin.colour)
  4756. } else {
  4757. (&twin.colour, depth)
  4758. };
  4759. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  4760. let key = std::sync::Arc::as_ptr(texture) as usize;
  4761. let real = texture.state.load(Ordering::Relaxed);
  4762. copying.insert(key, state);
  4763. if real != state {
  4764. to_copy.push(transition(
  4765. &texture.texture,
  4766. host_state(real),
  4767. host_state(state),
  4768. ));
  4769. if !states.contains_key(&key) {
  4770. barriers.push(transition(
  4771. &texture.texture,
  4772. host_state(state),
  4773. host_state(real),
  4774. ));
  4775. }
  4776. }
  4777. }
  4778. }
  4779. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  4780. let real = copy.state.swap(*last, Ordering::Relaxed);
  4781. let real = copying.get(key).copied().unwrap_or(real);
  4782. (real != *first)
  4783. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  4784. }));
  4785. if barriers.is_empty() && syncs.is_empty() {
  4786. return None;
  4787. }
  4788. let Some((allocator, list)) = self
  4789. .prelude
  4790. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  4791. .as_ref()
  4792. else {
  4793. fail(format_args!("no host list for a state prelude"));
  4794. };
  4795. // SAFETY: the prelude is not executing (every submission is waited
  4796. // for); the textures are live.
  4797. let recorded = unsafe {
  4798. allocator.Reset().and_then(|()| {
  4799. list.Reset(allocator, None)?;
  4800. if !to_copy.is_empty() {
  4801. list.ResourceBarrier(&to_copy);
  4802. }
  4803. for (depth, twin, colour) in &syncs {
  4804. record_twin_copy(list, &depth.texture, twin, *colour);
  4805. }
  4806. if !barriers.is_empty() {
  4807. list.ResourceBarrier(&barriers);
  4808. }
  4809. list.Close()
  4810. })
  4811. };
  4812. if let Err(e) = recorded {
  4813. fail(format_args!("a host state prelude did not record ({e})"));
  4814. }
  4815. list.cast().ok()
  4816. }
  4817. /// Notes what the command about to be recorded does, as a marker
  4818. /// command whose text the list keeps (diagnostics, with device-removed
  4819. /// data on): the report pairs the breadcrumbs' marker commands with the
  4820. /// texts in order and names the commands a fault stopped among.
  4821. #[cfg(feature = "diagnostics")]
  4822. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  4823. self.note(what, None);
  4824. }
  4825. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  4826. /// `(address, bytes)`: the report places the faulting address in it.
  4827. #[cfg(feature = "diagnostics")]
  4828. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  4829. self.note(what, Some(range));
  4830. }
  4831. #[cfg(feature = "diagnostics")]
  4832. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  4833. if !dred_on() {
  4834. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  4835. return;
  4836. }
  4837. {
  4838. let started = std::time::Instant::now();
  4839. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  4840. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  4841. // SAFETY: an open list and our query heap.
  4842. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  4843. }
  4844. let what = what();
  4845. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  4846. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  4847. const UNICODE: u32 = 0;
  4848. // SAFETY: an open list; the marker is copied when recorded.
  4849. unsafe {
  4850. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  4851. };
  4852. self.notes
  4853. .lock()
  4854. .unwrap_or_else(|e| e.into_inner())
  4855. .push((what, range));
  4856. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  4857. }
  4858. }
  4859. /// Whether nothing recorded since the list was opened does any work:
  4860. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  4861. /// upload or resolve (they defer a step or move a texture's state), no
  4862. /// bottom-of-pipe write. State set on the list does not count.
  4863. pub(crate) fn untouched(&self) -> bool {
  4864. {
  4865. let deferred = self.deferred();
  4866. if !(deferred.copies.is_empty()
  4867. && deferred.uploads.is_empty()
  4868. && deferred.kept.is_empty()
  4869. && deferred.textures.is_empty()
  4870. && deferred.writes.is_empty()
  4871. && deferred.backs.is_empty())
  4872. {
  4873. return false;
  4874. }
  4875. }
  4876. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  4877. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  4878. }
  4879. /// Notes a pipeline the list binds.
  4880. pub(crate) fn used_pipeline(&self, name: &str) {
  4881. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  4882. if !pipelines.contains(name) {
  4883. pipelines.insert(name.to_owned());
  4884. }
  4885. }
  4886. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  4887. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  4888. }
  4889. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  4890. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  4891. let mut deferred = self.deferred();
  4892. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  4893. // A copy that goes on where the one recorded just before it ended,
  4894. // source and destination both: with `join_copies` the two are one
  4895. // step.
  4896. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  4897. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  4898. {
  4899. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  4900. if join_copies() {
  4901. *n += len;
  4902. return;
  4903. }
  4904. }
  4905. deferred
  4906. .copies
  4907. .push(Step::Copy(dst as usize, src as usize, len));
  4908. deferred.refreshed.clear();
  4909. }
  4910. /// Copies `len` bytes of title memory at `src` into the list's upload
  4911. /// memory at `dst` when the list is submitted.
  4912. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  4913. self.deferred()
  4914. .copies
  4915. .push(Step::Fill(dst as usize, src as usize, len));
  4916. }
  4917. /// Brings `[address, address + len)` of a buffer's host copy up to date
  4918. /// when the list is submitted (once per range until a title copy
  4919. /// intervenes), keeping the copy alive until the list is reset.
  4920. pub(crate) fn defer_refresh(
  4921. &self,
  4922. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  4923. address: usize,
  4924. len: usize,
  4925. ) {
  4926. let mut deferred = self.deferred();
  4927. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  4928. if deferred.refreshed.insert(key) {
  4929. deferred
  4930. .copies
  4931. .push(Step::Refresh(shadow.clone(), address, len));
  4932. }
  4933. }
  4934. /// Shaders of the list write `[address, address + len)` of a buffer's
  4935. /// host copy: copied back into title memory once the list has run.
  4936. pub(crate) fn defer_gpu_write(
  4937. &self,
  4938. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  4939. address: usize,
  4940. len: usize,
  4941. ) {
  4942. self.deferred()
  4943. .copies
  4944. .push(Step::GpuWrite(shadow.clone(), address, len));
  4945. }
  4946. /// A read back: once the list has run, `rows` rows of `row` bytes go
  4947. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  4948. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  4949. /// the list is reset.
  4950. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  4951. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  4952. }
  4953. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  4954. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  4955. self.deferred().writes.push((dst as usize, what, bytes));
  4956. }
  4957. /// A mapped upload buffer of `size` bytes, alive until the list is
  4958. /// reset.
  4959. ///
  4960. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  4961. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  4962. let (buffer, data) = host.upload_buffer(size)?;
  4963. name(&buffer, || format!("list upload {size:#x}"));
  4964. self.deferred().hold_upload(buffer.clone(), size);
  4965. Some((buffer, data))
  4966. }
  4967. /// `len` bytes of upload memory (256-byte aligned) until the list is
  4968. /// reset: the host GPU address and the CPU pointer.
  4969. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  4970. let host = host()?;
  4971. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  4972. let len = len.max(1).next_multiple_of(256);
  4973. if len > SCRATCH_CHUNK {
  4974. let (buffer, data) = host.upload_buffer(len)?;
  4975. name(&buffer, || format!("list scratch {len:#x}"));
  4976. // SAFETY: a live buffer.
  4977. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4978. self.deferred().hold_upload(buffer, len);
  4979. return Some((gpu, data));
  4980. }
  4981. // The chunk in use while `len` fits in what is left of it, else the
  4982. // next one (a list's first chunk may be a small one).
  4983. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  4984. (s.current, s.used) = (s.current + 1, 0);
  4985. }
  4986. if s.current == s.chunks.len() {
  4987. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  4988. SCRATCH_FIRST
  4989. } else {
  4990. SCRATCH_CHUNK
  4991. };
  4992. let chunk = take_chunk(host, size)?;
  4993. s.chunks.push((chunk, size));
  4994. s.used = 0;
  4995. }
  4996. let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu);
  4997. let at = s.used;
  4998. s.used += len;
  4999. Some((gpu + at, (data + at as usize) as *mut u8))
  5000. }
  5001. /// The bytes of scratch chunks the list holds now (after a reset:
  5002. /// none while lists share their chunks).
  5003. pub(crate) fn scratch_kept(&self) -> u64 {
  5004. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5005. scratch.chunks.iter().map(|c| c.1).sum()
  5006. }
  5007. /// The host address of the list's indirect-work budget, zeroed at each
  5008. /// submission of the list from the first use after a reset on.
  5009. pub(crate) fn budget(&self) -> Option<u64> {
  5010. let (buffer, data) = self
  5011. .budget
  5012. .get_or_init(|| {
  5013. let (b, d) = host()?.shared_buffer(256)?;
  5014. Some((b, d as usize))
  5015. })
  5016. .as_ref()?;
  5017. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5018. let mut deferred = self.deferred();
  5019. if !deferred.budget_zeroed {
  5020. deferred.budget_zeroed = true;
  5021. let at = *data;
  5022. // SAFETY: the list's own mapped words, written before it runs.
  5023. // The words after the budget hold what the clamp noted about the
  5024. // list's last run (mesh dispatches: the largest group count
  5025. // asked for, the groups asked in all; with the card's copy, as
  5026. // the list's end copied them here): taken, then zeroed.
  5027. deferred.copies.push(Step::Host(Box::new(move || unsafe {
  5028. let words = at as *mut u32;
  5029. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  5030. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  5031. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  5032. for k in 0..3 {
  5033. words.add(k).write_volatile(0);
  5034. }
  5035. })));
  5036. drop(deferred);
  5037. if let Some(card) = card {
  5038. self.zero_card_budget(card);
  5039. }
  5040. }
  5041. // SAFETY: a live buffer.
  5042. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  5043. }
  5044. /// The budget's words in the card's own memory ([`card_budget`]), if
  5045. /// the list can zero them itself (`WriteBufferImmediate`).
  5046. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  5047. if !card_budget() {
  5048. return None;
  5049. }
  5050. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  5051. let buffer = host()?.uav_buffer(256)?;
  5052. name(&buffer, || "indirect budget".to_owned());
  5053. Some(buffer)
  5054. }
  5055. /// Records, before the list's first clamp, the zeroing of the card's
  5056. /// copy of the budget: common, written as a copy, then left for
  5057. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  5058. fn zero_card_budget(&self, card: &ID3D12Resource) {
  5059. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  5060. return;
  5061. };
  5062. // SAFETY: a live buffer.
  5063. let at = unsafe { card.GetGPUVirtualAddress() };
  5064. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  5065. Dest: at + offset,
  5066. Value: 0,
  5067. });
  5068. // SAFETY: an open list; the buffer is the list's own and in the
  5069. // common state at the start of every recording.
  5070. unsafe {
  5071. self.list.ResourceBarrier(&[transition(
  5072. card,
  5073. D3D12_RESOURCE_STATE_COMMON,
  5074. D3D12_RESOURCE_STATE_COPY_DEST,
  5075. )]);
  5076. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  5077. self.list.ResourceBarrier(&[transition(
  5078. card,
  5079. D3D12_RESOURCE_STATE_COPY_DEST,
  5080. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5081. )]);
  5082. }
  5083. }
  5084. /// Before the list closes, if this recording charged the card's copy
  5085. /// of the budget: its notes on mesh records go to the mapped words
  5086. /// (read at the next submission), and it goes back to common.
  5087. fn card_budget_out(&self) {
  5088. if !self.deferred().budget_zeroed {
  5089. return;
  5090. }
  5091. let (Some(Some(card)), Some(Some((mapped, _)))) =
  5092. (self.card_budget.get(), self.budget.get())
  5093. else {
  5094. return;
  5095. };
  5096. // SAFETY: an open list; both buffers are the list's own. The
  5097. // mapped one is promoted from common to the copy destination.
  5098. unsafe {
  5099. self.list.ResourceBarrier(&[transition(
  5100. card,
  5101. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5102. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5103. )]);
  5104. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  5105. self.list.ResourceBarrier(&[transition(
  5106. card,
  5107. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5108. D3D12_RESOURCE_STATE_COMMON,
  5109. )]);
  5110. }
  5111. }
  5112. /// A device-local unordered-access buffer of at least `size` bytes for
  5113. /// clamped indirect arguments, reused across executions and resets of the
  5114. /// list. Smaller buffers replaced mid-list stay alive until
  5115. /// [`HostList::reset`].
  5116. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  5117. let needed = size.max(64 << 10);
  5118. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  5119. if let Some((buffer, cap)) = &*slot
  5120. && *cap >= needed
  5121. {
  5122. return Some(buffer.clone());
  5123. }
  5124. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  5125. let alloc = prev
  5126. .saturating_mul(2)
  5127. .max(needed)
  5128. .next_multiple_of(64 << 10);
  5129. let buffer = host()?.uav_buffer(alloc)?;
  5130. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  5131. let old = slot.replace((buffer.clone(), alloc));
  5132. drop(slot);
  5133. if let Some((old_buf, _)) = old {
  5134. // It ends the list common, as every scratch buffer does.
  5135. self.indirect_common(&old_buf);
  5136. self.keep(&old_buf);
  5137. }
  5138. Some(buffer)
  5139. }
  5140. /// Moves `scratch` back to the common state if a clamp left it readable
  5141. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  5142. /// list's first clamp expects it. Done before the list closes and before
  5143. /// a bigger scratch buffer replaces it: one barrier per list (where
  5144. /// there was one per indirect execution), and the list ends as it
  5145. /// begins however it is submitted.
  5146. fn indirect_common(&self, scratch: &ID3D12Resource) {
  5147. {
  5148. let mut deferred = self.deferred();
  5149. if deferred.indirect_readable != scratch.as_raw() as usize {
  5150. return;
  5151. }
  5152. deferred.indirect_readable = 0;
  5153. }
  5154. let barrier = transition(
  5155. scratch,
  5156. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  5157. D3D12_RESOURCE_STATE_COMMON,
  5158. );
  5159. // SAFETY: an open list and a live buffer this recording left in
  5160. // `INDIRECT_ARGUMENT`.
  5161. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5162. }
  5163. /// The state the list's indirect scratch buffer `scratch` is in at this
  5164. /// point of the recording: indirect arguments if a clamp in this
  5165. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  5166. /// common: the state a buffer is made in, and the one a recording
  5167. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  5168. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  5169. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  5170. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  5171. } else {
  5172. D3D12_RESOURCE_STATE_COMMON
  5173. }
  5174. }
  5175. /// A clamp recorded in this list left `scratch` readable as indirect
  5176. /// arguments. It stays so for every execution that reads it, until the
  5177. /// next clamp moves it back to unordered access.
  5178. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  5179. self.deferred().indirect_readable = scratch.as_raw() as usize;
  5180. }
  5181. /// Keeps `object` alive until the list is reset.
  5182. pub(crate) fn keep(&self, object: &impl Interface) {
  5183. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  5184. self.deferred().kept.push(object);
  5185. }
  5186. }
  5187. /// Whether this is the first time since the reset that the list asks
  5188. /// about `key` (a texture to bring up to date).
  5189. pub(crate) fn first_use(&self, key: usize) -> bool {
  5190. self.deferred().textures.insert(key)
  5191. }
  5192. /// Runs `work` when the list is submitted, in order with its copies.
  5193. /// `work` may write title memory (refreshes after it copy again).
  5194. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  5195. self.deferred().copies.push(Step::Run(Box::new(work)));
  5196. self.deferred().refreshed.clear();
  5197. }
  5198. /// As [`HostList::defer`], for work that writes only host memory.
  5199. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  5200. self.deferred().copies.push(Step::Host(Box::new(work)));
  5201. }
  5202. /// Brings a texture's staging buffer up to date when the list is
  5203. /// submitted, keeping it alive until the list is reset.
  5204. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  5205. self.deferred().copies.push(Step::Texture(staging));
  5206. }
  5207. /// Runs the list's submission-time steps; refreshes go into `batch`
  5208. /// (the title's big buffers, a 174 MB one among them, are read by most
  5209. /// lists of a submission, through many ranges).
  5210. fn run_deferred(&self, batch: &mut Batch) {
  5211. #[cfg(feature = "diagnostics")]
  5212. use crate::copystat::{C, add};
  5213. for step in &self.deferred().copies {
  5214. let started = std::time::Instant::now();
  5215. let copied = match step {
  5216. &Step::Copy(dst, src, len) => {
  5217. #[cfg(feature = "diagnostics")]
  5218. {
  5219. add(C::Copies, 1);
  5220. add(C::CopyBytes, len as u64);
  5221. }
  5222. batch.title_written();
  5223. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  5224. // With the submission's one asking: the journal learns it.
  5225. crate::watch::wrote(dst, len);
  5226. len
  5227. }
  5228. &Step::Fill(dst, src, len) => {
  5229. #[cfg(feature = "diagnostics")]
  5230. {
  5231. add(C::Copies, 1);
  5232. add(C::CopyBytes, len as u64);
  5233. }
  5234. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  5235. len
  5236. }
  5237. Step::Refresh(shadow, address, len) => {
  5238. #[cfg(feature = "diagnostics")]
  5239. {
  5240. add(C::Refreshes, 1);
  5241. add(C::RefreshBytes, *len as u64);
  5242. }
  5243. batch.add(shadow, *address, *len);
  5244. continue;
  5245. }
  5246. Step::Run(work) | Step::Host(work) => {
  5247. if matches!(step, Step::Run(_)) {
  5248. batch.title_written();
  5249. }
  5250. work();
  5251. // It wrote title memory, where is not known here: the
  5252. // submission's one asking ends, later refreshes ask anew.
  5253. if matches!(step, Step::Run(_)) {
  5254. crate::watch::ask_once_end();
  5255. }
  5256. #[cfg(feature = "diagnostics")]
  5257. {
  5258. add(C::Runs, 1);
  5259. add(C::RunUs, started.elapsed().as_micros() as u64);
  5260. }
  5261. continue;
  5262. }
  5263. Step::GpuWrite(shadow, address, len) => {
  5264. // The shaders start from the title's data: this copy's
  5265. // pending refresh first. The other copies' wait for
  5266. // the next flush of all (flushing all of them at every
  5267. // range a dispatch writes made thousands of write-watch
  5268. // askings a frame).
  5269. batch.flush_one(shadow);
  5270. #[cfg(feature = "diagnostics")]
  5271. let snapshot = std::time::Instant::now();
  5272. shadow.writing(*address, *len);
  5273. #[cfg(feature = "diagnostics")]
  5274. {
  5275. add(C::GpuWrites, 1);
  5276. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  5277. }
  5278. continue;
  5279. }
  5280. Step::Texture(staging) => {
  5281. if batch.texture_due(staging) {
  5282. staging.refresh();
  5283. }
  5284. continue;
  5285. }
  5286. };
  5287. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  5288. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  5289. }
  5290. }
  5291. }
  5292. /// Whether a submission's refreshes of host copies run on several threads,
  5293. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  5294. ///
  5295. /// A submission brings some sixty copies up to date, one after the other
  5296. /// on the submitting thread: for each, the pages the title wrote are asked
  5297. /// for and read through the kernel into the copy. That is the frame line's
  5298. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  5299. /// another: each refresh writes its own copy and its own notes, and reads
  5300. /// title memory. With the switch the copies of a flush (four or more) are
  5301. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  5302. /// The write-watch journal and the guards are behind their own locks, as
  5303. /// they are for the title's threads.
  5304. fn wide_refresh() -> bool {
  5305. static ON: OnceLock<bool> = OnceLock::new();
  5306. *ON.get_or_init(|| {
  5307. wide_refresh_enabled(
  5308. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  5309. std::thread::available_parallelism().ok().map(|n| n.get()),
  5310. )
  5311. })
  5312. }
  5313. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  5314. match setting {
  5315. Some("1") => true,
  5316. Some("0") => false,
  5317. _ => logical_cpus.is_some_and(|n| n >= 4),
  5318. }
  5319. }
  5320. #[cfg(test)]
  5321. mod wide_refresh_tests {
  5322. use super::wide_refresh_enabled;
  5323. #[test]
  5324. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  5325. assert!(wide_refresh_enabled(None, Some(4)));
  5326. assert!(wide_refresh_enabled(None, Some(16)));
  5327. assert!(!wide_refresh_enabled(None, Some(2)));
  5328. assert!(!wide_refresh_enabled(None, None));
  5329. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  5330. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  5331. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  5332. }
  5333. }
  5334. /// A submission's refreshes not done yet, merged per buffer copy into the
  5335. /// range that covers them: done before a step that writes title memory or
  5336. /// gives a range to shaders, and before the lists run.
  5337. ///
  5338. /// Also the textures brought up to date in the submission so far: most
  5339. /// lists of a world submission sample the same textures, and a texture in
  5340. /// physical-page memory is hashed whole each time it is checked. Checked
  5341. /// once, it is checked again only after a step that writes title memory.
  5342. #[derive(Default)]
  5343. struct Batch {
  5344. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  5345. /// Where each copy (by address) is in `refreshes`: the list that makes
  5346. /// the heap's buffers ready adds some 4,100 copies, and searching them
  5347. /// for every refresh of a submission was tens of millions of
  5348. /// comparisons a frame.
  5349. index: std::collections::HashMap<usize, usize>,
  5350. /// Staging buffers (by address) refreshed since the last title write.
  5351. textures: std::collections::HashSet<usize>,
  5352. }
  5353. impl Batch {
  5354. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  5355. let end = address + len;
  5356. let key = std::sync::Arc::as_ptr(shadow) as usize;
  5357. match self.index.get(&key) {
  5358. Some(&at) => {
  5359. let r = &mut self.refreshes[at];
  5360. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  5361. }
  5362. None => {
  5363. self.index.insert(key, self.refreshes.len());
  5364. self.refreshes.push((shadow.clone(), address, end));
  5365. }
  5366. }
  5367. }
  5368. /// Before shaders are given a range of `shadow`'s copy: its pending
  5369. /// refresh is done, the others stay pending.
  5370. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  5371. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  5372. return;
  5373. };
  5374. let (shadow, from, to) = self.refreshes.swap_remove(at);
  5375. // The last entry took its place.
  5376. if let Some(moved) = self.refreshes.get(at) {
  5377. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  5378. }
  5379. Self::update(&shadow, from, to);
  5380. }
  5381. /// Brings `[from, to)` of a copy up to date, timed.
  5382. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  5383. let started = std::time::Instant::now();
  5384. let copied = shadow.update(from, to - from);
  5385. let us = started.elapsed().as_micros() as u64;
  5386. #[cfg(feature = "diagnostics")]
  5387. crate::copystat::range(from, to - from, us, 0);
  5388. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  5389. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  5390. }
  5391. /// Whether `staging` is still to be refreshed in this submission (and
  5392. /// notes it refreshed).
  5393. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  5394. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  5395. }
  5396. /// Before a step that writes title memory: pending refreshes are done
  5397. /// first, and textures are checked again after it.
  5398. fn title_written(&mut self) {
  5399. self.flush();
  5400. self.textures.clear();
  5401. }
  5402. fn flush(&mut self) {
  5403. self.index.clear();
  5404. // One write-watch asking for the copies that lie close together,
  5405. // not one per copy.
  5406. let ahead = self.refreshes.len() > 1;
  5407. if ahead {
  5408. let started = std::time::Instant::now();
  5409. let ranges: Vec<(usize, usize)> = self
  5410. .refreshes
  5411. .iter()
  5412. .filter(|r| !r.0.unwatched())
  5413. .map(|r| (r.1, r.2))
  5414. .collect();
  5415. crate::watch::ask_ahead(&ranges);
  5416. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  5417. }
  5418. if wide_refresh() && self.refreshes.len() >= 4 {
  5419. // Each copy on its own, several at a time: a copy's refresh
  5420. // writes that copy and reads title memory, nothing of another's.
  5421. // The time counted is the time it took, not the threads' sum.
  5422. let started = std::time::Instant::now();
  5423. let before = PREPARING[0].load(Ordering::Relaxed);
  5424. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  5425. .refreshes
  5426. .drain(..)
  5427. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  5428. .collect();
  5429. crate::shadow::wide_run(jobs);
  5430. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  5431. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  5432. } else {
  5433. for (shadow, from, to) in self.refreshes.drain(..) {
  5434. Self::update(&shadow, from, to);
  5435. }
  5436. }
  5437. if ahead {
  5438. crate::watch::ask_ahead_done();
  5439. }
  5440. }
  5441. }
  5442. /// Copies title memory at submission. The ranges were checked against their
  5443. /// resources when recorded, but the title may since have unmapped pages of
  5444. /// them (tiled memory, page mappings), which read as zeros here; a title
  5445. /// destination (`title_dst`) that is not all mapped is left alone.
  5446. ///
  5447. /// The source is read through the kernel (`ReadProcessMemory`), which
  5448. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  5449. /// cost about 2 ms per copy in the title's big pools (it walks the page
  5450. /// tables to the region's end), which made copies run at 100-200 MB/s.
  5451. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  5452. #[cfg(feature = "diagnostics")]
  5453. match crate::copystat::mode() {
  5454. 1 => {
  5455. // SAFETY: timing only: the caller vouches for the source.
  5456. unsafe { std::ptr::copy(src, dst, len) };
  5457. return;
  5458. }
  5459. 2 => return,
  5460. _ => {}
  5461. }
  5462. if len == 0 {
  5463. return;
  5464. }
  5465. // A title destination that is not all mapped is left alone. Asking
  5466. // Windows first (`VirtualQuery`) walks the page tables to the end of
  5467. // the destination's region: in the title's big blocks that is
  5468. // milliseconds a copy, and it was a seventh of the submitting thread's
  5469. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  5470. // says the same when it fails, so the question is only asked then.
  5471. // `VICTORY_COPY_ASK=1` asks first, as before.
  5472. static ASK: OnceLock<bool> = OnceLock::new();
  5473. let ask_first = title_dst
  5474. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  5475. if ask_first && !crate::texture::committed(dst, len) {
  5476. return;
  5477. }
  5478. if title_dst {
  5479. // The kernel writes the destination: it must not be guarded.
  5480. crate::watch::writing(dst as usize, len);
  5481. }
  5482. #[cfg(feature = "diagnostics")]
  5483. let moved = std::time::Instant::now();
  5484. let whole = read(src, dst, len);
  5485. #[cfg(feature = "diagnostics")]
  5486. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  5487. if whole {
  5488. return;
  5489. }
  5490. // The copy failed: a source page is not there, or the destination is
  5491. // not all mapped. Then the destination stays as it is (the kernel may
  5492. // have written its first pages).
  5493. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  5494. return;
  5495. }
  5496. #[cfg(feature = "diagnostics")]
  5497. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  5498. #[cfg(feature = "diagnostics")]
  5499. let sparse = std::time::Instant::now();
  5500. if !title_dst && len >= 64 << 10 {
  5501. read_sparse(src, dst, len);
  5502. } else {
  5503. read_pieces(src, dst, len);
  5504. }
  5505. #[cfg(feature = "diagnostics")]
  5506. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  5507. }
  5508. /// After a failed bulk read into host memory, skip contiguous holes. Never
  5509. /// cache the query across copies: the title may remap the same address.
  5510. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  5511. use windows_sys::Win32::System::Memory::{
  5512. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  5513. };
  5514. let mut offset = 0;
  5515. while offset < len {
  5516. let at = src.wrapping_add(offset);
  5517. let to = dst.wrapping_add(offset);
  5518. let remaining = len - offset;
  5519. // SAFETY: the query inspects an address and fills a local structure.
  5520. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  5521. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  5522. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  5523. .saturating_sub(at as usize).min(remaining);
  5524. if size != size_of_val(&info) || n == 0 {
  5525. read_pieces(at, to, remaining);
  5526. break;
  5527. }
  5528. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  5529. #[cfg(feature = "diagnostics")]
  5530. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  5531. // SAFETY: this path is only used with a writable host destination.
  5532. unsafe { to.write_bytes(0, n) };
  5533. } else if !read(at, to, n) {
  5534. // A mapping may change between query and read.
  5535. read_pieces(at, to, n);
  5536. }
  5537. offset += n;
  5538. }
  5539. }
  5540. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  5541. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  5542. // that fails), zeros for what cannot be read.
  5543. for_pieces(src as usize, len, 64 << 10, |at, n| {
  5544. let to = dst.wrapping_add(at - src as usize);
  5545. if !read(at as *const u8, to, n) {
  5546. for_pieces(at, n, 4 << 10, |at, n| {
  5547. let to = dst.wrapping_add(at - src as usize);
  5548. if !read(at as *const u8, to, n) {
  5549. #[cfg(feature = "diagnostics")]
  5550. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  5551. // SAFETY: inside the destination, which is mapped.
  5552. unsafe { to.write_bytes(0, n) };
  5553. }
  5554. });
  5555. }
  5556. });
  5557. }
  5558. /// Reads title memory at `src` into `dst`; false if a page of it is not
  5559. /// readable.
  5560. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  5561. read(src, dst.as_mut_ptr(), dst.len())
  5562. }
  5563. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  5564. /// readable.
  5565. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  5566. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  5567. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  5568. let mut done = 0;
  5569. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  5570. // kernel checks the source.
  5571. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  5572. }
  5573. #[link(name = "ntdll", kind = "raw-dylib")]
  5574. unsafe extern "system" {
  5575. /// The kernel's write into a process's memory, `(process, address,
  5576. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  5577. /// the range is not there or not writable. It changes no protection.
  5578. fn NtWriteVirtualMemory(
  5579. process: *mut std::ffi::c_void,
  5580. base: *mut std::ffi::c_void,
  5581. buffer: *const std::ffi::c_void,
  5582. size: usize,
  5583. written: *mut usize,
  5584. ) -> i32;
  5585. }
  5586. /// Whether title memory is written with the kernel's own call
  5587. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  5588. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  5589. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  5590. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  5591. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  5592. fn direct_writes() -> bool {
  5593. static ON: OnceLock<bool> = OnceLock::new();
  5594. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  5595. }
  5596. /// Copies host memory into title memory after a submission (what shaders
  5597. /// wrote), leaving pages that are not mapped alone.
  5598. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  5599. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  5600. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  5601. let direct = direct_writes();
  5602. let write = |at: usize, n: usize| {
  5603. let from = src.wrapping_add(at - dst as usize);
  5604. let mut done = 0;
  5605. if direct {
  5606. // SAFETY: as below; the kernel checks the destination and
  5607. // writes nothing it cannot (the caller opened its guards:
  5608. // `crate::watch::writing`).
  5609. return unsafe {
  5610. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  5611. };
  5612. }
  5613. // SAFETY: the source is our mapped host copy; the kernel checks the
  5614. // destination.
  5615. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  5616. };
  5617. if len == 0 || write(dst as usize, len) {
  5618. return;
  5619. }
  5620. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  5621. if !write(at, n) {
  5622. for_pieces(at, n, 4 << 10, |at, n| {
  5623. write(at, n);
  5624. });
  5625. }
  5626. });
  5627. }
  5628. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  5629. /// `step`.
  5630. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  5631. let end = start + len;
  5632. let mut at = start;
  5633. while at < end {
  5634. let next = ((at / step + 1) * step).min(end);
  5635. f(at, next - at);
  5636. at = next;
  5637. }
  5638. }
  5639. impl Host {
  5640. /// A buffer in the upload heap, mapped for writing.
  5641. /// A buffer of `size` bytes the card writes and we read (a read back),
  5642. /// in the state copies into it need.
  5643. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  5644. let heap = D3D12_HEAP_PROPERTIES {
  5645. Type: D3D12_HEAP_TYPE_READBACK,
  5646. ..Default::default()
  5647. };
  5648. let desc = D3D12_RESOURCE_DESC {
  5649. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5650. Width: size.max(1),
  5651. Height: 1,
  5652. DepthOrArraySize: 1,
  5653. MipLevels: 1,
  5654. SampleDesc: DXGI_SAMPLE_DESC {
  5655. Count: 1,
  5656. Quality: 0,
  5657. },
  5658. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5659. ..Default::default()
  5660. };
  5661. let mut buffer: Option<ID3D12Resource> = None;
  5662. // SAFETY: plain creation of a read-back buffer.
  5663. let made = unsafe {
  5664. self.device.CreateCommittedResource(
  5665. &heap,
  5666. D3D12_HEAP_FLAG_NONE,
  5667. &desc,
  5668. D3D12_RESOURCE_STATE_COPY_DEST,
  5669. None,
  5670. &mut buffer,
  5671. )
  5672. };
  5673. match made {
  5674. Ok(()) => buffer,
  5675. Err(e) => {
  5676. tracing::warn!(error = %e, size, "no read-back buffer");
  5677. None
  5678. }
  5679. }
  5680. }
  5681. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5682. MADE[0].fetch_add(1, Ordering::Relaxed);
  5683. MADE[1].fetch_add(size, Ordering::Relaxed);
  5684. let heap = D3D12_HEAP_PROPERTIES {
  5685. Type: D3D12_HEAP_TYPE_UPLOAD,
  5686. ..Default::default()
  5687. };
  5688. let desc = D3D12_RESOURCE_DESC {
  5689. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5690. Width: size.max(1),
  5691. Height: 1,
  5692. DepthOrArraySize: 1,
  5693. MipLevels: 1,
  5694. SampleDesc: DXGI_SAMPLE_DESC {
  5695. Count: 1,
  5696. Quality: 0,
  5697. },
  5698. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5699. ..Default::default()
  5700. };
  5701. let mut buffer: Option<ID3D12Resource> = None;
  5702. let mut data = std::ptr::null_mut();
  5703. // SAFETY: plain creation and mapping of an upload buffer.
  5704. let made = unsafe {
  5705. self.device
  5706. .CreateCommittedResource(
  5707. &heap,
  5708. D3D12_HEAP_FLAG_NONE,
  5709. &desc,
  5710. D3D12_RESOURCE_STATE_GENERIC_READ,
  5711. None,
  5712. &mut buffer,
  5713. )
  5714. .and_then(|()| {
  5715. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  5716. b.Map(0, None, Some(&mut data))
  5717. })
  5718. };
  5719. match made {
  5720. Ok(()) => Some((buffer?, data.cast())),
  5721. Err(e) => {
  5722. tracing::warn!(error = %e, size, "no upload buffer");
  5723. None
  5724. }
  5725. }
  5726. }
  5727. }
  5728. /// The swap chain formats a presented texture can be copied into: its own
  5729. /// family's.
  5730. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  5731. Some(match format.0 {
  5732. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  5733. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  5734. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  5735. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  5736. _ => return None,
  5737. })
  5738. }
  5739. const BUFFERS: u32 = 2;
  5740. struct Presenter {
  5741. swap_chain: IDXGISwapChain3,
  5742. width: u32,
  5743. height: u32,
  5744. format: DXGI_FORMAT,
  5745. copy: HostList,
  5746. /// With presents sent ahead ([`late_free_present`]): a list for each
  5747. /// present in the air, and the submission it last flew as (it is used
  5748. /// again once that one has finished).
  5749. ahead: Vec<(HostList, u64)>,
  5750. hwnd: HWND,
  5751. meter: Meter,
  5752. }
  5753. /// The frame rate, shown in the window's caption every second and logged
  5754. /// every few seconds.
  5755. struct Meter {
  5756. since: std::time::Instant,
  5757. frames: u32,
  5758. #[cfg(feature = "diagnostics")]
  5759. copy_stats_frames: u64,
  5760. drawn: u64,
  5761. logged: std::time::Instant,
  5762. /// The caption the window had, once read.
  5763. caption: Option<Vec<u16>>,
  5764. }
  5765. impl Meter {
  5766. fn new() -> Self {
  5767. let now = std::time::Instant::now();
  5768. Meter {
  5769. since: now,
  5770. frames: 0,
  5771. #[cfg(feature = "diagnostics")]
  5772. copy_stats_frames: 0,
  5773. drawn: crate::draw::drawn(),
  5774. logged: now,
  5775. caption: None,
  5776. }
  5777. }
  5778. /// Counts a presented frame.
  5779. fn frame(&mut self, hwnd: HWND) {
  5780. #[cfg(feature = "diagnostics")]
  5781. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  5782. #[cfg(feature = "diagnostics")]
  5783. crate::copystat::presented();
  5784. self.frames += 1;
  5785. #[cfg(feature = "diagnostics")]
  5786. {
  5787. self.copy_stats_frames += 1;
  5788. }
  5789. let elapsed = self.since.elapsed();
  5790. if elapsed < std::time::Duration::from_secs(1) {
  5791. return;
  5792. }
  5793. let drawn = crate::draw::drawn();
  5794. let frames = f64::from(self.frames);
  5795. let fps = frames / elapsed.as_secs_f64();
  5796. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  5797. let draws = (drawn - self.drawn) as f64 / frames;
  5798. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  5799. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  5800. let [cpu, gpu] = [0, 1].map(|i| {
  5801. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  5802. });
  5803. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  5804. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  5805. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  5806. });
  5807. let [back_ms, back_mb] = [0, 1].map(|i| {
  5808. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  5809. });
  5810. let dropped = crate::draw::take_dropped() as f64 / frames;
  5811. let indirect = crate::list::take_indirect() as f64 / frames;
  5812. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  5813. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  5814. tracing::info!(
  5815. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  5816. );
  5817. late_line(frames);
  5818. card_clock_line(frames, ms);
  5819. crate::shadow::back_line(frames);
  5820. {
  5821. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  5822. if passes + compares > 0.0 {
  5823. tracing::info!(
  5824. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  5825. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  5826. if rehash_runs() { "on" } else { "off" }
  5827. );
  5828. }
  5829. }
  5830. {
  5831. let [own, asking, still, all] =
  5832. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  5833. if all >= 1.0 {
  5834. tracing::info!(
  5835. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  5836. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  5837. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  5838. );
  5839. }
  5840. let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  5841. if through + left > 0.0 {
  5842. tracing::info!(
  5843. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  5844. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there)"
  5845. );
  5846. }
  5847. }
  5848. {
  5849. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  5850. if copies > 0.0 {
  5851. tracing::info!(
  5852. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  5853. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  5854. if join_copies() { "on" } else { "off" }
  5855. );
  5856. }
  5857. }
  5858. // Passes over the heap's buffer views for shaders that pick them by index.
  5859. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  5860. let picked_ms =
  5861. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  5862. // Copies between depth textures and their colour twins, each way.
  5863. let [twin_to_depth, twin_to_colour] =
  5864. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  5865. // Depth planes drawn from their twins.
  5866. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  5867. // Copies in the card's memory (`crate::shadow::cards`).
  5868. let card = crate::shadow::card_stats();
  5869. #[cfg(feature = "diagnostics")]
  5870. let slow = crate::watch::slow_asks();
  5871. // Over the same frames as the counts above.
  5872. #[cfg(feature = "diagnostics")]
  5873. let drops = crate::pipeline::take_drops();
  5874. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  5875. self.logged = std::time::Instant::now();
  5876. tracing::info!(
  5877. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  5878. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  5879. );
  5880. {
  5881. let [queued, due, away, partly, oldest] =
  5882. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  5883. let [same, parts, tails] =
  5884. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  5885. tracing::info!(
  5886. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  5887. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  5888. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  5889. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  5890. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  5891. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  5892. {} made slots found unmapped and made null",
  5893. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  5894. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  5895. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  5896. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  5897. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  5898. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  5899. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  5900. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  5901. );
  5902. }
  5903. #[cfg(feature = "diagnostics")]
  5904. tracing::info!(
  5905. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  5906. slow[0] as f64 / frames,
  5907. slow[1] as f64 / 1e3 / frames,
  5908. slow[2] as f64 / 1e3
  5909. );
  5910. if crate::shadow::cards() {
  5911. let per_frame = |i: usize| card[i] as f64 / frames;
  5912. tracing::info!(
  5913. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  5914. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  5915. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  5916. card[7],
  5917. card[8] >> 20,
  5918. card[9] >> 20,
  5919. per_frame(0) / 1e6,
  5920. per_frame(1),
  5921. per_frame(2),
  5922. per_frame(3),
  5923. per_frame(4) / 1e6,
  5924. per_frame(5),
  5925. per_frame(6) / 1e3
  5926. );
  5927. }
  5928. tracing::info!(
  5929. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  5930. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  5931. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  5932. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  5933. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  5934. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  5935. {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}",
  5936. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  5937. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  5938. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  5939. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  5940. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  5941. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  5942. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  5943. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  5944. refused = format!(
  5945. "{}; 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",
  5946. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  5947. crate::resource::TWINS[0].load(Ordering::Relaxed),
  5948. crate::resource::TWINS[1].load(Ordering::Relaxed),
  5949. crate::resource::PLANES[1].load(Ordering::Relaxed),
  5950. crate::resource::PLANES[2].load(Ordering::Relaxed)
  5951. ),
  5952. making = crate::pipeline::making(),
  5953. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  5954. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  5955. );
  5956. #[cfg(feature = "diagnostics")]
  5957. {
  5958. log_blame(frames);
  5959. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  5960. for (why, n) in drops.iter().take(40) {
  5961. tracing::info!(
  5962. "dropped {:.1}/frame without a host pipeline: {why}",
  5963. *n as f64 / frames
  5964. );
  5965. }
  5966. }
  5967. }
  5968. if self.caption.is_none() {
  5969. // The window's own text, read without a message.
  5970. let mut buffer = vec![0u16; 512];
  5971. // SAFETY: a window handle and a buffer of that length.
  5972. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  5973. buffer.truncate(n.max(0) as usize);
  5974. self.caption = Some(buffer);
  5975. }
  5976. let Some(caption) = &self.caption else { return };
  5977. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  5978. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  5979. text.push(0);
  5980. // Setting the text waits for the window's thread (a title thread,
  5981. // which may not pump for a while), so a thread of ours does it and
  5982. // presenting never waits; it takes the newest text when free.
  5983. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  5984. static SETTER: std::sync::Once = std::sync::Once::new();
  5985. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  5986. SETTER.call_once(|| {
  5987. let _ = std::thread::Builder::new()
  5988. .name("victory-caption".into())
  5989. .spawn(|| {
  5990. loop {
  5991. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  5992. match next {
  5993. // SAFETY: a window handle and a NUL-terminated text.
  5994. Some((hwnd, text)) => unsafe {
  5995. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  5996. },
  5997. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  5998. }
  5999. }
  6000. });
  6001. });
  6002. }
  6003. }
  6004. impl Host {
  6005. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  6006. /// as frame `frame` (saved if captures are on). `None` if nothing was
  6007. /// shown; else, in diagnostics builds, whether the frame was black.
  6008. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  6009. // SAFETY: a live resource.
  6010. let desc = unsafe { texture.GetDesc() };
  6011. let Some(format) = swap_format(desc.Format) else {
  6012. tracing::warn!(format = desc.Format.0, "cannot present this format");
  6013. return None;
  6014. };
  6015. let (width, height) = (desc.Width as u32, desc.Height);
  6016. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  6017. if presenter.is_none() {
  6018. *presenter = match self.presenter(width, height, format) {
  6019. Ok(p) => Some(p),
  6020. Err(e) => {
  6021. tracing::warn!(error = %e, "no swap chain");
  6022. return None;
  6023. }
  6024. };
  6025. }
  6026. let p = presenter.as_mut()?;
  6027. if (p.width, p.height, p.format) != (width, height, format) {
  6028. // Presents sent ahead hold back buffers until they have run.
  6029. settle_now(WHY_SYNC);
  6030. // SAFETY: no back buffer is held; every submission was waited for.
  6031. let resized = unsafe {
  6032. p.swap_chain
  6033. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  6034. };
  6035. match resized {
  6036. Ok(()) => (p.width, p.height, p.format) = (width, height, format),
  6037. Err(e) => {
  6038. tracing::warn!(error = %e, width, height, "swap chain not resized");
  6039. return None;
  6040. }
  6041. }
  6042. }
  6043. let state = D3D12_RESOURCE_STATES(state as i32);
  6044. // SAFETY: our swap chain, list and a live source texture.
  6045. unsafe {
  6046. let index = p.swap_chain.GetCurrentBackBufferIndex();
  6047. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  6048. return None;
  6049. };
  6050. // Sent ahead ([`late_free_present`]) unless the frame is to be
  6051. // read back at once (a saved or listed frame): then a list of
  6052. // its own, one whose last flight has finished or a new one.
  6053. #[cfg(feature = "diagnostics")]
  6054. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  6055. #[cfg(not(feature = "diagnostics"))]
  6056. let read_now = false;
  6057. let slot = if late_free_present() && !read_now {
  6058. let finished = FINISHED.load(Ordering::Acquire);
  6059. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  6060. let list = self.new_list().ok()?;
  6061. list.close();
  6062. p.ahead.push((list, 0));
  6063. Some(p.ahead.len() - 1)
  6064. })
  6065. } else {
  6066. None
  6067. };
  6068. let copy = match slot {
  6069. Some(i) => &p.ahead[i].0,
  6070. None => &p.copy,
  6071. };
  6072. copy.reset();
  6073. let list = &copy.list;
  6074. list.ResourceBarrier(&[
  6075. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  6076. transition(
  6077. &back,
  6078. D3D12_RESOURCE_STATE_PRESENT,
  6079. D3D12_RESOURCE_STATE_COPY_DEST,
  6080. ),
  6081. ]);
  6082. list.CopyResource(&back, texture);
  6083. #[cfg(feature = "diagnostics")]
  6084. let capture = crate::capture::wanted(frame)
  6085. .then(|| crate::capture::read_back(&self.device, list, texture))
  6086. .flatten();
  6087. #[cfg(feature = "diagnostics")]
  6088. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  6089. #[cfg(not(feature = "diagnostics"))]
  6090. let _ = frame;
  6091. list.ResourceBarrier(&[
  6092. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  6093. transition(
  6094. &back,
  6095. D3D12_RESOURCE_STATE_COPY_DEST,
  6096. D3D12_RESOURCE_STATE_PRESENT,
  6097. ),
  6098. ]);
  6099. copy.close();
  6100. match slot {
  6101. Some(i) => {
  6102. let flown = self.execute_own(copy);
  6103. p.ahead[i].1 = flown;
  6104. }
  6105. None => self.execute(&[copy]),
  6106. }
  6107. #[cfg(feature = "diagnostics")]
  6108. if let Some((buffer, footprint)) = capture {
  6109. crate::capture::save_read_back(frame, &buffer, &footprint);
  6110. }
  6111. #[cfg(feature = "diagnostics")]
  6112. crate::replay::record::present(texture, state);
  6113. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  6114. p.meter.frame(p.hwnd);
  6115. #[cfg(feature = "diagnostics")]
  6116. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  6117. #[cfg(not(feature = "diagnostics"))]
  6118. Some(false)
  6119. }
  6120. }
  6121. fn presenter(
  6122. &self,
  6123. width: u32,
  6124. height: u32,
  6125. format: DXGI_FORMAT,
  6126. ) -> windows::core::Result<Presenter> {
  6127. let hwnd = match title_window() {
  6128. Some(hwnd) => hwnd,
  6129. None => window(width, height)?,
  6130. };
  6131. // SAFETY: plain object creation for our window.
  6132. unsafe {
  6133. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  6134. let desc = DXGI_SWAP_CHAIN_DESC1 {
  6135. Width: width,
  6136. Height: height,
  6137. Format: format,
  6138. SampleDesc: DXGI_SAMPLE_DESC {
  6139. Count: 1,
  6140. Quality: 0,
  6141. },
  6142. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  6143. BufferCount: BUFFERS,
  6144. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  6145. ..Default::default()
  6146. };
  6147. let swap_chain = factory
  6148. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  6149. .cast::<IDXGISwapChain3>()?;
  6150. let copy = self.new_list()?;
  6151. copy.close();
  6152. tracing::info!(width, height, format = format.0, "presenting to a window");
  6153. Ok(Presenter {
  6154. swap_chain,
  6155. width,
  6156. height,
  6157. format,
  6158. copy,
  6159. ahead: Vec::new(),
  6160. hwnd,
  6161. meter: Meter::new(),
  6162. })
  6163. }
  6164. }
  6165. }
  6166. /// A visible top-level window of this process: the one the title made, if
  6167. /// it made one.
  6168. fn title_window() -> Option<HWND> {
  6169. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  6170. let mut process = 0;
  6171. // SAFETY: a window handle from the enumeration; `found` is ours.
  6172. unsafe {
  6173. GetWindowThreadProcessId(hwnd, Some(&mut process));
  6174. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  6175. && IsWindowVisible(hwnd).as_bool()
  6176. {
  6177. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  6178. return false.into();
  6179. }
  6180. }
  6181. true.into()
  6182. }
  6183. let mut found: Option<HWND> = None;
  6184. // SAFETY: the callback only writes `found`, which outlives the call.
  6185. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  6186. found
  6187. }
  6188. /// `state` without the bits the host texture's flags forbid: the console
  6189. /// lets the title name states its own resources allow (unordered access on
  6190. /// a depth target, whose host copy cannot have both).
  6191. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  6192. // SAFETY: a plain query.
  6193. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  6194. }
  6195. /// [`legal_state`] for a texture with resource flags `flags`.
  6196. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  6197. // (flag, set or clear forbids, state bits): render target, unordered
  6198. // access, depth, denied shader resource.
  6199. const FORBIDDEN: [(u32, bool, u32); 4] = [
  6200. (0x1, false, 0x4),
  6201. (0x4, false, 0x8),
  6202. (0x2, false, 0x10 | 0x20),
  6203. (0x8, true, 0x40 | 0x80),
  6204. ];
  6205. FORBIDDEN
  6206. .iter()
  6207. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  6208. .fold(state, |s, &(_, _, bits)| s & !bits)
  6209. }
  6210. impl Host {
  6211. /// The card's memory as the system accounts it to this process, in
  6212. /// bytes: the budget and the use of the card's own memory, then of the
  6213. /// PC's memory shared with the card (where the system moves what does
  6214. /// not fit on the card).
  6215. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  6216. let adapter = self.adapter.as_ref()?;
  6217. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  6218. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  6219. // SAFETY: plain queries that fill our structures.
  6220. unsafe {
  6221. adapter
  6222. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  6223. .ok()?;
  6224. adapter
  6225. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  6226. .ok()?;
  6227. }
  6228. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  6229. }
  6230. /// A buffer in system memory that the CPU maps (write-back, so reading
  6231. /// it is fast too) and shaders read and write: for host copies of title
  6232. /// memory that shaders write, which upload memory cannot be. Starts in
  6233. /// the common state (buffers move out of it implicitly).
  6234. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6235. MADE[2].fetch_add(1, Ordering::Relaxed);
  6236. MADE[3].fetch_add(size, Ordering::Relaxed);
  6237. let heap = D3D12_HEAP_PROPERTIES {
  6238. Type: D3D12_HEAP_TYPE_CUSTOM,
  6239. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  6240. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  6241. ..Default::default()
  6242. };
  6243. let desc = D3D12_RESOURCE_DESC {
  6244. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6245. Width: size.max(1),
  6246. Height: 1,
  6247. DepthOrArraySize: 1,
  6248. MipLevels: 1,
  6249. SampleDesc: DXGI_SAMPLE_DESC {
  6250. Count: 1,
  6251. Quality: 0,
  6252. },
  6253. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6254. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  6255. ..Default::default()
  6256. };
  6257. let mut buffer: Option<ID3D12Resource> = None;
  6258. let mut data = std::ptr::null_mut();
  6259. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  6260. let made = unsafe {
  6261. self.device
  6262. .CreateCommittedResource(
  6263. &heap,
  6264. D3D12_HEAP_FLAG_NONE,
  6265. &desc,
  6266. D3D12_RESOURCE_STATE_COMMON,
  6267. None,
  6268. &mut buffer,
  6269. )
  6270. .and_then(|()| {
  6271. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  6272. b.Map(0, None, Some(&mut data))
  6273. })
  6274. };
  6275. match made {
  6276. Ok(()) => Some((buffer?, data.cast())),
  6277. Err(e) => {
  6278. tracing::warn!(error = %e, size, "no shared buffer");
  6279. None
  6280. }
  6281. }
  6282. }
  6283. /// A device-local buffer shaders may write (unordered access) and indirect
  6284. /// execution may read, starting in the common state.
  6285. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  6286. MADE[4].fetch_add(1, Ordering::Relaxed);
  6287. MADE[5].fetch_add(size, Ordering::Relaxed);
  6288. let heap = D3D12_HEAP_PROPERTIES {
  6289. Type: D3D12_HEAP_TYPE_DEFAULT,
  6290. ..Default::default()
  6291. };
  6292. let desc = D3D12_RESOURCE_DESC {
  6293. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6294. Width: size.max(1),
  6295. Height: 1,
  6296. DepthOrArraySize: 1,
  6297. MipLevels: 1,
  6298. SampleDesc: DXGI_SAMPLE_DESC {
  6299. Count: 1,
  6300. Quality: 0,
  6301. },
  6302. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6303. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  6304. ..Default::default()
  6305. };
  6306. let mut buffer: Option<ID3D12Resource> = None;
  6307. // SAFETY: plain creation of a device-local buffer.
  6308. let made = unsafe {
  6309. self.device.CreateCommittedResource(
  6310. &heap,
  6311. D3D12_HEAP_FLAG_NONE,
  6312. &desc,
  6313. D3D12_RESOURCE_STATE_COMMON,
  6314. None,
  6315. &mut buffer,
  6316. )
  6317. };
  6318. match made {
  6319. Ok(()) => buffer,
  6320. Err(e) => {
  6321. tracing::warn!(error = %e, size, "no unordered-access buffer");
  6322. None
  6323. }
  6324. }
  6325. }
  6326. }
  6327. /// For adapters without device-removed data (the software one): the last
  6328. /// commands each list of the failed submission noted (diagnostics, with
  6329. /// `VICTORY_D3D12_DRED`).
  6330. fn last_notes(runs: &[&HostList]) -> String {
  6331. #[cfg(feature = "diagnostics")]
  6332. {
  6333. let mut text = String::new();
  6334. for (i, r) in runs.iter().enumerate() {
  6335. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  6336. for (n, _) in notes.iter().rev().take(6).rev() {
  6337. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  6338. }
  6339. }
  6340. text
  6341. }
  6342. #[cfg(not(feature = "diagnostics"))]
  6343. {
  6344. let _ = runs;
  6345. String::new()
  6346. }
  6347. }
  6348. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  6349. /// command reads (diagnostics).
  6350. #[cfg(feature = "diagnostics")]
  6351. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  6352. let end = start + bytes;
  6353. if va < start {
  6354. format!(" (fault {:#x} below its source)", start - va)
  6355. } else if va < end {
  6356. format!(" (fault at source +{:#x})", va - start)
  6357. } else {
  6358. format!(" (fault {:#x} past its source's end)", va - end)
  6359. }
  6360. }
  6361. /// The commands that may have been running where a list stopped at
  6362. /// command `done`: those between the barriers around it (work between
  6363. /// barriers overlaps on the GPU), by kind, and what the markers just
  6364. /// before them say (`HostList::note_op`: diagnostics builds with
  6365. /// device-removed data on).
  6366. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  6367. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  6368. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  6369. let to = history[done..]
  6370. .iter()
  6371. .position(barrier)
  6372. .map_or(history.len(), |b| (done + b).max(done + 1));
  6373. let mut text = format!(", commands {from}..{to} between its barriers:");
  6374. let mut shown = 0;
  6375. // From just before the command the GPU had not finished: the first
  6376. // twelve after the barrier named draws long done when a list of 79
  6377. // mesh draws stopped at its 45th (run 41).
  6378. for i in from.max(done.saturating_sub(4))..to {
  6379. let op = history[i];
  6380. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  6381. continue;
  6382. }
  6383. shown += 1;
  6384. let marker = i
  6385. .checked_sub(1)
  6386. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  6387. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  6388. .map_or("no marker", |(_, s)| s.as_str());
  6389. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  6390. }
  6391. text
  6392. }
  6393. pub(crate) fn transition(
  6394. resource: &ID3D12Resource,
  6395. before: D3D12_RESOURCE_STATES,
  6396. after: D3D12_RESOURCE_STATES,
  6397. ) -> D3D12_RESOURCE_BARRIER {
  6398. D3D12_RESOURCE_BARRIER {
  6399. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  6400. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  6401. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  6402. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  6403. // SAFETY: a borrowed pointer; the barrier never releases it.
  6404. pResource: unsafe { std::mem::transmute_copy(resource) },
  6405. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  6406. StateBefore: before,
  6407. StateAfter: after,
  6408. }),
  6409. },
  6410. }
  6411. }
  6412. /// A window of the given client size, owned by its own message thread.
  6413. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  6414. let (sender, receiver) = std::sync::mpsc::channel();
  6415. std::thread::Builder::new()
  6416. .name("victory-window".into())
  6417. .spawn(move || {
  6418. let made = make_window(width, height);
  6419. let ok = made.is_ok();
  6420. let _ = sender.send(made.map(|h| h.0 as usize));
  6421. if ok {
  6422. pump();
  6423. }
  6424. })
  6425. .map_err(|_| windows::core::Error::empty())?;
  6426. let hwnd = receiver
  6427. .recv()
  6428. .map_err(|_| windows::core::Error::empty())??;
  6429. Ok(HWND(hwnd as *mut _))
  6430. }
  6431. extern "system" fn window_proc(
  6432. hwnd: HWND,
  6433. message: u32,
  6434. wparam: WPARAM,
  6435. lparam: LPARAM,
  6436. ) -> LRESULT {
  6437. // SAFETY: the default handling for our window.
  6438. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  6439. }
  6440. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  6441. const CLASS: PCWSTR = w!("VIctory");
  6442. // SAFETY: registers our class once and creates a window of it.
  6443. unsafe {
  6444. let instance = GetModuleHandleW(None)?;
  6445. let class = WNDCLASSEXW {
  6446. cbSize: size_of::<WNDCLASSEXW>() as u32,
  6447. lpfnWndProc: Some(window_proc),
  6448. hInstance: instance.into(),
  6449. lpszClassName: CLASS,
  6450. hCursor: LoadCursorW(None, IDC_ARROW)?,
  6451. ..Default::default()
  6452. };
  6453. RegisterClassExW(&class);
  6454. let mut rect = RECT {
  6455. left: 0,
  6456. top: 0,
  6457. right: width as i32,
  6458. bottom: height as i32,
  6459. };
  6460. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  6461. CreateWindowExW(
  6462. WINDOW_EX_STYLE(0),
  6463. CLASS,
  6464. w!("VIctory"),
  6465. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  6466. CW_USEDEFAULT,
  6467. CW_USEDEFAULT,
  6468. rect.right - rect.left,
  6469. rect.bottom - rect.top,
  6470. None,
  6471. None,
  6472. Some(instance.into()),
  6473. None,
  6474. )
  6475. }
  6476. }
  6477. fn pump() {
  6478. let mut message = MSG::default();
  6479. // SAFETY: the standard message loop of this thread's window.
  6480. unsafe {
  6481. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  6482. let _ = TranslateMessage(&message);
  6483. DispatchMessageW(&message);
  6484. }
  6485. }
  6486. }
  6487. #[cfg(test)]
  6488. mod trail {
  6489. /// The trail keeps the newest things, and the report made when the
  6490. /// host device is removed says them and the pipeline library's state
  6491. /// (no card is asked for any of it).
  6492. #[test]
  6493. fn the_removal_report_says_the_newest_things_done() {
  6494. for n in 0..super::TRAIL_MOST + 5 {
  6495. super::trail(|| format!("thing {n} done"));
  6496. }
  6497. let text = super::removal_context();
  6498. assert!(text.contains("the submitting thread was"));
  6499. assert!(text.contains("pipeline library: no call running"));
  6500. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  6501. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  6502. }
  6503. }
  6504. #[cfg(test)]
  6505. mod spare {
  6506. use super::Spare;
  6507. /// Kept things come back by size, the last given first, and nothing is
  6508. /// kept past the limit.
  6509. #[test]
  6510. fn kept_things_come_back_by_size_within_the_limit() {
  6511. let mut spare: Spare<u32> = Spare::new();
  6512. assert_eq!(spare.take(4), None);
  6513. assert_eq!(spare.give(1, 4, 10), None);
  6514. assert_eq!(spare.give(2, 1, 10), None);
  6515. assert_eq!(spare.give(3, 4, 10), None);
  6516. assert_eq!(spare.bytes, 9);
  6517. // Past the limit: handed back, nothing changes.
  6518. assert_eq!(spare.give(4, 4, 10), Some(4));
  6519. assert_eq!(spare.bytes, 9);
  6520. assert_eq!(spare.take(2), None, "no thing of that size");
  6521. assert_eq!(spare.take(4), Some(3));
  6522. assert_eq!(spare.take(4), Some(1));
  6523. assert_eq!(spare.take(4), None);
  6524. assert_eq!(spare.take(1), Some(2));
  6525. assert_eq!(spare.bytes, 0);
  6526. assert!(spare.kept.is_empty());
  6527. }
  6528. }
  6529. #[cfg(test)]
  6530. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  6531. use super::Batch;
  6532. use std::sync::Arc;
  6533. #[test]
  6534. fn a_texture_is_checked_once_per_submission() {
  6535. let mut batch = Batch::default();
  6536. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  6537. // The first list sampling each texture checks it ...
  6538. assert!(batch.texture_due(&a));
  6539. assert!(batch.texture_due(&b));
  6540. // ... later lists of the same submission do not.
  6541. assert!(!batch.texture_due(&a));
  6542. assert!(!batch.texture_due(&a.clone()));
  6543. assert!(!batch.texture_due(&b));
  6544. }
  6545. #[test]
  6546. fn title_writes_make_textures_due_again() {
  6547. let mut batch = Batch::default();
  6548. let a = Arc::new(1u32);
  6549. assert!(batch.texture_due(&a));
  6550. assert!(!batch.texture_due(&a));
  6551. // A copy into title memory or work that may write it may have
  6552. // changed the texture's memory.
  6553. batch.title_written();
  6554. assert!(batch.texture_due(&a));
  6555. assert!(!batch.texture_due(&a));
  6556. // A fresh submission starts over.
  6557. let mut next = Batch::default();
  6558. assert!(next.texture_due(&a));
  6559. }
  6560. /// The hashing a submission does for textures in physical-page memory,
  6561. /// with every list checking the textures it samples (before) and with
  6562. /// each checked once (after). Run with
  6563. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  6564. #[test]
  6565. #[ignore = "benchmark"]
  6566. fn texture_checks_per_submission() {
  6567. const TEXTURES: usize = 48;
  6568. const SIZE: usize = 4 << 20;
  6569. const LISTS: usize = 12;
  6570. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  6571. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  6572. .collect();
  6573. let submit = |dedupe: bool| {
  6574. let mut batch = Batch::default();
  6575. let mut hashed = 0usize;
  6576. let started = std::time::Instant::now();
  6577. for _ in 0..LISTS {
  6578. for t in &textures {
  6579. if !dedupe || batch.texture_due(t) {
  6580. std::hint::black_box(blake3::hash(t));
  6581. hashed += 1;
  6582. }
  6583. }
  6584. }
  6585. (started.elapsed(), hashed)
  6586. };
  6587. submit(false); // warm up
  6588. let (before, n_before) = submit(false);
  6589. let (after, n_after) = submit(true);
  6590. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  6591. println!(
  6592. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  6593. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  6594. SIZE >> 20,
  6595. before.as_secs_f64() / after.as_secs_f64()
  6596. );
  6597. }
  6598. #[test]
  6599. fn vram_idle_ms_scales_with_pressure() {
  6600. use super::vram_idle_ms;
  6601. let gib = 1024 * 1024 * 1024;
  6602. // Normal (< 75%)
  6603. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  6604. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  6605. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  6606. // Moderate (75%..85%)
  6607. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  6608. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  6609. // High (>= 85%, including over-budget)
  6610. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  6611. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  6612. // Missing or zero budget falls back to normal
  6613. assert_eq!(vram_idle_ms(None), 5_000);
  6614. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  6615. }
  6616. #[test]
  6617. fn ram_idle_ms_scales_with_pressure() {
  6618. use super::ram_idle_ms;
  6619. let gib = 1024 * 1024 * 1024;
  6620. // Normal (>= 4 GiB)
  6621. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  6622. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  6623. // Moderate (2 GiB..4 GiB)
  6624. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  6625. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  6626. // High (< 2 GiB)
  6627. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  6628. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  6629. // Missing falls back to normal
  6630. assert_eq!(ram_idle_ms(None), 10_000);
  6631. }
  6632. }