host.rs 278 KB

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