host.rs 368 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444
  1. //! The host GPU: one D3D12 device and direct queue (decision 0007), and a
  2. //! window to present on.
  3. //!
  4. //! shortcut: every submission is waited for, so CPU and GPU never overlap
  5. //! (unless `VICTORY_LATE_WAIT=1`, see [`late`]);
  6. //! overlap them with per-submission fences once more than clears run.
  7. use std::sync::atomic::{AtomicU32, Ordering};
  8. use std::sync::{Mutex, OnceLock};
  9. use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
  10. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  11. use windows::Win32::Graphics::Direct3D12::*;
  12. use windows::Win32::Graphics::Dxgi::Common::*;
  13. use windows::Win32::Graphics::Dxgi::*;
  14. use windows::Win32::System::LibraryLoader::GetModuleHandleW;
  15. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  16. use windows::Win32::UI::WindowsAndMessaging::*;
  17. use windows::core::{Interface, PCWSTR, w};
  18. /// Resource states without the console's own bits (compression hints from
  19. /// bit 25 up), which the host rejects.
  20. pub(crate) fn pc_state(state: u32) -> u32 {
  21. state & 0x01ff_ffff
  22. }
  23. /// A console state as a host texture state: PC bits only, and none of the
  24. /// buffer-only ones the console allows on textures (vertex, constant and
  25. /// index buffer, stream out, indirect arguments, as in "generic read").
  26. pub(crate) fn texture_state(state: u32) -> u32 {
  27. const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
  28. pc_state(state) & !BUFFER_ONLY
  29. }
  30. /// Render target views live only until their command is recorded, so a
  31. /// ring of host descriptors is enough.
  32. const RTV_RING: u32 = 1024;
  33. pub(crate) struct Host {
  34. pub(crate) device: ID3D12Device,
  35. queue: ID3D12CommandQueue,
  36. fence: ID3D12Fence,
  37. /// The last value signalled on `fence`, behind the submission lock.
  38. submitted: Mutex<u64>,
  39. event: HANDLE,
  40. rtvs: ID3D12DescriptorHeap,
  41. rtv_size: u32,
  42. /// A ring of depth views, used as `rtvs`.
  43. dsvs: ID3D12DescriptorHeap,
  44. dsv_size: u32,
  45. next_dsv: AtomicU32,
  46. /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug
  47. /// layer's messages.
  48. messages: Option<ID3D12InfoQueue>,
  49. next_rtv: AtomicU32,
  50. presenter: Mutex<Option<Presenter>>,
  51. /// The adapter the device is on, for its memory budget
  52. /// ([`Host::video_memory`]); `None` if the system does not name it.
  53. adapter: Option<IDXGIAdapter3>,
  54. }
  55. // SAFETY: D3D12 devices, queues, fences and descriptor heaps are
  56. // free-threaded; the event handle is only waited on under `submitted`.
  57. unsafe impl Send for Host {}
  58. // SAFETY: as above.
  59. unsafe impl Sync for Host {}
  60. /// Host objects the title let go of while a submission may still use them
  61. /// (a texture its descriptors name, a descriptor slot's old resource), by
  62. /// the submission count they wait for. The title's descriptor writes and
  63. /// releases reach the host at once, from its own threads, while the host
  64. /// runs a submission: freeing there is a GPU page fault on the freed
  65. /// texture (a device hang).
  66. static RETIRED: Mutex<Vec<(u64, Retired)>> = Mutex::new(Vec::new());
  67. /// Submissions started and finished (waited for).
  68. static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  69. static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  70. /// A retired object, dropped on whatever thread finishes the submission.
  71. struct Retired(#[allow(dead_code)] Box<dyn std::any::Any>);
  72. // SAFETY: what is retired is D3D12 objects (free-threaded) and the
  73. // reference-counted wrappers holding them, dropped once.
  74. unsafe impl Send for Retired {}
  75. /// Milliseconds since the first call.
  76. pub(crate) fn now_ms() -> u64 {
  77. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  78. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  79. }
  80. /// This moment, for telling later how long ago it was ([`long_ago`]): the
  81. /// frames begun so far (high half, `crate::frame::current`) and tenths of a
  82. /// second since the start. Host copies of title memory, staging buffers and
  83. /// host textures note when they were last used with it.
  84. pub(crate) fn moment() -> u64 {
  85. (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff)
  86. }
  87. /// Whether `moment` lies at least `ms` milliseconds and `frames` frames
  88. /// back. Both: at seconds per frame, what every frame uses is not touched
  89. /// for seconds, and at many frames per second not for many frames. (A title
  90. /// that never waits for frames has no frame count: nothing is then idle.)
  91. pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
  92. let now = self::moment();
  93. let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
  94. (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
  95. }
  96. /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
  97. pub(crate) fn available_physical_ram() -> Option<u64> {
  98. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  99. // SAFETY: plain data the call fills in.
  100. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  101. m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
  102. // SAFETY: a sized structure.
  103. let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
  104. ok.then_some(m.ullAvailPhys)
  105. }
  106. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  107. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  108. /// handles not yet recorded into a list or slot remain protected.
  109. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  110. const NORMAL_MS: u64 = 5_000;
  111. const MODERATE_MS: u64 = 2_500;
  112. const HIGH_MS: u64 = 1_000;
  113. let Some([budget, used, ..]) = video_memory else {
  114. return NORMAL_MS;
  115. };
  116. if budget == 0 {
  117. return NORMAL_MS;
  118. }
  119. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  120. if used_pct >= 85 {
  121. HIGH_MS
  122. } else if used_pct >= 75 {
  123. MODERATE_MS
  124. } else {
  125. NORMAL_MS
  126. }
  127. }
  128. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  129. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  130. /// when free physical RAM is low. Never returns less than 2,000 ms.
  131. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  132. const GIB: u64 = 1024 * 1024 * 1024;
  133. const NORMAL_MS: u64 = 10_000;
  134. const MODERATE_MS: u64 = 5_000;
  135. const HIGH_MS: u64 = 2_000;
  136. let Some(avail) = avail_phys else {
  137. return NORMAL_MS;
  138. };
  139. if avail < 2 * GIB {
  140. HIGH_MS
  141. } else if avail < 4 * GIB {
  142. MODERATE_MS
  143. } else {
  144. NORMAL_MS
  145. }
  146. }
  147. /// How many references are held on a host object (its COM count): ours
  148. /// all, since the host's views and commands hold none. A buffer or texture
  149. /// with one is held by its owner alone: no descriptor slot keeps it
  150. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  151. pub(crate) fn references(object: &impl Interface) -> u32 {
  152. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  153. let raw = object.as_raw();
  154. // SAFETY: a live COM object, whose first three methods are those of
  155. // `IUnknown` (query, add a reference, release one); the pair leaves the
  156. // count as it was, and the release returns it. The first is not called.
  157. unsafe {
  158. let methods = *raw.cast::<*const [Method; 3]>();
  159. ((*methods)[1])(raw);
  160. ((*methods)[2])(raw)
  161. }
  162. }
  163. /// Once a second, before a submission starts: lets go of what nothing
  164. /// names any more (copies of windows of title memory, staging buffers,
  165. /// host copies of textures the title fills).
  166. /// `VICTORY_SWEEP=0` keeps everything, as before.
  167. fn sweep() {
  168. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  169. crate::inplace::tick();
  170. static ON: OnceLock<bool> = OnceLock::new();
  171. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  172. return;
  173. }
  174. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  175. let now = now_ms();
  176. let last = LAST.load(Ordering::Relaxed);
  177. if now < last + 1000
  178. || LAST
  179. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  180. .is_err()
  181. {
  182. return;
  183. }
  184. crate::pipeline::trim_library();
  185. crate::shadow::let_go_idle();
  186. crate::texture::let_go_idle();
  187. crate::resource::let_go_idle();
  188. }
  189. /// Drops `object` once every submission running now has finished: at once
  190. /// if none is.
  191. pub(crate) fn retire<T: 'static>(object: T) {
  192. let started = STARTED.load(Ordering::Acquire);
  193. if started <= FINISHED.load(Ordering::Acquire) {
  194. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  195. drop(object);
  196. return;
  197. }
  198. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  199. RETIRED
  200. .lock()
  201. .unwrap_or_else(|e| e.into_inner())
  202. .push((started, Retired(Box::new(object))));
  203. }
  204. /// Drops what waited for submissions up to `finished`.
  205. fn bury(finished: u64) {
  206. let done: Vec<(u64, Retired)> = {
  207. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  208. if retired.is_empty() {
  209. return;
  210. }
  211. let (done, keep) = std::mem::take(&mut *retired)
  212. .into_iter()
  213. .partition(|(at, _)| *at <= finished);
  214. *retired = keep;
  215. done
  216. };
  217. drop(done);
  218. }
  219. /// Objects [`retire`] dropped at once (no submission was running) and
  220. /// kept until a running submission finished, since the start.
  221. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  222. /// What the layer did to the host's objects lately, newest last (sweeps
  223. /// that let host copies go, pipeline library calls, saves and trims): said
  224. /// once when the host device is removed ([`log_removal_context`]), with
  225. /// what the submitting thread and the pipeline workers were doing at that
  226. /// moment. A device the driver removes "internally" names no command, and
  227. /// the pass that happens to notice first names only the view it was at:
  228. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  229. /// pipeline library call that no line of the log tied to them.
  230. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  231. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  232. /// The entries kept.
  233. const TRAIL_MOST: usize = 96;
  234. fn trail_on() -> bool {
  235. static ON: OnceLock<bool> = OnceLock::new();
  236. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  237. }
  238. /// Microseconds since the first call.
  239. pub(crate) fn now_us() -> u64 {
  240. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  241. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  242. }
  243. /// The calling thread, as the log's other lines name threads.
  244. pub(crate) fn thread_id() -> u32 {
  245. // SAFETY: a plain query.
  246. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  247. }
  248. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  249. /// run when the trail is kept.
  250. pub(crate) fn trail(what: impl FnOnce() -> String) {
  251. if !trail_on() {
  252. return;
  253. }
  254. let entry = (now_us(), thread_id(), what());
  255. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  256. if trail.len() >= TRAIL_MOST {
  257. trail.pop_front();
  258. }
  259. trail.push_back(entry);
  260. }
  261. /// What the submitting thread is doing (0 nothing: between submissions,
  262. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  263. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  264. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  265. fn submitting(phase: u64, lists: usize) {
  266. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  267. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  268. SUBMITTING[0].store(phase, Ordering::Relaxed);
  269. }
  270. /// What was going on when the host device went: whether a submission was
  271. /// on the card, the pipeline library's state and the calls running in it,
  272. /// and the trail.
  273. pub(crate) fn removal_context() -> String {
  274. use std::fmt::Write;
  275. let now = now_us();
  276. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  277. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  278. 0 => "between submissions (nothing of ours was running on the card)",
  279. 1 => "preparing a submission (nothing of ours was running on the card)",
  280. 2 => "waiting for the card to run a submission",
  281. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  282. };
  283. let mut text = format!(
  284. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  285. SUBMITTING[1].load(Ordering::Relaxed),
  286. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  287. crate::pipeline::library_removal_note(),
  288. RETIREMENTS[0].load(Ordering::Relaxed),
  289. RETIREMENTS[1].load(Ordering::Relaxed),
  290. STARTED.load(Ordering::Relaxed),
  291. FINISHED.load(Ordering::Relaxed),
  292. );
  293. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  294. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  295. for (at, thread, what) in trail.iter() {
  296. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  297. }
  298. text
  299. }
  300. /// Says [`removal_context`] in the log, once: called by whoever finds the
  301. /// host device removed.
  302. pub(crate) fn log_removal_context() {
  303. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  304. if !trail_on() || SAID.swap(true, Ordering::Relaxed) {
  305. return;
  306. }
  307. tracing::error!("when the host device went: {}", removal_context());
  308. }
  309. /// Time spent in submissions since the last frame-rate line, in
  310. /// microseconds: preparing them on the CPU (title memory copies, texture
  311. /// detiling), then waiting for the GPU.
  312. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  313. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  314. /// After submissions: shader-written ranges compared and copied back into
  315. /// title memory (microseconds, bytes that differed), since the last
  316. /// frame-rate line.
  317. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  318. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  319. /// The card's clock, for the frame line of every run, in microseconds since
  320. /// the last one: how long the card had nothing of ours queued; how much of
  321. /// that while the thread that holds the submission lock was working (the
  322. /// card idle behind us: preparing and copying back are done with the card
  323. /// standing); and how long that thread stood waiting for the card.
  324. ///
  325. /// Every send of lists to the queue is followed by a signal on a fence of
  326. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  327. /// the newest signal and notes the moment the card reached it with nothing
  328. /// newer sent; the next send ends that idle stretch.
  329. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  330. /// Of the thread that holds the submission lock: the microseconds it has
  331. /// worked so far (preparing, copying back; not its waits for the card), and
  332. /// since when it works now ([`now_us`] plus one; 0: it does not).
  333. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  334. /// The thread that holds the submission lock starts (`on`) or stops
  335. /// working; whether it worked until now.
  336. fn working(on: bool) -> bool {
  337. let now = now_us() + 1;
  338. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  339. if since != 0 {
  340. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  341. }
  342. since != 0
  343. }
  344. /// [`WORKING`] as of now: microseconds worked so far.
  345. fn worked() -> u64 {
  346. let since = WORKING[1].load(Ordering::Relaxed);
  347. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  348. WORKING[0].load(Ordering::Relaxed) + now
  349. }
  350. /// The thread that holds the submission lock stood waiting for the card
  351. /// from `since` until now ([`CARD_CLOCK_US`]).
  352. fn stood(since: std::time::Instant) {
  353. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  354. }
  355. /// What [`CARD_CLOCK_US`] is measured with.
  356. struct CardClock {
  357. fence: ID3D12Fence,
  358. /// Signals sent so far; and, while the card has reached the last of
  359. /// them, since when and what [`worked`] said then.
  360. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  361. sent: std::sync::Condvar,
  362. }
  363. // SAFETY: a fence (free-threaded) behind a lock.
  364. unsafe impl Send for CardClock {}
  365. // SAFETY: as above.
  366. unsafe impl Sync for CardClock {}
  367. /// The clock's thread: waits for the newest signal sent and notes when the
  368. /// card got there with nothing newer behind it.
  369. fn card_clock_watch(clock: &'static CardClock) {
  370. // SAFETY: a plain event of our own.
  371. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  372. return;
  373. };
  374. let mut seen = 0;
  375. loop {
  376. let target = {
  377. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  378. while state.0 == seen {
  379. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  380. }
  381. state.0
  382. };
  383. // SAFETY: the clock's fence and this thread's event.
  384. unsafe {
  385. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  386. WaitForSingleObject(event, INFINITE);
  387. }
  388. }
  389. seen = target;
  390. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  391. if state.0 == target && state.1.is_none() {
  392. state.1 = Some((std::time::Instant::now(), worked()));
  393. }
  394. }
  395. }
  396. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  397. /// frame's time.
  398. fn card_clock_line(frames: f64, ms: f64) {
  399. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  400. tracing::info!(
  401. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  402. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  403. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  404. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  405. );
  406. }
  407. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  408. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  409. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  410. std::sync::atomic::AtomicU64::new(0),
  411. std::sync::atomic::AtomicU64::new(0),
  412. std::sync::atomic::AtomicU64::new(0),
  413. std::sync::atomic::AtomicU64::new(0),
  414. ];
  415. /// Host buffers made since the start, as (count, bytes): in the upload heap
  416. /// (staging, list scratch), shared with the processor (host copies of title
  417. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  418. /// For the memory line: against what is alive, they show what was let go.
  419. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  420. /// What of that is alive now, for the memory line (`MADE` counts what was
  421. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  422. /// and nothing said how many were alive): host lists; the lists' scratch
  423. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  424. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  425. /// instead of made, since the start; and the lists' other upload buffers
  426. /// (texture data copied from buffers, scratch too big for a chunk) and
  427. /// their bytes.
  428. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  429. /// About host lists, for the memory line: lists made by the host since the
  430. /// start; preludes made (a list's second allocator and list, made when it
  431. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  432. /// bytes the process's private memory grew by while lists were being made
  433. /// (what a list costs: host objects with the driver's command memory; 631
  434. /// lists were alive in run 65, each with a prelude it may never use).
  435. /// Then the lists alive that were never reset since they were made: the
  436. /// host sides of title lists the title made and has not used (a host list
  437. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  438. /// makes at its start).
  439. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  440. /// The process's private bytes (diagnostics: around the making of lists).
  441. #[cfg(feature = "diagnostics")]
  442. fn private_bytes() -> u64 {
  443. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  444. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  445. let mut c = PROCESS_MEMORY_COUNTERS {
  446. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  447. ..Default::default()
  448. };
  449. // SAFETY: our own process and a sized structure.
  450. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  451. c.PagefileUsage as u64
  452. }
  453. /// What the runtime does when the host GPU fails for good: report it like a
  454. /// crash and end the run. The console has no such state, and carrying on
  455. /// draws nothing at seconds per frame.
  456. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  457. /// Sets what a host GPU failure does (the runtime's crash report).
  458. pub fn on_failure(report: fn(&str) -> !) {
  459. let _ = ON_FAILURE.set(report);
  460. }
  461. /// Ends the run on a host GPU failure: what failed, the removal reason and
  462. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  463. /// diagnostics build names the command).
  464. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  465. let mut text = what.to_string();
  466. if let Some(host) = host() {
  467. // SAFETY: a plain query.
  468. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  469. text.push_str(&format!("; device removed: {e}"));
  470. log_removal_context();
  471. }
  472. match host.log_messages() {
  473. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  474. None if host.messages.is_none() => text.push_str(
  475. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  476. ),
  477. None => {}
  478. }
  479. }
  480. tracing::error!("{text}");
  481. // Tests have no log: the reason goes to their output.
  482. #[cfg(test)]
  483. eprintln!("host GPU failure: {text}");
  484. match ON_FAILURE.get() {
  485. Some(report) => report(&text),
  486. None => std::process::abort(),
  487. }
  488. }
  489. /// The host GPU, created on first use; `None` without one (a run then
  490. /// behaves as before: nothing executes).
  491. pub(crate) fn host() -> Option<&'static Host> {
  492. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  493. HOST.get_or_init(|| match create() {
  494. Ok(host) => Some(host),
  495. Err(e) => {
  496. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  497. None
  498. }
  499. })
  500. .as_ref()
  501. }
  502. fn create() -> windows::core::Result<Host> {
  503. // SAFETY: plain D3D12 object creation with valid descriptions.
  504. unsafe {
  505. // The debug layer only in builds with diagnostics.
  506. let debug =
  507. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some();
  508. if debug {
  509. let mut layer: Option<ID3D12Debug> = None;
  510. match D3D12GetDebugInterface(&mut layer) {
  511. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  512. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  513. }
  514. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  515. // descriptor heap indices and the like become messages naming
  516. // the command instead of page faults. Without state tracking
  517. // (directly indexed textures are not transitioned).
  518. if std::env::var_os("VICTORY_D3D12_GBV").is_some()
  519. && let Some(l) = &layer
  520. {
  521. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  522. d1.SetEnableGPUBasedValidation(true);
  523. }
  524. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  525. d2.SetGPUBasedValidationFlags(
  526. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  527. );
  528. }
  529. tracing::info!("GPU-based validation on");
  530. }
  531. }
  532. // Diagnostics: device-removed data (the command that faulted, the
  533. // faulting address), read when the device is removed.
  534. if dred_on() {
  535. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  536. if D3D12GetDebugInterface(&mut dred).is_ok()
  537. && let Some(dred) = dred
  538. {
  539. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  540. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  541. }
  542. }
  543. let mut device: Option<ID3D12Device> = None;
  544. // Diagnostics: the software adapter, on which a shader's wild access
  545. // is an access violation in this process (a crash report with the
  546. // address and instruction) instead of a GPU fault and driver reset.
  547. if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() {
  548. let adapter = warp_adapter()?;
  549. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  550. tracing::info!("host device on the software adapter (WARP)");
  551. } else {
  552. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  553. }
  554. let device = device.ok_or_else(windows::core::Error::empty)?;
  555. // Before anything is made with it (`VICTORY_RECORD`).
  556. #[cfg(feature = "diagnostics")]
  557. crate::replay::record::from_env(&device);
  558. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  559. // driver compiling shaders again on the "D3D Background Thread"s,
  560. // for minutes after pipelines were made or loaded) is switched off.
  561. // An experiment: while those threads ran, the same shot took
  562. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  563. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  564. // whether the card is slower with the shaders it then keeps is not
  565. // known.
  566. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  567. && let Ok(device6) = device.cast::<ID3D12Device6>()
  568. {
  569. let set = device6.SetBackgroundProcessingMode(
  570. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  571. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  572. None,
  573. None,
  574. );
  575. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  576. }
  577. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  578. // cross-lane code stays in 32-lane halves translated for waves of 32
  579. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  580. if device
  581. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  582. .is_ok()
  583. {
  584. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  585. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  586. }
  587. let messages = debug
  588. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  589. .flatten();
  590. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  591. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  592. ..Default::default()
  593. })?;
  594. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  595. let event = CreateEventW(None, false, false, None)?;
  596. let rtvs: ID3D12DescriptorHeap =
  597. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  598. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  599. NumDescriptors: RTV_RING,
  600. ..Default::default()
  601. })?;
  602. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  603. let dsvs: ID3D12DescriptorHeap =
  604. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  605. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  606. NumDescriptors: RTV_RING,
  607. ..Default::default()
  608. })?;
  609. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  610. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  611. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  612. .ok();
  613. tracing::info!("host D3D12 device ready");
  614. Ok(Host {
  615. device,
  616. queue,
  617. fence,
  618. submitted: Mutex::new(0),
  619. event,
  620. rtvs,
  621. rtv_size,
  622. dsvs,
  623. dsv_size,
  624. next_dsv: AtomicU32::new(0),
  625. messages,
  626. next_rtv: AtomicU32::new(0),
  627. presenter: Mutex::new(None),
  628. adapter,
  629. })
  630. }
  631. }
  632. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  633. /// Reject it before creating a device in diagnostics' software-only mode.
  634. fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  635. // SAFETY: plain DXGI adapter queries.
  636. unsafe {
  637. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  638. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  639. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  640. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  641. tracing::warn!(
  642. vendor = format_args!("{:#x}", desc.VendorId),
  643. flags = format_args!("{:#x}", desc.Flags),
  644. "DXGI did not identify the WARP adapter as software; refusing device"
  645. );
  646. return Err(windows::core::Error::from_hresult(
  647. windows::Win32::Foundation::E_FAIL,
  648. ));
  649. }
  650. Ok(adapter)
  651. }
  652. }
  653. #[cfg(test)]
  654. mod tests {
  655. #[test]
  656. fn sparse_copies_preserve_islands_and_observe_remaps() {
  657. use windows_sys::Win32::System::Memory::*;
  658. const N: usize = 5 << 16;
  659. // SAFETY: we reserve a private region, commit selected pages inside it,
  660. // and only directly access the pages while they are writable.
  661. unsafe {
  662. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  663. assert!(!base.is_null());
  664. let mut expected = vec![0; N];
  665. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  666. let at = base.add(offset);
  667. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  668. at.write_bytes(value, 4096);
  669. expected[offset..offset + 4096].fill(value);
  670. }
  671. for remap in [false, true] {
  672. if remap {
  673. let mut old = 0;
  674. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  675. expected[..4096].fill(0);
  676. let at = base.add(1 << 16);
  677. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  678. at.write_bytes(0xc7, 4096);
  679. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  680. }
  681. let mut out = vec![0xee; N];
  682. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  683. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  684. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  685. }
  686. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  687. }
  688. }
  689. use super::*;
  690. #[test]
  691. fn warp_adapter_accepts_only_software() {
  692. // This probes DXGI without creating a D3D12 device or running a title.
  693. // SAFETY: plain DXGI adapter queries.
  694. let raw = unsafe {
  695. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  696. else {
  697. return;
  698. };
  699. factory.EnumWarpAdapter::<IDXGIAdapter>()
  700. };
  701. let Ok(raw) = raw else { return };
  702. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  703. // IDXGIAdapter1; `raw` owns that interface.
  704. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  705. eprintln!(
  706. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  707. desc.VendorId, desc.Flags
  708. );
  709. assert_eq!(
  710. warp_adapter().is_ok(),
  711. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  712. );
  713. }
  714. }
  715. /// The batches of clamped records in one scratch buffer
  716. /// ([`HostList::batch_place`]).
  717. const BATCHES: u32 = 8;
  718. /// A host command list and its allocator, always used together.
  719. pub(crate) struct HostList {
  720. allocator: ID3D12CommandAllocator,
  721. pub(crate) list: ID3D12GraphicsCommandList,
  722. /// Work for submission time, in recorded order.
  723. deferred: Mutex<Deferred>,
  724. /// Upload memory for data the list's draws make (expanded vertices),
  725. /// reused after a reset.
  726. scratch: Mutex<Scratch>,
  727. /// Host texture states the list assumes, by host copy: at its start and
  728. /// at its end. Lists are recorded on many threads and run in submission
  729. /// order, so the transitions from a texture's real state are made at
  730. /// submission, in `prelude`. Holding the copies keeps every texture the
  731. /// list names alive until it is reset, even if the title releases the
  732. /// resource first.
  733. states: Mutex<States>,
  734. /// What the list does with depth textures that have a colour twin, by
  735. /// twin ([`TwinUse`]).
  736. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  737. /// The list that runs those transitions just before this one, made
  738. /// when the list first has such transitions ([`lazy_prelude`]).
  739. prelude: OnceLock<Option<Prelude>>,
  740. /// The pipelines the list binds, for reports of slow submissions.
  741. pipelines: Mutex<std::collections::BTreeSet<String>>,
  742. /// The work its indirect executions may still do (`indirect`): a
  743. /// shader-writable word, zeroed when the list is submitted, and after
  744. /// it what the clamp notes about mesh records. In memory the CPU maps.
  745. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  746. /// The same words in the card's own memory ([`card_budget`]), which the
  747. /// clamp uses instead when there is one: zeroed in the list before its
  748. /// first clamp, its notes copied to `budget` when the list closes.
  749. card_budget: OnceLock<Option<ID3D12Resource>>,
  750. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  751. /// grown to the largest indirect execution recorded on the list.
  752. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  753. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  754. /// how many batches of this recording have a place in them.
  755. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  756. /// Counts the list in [`ALIVE`] while it lives.
  757. _alive: Counted,
  758. /// The texts of the markers `note_op` set, in order (for device-removed
  759. /// data without marker texts), with the host GPU range a copy reads.
  760. #[cfg(feature = "diagnostics")]
  761. notes: Mutex<Vec<Note>>,
  762. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  763. /// and at the end, and where they are read back.
  764. #[cfg(feature = "diagnostics")]
  765. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  766. }
  767. /// A list's prelude: an allocator and a closed list.
  768. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  769. /// Whether a host list's prelude is made when the list first needs one. A
  770. /// prelude runs the texture transitions and twin copies a list needs before
  771. /// it; lists that name no texture never have one, and every host list was
  772. /// made with one all the same: twice the host objects per list, for the
  773. /// title's 630 lists and for every list made anew.
  774. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  775. fn lazy_prelude() -> bool {
  776. static ON: OnceLock<bool> = OnceLock::new();
  777. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  778. }
  779. /// Timestamps per list (diagnostics); commands past them are not timed.
  780. #[cfg(feature = "diagnostics")]
  781. const STAMPS: u32 = 4096;
  782. /// A marker's text and the host range its command reads (diagnostics).
  783. #[cfg(feature = "diagnostics")]
  784. type Note = (String, Option<(u64, u64)>);
  785. type States = std::collections::HashMap<
  786. usize,
  787. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  788. >;
  789. /// What a list does with a depth texture that has a colour twin
  790. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  791. /// in submission order, so a list cannot know which side an earlier list
  792. /// leaves behind: it notes which sides it uses as it finds them, and its
  793. /// prelude copies one side into the other at submission if that side is
  794. /// behind then. From its first use of a side on, the list knows.
  795. struct TwinUse {
  796. /// The depth texture (the title resource's host copy) and its twin.
  797. depth: std::sync::Arc<crate::resource::HostTexture>,
  798. twin: std::sync::Arc<crate::resource::Twin>,
  799. /// The sides (depth texture, twin) the list uses as it finds them.
  800. needs: [bool; 2],
  801. /// Whether each side lacks what the other was written last, where the
  802. /// list is now; `None`: as the list found it.
  803. behind: [Option<bool>; 2],
  804. /// The draw or dispatch being prepared writes the twin.
  805. writing: bool,
  806. /// The depth plane's twin holds what the plane lacks although the list
  807. /// copied the twins since: the plane's pass waits for the list's close.
  808. late: bool,
  809. }
  810. /// The pass that draws the twin of a depth plane into the plane: one
  811. /// triangle over each mip of each slice, its pixel shader writing the
  812. /// twin's texel as the depth, with the depth test "always" and no stencil
  813. /// (the stencil plane is copied through a buffer and not touched here).
  814. ///
  815. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  816. /// the step times the float nearest 1/65535 (0x37800080). That is how
  817. /// The title's tiled lighting computes the depth of the
  818. /// rectangles it then draws with the test "equal", one class of materials
  819. /// a draw (all six of its vertex shaders multiply the class number by that
  820. /// constant), so the pass and the draw give the host the same float, and
  821. /// the host turns the same float into the same 24 bits. The step divided
  822. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  823. /// and lands in another 24-bit step for 127 of them (none under 385).
  824. const PLANE_CORNERS: &str = r#"
  825. float4 corner(uint i : SV_VertexID) : SV_Position {
  826. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  827. }
  828. "#;
  829. const PLANE_STEPS: &str = r#"
  830. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  831. Texture2DArray<uint> twin : register(t0);
  832. [RootSignature(RS)]
  833. float plane(float4 p : SV_Position) : SV_Depth {
  834. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  835. }
  836. "#;
  837. const PLANE_FLOATS: &str = r#"
  838. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  839. Texture2DArray<float> twin : register(t0);
  840. [RootSignature(RS)]
  841. float plane(float4 p : SV_Position) : SV_Depth {
  842. return twin.Load(int4(int2(p.xy), 0, 0));
  843. }
  844. "#;
  845. /// Views of twins the pass reads, in a heap of ours used as a ring.
  846. /// shortcut: a view must last until its list has run; with one or two
  847. /// passes a frame the ring is far from coming round.
  848. const PLANE_VIEWS: u32 = 256;
  849. /// What the pass draws with: the heap of its views of twins, and per kind
  850. /// of twin (16-bit steps or floats) and depth format the root signature
  851. /// and pipeline, made when first needed (`None`: the host refused).
  852. struct PlanePass {
  853. views: ID3D12DescriptorHeap,
  854. cpu: usize,
  855. gpu: u64,
  856. step: u32,
  857. next: AtomicU32,
  858. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  859. }
  860. /// The pass's root signature and pipeline for one kind of twin and one
  861. /// depth format.
  862. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  863. // SAFETY: D3D12 objects are free-threaded.
  864. unsafe impl Send for PlanePass {}
  865. // SAFETY: as above.
  866. unsafe impl Sync for PlanePass {}
  867. fn plane_pass() -> Option<&'static PlanePass> {
  868. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  869. PASS.get_or_init(|| {
  870. let host = host()?;
  871. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  872. // SAFETY: plain heap creation and queries.
  873. unsafe {
  874. let views: ID3D12DescriptorHeap = host
  875. .device
  876. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  877. Type: kind,
  878. NumDescriptors: PLANE_VIEWS,
  879. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  880. NodeMask: 0,
  881. })
  882. .ok()?;
  883. Some(PlanePass {
  884. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  885. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  886. step: host.device.GetDescriptorHandleIncrementSize(kind),
  887. views,
  888. next: AtomicU32::new(0),
  889. made: Mutex::default(),
  890. })
  891. }
  892. })
  893. .as_ref()
  894. }
  895. /// Compiles function `entry` of `source` for `target` with the system's
  896. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  897. pub(crate) fn compile(
  898. source: &str,
  899. entry: windows::core::PCSTR,
  900. target: windows::core::PCSTR,
  901. ) -> windows::core::Result<Vec<u8>> {
  902. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  903. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  904. let mut code: Option<ID3DBlob> = None;
  905. let mut errors: Option<ID3DBlob> = None;
  906. // SAFETY: the source and names live through the call; out pointers ours.
  907. let compiled = unsafe {
  908. D3DCompile(
  909. source.as_ptr().cast(),
  910. source.len(),
  911. windows::core::s!("victory"),
  912. None,
  913. None,
  914. entry,
  915. target,
  916. 0,
  917. 0,
  918. &mut code,
  919. Some(&mut errors),
  920. )
  921. };
  922. if let Err(e) = compiled {
  923. if let Some(errors) = errors {
  924. // SAFETY: the blob's own bytes.
  925. let text = unsafe {
  926. std::slice::from_raw_parts(
  927. errors.GetBufferPointer().cast::<u8>(),
  928. errors.GetBufferSize(),
  929. )
  930. };
  931. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  932. }
  933. return Err(e);
  934. }
  935. let code = code.ok_or_else(windows::core::Error::empty)?;
  936. // SAFETY: the blob's own bytes.
  937. let bytes = unsafe {
  938. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  939. };
  940. Ok(bytes.to_vec())
  941. }
  942. impl PlanePass {
  943. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  944. /// or of floats and the depth format `format`.
  945. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  946. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  947. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  948. return pipeline.clone();
  949. }
  950. let pipeline = match Self::make(steps, format) {
  951. Ok(pipeline) => Some(pipeline),
  952. Err(e) => {
  953. tracing::warn!(
  954. error = %e,
  955. steps,
  956. format = format.0,
  957. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  958. );
  959. None
  960. }
  961. };
  962. made.push((steps, format.0, pipeline.clone()));
  963. pipeline
  964. }
  965. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  966. use windows::core::s;
  967. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  968. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  969. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  970. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  971. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  972. pShaderBytecode: bytes.as_ptr().cast(),
  973. BytecodeLength: bytes.len(),
  974. };
  975. // SAFETY: the root signature is inside the pixel shader; the
  976. // description points at live data and never releases its pointer.
  977. unsafe {
  978. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  979. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  980. pRootSignature: std::mem::transmute_copy(&root),
  981. VS: code(&vs[..]),
  982. PS: code(&ps[..]),
  983. SampleMask: u32::MAX,
  984. RasterizerState: D3D12_RASTERIZER_DESC {
  985. FillMode: D3D12_FILL_MODE_SOLID,
  986. CullMode: D3D12_CULL_MODE_NONE,
  987. DepthClipEnable: true.into(),
  988. ..Default::default()
  989. },
  990. // Every texel is written; stencil stays off.
  991. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  992. DepthEnable: true.into(),
  993. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  994. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  995. ..Default::default()
  996. },
  997. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  998. DSVFormat: format,
  999. SampleDesc: DXGI_SAMPLE_DESC {
  1000. Count: 1,
  1001. Quality: 0,
  1002. },
  1003. ..Default::default()
  1004. };
  1005. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1006. Ok((root, pipeline))
  1007. }
  1008. }
  1009. }
  1010. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1011. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1012. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1013. /// heap, graphics root signature, pipeline, depth target, viewport,
  1014. /// scissor and topology and puts none of them back: it is for a list that
  1015. /// records nothing of the title's after it.
  1016. fn record_plane_pass(
  1017. list: &ID3D12GraphicsCommandList,
  1018. depth: &ID3D12Resource,
  1019. plane: &ID3D12Resource,
  1020. ) {
  1021. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1022. return;
  1023. };
  1024. // SAFETY: live resources.
  1025. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1026. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1027. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1028. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1029. let steps = twin.Format.0 == 53;
  1030. let format = DXGI_FORMAT(match of.Format.0 {
  1031. 44 => 45,
  1032. 19 => 20,
  1033. typed => typed,
  1034. });
  1035. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1036. return;
  1037. };
  1038. for slice in 0..u32::from(of.DepthOrArraySize) {
  1039. for mip in 0..u32::from(of.MipLevels) {
  1040. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1041. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1042. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1043. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1044. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1045. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1046. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1047. MostDetailedMip: mip,
  1048. MipLevels: 1,
  1049. FirstArraySlice: slice,
  1050. ArraySize: 1,
  1051. ..Default::default()
  1052. },
  1053. },
  1054. };
  1055. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1056. Format: format,
  1057. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1058. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1059. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1060. MipSlice: mip,
  1061. FirstArraySlice: slice,
  1062. ArraySize: 1,
  1063. },
  1064. },
  1065. ..Default::default()
  1066. };
  1067. let target = host.dsv(depth, Some(&target));
  1068. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1069. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1070. ptr: pass.cpu + (slot * pass.step) as usize,
  1071. };
  1072. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1073. ptr: pass.gpu + u64::from(slot * pass.step),
  1074. };
  1075. // SAFETY: an open list; a slot of our heap; live resources and
  1076. // objects (the pass's own live as long as the process).
  1077. unsafe {
  1078. host.device
  1079. .CreateShaderResourceView(plane, Some(&view), cpu);
  1080. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1081. list.SetGraphicsRootSignature(&root);
  1082. list.SetPipelineState(&pipeline);
  1083. list.SetGraphicsRootDescriptorTable(0, gpu);
  1084. list.OMSetRenderTargets(0, None, false, Some(&target));
  1085. list.RSSetViewports(&[D3D12_VIEWPORT {
  1086. TopLeftX: 0.0,
  1087. TopLeftY: 0.0,
  1088. Width: width as f32,
  1089. Height: height as f32,
  1090. MinDepth: 0.0,
  1091. MaxDepth: 1.0,
  1092. }]);
  1093. list.RSSetScissorRects(&[RECT {
  1094. left: 0,
  1095. top: 0,
  1096. right: width as i32,
  1097. bottom: height as i32,
  1098. }]);
  1099. list.IASetPrimitiveTopology(
  1100. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1101. );
  1102. list.DrawInstanced(3, 1, 0, 0);
  1103. }
  1104. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1105. }
  1106. }
  1107. }
  1108. /// Records into `list` the copy of a depth texture into its colour twin
  1109. /// (`colour`) or of the twin into the depth texture, both already in their
  1110. /// copy states: whole textures of one size in one format family, which the
  1111. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1112. /// alone, through the twin's buffer.
  1113. fn record_twin_copy(
  1114. list: &ID3D12GraphicsCommandList,
  1115. depth: &ID3D12Resource,
  1116. twin: &crate::resource::Twin,
  1117. colour: bool,
  1118. ) {
  1119. let (from, to) = if colour {
  1120. (depth, &twin.colour.texture)
  1121. } else {
  1122. (&twin.colour.texture, depth)
  1123. };
  1124. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1125. // shortcut: the depth plane's twin is not given the plane (that is a
  1126. // pass the other way: the plane read by a shader, the twin as its
  1127. // target). The twin then lacks what draws and clears wrote to the
  1128. // plane since shaders last wrote the twin. In the title
  1129. // nothing writes that plane but the twin's pass (its 192 draws against
  1130. // it only test, run 29), so the twin lacks nothing. Counted.
  1131. if colour && twin.plane.is_some() {
  1132. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1133. }
  1134. let Some(through) = &twin.through else {
  1135. // SAFETY: an open list and two live textures.
  1136. unsafe { list.CopyResource(to, from) };
  1137. return;
  1138. };
  1139. // A stencil plane and its twin: each mip and slice of the plane goes
  1140. // into the buffer, laid out as the host lays the plane out for copies,
  1141. // and from the buffer into the other texture, whole subresources both
  1142. // times. In the depth texture the stencil plane's subresources follow
  1143. // the depth plane's; the twin has the one plane.
  1144. let Some(host) = host() else { return };
  1145. // SAFETY: a live texture.
  1146. let of = unsafe { depth.GetDesc() };
  1147. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1148. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1149. // SAFETY: a plain query writing `planes` footprints.
  1150. unsafe {
  1151. host.device.GetCopyableFootprints(
  1152. &of,
  1153. planes,
  1154. planes,
  1155. 0,
  1156. Some(rows.as_mut_ptr()),
  1157. None,
  1158. None,
  1159. None,
  1160. );
  1161. }
  1162. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1163. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1164. // SAFETY: a borrowed pointer the location never releases.
  1165. pResource: unsafe { std::mem::transmute_copy(texture) },
  1166. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1167. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1168. SubresourceIndex: index,
  1169. },
  1170. };
  1171. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1172. // SAFETY: as above.
  1173. pResource: unsafe { std::mem::transmute_copy(through) },
  1174. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1175. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1176. PlacedFootprint: *row,
  1177. },
  1178. };
  1179. let (common, source, dest) = (
  1180. D3D12_RESOURCE_STATE_COMMON,
  1181. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1182. D3D12_RESOURCE_STATE_COPY_DEST,
  1183. );
  1184. // SAFETY: an open list and live resources; the buffer was made as big
  1185. // as these footprints, and rests in the common state between copies.
  1186. unsafe {
  1187. list.ResourceBarrier(&[transition(through, common, dest)]);
  1188. for (i, row) in rows.iter().enumerate() {
  1189. let index = first_from + i as u32;
  1190. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1191. }
  1192. list.ResourceBarrier(&[transition(through, dest, source)]);
  1193. for (i, row) in rows.iter().enumerate() {
  1194. let index = first_to + i as u32;
  1195. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1196. }
  1197. list.ResourceBarrier(&[transition(through, source, common)]);
  1198. }
  1199. }
  1200. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1201. /// builds).
  1202. pub(crate) fn dred_on() -> bool {
  1203. static ON: OnceLock<bool> = OnceLock::new();
  1204. *ON.get_or_init(|| {
  1205. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some()
  1206. })
  1207. }
  1208. /// Indirect mesh dispatches since the last frame line: the largest group
  1209. /// count a record asked for, and the groups asked in all (from the lists'
  1210. /// budget buffers, a run late).
  1211. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1212. /// Whether a list's indirect-work budget lives in the card's own memory
  1213. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1214. /// before). The clamp charges it with atomics, at least two in a row for
  1215. /// every clamp; in mapped memory on a card of its own each of them
  1216. /// crosses the bus.
  1217. fn card_budget() -> bool {
  1218. static ON: OnceLock<bool> = OnceLock::new();
  1219. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1220. }
  1221. /// Whether each list of a submission runs and is timed on its own, slow
  1222. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1223. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1224. #[cfg(feature = "diagnostics")]
  1225. fn timing() -> bool {
  1226. static ON: OnceLock<bool> = OnceLock::new();
  1227. *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some())
  1228. }
  1229. /// Names a host object for the device-removed report, which names the
  1230. /// allocations a page fault hit (only with device-removed data on), or for
  1231. /// the frame recorder (`VICTORY_RECORD`).
  1232. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1233. #[cfg(feature = "diagnostics")]
  1234. if crate::replay::record::on() {
  1235. let text = text();
  1236. crate::replay::record::name(object, &text);
  1237. if dred_on()
  1238. && let Ok(object) = object.cast::<ID3D12Object>()
  1239. {
  1240. // SAFETY: a plain call on a live object.
  1241. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1242. }
  1243. return;
  1244. }
  1245. if dred_on()
  1246. && let Ok(object) = object.cast::<ID3D12Object>()
  1247. {
  1248. // SAFETY: a plain call on a live object.
  1249. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1250. }
  1251. }
  1252. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1253. /// [`LISTS`]`[3]` until it is first reset.
  1254. struct Counted {
  1255. /// Not reset since it was made.
  1256. fresh: std::sync::atomic::AtomicBool,
  1257. }
  1258. impl Counted {
  1259. fn new() -> Counted {
  1260. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1261. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1262. Counted {
  1263. fresh: std::sync::atomic::AtomicBool::new(true),
  1264. }
  1265. }
  1266. /// The list is reset: it is in use.
  1267. fn used(&self) {
  1268. if self.fresh.swap(false, Ordering::Relaxed) {
  1269. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1270. }
  1271. }
  1272. }
  1273. impl Drop for Counted {
  1274. fn drop(&mut self) {
  1275. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1276. self.used();
  1277. }
  1278. }
  1279. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1280. /// mapping and its host GPU address.
  1281. struct Chunk {
  1282. _buffer: ID3D12Resource,
  1283. data: usize,
  1284. gpu: u64,
  1285. }
  1286. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1287. // written only by the list that holds the chunk.
  1288. unsafe impl Send for Chunk {}
  1289. /// Upload chunks handed out front to back: the chunks (each with its
  1290. /// bytes), the one in use and the bytes used in it.
  1291. #[derive(Default)]
  1292. struct Scratch {
  1293. chunks: Vec<(Chunk, u64)>,
  1294. current: usize,
  1295. used: u64,
  1296. }
  1297. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1298. unsafe impl Send for Scratch {}
  1299. impl Drop for Scratch {
  1300. fn drop(&mut self) {
  1301. give_chunks(std::mem::take(&mut self.chunks));
  1302. }
  1303. }
  1304. const SCRATCH_CHUNK: u64 = 4 << 20;
  1305. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1306. /// lists put a few constants or a rectangle's corners there, and every
  1307. /// list that did took 4 MiB of the PC's memory for it.
  1308. const SCRATCH_FIRST: u64 = 256 << 10;
  1309. /// The most bytes of chunks kept while no list holds them.
  1310. const SPARE_MOST: u64 = 128 << 20;
  1311. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1312. /// first needs one, a small one first, and gives all of them back when it
  1313. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1314. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1315. /// host lists of held submissions, which live for one submission, each
  1316. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1317. /// freed per frame of gameplay (run 60).
  1318. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1319. fn scratch_pool() -> bool {
  1320. static ON: OnceLock<bool> = OnceLock::new();
  1321. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1322. }
  1323. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1324. /// for one of the same size.
  1325. struct Spare<T> {
  1326. kept: Vec<(T, u64)>,
  1327. bytes: u64,
  1328. }
  1329. impl<T> Spare<T> {
  1330. const fn new() -> Self {
  1331. Spare { kept: Vec::new(), bytes: 0 }
  1332. }
  1333. /// A kept thing of `size` bytes, the one given last.
  1334. fn take(&mut self, size: u64) -> Option<T> {
  1335. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1336. self.bytes -= size;
  1337. Some(self.kept.remove(at).0)
  1338. }
  1339. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1340. /// `most`: then it comes back.
  1341. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1342. if self.bytes + size > most {
  1343. return Some(thing);
  1344. }
  1345. self.bytes += size;
  1346. self.kept.push((thing, size));
  1347. None
  1348. }
  1349. }
  1350. /// Scratch chunks no list holds.
  1351. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1352. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1353. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1354. if scratch_pool()
  1355. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1356. {
  1357. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1358. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1359. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1360. return Some(chunk);
  1361. }
  1362. let (buffer, data) = host.upload_buffer(size)?;
  1363. name(&buffer, || "list scratch".into());
  1364. // SAFETY: a live buffer.
  1365. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  1366. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1367. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1368. Some(Chunk {
  1369. _buffer: buffer,
  1370. data: data as usize,
  1371. gpu,
  1372. })
  1373. }
  1374. /// A list is done with `chunks` (it was reset after its submissions ran,
  1375. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1376. /// without the pool.
  1377. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1378. if chunks.is_empty() {
  1379. return;
  1380. }
  1381. let mut freed = Vec::new();
  1382. {
  1383. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1384. for (chunk, size) in chunks {
  1385. let back = if scratch_pool() {
  1386. spare.give(chunk, size, SPARE_MOST)
  1387. } else {
  1388. Some(chunk)
  1389. };
  1390. match back {
  1391. None => {
  1392. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1393. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1394. }
  1395. Some(chunk) => {
  1396. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1397. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1398. freed.push(chunk);
  1399. }
  1400. }
  1401. }
  1402. }
  1403. // Freed outside the lock.
  1404. drop(freed);
  1405. }
  1406. /// What the host keeps for copies in the card's own memory
  1407. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1408. struct CardWork {
  1409. /// Before a submission's lists: what changed on the copies' CPU side
  1410. /// goes to their card side. Those not in use: a plan takes one and
  1411. /// gives it back when its submission has run (`Host::card_done`), so
  1412. /// that submissions sent ahead ([`late`]) each have their own.
  1413. sync: Vec<Prelude>,
  1414. /// After them, in the same submission: the compare of the declared
  1415. /// ranges with their bytes from before. As `sync`.
  1416. check: Vec<Prelude>,
  1417. /// After it ran: the pieces that differ come down.
  1418. fetch: Prelude,
  1419. root: ID3D12RootSignature,
  1420. pso: ID3D12PipelineState,
  1421. /// One dword per piece compared, odd where the piece differs: PC
  1422. /// memory, mapped (buffer, mapping, bytes).
  1423. differs: (ID3D12Resource, usize, u64),
  1424. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1425. fetched: Option<(ID3D12Resource, usize, u64)>,
  1426. /// The dwords of `differs` taken by plans whose results were not read
  1427. /// yet.
  1428. taken: u32,
  1429. /// Plans made and not done with (`Host::card_done`).
  1430. out: u32,
  1431. }
  1432. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1433. // under the submission lock.
  1434. unsafe impl Send for CardWork {}
  1435. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1436. /// The compare of a declared range of a copy in the card's memory with
  1437. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1438. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1439. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1440. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1441. /// byte just outside the range costs a fetch that finds nothing.
  1442. ///
  1443. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1444. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1445. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1446. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1447. /// those steps.
  1448. pub(crate) const CARD_COMPARE: &str = r#"
  1449. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1450. cbuffer Span : register(b0) {
  1451. uint first; // the first piece
  1452. uint skew; // where the copy starts in its piece 0
  1453. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1454. uint pieces;
  1455. uint out_at; // the first piece's dword in `differs`, in bytes
  1456. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1457. };
  1458. ByteAddressBuffer now : register(t0);
  1459. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1460. // last sent up (or hashed whole, the first time).
  1461. RWByteAddressBuffer hashes : register(u0);
  1462. RWByteAddressBuffer differs : register(u1);
  1463. groupshared uint4 parts[64];
  1464. [RootSignature(RS)]
  1465. [numthreads(64, 1, 1)]
  1466. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1467. uint piece = first + id.x;
  1468. uint lo = piece * 65536u;
  1469. lo = lo > skew ? lo - skew : 0u;
  1470. uint hi = min((piece + 1u) * 65536u - skew, size);
  1471. lo = lo & ~15u;
  1472. hi = (hi + 15u) & ~15u;
  1473. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1474. [loop]
  1475. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1476. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1477. h = h.yzwx ^ (h >> 15);
  1478. }
  1479. parts[thread] = h;
  1480. GroupMemoryBarrierWithGroupSync();
  1481. if (thread != 0u) return;
  1482. h = parts[0];
  1483. [loop]
  1484. for (uint i = 1u; i < 64u; ++i) {
  1485. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1486. h = h.yzwx ^ (h >> 15);
  1487. }
  1488. if (compare != 0u) {
  1489. // The flag, and above it 31 bits of the hash (`torn`).
  1490. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1491. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1492. // With the copy-back on its own thread: the next compare of the
  1493. // piece finds what is written from here on.
  1494. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1495. } else {
  1496. hashes.Store4(piece * 16u, h);
  1497. }
  1498. }
  1499. "#;
  1500. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1501. #[cfg(test)]
  1502. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1503. torn::hash(bytes)
  1504. }
  1505. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1506. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1507. /// parts a dispatch can hold.
  1508. ///
  1509. /// # Safety
  1510. /// The list is open with the compare's root signature, pipeline and buffers
  1511. /// set, and the pieces lie in the buffer.
  1512. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1513. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1514. let mut done = 0;
  1515. while done < span.pieces {
  1516. let n = (span.pieces - done).min(MOST);
  1517. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1518. // SAFETY: the caller's.
  1519. unsafe {
  1520. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1521. list.Dispatch(n, 1, 1);
  1522. }
  1523. done += n;
  1524. }
  1525. }
  1526. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1527. /// the card's memory are hashed in runs of pieces that touch, each piece
  1528. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1529. /// per range sent up.
  1530. ///
  1531. /// These passes are ours, they run on the card before every submission's
  1532. /// lists: a pass takes the time of one piece however few its pieces are.
  1533. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1534. /// a piece hashed when it need not be, or not hashed when it should, costs
  1535. /// a fetch that finds nothing and loses no shader write.
  1536. fn rehash_runs() -> bool {
  1537. static ON: OnceLock<bool> = OnceLock::new();
  1538. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1539. }
  1540. /// Since the last frame-rate line, of our own passes over copies in the
  1541. /// card's memory: hash passes after ranges were sent up, the pieces they
  1542. /// hashed, and compare passes after the lists.
  1543. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1544. /// Whether what shaders wrote to copies in the card's memory is merged
  1545. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1546. /// default). The pieces the card's compare found differing come down in
  1547. /// one fetch and were then merged one after the other on the thread that
  1548. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1549. /// with the copy's CPU side byte by byte and put into title memory through
  1550. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1551. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1552. /// landings do not come here: `crate::land` has threads of its own.)
  1553. fn wide_merge() -> bool {
  1554. static ON: OnceLock<bool> = OnceLock::new();
  1555. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1556. }
  1557. /// One declared range of a copy in the card's memory, in a submission.
  1558. struct CardRange {
  1559. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1560. /// As declared (title addresses), for the statistics.
  1561. declared: (usize, usize),
  1562. span: crate::shadow::CardSpan,
  1563. /// Its first piece's dword in the compare's results.
  1564. at: u32,
  1565. /// Whether the card compares it; else every piece is fetched.
  1566. compared: bool,
  1567. /// Looked at by `crate::picked`, and not declared: what is found changed
  1568. /// there was written through a view nobody declared. Not landed.
  1569. picked: bool,
  1570. }
  1571. impl CardPlan {
  1572. /// `crate::picked` is told where what it looked at changed, by the
  1573. /// compare's results.
  1574. fn picked_found(&self, differs: &[u32]) {
  1575. for r in self.ranges.iter().filter(|r| r.picked) {
  1576. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1577. if let Some(p) = changed {
  1578. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. /// What a submission does for copies in the card's memory.
  1584. struct CardPlan {
  1585. ranges: Vec<CardRange>,
  1586. /// The compare, run after the submission's lists.
  1587. check: Option<ID3D12CommandList>,
  1588. /// The copies whose card side was brought up to date, alive until the
  1589. /// submission has run.
  1590. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1591. /// The lists of ours the plan recorded (whether the compare, the
  1592. /// list), given back by `Host::card_done`.
  1593. lists: Vec<(bool, Prelude)>,
  1594. /// With [`relay`]: the number of the send to copies in the card's memory
  1595. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1596. sent_as: u64,
  1597. /// With [`upcheck`]: the look at what it sent up.
  1598. looks: Option<upcheck::Looks>,
  1599. }
  1600. /// One piece of submission-time work, in recorded order.
  1601. enum Step {
  1602. /// A copy into title memory (destination, source, bytes): the title's
  1603. /// buffer copies, which later refreshes must see.
  1604. Copy(usize, usize, usize),
  1605. /// A copy of title memory into the list's own upload memory, and how
  1606. /// the card could bring the bytes instead.
  1607. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  1608. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1609. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1610. /// intervenes.
  1611. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1612. /// Work that may write title memory.
  1613. Run(Box<dyn Fn() + Send>),
  1614. /// Work that writes host memory only, and the title memory it reads
  1615. /// (from, to; empty for none).
  1616. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1617. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1618. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1619. /// Brings a texture's staging buffer up to date: once per submission,
  1620. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1621. Texture(std::sync::Arc<crate::texture::Staging>),
  1622. }
  1623. /// What a list does on the CPU when it is submitted: copies between host
  1624. /// memory regions (title buffers, upload buffers and buffer copies), and
  1625. /// the upload buffers its GPU commands read, kept until the list is reset.
  1626. #[derive(Default)]
  1627. struct Deferred {
  1628. /// Destination, source, bytes.
  1629. copies: Vec<Step>,
  1630. uploads: Vec<ID3D12Resource>,
  1631. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1632. upload_bytes: u64,
  1633. /// Host objects the list's commands name (pipelines, root signatures,
  1634. /// descriptor heaps): the title may release its objects before it
  1635. /// submits the list.
  1636. kept: Vec<windows::core::IUnknown>,
  1637. /// Buffer ranges refreshed since the last title copy (host copy,
  1638. /// address, bytes): refreshing them again would find the same bytes.
  1639. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1640. /// Textures whose contents the list brings up to date.
  1641. textures: std::collections::HashSet<usize>,
  1642. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1643. /// bytes.
  1644. writes: Vec<(usize, crate::queue::Written, usize)>,
  1645. /// Textures read back (texture to buffer copies), done once the list
  1646. /// has run: the host buffer the list copies the texels into, the title
  1647. /// memory they go to, the bytes of a row, the rows, the title's row
  1648. /// pitch.
  1649. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1650. /// Whether the indirect-work budget is zeroed for this recording (a
  1651. /// step on the CPU, or in the list for the card's copy).
  1652. budget_zeroed: bool,
  1653. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1654. /// interface pointer) that a clamp in this recording left readable as
  1655. /// indirect arguments; 0 if none. It stays readable until the next
  1656. /// clamp into it ([`HostList::indirect_state`]).
  1657. indirect_readable: usize,
  1658. }
  1659. impl Deferred {
  1660. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1661. /// reset.
  1662. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1663. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1664. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1665. self.upload_bytes += size;
  1666. self.uploads.push(buffer);
  1667. }
  1668. }
  1669. impl Drop for Deferred {
  1670. fn drop(&mut self) {
  1671. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1672. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1673. }
  1674. }
  1675. /// Whether a queue's submissions go to the card without a wait for each
  1676. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1677. /// waits for every list on its own).
  1678. ///
  1679. /// Every submission was prepared, sent, waited for and copied back before
  1680. /// the next one was looked at, so the card stood idle while we prepared
  1681. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1682. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1683. /// other, on the one thread that submits.
  1684. ///
  1685. /// With the switch a queue's submission is sent and joins a line of
  1686. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1687. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1688. /// for the card, what their shaders wrote copied back once per byte, then
  1689. /// their bottom-of-pipe writes and the fence signals behind them, in
  1690. /// order) at the next point where the title, or our own preparing, can
  1691. /// observe what they do. Those points, exactly:
  1692. ///
  1693. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1694. /// read-back or map of a texture, a clear or upload run at once;
  1695. /// 2. the next submission reads title memory that a flight's shaders may
  1696. /// write: a title buffer copy, a fill of upload memory, a texture's
  1697. /// memory, any step that runs code of ours on title memory
  1698. /// ([`late_blocked`]);
  1699. /// 3. the next submission refreshes a range of a host copy that a flight's
  1700. /// shaders may write, and the title wrote a page of it since it was last
  1701. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1702. /// alone until the flight's writes are back, as it always did within a
  1703. /// submission;
  1704. /// 4. a queue stands at a wait for a memory value that no flight's
  1705. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1706. /// write ([`late_met`]);
  1707. /// 5. the title blocks on a fence without an event;
  1708. /// 6. the card has run every flight (a thread of ours waits for that:
  1709. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1710. ///
  1711. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1712. /// when the card has really run the work, later than before and never
  1713. /// earlier; a fence signalled on a queue while flights are in the air is
  1714. /// set behind them. A wait for a memory value that a flight's
  1715. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1716. /// the card behind that flight, which is the order the wait asks for.
  1717. ///
  1718. /// What it assumes beyond today: memory the title rewrites between two of
  1719. /// its submissions, without waiting for the first, may be seen by the
  1720. /// first's shaders (as on the console, where the card reads title memory
  1721. /// when it runs, not when the list is submitted).
  1722. pub(crate) fn late() -> bool {
  1723. late_stage() > 0
  1724. }
  1725. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1726. fn late_stage() -> u8 {
  1727. static STAGE: OnceLock<u8> = OnceLock::new();
  1728. *STAGE.get_or_init(|| {
  1729. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1730. return 0;
  1731. }
  1732. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1733. Ok("1") => 1,
  1734. Ok("2") => 2,
  1735. Ok("3") => 3,
  1736. // The relay alone: on top of stage 3.
  1737. Err(_) if crate::shadow::relay() => 3,
  1738. _ => 0,
  1739. }
  1740. })
  1741. }
  1742. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1743. /// longer a point. Where the title wrote a page that lies in a range a
  1744. /// flight's shaders may write, the bytes the title changed are found (the
  1745. /// page as it is now against what the copy held when the flight was
  1746. /// prepared) and put into the copy, and only those: what the flight's
  1747. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1748. /// flights are settled for it only where that cannot be done: memory that
  1749. /// is not write-watched, or a copy in the card's memory with more changed
  1750. /// runs than a submission should send up one by one.
  1751. ///
  1752. /// In run 92 (stage 1) this point settled the flights five times a frame
  1753. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1754. /// frame of waiting were left of 200.
  1755. ///
  1756. /// What differs from settling first: a byte both the title and a flight's
  1757. /// shader wrote is the title's if the shader wrote it first, the shader's
  1758. /// if it wrote it afterwards; settled first it was always the shader's.
  1759. /// The title writing a byte a shader of its own is writing is a race on
  1760. /// the console too.
  1761. fn late_exact() -> bool {
  1762. late_stage() > 1
  1763. }
  1764. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1765. /// no longer a point where flights are settled). The copy to the back
  1766. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1767. /// its own for each present in the air) and the swap chain is told to
  1768. /// present behind it; the queue's call returns, and the card finishes the
  1769. /// frame while the title records the next one. What the title is told
  1770. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1771. /// has run it, by the settling thread.
  1772. ///
  1773. /// What is left out with it: the look whether the presented frame is black
  1774. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1775. /// or listed is presented the old way. Once every second and a half a
  1776. /// submission settles the flights all the same, for the sweep that lets
  1777. /// idle host objects go (it needs nothing in the air).
  1778. pub(crate) fn late_free_present() -> bool {
  1779. late_stage() > 2
  1780. }
  1781. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1782. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1783. /// and is off with it, in the timing run and with kept snapshots).
  1784. ///
  1785. /// With [`late`] alone every settle does three things on the thread that
  1786. /// holds the submission lock: it waits for everything in the air, copies
  1787. /// back with the card standing, and only then goes on preparing. The frame
  1788. /// stays a relay: the card works about 242 ms of it and one thread
  1789. /// prepares, waits and copies back for about 220.
  1790. ///
  1791. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1792. /// soon as the card has run them, in the order they were sent and without
  1793. /// the submission lock: it fetches and merges what their shaders wrote to
  1794. /// copies in the card's memory, compares and merges the other copies,
  1795. /// frees the flights' ranges, and then does their read-backs, their
  1796. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1797. /// order. The submitting thread meanwhile prepares and sends the next
  1798. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  1799. /// that thread has landed everything in the air, at the same points as
  1800. /// before (the list in [`late`]), so whoever can observe title memory, a
  1801. /// fence or a present still does so only after the flights before it are
  1802. /// merged.
  1803. ///
  1804. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  1805. /// flight; a merge that never stores into memory the card may be writing;
  1806. /// sends to card copies numbered) and here: flights land in the order of
  1807. /// [`LINE`] by one thread, so a later flight's results never reach title
  1808. /// memory before an earlier flight's; the compare on the card stores the
  1809. /// hash it made, so each flight's compare flags exactly what changed since
  1810. /// the compare before it, however late the pieces are fetched; the fetch
  1811. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  1812. /// title bytes the card had received when it ran.
  1813. pub(crate) fn relay() -> bool {
  1814. static ON: OnceLock<bool> = OnceLock::new();
  1815. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  1816. }
  1817. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  1818. /// title memory a flight's shaders may write (a title buffer copy, a fill
  1819. /// of upload memory, a texture) waits only until the flights that declared
  1820. /// that memory have landed, not for everything in the air; and at
  1821. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  1822. /// both wait for everything.
  1823. fn relay_exact() -> bool {
  1824. static ON: OnceLock<bool> = OnceLock::new();
  1825. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  1826. // since the walls of the first room were found drawn in every run with
  1827. // this set and in fewer than half without it).
  1828. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  1829. }
  1830. /// Whether the pieces the relay fetches from the card's memory come over the
  1831. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  1832. /// draws.
  1833. ///
  1834. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  1835. /// and with the relay that is most of a frame: the thread that lands flights
  1836. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  1837. /// a few milliseconds of copying, and everything that waits for a landing
  1838. /// (the title's fences, reads of memory flights may write) waited with it.
  1839. ///
  1840. /// What changes: the fetch runs when its flights are done and beside later
  1841. /// submissions, so of the sends of title bytes it is only known to have run
  1842. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  1843. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  1844. /// the title's, newer than what the flights wrote. A later flight's bytes
  1845. /// may be in what is fetched, as before.
  1846. fn relay_copy() -> bool {
  1847. static ON: OnceLock<bool> = OnceLock::new();
  1848. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  1849. }
  1850. /// Told when something joins [`LINE`], for the thread that lands flights
  1851. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  1852. /// what queues hold.
  1853. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  1854. /// Told when flights have landed ([`relay`]): who waits for that looks
  1855. /// again.
  1856. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  1857. /// With [`relay`], the order of what we put on the queue: the number of
  1858. /// sends of changed ranges to copies in the card's memory so far
  1859. /// (`Host::card_before`). Held from the taking of the ranges until their
  1860. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  1861. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  1862. /// later one.
  1863. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  1864. /// Since the last frame-rate line, of the thread that lands flights
  1865. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  1866. /// card with nothing to land, microseconds it waited for fetches of card
  1867. /// copies' pieces, microseconds of landing in all.
  1868. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  1869. /// Of the line's things in order (a flight: the value signalled on the
  1870. /// host's fence behind it; a write or a signal behind a flight: `None`):
  1871. /// how many, from the front, can be landed when the card has reached
  1872. /// `completed`: everything ahead of the first flight it has not run. A
  1873. /// later flight never lands before an earlier one, and what follows a
  1874. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  1875. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  1876. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  1877. }
  1878. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  1879. /// holds, for every piece of every range of the plan, the copy, the
  1880. /// piece's number in the copy and whether the compare flagged it there (or
  1881. /// did not run). The pieces to fetch, under whichever range, in order: all
  1882. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  1883. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  1884. /// the hash, so the second of them may find it stored already and not
  1885. /// flag it.
  1886. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  1887. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  1888. pieces.sort_unstable();
  1889. pieces.dedup();
  1890. pieces
  1891. }
  1892. #[cfg(test)]
  1893. mod relay_tests {
  1894. use super::{flagged_pieces, landable};
  1895. /// Two flights and what follows each: nothing of the second lands
  1896. /// before the card has run it, and nothing behind a flight lands
  1897. /// before the flight.
  1898. #[test]
  1899. fn flights_land_in_the_order_they_were_sent() {
  1900. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  1901. let line = [Some(5), None, None, Some(6), None];
  1902. assert_eq!(landable(&line, 4), 0);
  1903. assert_eq!(landable(&line, 5), 3);
  1904. assert_eq!(landable(&line, 6), 5);
  1905. assert_eq!(landable(&line, u64::MAX), 5);
  1906. // Signals with no flight ahead land at once; behind one they wait.
  1907. assert_eq!(landable(&[None, None], 0), 2);
  1908. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  1909. assert_eq!(landable(&[], 3), 0);
  1910. // After the first three landed, the rest when its turn comes.
  1911. assert_eq!(landable(&line[3..], 5), 0);
  1912. assert_eq!(landable(&line[3..], 6), 2);
  1913. }
  1914. /// A piece flagged under one range of a plan is fetched under every
  1915. /// range that holds a part of it; pieces of other copies are not.
  1916. #[test]
  1917. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  1918. let (a, b) = (0x1000usize, 0x2000usize);
  1919. // Copy a: piece 3 under two ranges, flagged under the first only;
  1920. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  1921. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  1922. let fetch = flagged_pieces(&flags);
  1923. assert!(fetch.contains(&(a, 3)));
  1924. assert!(!fetch.contains(&(a, 4)));
  1925. assert!(!fetch.contains(&(b, 3)));
  1926. assert!(fetch.contains(&(b, 9)));
  1927. assert_eq!(fetch.len(), 2);
  1928. }
  1929. }
  1930. /// The most host lists in the air before the flights are settled
  1931. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  1932. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  1933. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  1934. /// 32 settled the flights three times a
  1935. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  1936. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  1937. /// descriptor slots, upload
  1938. /// memory and scratch chunks are held until then, and a frame's lists held
  1939. /// all at once ran the slots out before (run 45).
  1940. fn late_most() -> usize {
  1941. static MOST: OnceLock<usize> = OnceLock::new();
  1942. *MOST.get_or_init(|| {
  1943. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  1944. })
  1945. }
  1946. /// Whether a submission with bottom-of-pipe writes may fly
  1947. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  1948. /// the title is told at once, as before; for telling a title that polls
  1949. /// such a value from one that does not).
  1950. fn late_writes() -> bool {
  1951. static ON: OnceLock<bool> = OnceLock::new();
  1952. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  1953. }
  1954. /// Per host copy, the ranges a submission's shaders may write, as declared
  1955. /// (address, end).
  1956. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  1957. /// What [`Host::submit`] hands back for a submission it sent and did not
  1958. /// wait for.
  1959. struct Sent {
  1960. /// Its number among the submissions started.
  1961. number: u64,
  1962. card: Option<CardPlan>,
  1963. back: Vec<Declared>,
  1964. /// What was taken off it to be done on the card.
  1965. own: Option<card_steps::Taken>,
  1966. /// Its bottom-of-pipe writes.
  1967. writes: Vec<(usize, crate::queue::Written, usize)>,
  1968. }
  1969. /// A submission on the card that has not been waited for ([`late`]): its
  1970. /// host lists, taken from the title's (which it may reset meanwhile), and
  1971. /// what is to be done once it has run.
  1972. struct Flight {
  1973. number: u64,
  1974. /// The value signalled on the host's fence behind it.
  1975. fence: u64,
  1976. lists: Vec<crate::list::Detached>,
  1977. order: Vec<usize>,
  1978. card: Option<CardPlan>,
  1979. back: Vec<Declared>,
  1980. /// The list of ours that ran ahead of them ([`card_steps`]).
  1981. own: Option<card_steps::Taken>,
  1982. }
  1983. /// One thing in the line of what waits for the card, in order.
  1984. enum Late {
  1985. Run(Flight),
  1986. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  1987. Write(usize, crate::queue::Written, usize),
  1988. /// A fence (its address) signalled behind the flights before it.
  1989. Signal(usize, u64),
  1990. }
  1991. struct Line {
  1992. line: Vec<Late>,
  1993. /// The title memory the flights' shaders may write (address, end), in
  1994. /// order and joined.
  1995. written: Vec<(usize, usize)>,
  1996. /// Host lists in the flights.
  1997. lists: usize,
  1998. /// The value signalled on the host's fence behind the last flight.
  1999. target: u64,
  2000. /// A settle has taken the line and is not done: a signal still goes
  2001. /// behind it.
  2002. settling: bool,
  2003. /// Something was settled away from a queue's own calls: the helper
  2004. /// thread looks at what queues hold.
  2005. poke: bool,
  2006. /// Host lists of settled flights, reset and given back outside the
  2007. /// submission lock ([`land`]: a settle may run under a caller's own
  2008. /// locks).
  2009. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2010. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2011. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2012. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2013. /// With [`card_steps`]: what the flights being landed write.
  2014. landing: Vec<card_steps::Writer>,
  2015. }
  2016. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2017. // into; touched under the lock.
  2018. unsafe impl Send for Line {}
  2019. static LINE: Mutex<Line> = Mutex::new(Line {
  2020. line: Vec::new(),
  2021. written: Vec::new(),
  2022. lists: 0,
  2023. target: 0,
  2024. settling: false,
  2025. poke: false,
  2026. landed: Vec::new(),
  2027. in_hand: Vec::new(),
  2028. landing: Vec::new(),
  2029. });
  2030. /// Told when a flight joins [`LINE`] or it is poked.
  2031. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2032. fn line() -> std::sync::MutexGuard<'static, Line> {
  2033. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2034. }
  2035. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2036. const WHY_SYNC: usize = 2;
  2037. const WHY_CARD_DONE: usize = 3;
  2038. const WHY_VALUE: usize = 4;
  2039. const WHY_STALE: usize = 5;
  2040. const WHY_READ: usize = 6;
  2041. const WHY_RUN: usize = 7;
  2042. const WHY_MOST: usize = 8;
  2043. const WHY_WRITES: usize = 9;
  2044. const WHY_FENCE: usize = 10;
  2045. /// Since the last frame-rate line: submissions sent without a wait;
  2046. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2047. /// microseconds settles waited for the card; value waits met by a flight's
  2048. /// bottom-of-pipe write; fence signals set behind flights.
  2049. /// Then: the settles for title memory read, by what read it (a buffer
  2050. /// copy, a fill of upload memory, a texture).
  2051. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2052. /// Since the last frame-rate line: the microseconds settles waited for the
  2053. /// card, by why they settled (the `WHY_` places).
  2054. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2055. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2056. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2057. if from >= to {
  2058. return false;
  2059. }
  2060. let at = ranges.partition_point(|r| r.1 <= from);
  2061. ranges.get(at).is_some_and(|r| r.0 < to)
  2062. }
  2063. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2064. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2065. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2066. ranges.sort_unstable();
  2067. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2068. for &(from, to) in ranges.iter() {
  2069. match out.last_mut() {
  2070. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2071. _ => out.push((from, to)),
  2072. }
  2073. }
  2074. *ranges = out;
  2075. }
  2076. /// Whether anything is in the air.
  2077. fn flying() -> bool {
  2078. if !late() {
  2079. return false;
  2080. }
  2081. let line = line();
  2082. // (With the relay: also while flights are being landed.)
  2083. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2084. }
  2085. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2086. /// before they are settled, if so. Preparing reads title memory on the
  2087. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2088. /// runs steps of ours that may read or write it anywhere; what the
  2089. /// flights' shaders write is not there yet.
  2090. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2091. let (written, copies) = {
  2092. let line = line();
  2093. if line.written.is_empty() {
  2094. return None;
  2095. }
  2096. (line.written.clone(), card_steps::copies(&line))
  2097. };
  2098. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2099. }
  2100. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2101. /// flights when the title itself wrote the memory since they were given it
  2102. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2103. ///
  2104. /// The title's 174 MB heap is declared written as a whole (a root view has
  2105. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2106. /// bytes a frame, at a new place each time, waited for every flight's
  2107. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2108. /// named). The title writes those bytes just before the draw that reads
  2109. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2110. ///
  2111. /// Or no shader's write went into that page in the last 600 frames
  2112. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2113. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2114. /// before the page was taken.
  2115. ///
  2116. /// What can go wrong: a constant a flight's shader really writes, in a
  2117. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2118. /// for the first time, is read as it was before that flight.
  2119. fn fill_is_titles(src: usize, len: usize) -> bool {
  2120. const SMALL: usize = 64 << 10;
  2121. static ON: OnceLock<bool> = OnceLock::new();
  2122. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2123. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2124. }
  2125. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2126. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2127. /// in (start, bytes).
  2128. #[cfg(feature = "diagnostics")]
  2129. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2130. /// How often and how long, and the address the last one read.
  2131. #[cfg(feature = "diagnostics")]
  2132. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2133. /// What the wait that comes next is for, and why not on the card.
  2134. #[cfg(feature = "diagnostics")]
  2135. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2136. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2137. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2138. /// shaders.
  2139. #[cfg(feature = "diagnostics")]
  2140. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2141. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2142. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2143. /// raw address (1).
  2144. #[cfg(feature = "diagnostics")]
  2145. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2146. if len < 1 << 20 {
  2147. return;
  2148. }
  2149. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2150. let e = all
  2151. .get_or_insert_with(Default::default)
  2152. .entry((address as usize, (address + len) as usize, pipeline))
  2153. .or_insert_with(|| {
  2154. let shaders = match pipeline {
  2155. 0 => "a view in a table".into(),
  2156. 1 => "a raw address".into(),
  2157. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2158. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2159. }),
  2160. };
  2161. (0, shaders)
  2162. });
  2163. e.0 += 1;
  2164. }
  2165. #[cfg(feature = "diagnostics")]
  2166. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2167. let i = written.partition_point(|r| r.1 <= at);
  2168. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2169. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2170. let why = blamed.1;
  2171. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2172. }
  2173. /// Why [`card_steps`] left the submission to the wait that comes next.
  2174. #[cfg(feature = "diagnostics")]
  2175. fn refused(why: &'static str) {
  2176. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2177. }
  2178. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2179. #[cfg(feature = "diagnostics")]
  2180. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2181. if let Some((shadow, from, _)) = stale.first() {
  2182. let (start, len) = shadow.span();
  2183. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2184. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2185. }
  2186. }
  2187. /// The wait for what [`blame`] last named, or a wait of another reason than
  2188. /// title memory read, took `us`.
  2189. #[cfg(feature = "diagnostics")]
  2190. fn blamed(why: usize, us: u64) {
  2191. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2192. let (key, at) = match (why, named) {
  2193. (WHY_READ | WHY_STALE, Some(named)) => named,
  2194. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2195. _ => {
  2196. let kind = match why {
  2197. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2198. WHY_VALUE => "a memory value",
  2199. WHY_STALE => "title memory changed under shader writes",
  2200. WHY_RUN => "a step of ours",
  2201. WHY_MOST => "lists in the air",
  2202. WHY_FENCE => "a blocking fence wait",
  2203. _ => "another reason",
  2204. };
  2205. ((kind, "", 0, 0, 0), 0)
  2206. }
  2207. };
  2208. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2209. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2210. *e = (e.0 + 1, e.1 + us, at);
  2211. }
  2212. /// For the frame-rate line: the five that waited longest.
  2213. #[cfg(feature = "diagnostics")]
  2214. fn log_blame(frames: f64) {
  2215. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2216. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2217. let mut all: Vec<_> = all.into_iter().collect();
  2218. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2219. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2220. // The passes that declare it written, the ones that do so most.
  2221. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2222. for ((a, b, _), (n, shaders)) in &wide {
  2223. if *a < at + len && at < *b {
  2224. *passes.entry(shaders).or_default() += n;
  2225. }
  2226. }
  2227. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2228. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2229. let passes: Vec<String> =
  2230. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2231. tracing::info!(
  2232. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2233. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2234. us as f64 / 1e3 / frames,
  2235. n as f64 / frames,
  2236. passes.join(", "),
  2237. match (why.is_empty(), kind) {
  2238. (true, _) => "",
  2239. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2240. _ => "; not done on the card: ",
  2241. },
  2242. );
  2243. }
  2244. }
  2245. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2246. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2247. touches(written, src, src + len) && !fill_is_titles(src, len)
  2248. }
  2249. /// Whether they stop a title buffer copy, and if so whether by its source.
  2250. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2251. let read = read_blocked(written, src, len);
  2252. (read || touches(written, dst, dst + len)).then_some(read)
  2253. }
  2254. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2255. /// may write (in order, joined); `count` whether the kind of read is
  2256. /// counted for the frame line.
  2257. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2258. if written.is_empty() {
  2259. return None;
  2260. }
  2261. for list in runs {
  2262. for step in &list.deferred().copies {
  2263. match step {
  2264. &Step::Copy(dst, src, len) => {
  2265. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2266. if count {
  2267. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2268. #[cfg(feature = "diagnostics")]
  2269. if _read {
  2270. blame("a buffer copy's source", written, src, len);
  2271. } else {
  2272. blame("a buffer copy's destination", written, dst, len);
  2273. }
  2274. }
  2275. return Some(WHY_READ);
  2276. }
  2277. }
  2278. &Step::Fill(_, src, len, _) => {
  2279. if read_blocked(written, src, len) {
  2280. if count {
  2281. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2282. #[cfg(feature = "diagnostics")]
  2283. blame("a fill of upload memory", written, src, len);
  2284. }
  2285. return Some(WHY_READ);
  2286. }
  2287. }
  2288. Step::Texture(staging) => {
  2289. let (at, len) = staging.memory();
  2290. if touches(written, at, at + len) {
  2291. if count {
  2292. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2293. #[cfg(feature = "diagnostics")]
  2294. blame("a texture", written, at, len);
  2295. }
  2296. return Some(WHY_READ);
  2297. }
  2298. }
  2299. Step::Run(_) => return Some(WHY_RUN),
  2300. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2301. }
  2302. }
  2303. }
  2304. None
  2305. }
  2306. /// With flights in the air, after the submission's write-watch asking:
  2307. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2308. /// may write and that the title wrote since it was last copied. The
  2309. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2310. /// the title's bytes there would reach the card a submission late.
  2311. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2312. use std::sync::Arc;
  2313. // Per copy, the span of what is refreshed (a flush brings that much
  2314. // up to date at most).
  2315. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2316. // Where each copy is in it, if shaders may be writing it (none begins to
  2317. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2318. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2319. for list in runs {
  2320. for step in &list.deferred().copies {
  2321. if let Step::Refresh(shadow, address, len) = step {
  2322. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2323. shadow.writes_pending().then(|| {
  2324. spans.push((shadow.clone(), *address, *address + *len));
  2325. spans.len() - 1
  2326. })
  2327. });
  2328. if let Some(i) = *place {
  2329. let s = &mut spans[i];
  2330. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2331. }
  2332. }
  2333. }
  2334. }
  2335. if late_exact() {
  2336. // The title's bytes are put in beside the flights' writes; a
  2337. // settle is still due where that could not be done. At most this
  2338. // many changed runs go up to copies in the card's memory, each a
  2339. // copy of its own there. With [`card_steps`] the pages of the
  2340. // title's ring of constants come here too, which were waited for
  2341. // before: hundreds of short runs each, at about 1.5 us a run.
  2342. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2343. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2344. return spans;
  2345. }
  2346. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2347. spans
  2348. }
  2349. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2350. /// air, if there are any, and is set when they are settled. Whether it
  2351. /// did; if not the caller sets the fence now.
  2352. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2353. if !late() {
  2354. return false;
  2355. }
  2356. let mut line = line();
  2357. if line.line.is_empty() && !line.settling {
  2358. return false;
  2359. }
  2360. line.line.push(Late::Signal(fence, value));
  2361. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2362. drop(line);
  2363. // A signal alone (behind a settle under way) has no flight to wake
  2364. // the helper thread for it.
  2365. LINE_MOVED.notify_one();
  2366. RELAY_MOVED.notify_one();
  2367. true
  2368. }
  2369. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2370. /// whether it is met once the flights in the air have run. A flight's
  2371. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2372. /// for the card: the part behind the wait goes to the card behind that
  2373. /// flight, which is the order the wait asks for. If the flights may write
  2374. /// the value in a way not known here (shaders, a timestamp, another
  2375. /// width), they are settled and memory is asked again.
  2376. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2377. let (address, bytes) = wait.place();
  2378. {
  2379. let line = line();
  2380. if line.line.is_empty() && line.in_hand.is_empty() {
  2381. return false;
  2382. }
  2383. let mut unsure = touches(&line.written, address, address + bytes);
  2384. // (With the relay: first the writes of flights being landed.)
  2385. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2386. Late::Write(at, what, n) => Some((at, what, n)),
  2387. _ => None,
  2388. }));
  2389. for (at, what, n) in writes {
  2390. if *at >= address + bytes || address >= *at + *n {
  2391. continue;
  2392. }
  2393. match what {
  2394. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2395. if wait.holds_for(*v) {
  2396. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2397. return true;
  2398. }
  2399. }
  2400. _ => unsure = true,
  2401. }
  2402. }
  2403. if !unsure {
  2404. return false;
  2405. }
  2406. }
  2407. settle_now(WHY_VALUE);
  2408. wait.met()
  2409. }
  2410. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2411. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2412. pub(crate) fn settle_now(why: usize) {
  2413. if !late() {
  2414. return;
  2415. }
  2416. let Some(host) = host() else {
  2417. return;
  2418. };
  2419. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2420. host.settle(&mut submitted, why);
  2421. }
  2422. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2423. pub(crate) fn settle_for_present() {
  2424. settle_now(WHY_SYNC);
  2425. }
  2426. pub(crate) fn settle_for_fence() {
  2427. settle_now(WHY_FENCE);
  2428. }
  2429. /// Resets the host lists of settled flights and keeps them for reuse, as
  2430. /// a queue does for the lists it ran (`crate::list::recycle`).
  2431. fn land() {
  2432. let landed = std::mem::take(&mut line().landed);
  2433. for (lists, order) in landed {
  2434. crate::list::recycle(lists, &order);
  2435. }
  2436. }
  2437. /// The thread that settles the flights once the card has run them all
  2438. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2439. /// at the next call that settles, and a title thread that polls such a
  2440. /// value while the submitting thread waits for that thread would never
  2441. /// see it.
  2442. fn late_helper() {
  2443. let Some(host) = host() else {
  2444. return;
  2445. };
  2446. // SAFETY: a plain event of our own.
  2447. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2448. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2449. return;
  2450. };
  2451. loop {
  2452. let target = {
  2453. let mut line = line();
  2454. loop {
  2455. if line.poke {
  2456. line.poke = false;
  2457. break None;
  2458. }
  2459. // (With the relay the flights are another thread's.)
  2460. if !relay() && !line.line.is_empty() && !line.settling {
  2461. break Some(line.target);
  2462. }
  2463. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2464. }
  2465. };
  2466. let Some(target) = target else {
  2467. land();
  2468. crate::queue::release_held(false);
  2469. continue;
  2470. };
  2471. // The card first, without the submission lock: the submitting
  2472. // thread prepares and sends meanwhile.
  2473. // SAFETY: our fence and event.
  2474. unsafe {
  2475. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2476. WaitForSingleObject(event, INFINITE);
  2477. }
  2478. }
  2479. {
  2480. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2481. // Something newer went up meanwhile: the card is waited for
  2482. // again, the submitting thread is not held up for it.
  2483. if line().target != target {
  2484. continue;
  2485. }
  2486. host.settle(&mut submitted, WHY_CARD_DONE);
  2487. }
  2488. land();
  2489. crate::queue::release_held(false);
  2490. }
  2491. }
  2492. /// Starts the threads of [`late`], once: the one that settles flights when
  2493. /// the card has run them and looks at what queues hold, and with [`relay`]
  2494. /// the one that lands flights.
  2495. fn late_threads() {
  2496. static HELPER: std::sync::Once = std::sync::Once::new();
  2497. HELPER.call_once(|| {
  2498. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2499. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2500. }
  2501. tracing::info!(
  2502. most = late_most(),
  2503. writes = late_writes(),
  2504. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2505. );
  2506. if relay() {
  2507. // Without it nothing would ever land.
  2508. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2509. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2510. }
  2511. tracing::info!(
  2512. exact = relay_exact(),
  2513. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2514. );
  2515. }
  2516. });
  2517. }
  2518. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2519. /// time flights have landed. Counted as a settle for `why`, and its time
  2520. /// as waiting for the card. The caller may hold the submission lock: the
  2521. /// thread that lands flights never takes it.
  2522. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2523. let mut line = line();
  2524. if done(&line) {
  2525. return;
  2526. }
  2527. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2528. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2529. let was_working = working(false);
  2530. let waiting = std::time::Instant::now();
  2531. while !done(&line) {
  2532. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2533. }
  2534. drop(line);
  2535. stood(waiting);
  2536. working(was_working);
  2537. let us = waiting.elapsed().as_micros() as u64;
  2538. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2539. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2540. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2541. #[cfg(feature = "diagnostics")]
  2542. blamed(why, us);
  2543. }
  2544. /// What the thread that lands flights fetches card copies' pieces with
  2545. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2546. /// behind the submission lock), and the memory the pieces come down to.
  2547. struct RelayFetch {
  2548. list: Prelude,
  2549. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2550. queue: Option<ID3D12CommandQueue>,
  2551. fence: ID3D12Fence,
  2552. event: HANDLE,
  2553. /// The last value signalled on `fence`.
  2554. sent: u64,
  2555. /// Buffer, mapping, bytes.
  2556. buffer: Option<(ID3D12Resource, usize, u64)>,
  2557. /// Pieces caught while a later flight was writing them.
  2558. suspects: torn::Suspects,
  2559. /// What earlier fetches brought of flights not landed yet.
  2560. had: crate::land::Had,
  2561. }
  2562. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2563. /// the first flights of the line it takes them, with what follows them,
  2564. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2565. /// the card, or for a flight. It takes neither the submission lock nor
  2566. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2567. /// lists and looking at what queues hold are left to [`late_helper`].
  2568. fn relay_worker() {
  2569. let Some(host) = host() else {
  2570. return;
  2571. };
  2572. // SAFETY: a plain event of our own.
  2573. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2574. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2575. };
  2576. let mut fetch: Option<RelayFetch> = None;
  2577. loop {
  2578. let next = {
  2579. let mut line = line();
  2580. loop {
  2581. if line.line.is_empty() {
  2582. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2583. continue;
  2584. }
  2585. let fences: Vec<Option<u64>> = line
  2586. .line
  2587. .iter()
  2588. .map(|l| match l {
  2589. Late::Run(flight) => Some(flight.fence),
  2590. _ => None,
  2591. })
  2592. .collect();
  2593. // SAFETY: a plain query.
  2594. let completed = unsafe { host.fence.GetCompletedValue() };
  2595. let n = landable(&fences, completed);
  2596. if n == 0 {
  2597. // The first thing is a flight the card has not run.
  2598. break Err(fences[0].unwrap_or(0));
  2599. }
  2600. line.settling = true;
  2601. let items: Vec<Late> = line.line.drain(..n).collect();
  2602. line.in_hand = items
  2603. .iter()
  2604. .filter_map(|l| match l {
  2605. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2606. _ => None,
  2607. })
  2608. .collect();
  2609. if card_steps::stage() > 0 {
  2610. line.landing = card_steps::writers(&items);
  2611. }
  2612. break Ok(items);
  2613. }
  2614. };
  2615. match next {
  2616. Ok(items) => host.relay_land(items, &mut fetch),
  2617. Err(target) => {
  2618. let waiting = std::time::Instant::now();
  2619. // SAFETY: the host's fence and this thread's event.
  2620. let waited = unsafe {
  2621. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2622. WaitForSingleObject(event, INFINITE);
  2623. })
  2624. };
  2625. if waited.is_err() {
  2626. std::thread::sleep(std::time::Duration::from_millis(1));
  2627. }
  2628. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2629. }
  2630. }
  2631. }
  2632. }
  2633. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2634. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2635. /// once, the pieces that differ found on several threads; but the merge is
  2636. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2637. /// are not done with here (each flight's are, afterwards). In two steps:
  2638. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  2639. /// which needs nothing that the fetch from the card's memory brings), and
  2640. /// the merge.
  2641. struct RelayBack {
  2642. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  2643. found: Option<Vec<Vec<(usize, usize)>>>,
  2644. }
  2645. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  2646. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2647. for (shadow, declared) in back {
  2648. if shadow.carded() {
  2649. continue;
  2650. }
  2651. let mut spans: Vec<(usize, usize)> = Vec::new();
  2652. join_ranges(&mut spans, declared.iter().copied());
  2653. for &(from, to) in &spans {
  2654. shadow.relay_compared(from, to - from);
  2655. }
  2656. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2657. }
  2658. RelayBack { work, found: None }
  2659. }
  2660. impl RelayBack {
  2661. /// Looks the ranges through, once; its time counts as `stat`.
  2662. fn look(&mut self, stat: usize) {
  2663. if self.work.is_empty() || self.found.is_some() {
  2664. return;
  2665. }
  2666. let scanning = std::time::Instant::now();
  2667. // Looked through without a lock: a piece that changes meanwhile (a
  2668. // later flight writing, the title's bytes going in) is found now or
  2669. // by that flight's landing, and the merge looks again under the
  2670. // lock.
  2671. self.found = Some(crate::shadow::find_all(&self.work));
  2672. crate::land::spent(stat, scanning);
  2673. #[cfg(feature = "diagnostics")]
  2674. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2675. }
  2676. /// What differs goes into title memory.
  2677. fn merge(mut self) {
  2678. use crate::land;
  2679. self.look(land::stat::SCAN);
  2680. let Some(found) = self.found else {
  2681. return;
  2682. };
  2683. let merging = std::time::Instant::now();
  2684. let mut written: Vec<u64> = Vec::new();
  2685. if land::on() {
  2686. // Pieces in the same block of title memory in one job, in order.
  2687. let pieces: Vec<(usize, usize, usize)> =
  2688. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  2689. let start = |i: usize| self.work[i].0.span().0 as usize;
  2690. let mut order: Vec<usize> = (0..pieces.len()).collect();
  2691. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  2692. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  2693. let jobs = land::jobs(&cut);
  2694. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  2695. land::each(jobs.len(), &|j| {
  2696. let working = std::time::Instant::now();
  2697. let mut notes = land::Notes::default();
  2698. for &p in &order[jobs[j].clone()] {
  2699. let (i, at, n) = pieces[p];
  2700. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  2701. }
  2702. notes.flush();
  2703. land::spent(land::stat::BACK_ALL, working);
  2704. });
  2705. land::count(land::stat::JOBS, jobs.len() as u64);
  2706. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  2707. } else {
  2708. let (mut now, mut title) = (Vec::new(), Vec::new());
  2709. for ((shadow, ..), found) in self.work.iter().zip(found) {
  2710. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  2711. written.push(found.into_iter().map(merge).sum());
  2712. }
  2713. }
  2714. land::spent(land::stat::BACK, merging);
  2715. for ((_, from, to), written) in self.work.iter().zip(written) {
  2716. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  2717. #[cfg(feature = "diagnostics")]
  2718. crate::copystat::compared(*from, to - from, written as usize);
  2719. let _ = (from, to);
  2720. }
  2721. }
  2722. }
  2723. /// For the frame-rate line, with [`late`]: what the line of flights did
  2724. /// per frame since the last one.
  2725. fn late_line(frames: f64) {
  2726. if !late() {
  2727. return;
  2728. }
  2729. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2730. tracing::info!(
  2731. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2732. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2733. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2734. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2735. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2736. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2737. s[0],
  2738. s[1],
  2739. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2740. s[12] / 1000.0,
  2741. s[WHY_SYNC],
  2742. s[WHY_CARD_DONE],
  2743. s[WHY_VALUE],
  2744. s[WHY_STALE],
  2745. s[WHY_READ],
  2746. s[15],
  2747. s[16],
  2748. s[17],
  2749. s[WHY_RUN],
  2750. late_most(),
  2751. s[WHY_MOST],
  2752. s[WHY_WRITES],
  2753. s[WHY_FENCE],
  2754. s[13],
  2755. s[14],
  2756. );
  2757. {
  2758. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2759. tracing::info!(
  2760. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2761. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2762. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2763. w[WHY_SYNC],
  2764. w[WHY_CARD_DONE],
  2765. w[WHY_VALUE],
  2766. w[WHY_STALE],
  2767. w[WHY_READ],
  2768. w[WHY_RUN],
  2769. w[WHY_MOST],
  2770. w[WHY_WRITES],
  2771. w[WHY_FENCE],
  2772. );
  2773. }
  2774. if relay() {
  2775. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2776. tracing::info!(
  2777. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2778. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2779. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2780. \"settles\" above are waits of other threads for it)",
  2781. r[1],
  2782. r[0],
  2783. r[2] / 1000.0,
  2784. r[3] / 1000.0,
  2785. r[4] / 1000.0,
  2786. );
  2787. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2788. if t[0] > 0.0 {
  2789. tracing::info!(
  2790. "fetched pieces checked per frame (VICTORY_FETCH_CHECK): {:.1}, of which {:.2} were not what their flight ended with (caught while a later flight was at them, or title bytes went up meanwhile); {:.2} were found whole when fetched again",
  2791. t[0],
  2792. t[1],
  2793. t[2],
  2794. );
  2795. }
  2796. }
  2797. crate::land::log(frames);
  2798. card_steps::log(frames);
  2799. crate::picked::log(frames);
  2800. #[cfg(feature = "diagnostics")]
  2801. log_blame(frames);
  2802. if late_exact() {
  2803. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  2804. tracing::info!(
  2805. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  2806. {runs:.0} changed runs, {:.2} MB",
  2807. bytes / (1 << 20) as f64
  2808. );
  2809. }
  2810. }
  2811. mod card_steps;
  2812. mod torn;
  2813. pub(crate) mod upcheck;
  2814. #[cfg(test)]
  2815. mod late_tests {
  2816. use super::{continues, join_ranges, touches};
  2817. /// Copies join only when both ends continue and the whole does not
  2818. /// overlap itself.
  2819. #[test]
  2820. fn copies_join_only_end_to_end_and_apart() {
  2821. // (destination, source, bytes)
  2822. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  2823. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  2824. // A gap, or only one side continues.
  2825. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  2826. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  2827. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  2828. // Together they would overlap: the second reads what the first wrote.
  2829. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  2830. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  2831. // They touch without overlapping.
  2832. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  2833. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  2834. }
  2835. /// Ranges are found by what they hold, not by where they start, and a
  2836. /// range that only touches another's end does not touch it.
  2837. #[test]
  2838. fn ranges_touch_where_they_overlap() {
  2839. let mut ranges = Vec::new();
  2840. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  2841. assert_eq!(ranges, [(10, 25), (40, 60)]);
  2842. join_ranges(&mut ranges, [(25, 40)]);
  2843. assert_eq!(ranges, [(10, 60)]);
  2844. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  2845. for (from, to, hit) in [
  2846. (0, 10, false),
  2847. (0, 11, true),
  2848. (24, 25, true),
  2849. (25, 40, false),
  2850. (25, 41, true),
  2851. (59, 200, true),
  2852. (60, 100, false),
  2853. (100, 101, true),
  2854. (101, 500, false),
  2855. (30, 30, false),
  2856. (50, 50, false),
  2857. ] {
  2858. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  2859. }
  2860. assert!(!touches(&[], 0, usize::MAX));
  2861. }
  2862. }
  2863. /// Whether a title buffer copy that continues the one recorded before it
  2864. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  2865. /// default).
  2866. ///
  2867. /// Each copy is done at submission through the kernel, which reports a
  2868. /// page that is not there instead of faulting (`copy_mapped`), tells the
  2869. /// write watch and the guards, and ends the refreshes gathered so far: a
  2870. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  2871. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  2872. /// continue the one before is counted either way and said on its own line
  2873. /// with the frame rate; the switch is worth that many kernel calls.
  2874. ///
  2875. /// Joined, the same bytes move: [`continues`] joins only copies whose
  2876. /// ranges, taken together, do not overlap, and nothing is recorded between
  2877. /// two steps that follow each other. What differs: a page that is not
  2878. /// mapped now fails the joined copy as a whole (it then goes page by page,
  2879. /// zeros for what cannot be read, as a single copy does), where before
  2880. /// only the copy that held it did.
  2881. fn join_copies() -> bool {
  2882. static ON: OnceLock<bool> = OnceLock::new();
  2883. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  2884. }
  2885. /// Since the last frame-rate line: title buffer copies recorded, and those
  2886. /// that continue the one before ([`join_copies`]).
  2887. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  2888. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  2889. /// where `last` ended, source and destination both, and the two as one do
  2890. /// not overlap (source over destination): then one copy of both moves the
  2891. /// bytes the two would move in turn.
  2892. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  2893. let ((d, s, n), (dst, src, len)) = (last, next);
  2894. let Some(all) = n.checked_add(len) else {
  2895. return false;
  2896. };
  2897. d.checked_add(n) == Some(dst)
  2898. && s.checked_add(n) == Some(src)
  2899. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  2900. }
  2901. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  2902. /// One list's lock at a time: a submission may name a list twice.
  2903. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  2904. let mut back: Vec<Declared> = Vec::new();
  2905. // Where each copy is in it, and the ranges seen: dispatches declare the
  2906. // same ranges thousands of times a frame.
  2907. let mut places: ByCopy<usize> = ByCopy::default();
  2908. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  2909. for list in runs {
  2910. for step in &list.deferred().copies {
  2911. if let Step::GpuWrite(shadow, address, len) = step {
  2912. let key = std::sync::Arc::as_ptr(shadow) as usize;
  2913. if !seen.insert((key, *address, *len)) {
  2914. continue;
  2915. }
  2916. let i = *places.entry(key).or_insert_with(|| {
  2917. back.push((shadow.clone(), Vec::new()));
  2918. back.len() - 1
  2919. });
  2920. back[i].1.push((*address, *address + *len));
  2921. }
  2922. }
  2923. }
  2924. back
  2925. }
  2926. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  2927. /// lines that say what the title's CPU was given while it decided whether
  2928. /// the camera is in a room. The values of the small read-backs
  2929. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  2930. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  2931. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  2932. /// copies found stale after their refresh (`shadow.rs`), and, in the
  2933. /// runtime, the read requests that fail (with 2: every request).
  2934. pub(crate) fn walls_trace() -> bool {
  2935. static ON: OnceLock<bool> = OnceLock::new();
  2936. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  2937. }
  2938. /// After `list` has run: the texels its read-backs copied into host
  2939. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  2940. ///
  2941. /// A submission that is waited for did this itself. One sent ahead
  2942. /// ([`late`]) did not, at any stage: the flights' lists were settled
  2943. /// without it, so the title read a buffer nobody wrote, as before read-backs
  2944. /// were made (the exposure metering's two small float targets, every frame).
  2945. fn read_backs(list: &HostList) {
  2946. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  2947. let mut data = std::ptr::null_mut();
  2948. // SAFETY: a read-back buffer of ours, written by the list that has
  2949. // run; the title's destination holds every row (checked when the
  2950. // copy was recorded).
  2951. unsafe {
  2952. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  2953. let from = data.cast::<u8>().cast_const();
  2954. for line in 0..*rows {
  2955. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  2956. }
  2957. // The walls trace: what the title is handed (one row of at
  2958. // most 24 values: its 5x1 and 1x1 float targets).
  2959. if walls_trace() && *rows == 1 && *row <= 96 {
  2960. let mut values = [0f32; 24];
  2961. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  2962. tracing::info!(
  2963. frame = crate::frame::current(),
  2964. to = format_args!("{:#x}", *at),
  2965. bytes = *row,
  2966. values = ?&values[..*row / 4],
  2967. "walls trace: a read-back lands in title memory"
  2968. );
  2969. }
  2970. buffer.Unmap(0, None);
  2971. }
  2972. }
  2973. }
  2974. }
  2975. /// After the card ran what declared `back`: what shaders wrote there goes
  2976. /// into title memory, and the ranges are done with.
  2977. fn hand_back(back: &[Declared]) {
  2978. if crate::shadow::wide_back() {
  2979. // Every range first (the pieces that differ, found on several
  2980. // threads), then the merges, in order, as below.
  2981. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2982. for (shadow, declared) in back {
  2983. if shadow.carded() {
  2984. continue;
  2985. }
  2986. let mut sorted = declared.clone();
  2987. sorted.sort_unstable();
  2988. let mut spans: Vec<(usize, usize)> = Vec::new();
  2989. for (from, to) in sorted {
  2990. match spans.last_mut() {
  2991. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2992. _ => spans.push((from, to)),
  2993. }
  2994. }
  2995. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2996. }
  2997. #[cfg(feature = "diagnostics")]
  2998. let scanning = std::time::Instant::now();
  2999. let found = crate::shadow::find_all(&work);
  3000. #[cfg(feature = "diagnostics")]
  3001. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3002. for ((shadow, from, to), found) in work.iter().zip(found) {
  3003. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3004. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3005. #[cfg(feature = "diagnostics")]
  3006. crate::copystat::compared(*from, to - from, written);
  3007. }
  3008. for (shadow, declared) in back {
  3009. shadow.copy_back_done(declared);
  3010. }
  3011. return;
  3012. }
  3013. for (shadow, declared) in back {
  3014. if shadow.carded() {
  3015. // Done before (`Host::card_back`).
  3016. shadow.copy_back_done(declared);
  3017. continue;
  3018. }
  3019. // Each byte compared once: the world declares dozens of views
  3020. // of its 174 MB heap that overlap almost entirely, and comparing
  3021. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3022. // MB shaders wrote. Only ranges that overlap or touch are
  3023. // joined: what lies between two was not given to shaders (the
  3024. // snapshot does not hold it).
  3025. let mut sorted = declared.clone();
  3026. sorted.sort_unstable();
  3027. let mut spans: Vec<(usize, usize)> = Vec::new();
  3028. for (from, to) in sorted {
  3029. match spans.last_mut() {
  3030. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3031. _ => spans.push((from, to)),
  3032. }
  3033. }
  3034. for (from, to) in spans {
  3035. let written = shadow.copy_back(from, to - from);
  3036. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3037. #[cfg(feature = "diagnostics")]
  3038. crate::copystat::compared(from, to - from, written);
  3039. }
  3040. shadow.copy_back_done(declared);
  3041. }
  3042. }
  3043. impl Host {
  3044. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3045. /// mesh shaders need both); logged once.
  3046. pub(crate) fn mesh_shaders(&self) -> bool {
  3047. static MESH: OnceLock<bool> = OnceLock::new();
  3048. *MESH.get_or_init(|| {
  3049. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3050. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3051. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3052. };
  3053. // SAFETY: each query writes its own structure of the given size.
  3054. let ok = unsafe {
  3055. self.device
  3056. .CheckFeatureSupport(
  3057. D3D12_FEATURE_D3D12_OPTIONS7,
  3058. (&raw mut options).cast(),
  3059. size_of_val(&options) as u32,
  3060. )
  3061. .is_ok()
  3062. && self
  3063. .device
  3064. .CheckFeatureSupport(
  3065. D3D12_FEATURE_SHADER_MODEL,
  3066. (&raw mut model).cast(),
  3067. size_of_val(&model) as u32,
  3068. )
  3069. .is_ok()
  3070. };
  3071. let mesh = ok
  3072. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3073. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3074. tracing::info!(mesh, "host mesh shader support");
  3075. mesh
  3076. })
  3077. }
  3078. /// Whether the host GPU supports the depth bounds test; logged once.
  3079. pub(crate) fn depth_bounds(&self) -> bool {
  3080. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3081. *BOUNDS.get_or_init(|| {
  3082. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3083. // SAFETY: writes `options` of the given size.
  3084. let ok = unsafe {
  3085. self.device
  3086. .CheckFeatureSupport(
  3087. D3D12_FEATURE_D3D12_OPTIONS2,
  3088. (&raw mut options).cast(),
  3089. size_of_val(&options) as u32,
  3090. )
  3091. .is_ok()
  3092. };
  3093. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3094. tracing::info!(supported, "host depth bounds support");
  3095. supported
  3096. })
  3097. }
  3098. /// A new list, open for recording.
  3099. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3100. #[cfg(feature = "diagnostics")]
  3101. let started = std::time::Instant::now();
  3102. #[cfg(feature = "diagnostics")]
  3103. let before = private_bytes();
  3104. let list = self.make_list();
  3105. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3106. // (May shrink while a list is made, on another thread's account:
  3107. // added as it is, the sum is what counts.)
  3108. #[cfg(feature = "diagnostics")]
  3109. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3110. #[cfg(feature = "diagnostics")]
  3111. {
  3112. use crate::copystat::{C, add};
  3113. add(C::HostLists, 1);
  3114. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3115. }
  3116. list
  3117. }
  3118. /// An allocator and a closed list for a prelude.
  3119. fn make_prelude(&self) -> Option<Prelude> {
  3120. // SAFETY: plain object creation.
  3121. let made: windows::core::Result<Prelude> = unsafe {
  3122. (|| {
  3123. let allocator: ID3D12CommandAllocator =
  3124. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3125. let list: ID3D12GraphicsCommandList =
  3126. self.device
  3127. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3128. list.Close()?;
  3129. Ok((allocator, list))
  3130. })()
  3131. };
  3132. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3133. match made {
  3134. Ok(prelude) => Some(prelude),
  3135. Err(e) => {
  3136. tracing::warn!(error = %e, "no host list for a prelude");
  3137. None
  3138. }
  3139. }
  3140. }
  3141. fn make_list(&self) -> windows::core::Result<HostList> {
  3142. // SAFETY: plain object creation.
  3143. unsafe {
  3144. let allocator: ID3D12CommandAllocator = self
  3145. .device
  3146. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3147. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3148. 0,
  3149. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3150. &allocator,
  3151. None,
  3152. )?;
  3153. let prelude = OnceLock::new();
  3154. if !lazy_prelude() {
  3155. let _ = prelude.set(self.make_prelude());
  3156. }
  3157. Ok(HostList {
  3158. allocator,
  3159. list,
  3160. deferred: Mutex::default(),
  3161. scratch: Mutex::default(),
  3162. states: Mutex::default(),
  3163. twins: Mutex::default(),
  3164. prelude,
  3165. pipelines: Mutex::default(),
  3166. budget: OnceLock::new(),
  3167. card_budget: OnceLock::new(),
  3168. indirect_args: Mutex::default(),
  3169. batch_args: Mutex::default(),
  3170. _alive: Counted::new(),
  3171. #[cfg(feature = "diagnostics")]
  3172. notes: Mutex::default(),
  3173. #[cfg(feature = "diagnostics")]
  3174. stamps: OnceLock::new(),
  3175. })
  3176. }
  3177. }
  3178. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3179. fn card_clock(&self) -> Option<&'static CardClock> {
  3180. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3181. static WATCH: std::sync::Once = std::sync::Once::new();
  3182. let clock = CLOCK
  3183. .get_or_init(|| {
  3184. // SAFETY: a plain fence on our device.
  3185. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3186. Some(CardClock {
  3187. fence,
  3188. state: Mutex::new((0, None)),
  3189. sent: std::sync::Condvar::new(),
  3190. })
  3191. })
  3192. .as_ref()?;
  3193. WATCH.call_once(|| {
  3194. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3195. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3196. }
  3197. });
  3198. Some(clock)
  3199. }
  3200. /// Lists of ours just went to the queue: the clock's signal goes
  3201. /// behind them, and an idle stretch of the card, if one was under way,
  3202. /// ends here ([`CARD_CLOCK_US`]).
  3203. fn card_sent(&self) {
  3204. let Some(clock) = self.card_clock() else {
  3205. return;
  3206. };
  3207. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3208. state.0 += 1;
  3209. // SAFETY: our queue and the clock's fence.
  3210. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3211. if let Some((since, worked_then)) = state.1.take() {
  3212. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3213. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3214. }
  3215. drop(state);
  3216. clock.sent.notify_one();
  3217. }
  3218. /// Whether the host has what copies in the card's memory need (three
  3219. /// lists and the compare); made at the first ask. A copy goes to the
  3220. /// card's memory only if it has.
  3221. pub(crate) fn card_ready(&self) -> bool {
  3222. static READY: OnceLock<bool> = OnceLock::new();
  3223. *READY.get_or_init(|| match self.make_card_work() {
  3224. Ok(work) => {
  3225. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3226. true
  3227. }
  3228. Err(e) => {
  3229. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3230. false
  3231. }
  3232. })
  3233. }
  3234. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3235. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3236. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3237. let mut code: Option<ID3DBlob> = None;
  3238. // SAFETY: the source and names live through the call; the out
  3239. // pointer is ours.
  3240. unsafe {
  3241. D3DCompile(
  3242. CARD_COMPARE.as_ptr().cast(),
  3243. CARD_COMPARE.len(),
  3244. windows::core::s!("card compare"),
  3245. None,
  3246. None,
  3247. windows::core::s!("main"),
  3248. windows::core::s!("cs_5_1"),
  3249. 0,
  3250. 0,
  3251. &mut code,
  3252. None,
  3253. )?;
  3254. }
  3255. let code = code.ok_or_else(windows::core::Error::empty)?;
  3256. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3257. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3258. // in one submission.
  3259. const RESULTS: u64 = 1 << 20;
  3260. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3261. name(&differs, || "card compare results".into());
  3262. // SAFETY: the blob's own bytes; the root signature is inside the
  3263. // shader.
  3264. unsafe {
  3265. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3266. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3267. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3268. pRootSignature: std::mem::transmute_copy(&root),
  3269. CS: D3D12_SHADER_BYTECODE {
  3270. pShaderBytecode: bytes.as_ptr().cast(),
  3271. BytecodeLength: bytes.len(),
  3272. },
  3273. ..Default::default()
  3274. })?;
  3275. #[cfg(feature = "diagnostics")]
  3276. name(&pso, || crate::replay::play::COMPARE.into());
  3277. Ok(CardWork {
  3278. sync: vec![list()?],
  3279. check: vec![list()?],
  3280. fetch: list()?,
  3281. root,
  3282. pso,
  3283. differs: (differs, data as usize, RESULTS),
  3284. fetched: None,
  3285. taken: 0,
  3286. out: 0,
  3287. })
  3288. }
  3289. }
  3290. /// Before a submission's lists run, for copies in the card's memory
  3291. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3292. /// the last submission goes to their card side (a list of ours, run
  3293. /// now; the submission's lists follow it on the queue), and the ranges
  3294. /// this submission's shaders may write get a compare to run after its
  3295. /// lists. `None` if there is nothing to do.
  3296. ///
  3297. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3298. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3299. /// `relay`).
  3300. /// `picked`: ranges that may be written too, and ranges to look at
  3301. /// (`crate::picked`).
  3302. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3303. use std::sync::Arc;
  3304. if !crate::shadow::cards() {
  3305. return None;
  3306. }
  3307. // The ranges this submission's shaders may write, per copy.
  3308. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3309. for list in runs {
  3310. for step in &list.deferred().copies {
  3311. if let Step::GpuWrite(shadow, address, len) = step
  3312. && shadow.carded()
  3313. {
  3314. let range = (*address, *address + *len);
  3315. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3316. Some((_, ranges)) => {
  3317. if !ranges.contains(&range) {
  3318. ranges.push(range);
  3319. }
  3320. }
  3321. None => declared.push((shadow.clone(), vec![range])),
  3322. }
  3323. }
  3324. }
  3325. }
  3326. let declared = crate::picked::with(declared, &picked.written);
  3327. // (Of a copy with a declared range here, that says it.)
  3328. let looked: Vec<&crate::picked::Range> =
  3329. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3330. // With the relay: the order of the queue is held from here until
  3331. // what is taken is on the queue, and the taking is numbered.
  3332. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3333. let sent_as = match order.as_mut() {
  3334. Some(order) => {
  3335. **order += 1;
  3336. **order
  3337. }
  3338. None => 0,
  3339. };
  3340. let mut dirty = crate::shadow::card_dirty(sent_as);
  3341. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3342. return None;
  3343. }
  3344. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3345. let work = work.as_mut()?;
  3346. // A copy whose shader writes are declared for the first time gets
  3347. // its bytes from before, whole.
  3348. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3349. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3350. if shadow.card_make_before(|size| {
  3351. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3352. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3353. Some(before)
  3354. }) {
  3355. whole.push(shadow.clone());
  3356. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3357. dirty.push((shadow.clone(), Vec::new()));
  3358. }
  3359. }
  3360. }
  3361. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3362. let mut looks = None;
  3363. if !dirty.is_empty() {
  3364. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3365. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3366. };
  3367. let (allocator, list) = &sync;
  3368. // SAFETY: the list's last run finished (it ran ahead of a
  3369. // submission that was waited for, and came back after that);
  3370. // live buffers, and the ranges lie in them.
  3371. let recorded = unsafe {
  3372. (|| -> windows::core::Result<()> {
  3373. allocator.Reset()?;
  3374. list.Reset(allocator, None)?;
  3375. if upcheck::on() {
  3376. looks = upcheck::record(self, list, &dirty);
  3377. }
  3378. // Every copy first, then one barrier call, then every
  3379. // pass: a wait between each copy and its pass had the
  3380. // card do them one after the other.
  3381. let mut sent = Vec::new();
  3382. for (shadow, ranges) in &dirty {
  3383. let Some((staging, before, _)) = shadow.card_sides() else {
  3384. continue;
  3385. };
  3386. for &(a, b) in ranges {
  3387. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3388. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3389. }
  3390. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3391. if before.is_some() && !ranges.is_empty() {
  3392. sent.push(transition(
  3393. &shadow.buffer,
  3394. D3D12_RESOURCE_STATE_COPY_DEST,
  3395. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3396. ));
  3397. }
  3398. }
  3399. if !sent.is_empty() {
  3400. list.ResourceBarrier(&sent);
  3401. }
  3402. list.SetComputeRootSignature(&work.root);
  3403. list.SetPipelineState(&work.pso);
  3404. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3405. for (shadow, ranges) in &dirty {
  3406. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3407. continue;
  3408. };
  3409. // No twin (it cost the card the copy's size again,
  3410. // 399 MB in run 75): `before` holds a 128-bit hash
  3411. // of each 64 KiB piece. The pieces just sent up are
  3412. // hashed again, all of them the first time; the
  3413. // compare after the lists hashes the declared
  3414. // pieces and flags those whose hash is another.
  3415. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3416. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3417. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3418. vec![shadow.card_run(0, usize::MAX)]
  3419. } else {
  3420. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3421. };
  3422. // The same pieces in fewer passes (`rehash_runs`).
  3423. let runs = if rehash_runs() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3424. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3425. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3426. for run in runs {
  3427. card_pass(list, &run, size as u32, 0, 0);
  3428. }
  3429. }
  3430. list.Close()?;
  3431. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3432. Ok(())
  3433. })()
  3434. };
  3435. if let Err(e) = recorded {
  3436. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3437. }
  3438. used.push((false, sync));
  3439. }
  3440. drop(order);
  3441. let mut plan = CardPlan {
  3442. ranges: Vec::new(),
  3443. check: None,
  3444. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3445. lists: used,
  3446. sent_as,
  3447. looks,
  3448. };
  3449. // Each byte once, as the copy-back joins the declared ranges. The
  3450. // results go behind those of plans still in the air.
  3451. let mut at = work.taken;
  3452. for (shadow, ranges) in &declared {
  3453. let mut sorted = ranges.clone();
  3454. sorted.sort_unstable();
  3455. let mut spans: Vec<(usize, usize)> = Vec::new();
  3456. for (from, to) in sorted {
  3457. match spans.last_mut() {
  3458. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3459. _ => spans.push((from, to)),
  3460. }
  3461. }
  3462. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3463. for (from, to) in spans {
  3464. let Some(span) = shadow.card_span(from, to) else {
  3465. continue;
  3466. };
  3467. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3468. plan.ranges.push(CardRange {
  3469. shadow: shadow.clone(),
  3470. declared: (from, to),
  3471. span,
  3472. at,
  3473. compared,
  3474. picked: false,
  3475. });
  3476. if compared {
  3477. at += span.pieces;
  3478. }
  3479. }
  3480. }
  3481. for (shadow, from, len) in looked {
  3482. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3483. if let Some(span) = shadow.card_span(*from, from + len)
  3484. && twin
  3485. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3486. {
  3487. plan.ranges.push(CardRange {
  3488. shadow: shadow.clone(),
  3489. declared: (*from, from + len),
  3490. span,
  3491. at,
  3492. compared: true,
  3493. picked: true,
  3494. });
  3495. at += span.pieces;
  3496. }
  3497. }
  3498. work.taken = at;
  3499. if plan.ranges.iter().any(|r| r.compared) {
  3500. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3501. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3502. };
  3503. let (allocator, list) = &check;
  3504. // SAFETY: the list's last run finished (its submission was
  3505. // waited for, and it came back after that); live buffers; the
  3506. // compare's own root signature.
  3507. let recorded = unsafe {
  3508. (|| -> windows::core::Result<ID3D12CommandList> {
  3509. allocator.Reset()?;
  3510. list.Reset(allocator, None)?;
  3511. // What the submission's shaders wrote, first.
  3512. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3513. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3514. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3515. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3516. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3517. pResource: std::mem::ManuallyDrop::new(None),
  3518. }),
  3519. },
  3520. }]);
  3521. list.SetComputeRootSignature(&work.root);
  3522. list.SetPipelineState(&work.pso);
  3523. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3524. for r in plan.ranges.iter().filter(|r| r.compared) {
  3525. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3526. continue;
  3527. };
  3528. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3529. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3530. // (What is only looked at keeps its hashes: what
  3531. // changed there is the next declared range's to land.)
  3532. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  3533. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3534. }
  3535. list.Close()?;
  3536. list.cast()
  3537. })()
  3538. };
  3539. match recorded {
  3540. Ok(list) => plan.check = Some(list),
  3541. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3542. }
  3543. plan.lists.push((true, check));
  3544. }
  3545. work.out += 1;
  3546. Some(plan)
  3547. }
  3548. /// With [`relay`]: whether the compare's result area is half taken by
  3549. /// plans in the air. It starts from the beginning only when no plan is
  3550. /// out, so the caller lets the flights land first.
  3551. fn card_results_low(&self) -> bool {
  3552. CARD_WORK
  3553. .lock()
  3554. .unwrap_or_else(|e| e.into_inner())
  3555. .as_ref()
  3556. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3557. }
  3558. /// The plan's submission has run and its results were read
  3559. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3560. /// when nothing of ours is on the card, so the compare's results start
  3561. /// from the beginning again.
  3562. fn card_done(&self, plan: CardPlan) {
  3563. if let Some(looks) = plan.looks {
  3564. looks.read();
  3565. }
  3566. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3567. let Some(work) = work.as_mut() else {
  3568. return;
  3569. };
  3570. for (check, list) in plan.lists {
  3571. if check { work.check.push(list) } else { work.sync.push(list) }
  3572. }
  3573. work.out = work.out.saturating_sub(1);
  3574. // With the relay other plans may be on the card, their results
  3575. // not read yet: the area starts again only when none is out.
  3576. if !relay() || work.out == 0 {
  3577. work.taken = 0;
  3578. }
  3579. }
  3580. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3581. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3582. // SAFETY: plain object creation.
  3583. let copying = relay_copy().then(|| unsafe {
  3584. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3585. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3586. let list: ID3D12GraphicsCommandList =
  3587. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3588. list.Close()?;
  3589. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3590. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3591. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3592. ..Default::default()
  3593. })?;
  3594. Ok(((allocator, list), queue))
  3595. })()
  3596. });
  3597. let (list, queue) = match copying {
  3598. Some(Ok((list, queue))) => (list, Some(queue)),
  3599. Some(Err(e)) => {
  3600. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3601. (self.make_prelude()?, None)
  3602. }
  3603. None => (self.make_prelude()?, None),
  3604. };
  3605. // SAFETY: plain objects of our own.
  3606. unsafe {
  3607. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3608. let event = CreateEventW(None, false, false, None).ok()?;
  3609. Some(RelayFetch {
  3610. list,
  3611. queue,
  3612. fence,
  3613. event,
  3614. sent: 0,
  3615. buffer: None,
  3616. suspects: torn::Suspects::default(),
  3617. had: crate::land::Had::default(),
  3618. })
  3619. }
  3620. }
  3621. /// [`relay`], on the thread that lands flights: for the plans of the
  3622. /// flights being landed (the card has run them), the pieces their
  3623. /// compares flagged are fetched, once each, with a list and a wait of
  3624. /// this thread's own, and what shaders wrote in them goes into title
  3625. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3626. /// no submission lock; a piece flagged under one range of a plan is
  3627. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3628. /// whatever was sent meanwhile, so it may bring a later flight's
  3629. /// bytes, which that flight's landing then finds merged already; and
  3630. /// nothing is sent back up. `plans` come with the value signalled behind
  3631. /// their flight. `meanwhile` is called while the fetch is on its way, if
  3632. /// there is one.
  3633. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  3634. use crate::land;
  3635. let gathering = std::time::Instant::now();
  3636. let differs = {
  3637. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3638. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3639. };
  3640. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3641. let mut total = 0u64;
  3642. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  3643. fetch.had.landing(first);
  3644. }
  3645. // SAFETY: the mapping of the results. The compares of these plans
  3646. // have run, and their dwords are given to no other plan before these
  3647. // are done with (`card_done`).
  3648. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  3649. if let Some(differs) = differs {
  3650. // Pieces caught while a later flight was at them (`torn`).
  3651. let suspects = fetch.as_ref().map(|f| &f.suspects);
  3652. let mut seen = std::collections::HashSet::new();
  3653. for &(plan, behind) in plans {
  3654. plan.picked_found(differs);
  3655. let flags: Vec<(usize, u32, bool)> = plan
  3656. .ranges
  3657. .iter()
  3658. .filter(|r| !r.picked)
  3659. .flat_map(|r| {
  3660. (0..r.span.pieces).map(move |p| {
  3661. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  3662. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  3663. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  3664. })
  3665. })
  3666. .collect();
  3667. let fetched = flagged_pieces(&flags);
  3668. for r in plan.ranges.iter().filter(|r| !r.picked) {
  3669. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3670. if upcheck::on() {
  3671. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  3672. }
  3673. for p in 0..r.span.pieces {
  3674. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  3675. continue;
  3676. }
  3677. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3678. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  3679. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  3680. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  3681. land::count(land::stat::HAD, 1);
  3682. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  3683. if land::skip_on() {
  3684. continue;
  3685. }
  3686. }
  3687. if upcheck::on() {
  3688. upcheck::fetched(r.shadow.id(), lo);
  3689. }
  3690. seen.insert((copy, lo, hi));
  3691. pieces.push((r.shadow.clone(), lo, hi, total));
  3692. total += (hi - lo) as u64;
  3693. }
  3694. }
  3695. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3696. }
  3697. }
  3698. }
  3699. if land::on() {
  3700. // In the order they are landed, each byte of a copy once.
  3701. let keys: Vec<land::Piece> =
  3702. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  3703. total = 0;
  3704. pieces = land::ordered(&keys)
  3705. .into_iter()
  3706. .map(|(i, title, len)| {
  3707. let shadow = &pieces[i].0;
  3708. let lo = title - shadow.span().0 as usize;
  3709. let at = total;
  3710. total += len as u64;
  3711. (shadow.clone(), lo, lo + len, at)
  3712. })
  3713. .collect();
  3714. }
  3715. land::spent(land::stat::GATHER, gathering);
  3716. if fetch.is_none() {
  3717. *fetch = self.make_relay_fetch();
  3718. }
  3719. // On the copy queue a later flight may be at a piece while it is
  3720. // fetched: the pieces come down whole, to be hashed.
  3721. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  3722. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  3723. if let Some(check) = &check {
  3724. total = check.total;
  3725. }
  3726. // The sends these flights ran behind, all a fetch on the copy queue
  3727. // is known to have run behind.
  3728. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  3729. if pieces.is_empty() {
  3730. // Nothing to fetch: every send so far is older than the next
  3731. // fetch, if that goes to the queue the sends went to.
  3732. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  3733. true => behind,
  3734. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  3735. };
  3736. crate::shadow::relay_fetched(after);
  3737. return;
  3738. }
  3739. let Some(f) = fetch.as_mut() else {
  3740. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  3741. };
  3742. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  3743. let size = total.next_multiple_of(16 << 20);
  3744. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3745. }
  3746. let Some((buffer, data, _)) = f.buffer.clone() else {
  3747. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  3748. };
  3749. f.sent += 1;
  3750. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  3751. let copy_queue = f.queue.clone();
  3752. let waiting = std::time::Instant::now();
  3753. // The flights the fetch runs behind: those in the line by now have
  3754. // been given to the queue. On the copy queue, those landed here.
  3755. let ahead = match copy_queue {
  3756. Some(_) => 0,
  3757. None => line().target,
  3758. };
  3759. // SAFETY: the list's last run was waited for by this thread; live
  3760. // buffers (the copies are held by the plans); the fence and the
  3761. // event are this thread's.
  3762. let ran = unsafe {
  3763. (|| -> windows::core::Result<u64> {
  3764. allocator.Reset()?;
  3765. list.Reset(&allocator, None)?;
  3766. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  3767. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  3768. }
  3769. list.Close()?;
  3770. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  3771. if let Some(queue) = &copy_queue {
  3772. queue.ExecuteCommandLists(&lists);
  3773. queue.Signal(&fence, sent)?;
  3774. meanwhile();
  3775. fence.SetEventOnCompletion(sent, event)?;
  3776. WaitForSingleObject(event, INFINITE);
  3777. return Ok(behind);
  3778. }
  3779. // In the order of the queue: the sends of title bytes so
  3780. // far are ahead of this fetch, every later one behind it.
  3781. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  3782. self.queue.ExecuteCommandLists(&lists);
  3783. let after = *order;
  3784. drop(order);
  3785. self.card_sent();
  3786. self.queue.Signal(&fence, sent)?;
  3787. meanwhile();
  3788. fence.SetEventOnCompletion(sent, event)?;
  3789. WaitForSingleObject(event, INFINITE);
  3790. Ok(after)
  3791. })()
  3792. };
  3793. let after = match ran {
  3794. Ok(after) => after,
  3795. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  3796. };
  3797. let us = waiting.elapsed().as_micros() as u64;
  3798. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  3799. {
  3800. use crate::shadow::CARD_STATS;
  3801. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  3802. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  3803. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  3804. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  3805. }
  3806. let merging = std::time::Instant::now();
  3807. let mut written = 0;
  3808. if land::on() {
  3809. let titles: Vec<(usize, usize)> =
  3810. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  3811. let jobs = land::jobs(&titles);
  3812. let put = std::sync::atomic::AtomicU64::new(0);
  3813. land::each(jobs.len(), &|j| {
  3814. let working = std::time::Instant::now();
  3815. if let Some(check) = &check {
  3816. for i in jobs[j].clone() {
  3817. // SAFETY: as below.
  3818. unsafe { check.look(i, data) };
  3819. }
  3820. }
  3821. let mut notes = land::Notes::default();
  3822. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  3823. let addressed: Vec<(usize, usize, usize)> =
  3824. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  3825. // SAFETY: the mapping of the fetched bytes, `total` of
  3826. // them; the copy into it has run, and the next waits
  3827. // for this call.
  3828. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  3829. }
  3830. notes.flush();
  3831. land::spent(land::stat::CARD_ALL, working);
  3832. });
  3833. land::count(land::stat::JOBS, jobs.len() as u64);
  3834. written = put.into_inner();
  3835. } else {
  3836. let mut title = Vec::new();
  3837. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  3838. if let Some(check) = &check {
  3839. // SAFETY: as below.
  3840. unsafe { check.look(i, data) };
  3841. }
  3842. // SAFETY: the mapping of the fetched bytes, `total` of them;
  3843. // the copy into it has run.
  3844. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  3845. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  3846. shadow.walls_merged(gpu.len(), merged);
  3847. written += merged as u64;
  3848. }
  3849. }
  3850. land::spent(land::stat::CARD, merging);
  3851. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  3852. if let Some(f) = fetch.as_mut() {
  3853. if let Some(check) = &check {
  3854. check.done(&mut f.suspects);
  3855. }
  3856. f.had.fetched(
  3857. ahead,
  3858. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  3859. );
  3860. }
  3861. // Sends up to `after` are of no use to any later merge.
  3862. crate::shadow::relay_fetched(after);
  3863. }
  3864. /// [`relay`], on the thread that lands flights: `items` are the first
  3865. /// things of the line, flights the card has run and what follows them.
  3866. /// What their shaders wrote goes into title memory (copies in the
  3867. /// card's memory first, then the others, each byte once whichever
  3868. /// flights declared it); then every flight's ranges are done with;
  3869. /// then, in the line's order, each flight's read-backs, its
  3870. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  3871. /// is complete before the title is told anything.
  3872. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  3873. let landing = std::time::Instant::now();
  3874. {
  3875. let flights: Vec<&Flight> = items
  3876. .iter()
  3877. .filter_map(|l| match l {
  3878. Late::Run(flight) => Some(flight),
  3879. _ => None,
  3880. })
  3881. .collect();
  3882. if !flights.is_empty() {
  3883. // SAFETY: a plain query.
  3884. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  3885. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  3886. fail(format_args!(
  3887. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  3888. flights.len(),
  3889. runs.len(),
  3890. self.removal_data(&runs),
  3891. last_notes(&runs)
  3892. ));
  3893. }
  3894. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  3895. // (Each byte once: the ranges are joined.)
  3896. let mut back: Vec<Declared> = Vec::new();
  3897. for flight in &flights {
  3898. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  3899. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  3900. Some((_, all)) => all.extend_from_slice(ranges),
  3901. None => back.push((shadow.clone(), ranges.clone())),
  3902. }
  3903. }
  3904. }
  3905. let mut hand_back = relay_hand_back(&back);
  3906. self.relay_card_back(&plans, fetch, &mut || {
  3907. if crate::land::on() {
  3908. hand_back.look(crate::land::stat::SCAN_BESIDE);
  3909. }
  3910. });
  3911. hand_back.merge();
  3912. let finishing = std::time::Instant::now();
  3913. // Only now, and flight by flight: a range another flight
  3914. // in the air declared too stays closed to refreshes.
  3915. for flight in &flights {
  3916. for (shadow, ranges) in &flight.back {
  3917. shadow.copy_back_done(ranges);
  3918. }
  3919. }
  3920. crate::land::spent(crate::land::stat::DONE, finishing);
  3921. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  3922. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  3923. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  3924. }
  3925. }
  3926. // In the order given: what tells the title the card is done.
  3927. let mut last = 0;
  3928. let mut landed = Vec::new();
  3929. let mut telling = std::time::Instant::now();
  3930. for item in items {
  3931. telling = match item {
  3932. Late::Run(flight) => {
  3933. last = flight.number;
  3934. for &i in &flight.order {
  3935. read_backs(flight.lists[i].host());
  3936. }
  3937. if let Some(card) = flight.card {
  3938. self.card_done(card);
  3939. }
  3940. if let Some(own) = flight.own {
  3941. own.landed();
  3942. }
  3943. landed.push((flight.lists, flight.order));
  3944. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  3945. }
  3946. Late::Write(at, what, bytes) => {
  3947. what.write(at as *mut u8, bytes);
  3948. crate::land::spent(crate::land::stat::TOLD, telling)
  3949. }
  3950. Late::Signal(fence, value) => {
  3951. crate::fence::set(fence as crate::object::This, value);
  3952. crate::land::spent(crate::land::stat::TOLD, telling)
  3953. }
  3954. };
  3955. }
  3956. if last > 0 {
  3957. FINISHED.store(last, Ordering::Release);
  3958. bury(last);
  3959. }
  3960. self.log_messages();
  3961. crate::land::spent(crate::land::stat::REST, telling);
  3962. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  3963. {
  3964. let mut line = line();
  3965. let Line {
  3966. line: items,
  3967. written,
  3968. lists,
  3969. settling,
  3970. poke,
  3971. landed: kept,
  3972. in_hand,
  3973. landing,
  3974. ..
  3975. } = &mut *line;
  3976. kept.extend(landed);
  3977. in_hand.clear();
  3978. landing.clear();
  3979. // What is still in the air, from the flights that are.
  3980. written.clear();
  3981. *lists = 0;
  3982. let mut ranges = Vec::new();
  3983. for item in items.iter() {
  3984. if let Late::Run(flight) = item {
  3985. *lists += flight.order.len().max(1);
  3986. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  3987. }
  3988. }
  3989. join_ranges(written, ranges);
  3990. *settling = false;
  3991. // The landed lists are reset, and what queues hold looked at,
  3992. // by the helper thread (they take locks a waiter may hold).
  3993. *poke = true;
  3994. }
  3995. LINE_MOVED.notify_all();
  3996. LINE_LANDED.notify_all();
  3997. }
  3998. /// After a submission ran, for copies in the card's memory: the pieces
  3999. /// of the declared ranges that the compare found differing (all of a
  4000. /// range it did not compare) are fetched, with one more wait for the
  4001. /// card, and what shaders wrote in them goes into title memory.
  4002. /// `submitted` is the last value signalled on the fence. `seen` holds
  4003. /// the pieces fetched already since the card was last waited for
  4004. /// (several submissions settled together name the same ones).
  4005. fn card_back(
  4006. &self,
  4007. plan: &CardPlan,
  4008. submitted: &mut u64,
  4009. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4010. ) {
  4011. if plan.ranges.is_empty() {
  4012. return;
  4013. }
  4014. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4015. let Some(work) = work.as_mut() else {
  4016. return;
  4017. };
  4018. // SAFETY: the mapping of the results, which the compare (it has
  4019. // run) wrote.
  4020. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4021. // The pieces to fetch: the range, the offsets in its copy, and
  4022. // where the bytes come down.
  4023. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4024. let mut total = 0u64;
  4025. plan.picked_found(differs);
  4026. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4027. for p in 0..r.span.pieces {
  4028. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4029. continue;
  4030. }
  4031. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4032. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4033. pieces.push((i, lo, hi, total));
  4034. total += (hi - lo) as u64;
  4035. }
  4036. }
  4037. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4038. }
  4039. let mut written = vec![0usize; plan.ranges.len()];
  4040. if !pieces.is_empty() {
  4041. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4042. let size = total.next_multiple_of(16 << 20);
  4043. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4044. }
  4045. let Some((fetched, data, _)) = &work.fetched else {
  4046. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4047. };
  4048. let waiting = std::time::Instant::now();
  4049. let (allocator, list) = &work.fetch;
  4050. // SAFETY: the list's last run was waited for; live buffers; the
  4051. // fence and event are ours, under the submission lock.
  4052. let ran = unsafe {
  4053. (|| -> windows::core::Result<()> {
  4054. allocator.Reset()?;
  4055. list.Reset(allocator, None)?;
  4056. for &(i, lo, hi, at) in &pieces {
  4057. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4058. }
  4059. list.Close()?;
  4060. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4061. self.card_sent();
  4062. *submitted += 1;
  4063. self.queue.Signal(&self.fence, *submitted)?;
  4064. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4065. let was_working = working(false);
  4066. WaitForSingleObject(self.event, INFINITE);
  4067. stood(waiting);
  4068. working(was_working);
  4069. Ok(())
  4070. })()
  4071. };
  4072. if let Err(e) = ran {
  4073. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4074. }
  4075. {
  4076. use crate::shadow::CARD_STATS;
  4077. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4078. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4079. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4080. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4081. }
  4082. if wide_merge() && pieces.len() >= 8 {
  4083. // The pieces are apart from one another (each its own bytes
  4084. // of its copy and of title memory): several at a time.
  4085. let fetched = *data;
  4086. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4087. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4088. let each = pieces.len().div_ceil(8);
  4089. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4090. .chunks(each)
  4091. .map(|chunk| {
  4092. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4093. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4094. let counts = counts.clone();
  4095. Box::new(move || {
  4096. let mut title = Vec::new();
  4097. for (shadow, i, lo, hi, at) in chunk {
  4098. // SAFETY: the mapping of the fetched bytes;
  4099. // the copy into it has run, and the caller
  4100. // waits for this job.
  4101. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4102. let merged = shadow.card_merge(lo, gpu, &mut title);
  4103. shadow.walls_merged(gpu.len(), merged);
  4104. counts[i].fetch_add(merged, Ordering::Relaxed);
  4105. }
  4106. }) as Box<dyn FnOnce() + Send>
  4107. })
  4108. .collect();
  4109. crate::shadow::wide_run(jobs);
  4110. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4111. *written += count.load(Ordering::Relaxed);
  4112. }
  4113. } else {
  4114. let mut title = Vec::new();
  4115. for &(i, lo, hi, at) in &pieces {
  4116. // SAFETY: the mapping of the fetched bytes, `total` of
  4117. // them; the copy into it has run.
  4118. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4119. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4120. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4121. written[i] += merged;
  4122. }
  4123. }
  4124. }
  4125. for (r, written) in plan.ranges.iter().zip(written) {
  4126. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4127. let (from, to) = r.declared;
  4128. #[cfg(feature = "diagnostics")]
  4129. crate::copystat::compared(from, to - from, written);
  4130. let _ = (from, to);
  4131. }
  4132. }
  4133. /// Runs closed lists and waits for them, and with [`late`] for
  4134. /// everything sent to the card before them, which is settled first.
  4135. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4136. let _ = self.submit(runs, false);
  4137. }
  4138. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4139. /// from the title's, go to the card in `order` and are not waited for.
  4140. /// They join the line of flights and are settled, with the others in
  4141. /// the air, at the next point where what they do can be observed
  4142. /// ([`late`] lists those points); their host lists are reset and kept
  4143. /// for reuse then, as a queue does for the lists it ran.
  4144. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4145. if order.is_empty() {
  4146. crate::list::recycle(lists, &order);
  4147. return;
  4148. }
  4149. late_threads();
  4150. let sent = {
  4151. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4152. self.submit(&runs, true)
  4153. };
  4154. let Some((mut submitted, sent)) = sent else {
  4155. // (Not reached: a submission sent ahead always comes back.)
  4156. crate::list::recycle(lists, &order);
  4157. return;
  4158. };
  4159. let told = !sent.writes.is_empty();
  4160. let most = {
  4161. let mut line = line();
  4162. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4163. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4164. *flying += order.len();
  4165. *target = *submitted;
  4166. items.push(Late::Run(Flight {
  4167. number: sent.number,
  4168. fence: *target,
  4169. lists,
  4170. order,
  4171. card: sent.card,
  4172. back: sent.back,
  4173. own: sent.own,
  4174. }));
  4175. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4176. *flying >= late_most()
  4177. };
  4178. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4179. RELAY_MOVED.notify_one();
  4180. if told && !late_writes() {
  4181. self.settle(&mut submitted, WHY_WRITES);
  4182. } else if most && relay_exact() {
  4183. // Until there are fewer, not until there are none.
  4184. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4185. } else if most {
  4186. self.settle(&mut submitted, WHY_MOST);
  4187. } else {
  4188. LINE_MOVED.notify_one();
  4189. }
  4190. drop(submitted);
  4191. land();
  4192. }
  4193. /// Sends `list`, a closed list of ours (the present's copy), as a
  4194. /// flight ([`late_free_present`]): not waited for, settled with the
  4195. /// others. The caller keeps the list and does not reset it before the
  4196. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4197. /// it ran and was waited for after all.
  4198. fn execute_own(&self, list: &HostList) -> u64 {
  4199. late_threads();
  4200. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4201. return 0;
  4202. };
  4203. let number = sent.number;
  4204. {
  4205. let mut line = line();
  4206. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4207. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4208. *flying += 1;
  4209. *target = *submitted;
  4210. items.push(Late::Run(Flight {
  4211. number,
  4212. fence: *target,
  4213. lists: Vec::new(),
  4214. order: Vec::new(),
  4215. card: sent.card,
  4216. back: sent.back,
  4217. own: sent.own,
  4218. }));
  4219. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4220. }
  4221. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4222. LINE_MOVED.notify_one();
  4223. RELAY_MOVED.notify_one();
  4224. drop(submitted);
  4225. number
  4226. }
  4227. /// Waits for the card to run every flight in the air ([`late`]) and
  4228. /// does what they left to do, as [`Host::execute`] does for one
  4229. /// submission after its wait: the pieces their shaders wrote in copies
  4230. /// in the card's memory are fetched and merged (each once), the ranges
  4231. /// they declared in the other copies are compared and copied back
  4232. /// (each byte once, whichever flights declared it), and then, in the
  4233. /// order they were given: their bottom-of-pipe writes and the fence
  4234. /// signals behind them. `submitted` is the submission lock's value;
  4235. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4236. ///
  4237. /// Everything in the air is settled, never the first flights alone:
  4238. /// the merge writes the copies' CPU side, which a flight still on the
  4239. /// card may be writing too.
  4240. fn settle(&self, submitted: &mut u64, why: usize) {
  4241. if !late() {
  4242. return;
  4243. }
  4244. if relay() {
  4245. // Nothing is settled here: the thread that lands flights does
  4246. // it, in order, and this waits until nothing is in the air and
  4247. // nothing is being landed. Every point that settled before
  4248. // comes here, so each still sees title memory, fences and
  4249. // bottom-of-pipe values as after a settle.
  4250. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4251. return;
  4252. }
  4253. let was_working = working(true);
  4254. let mut counted = false;
  4255. loop {
  4256. let items = {
  4257. let mut line = line();
  4258. if line.line.is_empty() {
  4259. line.settling = false;
  4260. break;
  4261. }
  4262. line.settling = true;
  4263. line.written.clear();
  4264. line.lists = 0;
  4265. std::mem::take(&mut line.line)
  4266. };
  4267. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4268. if !counted {
  4269. counted = true;
  4270. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4271. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4272. }
  4273. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4274. if flights > 0 {
  4275. submitting(2, flights);
  4276. let waiting = std::time::Instant::now();
  4277. // SAFETY: the fence and event are ours, under the
  4278. // submission lock; `submitted` is the last value signalled.
  4279. unsafe {
  4280. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4281. Ok(()) => {
  4282. working(false);
  4283. WaitForSingleObject(self.event, INFINITE);
  4284. stood(waiting);
  4285. working(true);
  4286. }
  4287. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4288. }
  4289. }
  4290. let gpu = waiting.elapsed();
  4291. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4292. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4293. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4294. #[cfg(feature = "diagnostics")]
  4295. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4296. format!("{flights} submissions sent ahead, settled together")
  4297. });
  4298. // SAFETY: a plain query.
  4299. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4300. let runs: Vec<&HostList> = items
  4301. .iter()
  4302. .filter_map(|i| match i {
  4303. Late::Run(f) => Some(f),
  4304. _ => None,
  4305. })
  4306. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4307. .collect();
  4308. fail(format_args!(
  4309. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4310. runs.len(),
  4311. self.removal_data(&runs),
  4312. last_notes(&runs)
  4313. ));
  4314. }
  4315. submitting(3, flights);
  4316. let copying = std::time::Instant::now();
  4317. let mut seen = std::collections::HashSet::new();
  4318. let mut back: Vec<Declared> = Vec::new();
  4319. for item in &items {
  4320. let Late::Run(flight) = item else {
  4321. continue;
  4322. };
  4323. if let Some(card) = &flight.card {
  4324. self.card_back(card, submitted, &mut seen);
  4325. }
  4326. for (shadow, ranges) in &flight.back {
  4327. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4328. Some((_, all)) => {
  4329. for range in ranges {
  4330. if !all.contains(range) {
  4331. all.push(*range);
  4332. }
  4333. }
  4334. }
  4335. None => back.push((shadow.clone(), ranges.clone())),
  4336. }
  4337. }
  4338. }
  4339. hand_back(&back);
  4340. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4341. }
  4342. // In the order given: what tells the title the card is done.
  4343. let mut last = 0;
  4344. let mut landed = Vec::new();
  4345. for item in items {
  4346. match item {
  4347. Late::Run(flight) => {
  4348. last = flight.number;
  4349. for &i in &flight.order {
  4350. read_backs(flight.lists[i].host());
  4351. }
  4352. if let Some(card) = flight.card {
  4353. self.card_done(card);
  4354. }
  4355. landed.push((flight.lists, flight.order));
  4356. }
  4357. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4358. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4359. }
  4360. }
  4361. if last > 0 {
  4362. FINISHED.store(last, Ordering::Release);
  4363. bury(last);
  4364. }
  4365. line().landed.extend(landed);
  4366. }
  4367. if counted {
  4368. self.log_messages();
  4369. submitting(0, 0);
  4370. // What was settled may be what a queue stands at, and the
  4371. // caller may not be one that looks (a read-back, a present).
  4372. if why != WHY_CARD_DONE {
  4373. line().poke = true;
  4374. LINE_MOVED.notify_one();
  4375. }
  4376. }
  4377. working(was_working);
  4378. }
  4379. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4380. /// copies, which flights may be writing and the title wrote too
  4381. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4382. /// those of the submission's one asking, which is made again.
  4383. ///
  4384. /// With [`card_steps`] only the flights that declared them: a range of
  4385. /// a copy nobody declared any more is refreshed like any other. What
  4386. /// they landed is title memory written, so everything is asked and
  4387. /// looked at again; what is left after three times waits as before.
  4388. fn settle_stale(
  4389. &self,
  4390. submitted: &mut u64,
  4391. runs: &[&HostList],
  4392. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4393. ranges: &[(usize, usize)],
  4394. ) {
  4395. if relay_exact() && card_steps::stage() > 0 {
  4396. for _ in 0..3 {
  4397. #[cfg(feature = "diagnostics")]
  4398. blame_stale(&stale);
  4399. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4400. crate::watch::ask_once(ranges);
  4401. stale = stale_under_flights(runs);
  4402. if stale.is_empty() {
  4403. return;
  4404. }
  4405. }
  4406. }
  4407. #[cfg(feature = "diagnostics")]
  4408. blame_stale(&stale);
  4409. self.settle(submitted, WHY_STALE);
  4410. crate::watch::ask_once(ranges);
  4411. }
  4412. /// [`Host::execute`], or with `late` the first half of
  4413. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4414. /// to be done once they have run comes back with the submission lock
  4415. /// still held.
  4416. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4417. #[cfg(feature = "diagnostics")]
  4418. let called = std::time::Instant::now();
  4419. #[cfg(feature = "diagnostics")]
  4420. crate::copystat::submission_begins();
  4421. // One submission at a time from preparation to copy-back: snapshots
  4422. // and the ranges shaders write are per host copy, not per submission.
  4423. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4424. let was_working = working(true);
  4425. submitting(1, runs.len());
  4426. // Flights in the air ([`late`]): a submission that is waited for
  4427. // settles them first, one sent ahead only if preparing it reads
  4428. // what they write.
  4429. // Or the reads are done on the card, behind the flights.
  4430. let own = if late { self.card_steps(runs) } else { None };
  4431. if !late {
  4432. self.settle(&mut submitted, WHY_SYNC);
  4433. } else if own.is_none()
  4434. && let Some(why) = late_blocked(runs)
  4435. {
  4436. if relay_exact() && why == WHY_READ {
  4437. // Only until the flights that may write what is read have
  4438. // landed: their copy-back's end, not the card's other work.
  4439. relay_wait(why, |line| {
  4440. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4441. });
  4442. } else {
  4443. self.settle(&mut submitted, why);
  4444. }
  4445. }
  4446. // That list runs first, and is one of the submission's from here on.
  4447. let with: Vec<&HostList>;
  4448. let runs = match &own {
  4449. Some(own) => {
  4450. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4451. &with[..]
  4452. }
  4453. None => runs,
  4454. };
  4455. let behind = late && flying();
  4456. // Before this submission counts as started: what the sweep lets go
  4457. // of is named by no list, and nothing runs now (behind flights the
  4458. // sweep waits for a submission that finds none in the air: there is
  4459. // one at every present).
  4460. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4461. if !behind {
  4462. if upcheck::on() {
  4463. upcheck::at_rest(self);
  4464. }
  4465. sweep();
  4466. SWEPT.store(now_ms(), Ordering::Relaxed);
  4467. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4468. // With the present sent ahead nothing else brings a moment
  4469. // with nothing in the air: one is made for the sweep.
  4470. self.settle(&mut submitted, WHY_SYNC);
  4471. if upcheck::on() {
  4472. upcheck::at_rest(self);
  4473. }
  4474. sweep();
  4475. SWEPT.store(now_ms(), Ordering::Relaxed);
  4476. }
  4477. let behind = late && flying();
  4478. // The slots that waited for a texture's host copy, before the
  4479. // lists that may read them run.
  4480. crate::descriptor::make_waiting();
  4481. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4482. // The ranges shaders write are counted for it (with the relay).
  4483. crate::shadow::preparing(this_submission);
  4484. let started = std::time::Instant::now();
  4485. #[cfg(feature = "diagnostics")]
  4486. let lock = (started - called).as_micros() as u64;
  4487. #[cfg(feature = "diagnostics")]
  4488. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4489. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4490. // Where each run's lists start in `lists`.
  4491. let mut firsts = Vec::with_capacity(runs.len());
  4492. let mut batch = Batch::default();
  4493. #[cfg(feature = "diagnostics")]
  4494. let split = Split::begin();
  4495. // The time a settle of flights takes inside this preparing: the
  4496. // wait for the card and the copy-back have their own places on the
  4497. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4498. let mut settled = std::time::Duration::ZERO;
  4499. // One write-watch asking for everything the submission refreshes
  4500. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4501. if crate::watch::once() {
  4502. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  4503. for list in runs {
  4504. for step in &list.deferred().copies {
  4505. if let Step::Refresh(shadow, address, len) = step
  4506. && !shadow.unwatched()
  4507. {
  4508. let span = spans
  4509. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4510. .or_insert((*address, *address + *len));
  4511. *span = (span.0.min(*address), span.1.max(*address + *len));
  4512. }
  4513. }
  4514. }
  4515. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4516. crate::watch::ask_once(&ranges);
  4517. #[cfg(feature = "diagnostics")]
  4518. split.part(0);
  4519. // Behind flights: the title wrote memory that a flight's shaders
  4520. // may write too, and this submission refreshes it. The flights
  4521. // are settled, and the asking made again: the copy-back wrote
  4522. // title memory, which other copies of it must see.
  4523. if behind && upcheck::on() {
  4524. upcheck::reads(runs);
  4525. }
  4526. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  4527. if !stale.is_empty() {
  4528. let settling = std::time::Instant::now();
  4529. self.settle_stale(&mut submitted, runs, stale, &ranges);
  4530. settled += settling.elapsed();
  4531. }
  4532. } else if behind && !stale_under_flights(runs).is_empty() {
  4533. let settling = std::time::Instant::now();
  4534. self.settle(&mut submitted, WHY_STALE);
  4535. settled += settling.elapsed();
  4536. }
  4537. #[cfg(feature = "diagnostics")]
  4538. split.part(1);
  4539. for list in runs {
  4540. list.run_deferred(&mut batch, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4541. firsts.push(lists.len());
  4542. if let Some(prelude) = list.prelude() {
  4543. lists.push(Some(prelude));
  4544. }
  4545. lists.push(list.list.cast().ok());
  4546. }
  4547. batch.flush();
  4548. crate::watch::ask_once_end();
  4549. #[cfg(feature = "diagnostics")]
  4550. split.part(2);
  4551. // The snapshots of the ranges shaders may write, if they were left
  4552. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4553. // lists have not gone to the card.
  4554. {
  4555. #[cfg(feature = "diagnostics")]
  4556. let snapshots = std::time::Instant::now();
  4557. crate::shadow::take_snapshots();
  4558. #[cfg(feature = "diagnostics")]
  4559. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4560. }
  4561. #[cfg(feature = "diagnostics")]
  4562. split.part(3);
  4563. // Copies in the card's memory: what changed on their CPU side goes
  4564. // up ahead of the lists, and a compare of what the shaders may
  4565. // write follows them in the same submission.
  4566. let flown = late && relay();
  4567. if flown && self.card_results_low() {
  4568. let settling = std::time::Instant::now();
  4569. self.settle(&mut submitted, WHY_MOST);
  4570. settled += settling.elapsed();
  4571. }
  4572. // What shaders may write through views they pick: last, so that no
  4573. // refresh of this submission leaves it alone.
  4574. let picked = crate::picked::declare(runs);
  4575. for (shadow, at, len) in &picked.written {
  4576. shadow.writing(*at, *len);
  4577. }
  4578. let card = self.card_before(runs, &picked, flown);
  4579. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4580. lists.push(Some(check));
  4581. }
  4582. #[cfg(feature = "diagnostics")]
  4583. split.part(4);
  4584. let prepared = std::time::Instant::now();
  4585. if late {
  4586. *submitted += 1;
  4587. // SAFETY: closed lists; the fence is ours.
  4588. let signalled = unsafe {
  4589. self.queue.ExecuteCommandLists(&lists);
  4590. self.queue.Signal(&self.fence, *submitted)
  4591. };
  4592. self.card_sent();
  4593. if let Err(e) = signalled {
  4594. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4595. }
  4596. #[cfg(feature = "diagnostics")]
  4597. split.part(5);
  4598. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4599. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4600. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4601. submitting(0, 0);
  4602. #[cfg(feature = "diagnostics")]
  4603. crate::copystat::submission_ends(lock);
  4604. let sent = Sent {
  4605. number: this_submission,
  4606. card,
  4607. back,
  4608. own,
  4609. writes,
  4610. };
  4611. working(was_working);
  4612. return Some((submitted, sent));
  4613. }
  4614. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4615. #[cfg(feature = "diagnostics")]
  4616. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4617. firsts
  4618. .iter()
  4619. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4620. .map(|(&a, &b)| &lists[a..b])
  4621. .collect()
  4622. } else {
  4623. vec![&lists[..]]
  4624. };
  4625. #[cfg(not(feature = "diagnostics"))]
  4626. let groups = [&lists[..]];
  4627. submitting(2, runs.len());
  4628. for (i, group) in groups.iter().enumerate() {
  4629. *submitted += 1;
  4630. let started = std::time::Instant::now();
  4631. // SAFETY: closed lists; the fence and event are ours.
  4632. unsafe {
  4633. self.queue.ExecuteCommandLists(group);
  4634. self.card_sent();
  4635. let waited = self
  4636. .queue
  4637. .Signal(&self.fence, *submitted)
  4638. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4639. match waited {
  4640. Ok(()) => {
  4641. working(false);
  4642. WaitForSingleObject(self.event, INFINITE);
  4643. stood(started);
  4644. working(true);
  4645. }
  4646. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4647. }
  4648. }
  4649. // With timing on each group is one of `runs` (and the compare
  4650. // of copies in the card's memory, with the last): every
  4651. // command's time on the card goes to the sums by pipeline.
  4652. #[cfg(feature = "diagnostics")]
  4653. if timing() {
  4654. // SAFETY: a plain query.
  4655. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4656. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4657. crate::copystat::command_took(&op, ms);
  4658. }
  4659. }
  4660. // A submission of one list was never named here (`groups.len()
  4661. // > 1` was the test): the two 50 ms lists of the gameplay
  4662. // frame, each a submission of its own, printed nothing.
  4663. #[cfg(feature = "diagnostics")]
  4664. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4665. // SAFETY: a plain query.
  4666. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4667. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4668. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4669. for (ms, op) in runs[i].slowest(frequency, 6) {
  4670. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4671. }
  4672. }
  4673. let _ = (i, started);
  4674. }
  4675. let _ = &firsts;
  4676. FINISHED.store(this_submission, Ordering::Release);
  4677. bury(this_submission);
  4678. let gpu = prepared.elapsed();
  4679. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4680. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4681. #[cfg(feature = "diagnostics")]
  4682. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4683. let pipelines: std::collections::BTreeSet<String> = runs
  4684. .iter()
  4685. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4686. .collect();
  4687. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  4688. text.chars().take(1200).collect()
  4689. });
  4690. // The host resets a device whose submission runs for about 2 s.
  4691. if gpu > std::time::Duration::from_millis(250) {
  4692. let pipelines: std::collections::BTreeSet<String> = runs
  4693. .iter()
  4694. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4695. .collect();
  4696. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  4697. }
  4698. // SAFETY: a plain query.
  4699. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4700. fail(format_args!(
  4701. "host GPU device removed after a submission of {} lists{}{}",
  4702. runs.len(),
  4703. self.removal_data(runs),
  4704. last_notes(runs)
  4705. ));
  4706. }
  4707. submitting(3, runs.len());
  4708. // What shaders wrote goes back before the bottom-of-pipe writes,
  4709. // which tell the title the GPU is done; each range once per
  4710. // submission, however many dispatches declared it (the world's
  4711. // passes declare the same big ranges dozens of times).
  4712. let copying = std::time::Instant::now();
  4713. // For copies in the card's memory the compare has run there: the
  4714. // pieces that differ are fetched and merged.
  4715. if let Some(card) = &card {
  4716. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  4717. }
  4718. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4719. hand_back(&back);
  4720. if let Some(card) = card {
  4721. self.card_done(card);
  4722. }
  4723. #[cfg(feature = "diagnostics")]
  4724. if !back.is_empty() {
  4725. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  4726. }
  4727. // Nothing of this submission goes back to the title: no range of
  4728. // shader writes, no value written when it is done. The wait for
  4729. // such a one is only for order and for what the card still holds.
  4730. #[cfg(feature = "diagnostics")]
  4731. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  4732. use crate::copystat::{C, add};
  4733. add(C::NothingBack, 1);
  4734. add(C::NothingBackUs, gpu.as_micros() as u64);
  4735. }
  4736. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4737. for list in runs {
  4738. // Read backs first: a value written at the bottom of the pipe
  4739. // may be what tells the title that they are there.
  4740. read_backs(list);
  4741. for &(at, what, bytes) in &list.deferred().writes {
  4742. what.write(at as *mut u8, bytes);
  4743. }
  4744. }
  4745. self.log_messages();
  4746. submitting(0, 0);
  4747. #[cfg(feature = "diagnostics")]
  4748. crate::copystat::submission_ends(lock);
  4749. // With the relay: nothing is in the air now, so no fetch still to
  4750. // be merged is older than the sends to card copies so far, and
  4751. // their notes can go.
  4752. if relay() {
  4753. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  4754. }
  4755. working(was_working);
  4756. None
  4757. }
  4758. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  4759. /// it lies in (by the names we give them) or the title memory copy just
  4760. /// below it; for each list that did not finish, the command it stopped
  4761. /// at and what the draws and dispatches in flight there run (or, in
  4762. /// lists that never started, the pipelines they bind).
  4763. fn removal_data(&self, runs: &[&HostList]) -> String {
  4764. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  4765. return String::new();
  4766. };
  4767. let mut text = String::new();
  4768. let mut fault_va = None;
  4769. // SAFETY: the outputs are the runtime's, valid while the device
  4770. // lives; nodes are walked as linked, histories have their counts.
  4771. unsafe {
  4772. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  4773. && fault.PageFaultVA != 0
  4774. {
  4775. let va = fault.PageFaultVA;
  4776. fault_va = Some(va);
  4777. text.push_str(&format!("; page fault at {va:#x}"));
  4778. for (what, head) in [
  4779. ("inside", fault.pHeadExistingAllocationNode),
  4780. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  4781. ] {
  4782. let mut names = Vec::new();
  4783. let mut node = head;
  4784. while let Some(n) = node.as_ref()
  4785. && names.len() < 8
  4786. {
  4787. let name = if n.ObjectNameW.is_null() {
  4788. "unnamed".to_owned()
  4789. } else {
  4790. n.ObjectNameW.to_string().unwrap_or_default()
  4791. };
  4792. names.push(format!("{name} (type {})", n.AllocationType.0));
  4793. node = n.pNext;
  4794. }
  4795. if !names.is_empty() {
  4796. text.push_str(&format!("; {what} {names:?}"));
  4797. }
  4798. }
  4799. text.push_str(&crate::shadow::near(va));
  4800. text.push_str(&crate::descriptor::host::near_heaps(va));
  4801. }
  4802. // The plain output: the extended one (with marker texts) came
  4803. // back without stopped lists on this host.
  4804. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  4805. Ok(crumbs) => crumbs,
  4806. Err(e) => {
  4807. text.push_str(&format!("; no breadcrumbs ({e})"));
  4808. return text;
  4809. }
  4810. };
  4811. // Every list's progress (done/count), in the runtime's order.
  4812. let mut progress = Vec::new();
  4813. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  4814. while let Some(p) = node.as_ref() {
  4815. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4816. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  4817. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  4818. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  4819. node = p.pNext;
  4820. }
  4821. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  4822. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  4823. while let Some(p) = plain.as_ref() {
  4824. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4825. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  4826. let history =
  4827. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  4828. text.push_str(&format!(
  4829. "; a list stopped at command {done} of {} (op {})",
  4830. p.BreadcrumbCount, history[done as usize].0
  4831. ));
  4832. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  4833. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  4834. // The k-th marker command is the k-th note.
  4835. #[cfg(feature = "diagnostics")]
  4836. let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| {
  4837. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  4838. history
  4839. .iter()
  4840. .enumerate()
  4841. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  4842. .zip(notes.iter())
  4843. .map(|((at, _), (note, range))| {
  4844. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  4845. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  4846. })
  4847. .collect()
  4848. });
  4849. #[cfg(not(feature = "diagnostics"))]
  4850. let markers: Vec<(u32, String)> = Vec::new();
  4851. #[cfg(not(feature = "diagnostics"))]
  4852. let _ = fault_va;
  4853. if done > 0 {
  4854. text.push_str(&in_flight(history, &markers, done as usize));
  4855. } else if let Some(r) = run {
  4856. let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  4857. text.push_str(&format!(", its pipelines {pipelines:?}"));
  4858. }
  4859. }
  4860. plain = p.pNext;
  4861. }
  4862. }
  4863. text
  4864. }
  4865. /// Moves the debug layer's messages into our log; returns the first
  4866. /// error among them.
  4867. pub(crate) fn log_messages(&self) -> Option<String> {
  4868. let Some(queue) = &self.messages else {
  4869. return None;
  4870. };
  4871. let mut first_error = None;
  4872. // SAFETY: each message is read into a buffer of the size the queue
  4873. // reports, then the queue is emptied.
  4874. unsafe {
  4875. for i in 0..queue.GetNumStoredMessages() {
  4876. let mut size = 0;
  4877. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  4878. continue;
  4879. }
  4880. let mut buffer = vec![0u64; size.div_ceil(8)];
  4881. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  4882. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  4883. let m = &*message;
  4884. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  4885. let text = String::from_utf8_lossy(text);
  4886. let text = text.trim_end_matches('\0');
  4887. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  4888. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  4889. first_error = Some(text.to_owned());
  4890. }
  4891. }
  4892. }
  4893. queue.ClearStoredMessages();
  4894. }
  4895. first_error
  4896. }
  4897. /// A host render target view of `resource`, valid until it is recorded.
  4898. pub(crate) fn rtv(
  4899. &self,
  4900. resource: Option<&ID3D12Resource>,
  4901. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  4902. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4903. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4904. // SAFETY: a slot of our heap and a live resource, or none with a
  4905. // description (a typed null view).
  4906. unsafe {
  4907. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  4908. handle.ptr += (slot * self.rtv_size) as usize;
  4909. self.device
  4910. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  4911. handle
  4912. }
  4913. }
  4914. /// A host depth view of `resource`, valid until it is recorded.
  4915. pub(crate) fn dsv(
  4916. &self,
  4917. resource: &ID3D12Resource,
  4918. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  4919. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4920. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4921. // SAFETY: a slot of our heap and a live resource.
  4922. unsafe {
  4923. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  4924. handle.ptr += (slot * self.dsv_size) as usize;
  4925. self.device
  4926. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  4927. handle
  4928. }
  4929. }
  4930. }
  4931. impl HostList {
  4932. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  4933. #[cfg(feature = "diagnostics")]
  4934. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  4935. if !timing() {
  4936. return None;
  4937. }
  4938. self.stamps
  4939. .get_or_init(|| {
  4940. let device = &host()?.device;
  4941. let mut heap: Option<ID3D12QueryHeap> = None;
  4942. let mut back: Option<ID3D12Resource> = None;
  4943. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  4944. let desc = D3D12_RESOURCE_DESC {
  4945. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  4946. Width: u64::from(STAMPS) * 8,
  4947. Height: 1,
  4948. DepthOrArraySize: 1,
  4949. MipLevels: 1,
  4950. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  4951. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  4952. ..Default::default()
  4953. };
  4954. // SAFETY: plain object creation.
  4955. unsafe {
  4956. device
  4957. .CreateQueryHeap(
  4958. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  4959. &mut heap,
  4960. )
  4961. .ok()?;
  4962. device
  4963. .CreateCommittedResource(
  4964. &readback,
  4965. D3D12_HEAP_FLAG_NONE,
  4966. &desc,
  4967. D3D12_RESOURCE_STATE_COPY_DEST,
  4968. None,
  4969. &mut back,
  4970. )
  4971. .ok()?;
  4972. }
  4973. Some((heap?, back?))
  4974. })
  4975. .as_ref()
  4976. }
  4977. /// The noted commands that took longest on the GPU, longest first, as
  4978. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  4979. #[cfg(feature = "diagnostics")]
  4980. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  4981. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  4982. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  4983. return Vec::new();
  4984. };
  4985. let mut data = std::ptr::null_mut();
  4986. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  4987. // SAFETY: a read-back buffer the finished list resolved into.
  4988. let stamps: Vec<u64> = unsafe {
  4989. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  4990. return Vec::new();
  4991. }
  4992. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  4993. back.Unmap(0, None);
  4994. s
  4995. };
  4996. let mut times: Vec<(f64, String)> = (0..count)
  4997. .map(|i| {
  4998. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  4999. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5000. })
  5001. .collect();
  5002. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5003. times.truncate(n);
  5004. times
  5005. }
  5006. pub(crate) fn close(&self) {
  5007. self.twins_to_depth();
  5008. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5009. if let Some((scratch, _)) = scratch {
  5010. self.indirect_common(&scratch);
  5011. }
  5012. self.batches_common();
  5013. self.card_budget_out();
  5014. #[cfg(feature = "diagnostics")]
  5015. if let Some((heap, back)) = self.stamps() {
  5016. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5017. // SAFETY: an open list, our heap and read-back buffer.
  5018. unsafe {
  5019. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5020. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5021. }
  5022. }
  5023. // SAFETY: our list.
  5024. if let Err(e) = unsafe { self.list.Close() } {
  5025. fail(format_args!(
  5026. "a host command list did not close ({e}): a command recorded into it was invalid"
  5027. ));
  5028. }
  5029. }
  5030. /// Only after the list's last submission finished (every one is waited
  5031. /// for).
  5032. pub(crate) fn reset(&self) {
  5033. #[cfg(feature = "diagnostics")]
  5034. let started = std::time::Instant::now();
  5035. self._alive.used();
  5036. *self.deferred() = Deferred::default();
  5037. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5038. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5039. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5040. #[cfg(feature = "diagnostics")]
  5041. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5042. {
  5043. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5044. (scratch.current, scratch.used) = (0, 0);
  5045. // Every submission of the list has run: nothing reads its
  5046. // scratch memory any more, and the next list to ask takes it.
  5047. if scratch_pool() {
  5048. give_chunks(std::mem::take(&mut scratch.chunks));
  5049. }
  5050. }
  5051. // SAFETY: the list is not executing.
  5052. let reset = unsafe {
  5053. self.allocator
  5054. .Reset()
  5055. .and_then(|()| self.list.Reset(&self.allocator, None))
  5056. };
  5057. if let Err(e) = reset {
  5058. fail(format_args!("a host command list did not reset ({e})"));
  5059. }
  5060. #[cfg(feature = "diagnostics")]
  5061. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5062. }
  5063. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5064. /// list: the host texture and the state it leaves, if that is a change.
  5065. /// The list's first use of a texture records nothing: its prelude brings
  5066. /// the texture there at submission.
  5067. pub(crate) fn transition(
  5068. &self,
  5069. resource: crate::object::This,
  5070. wanted: u32,
  5071. ) -> Option<(&'static ID3D12Resource, u32)> {
  5072. let texture = crate::resource::host_resource(resource)?;
  5073. let copy = crate::resource::host_copy(resource)?;
  5074. let wanted = legal_state(texture, wanted);
  5075. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5076. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5077. std::collections::hash_map::Entry::Vacant(v) => {
  5078. v.insert((wanted, wanted, copy));
  5079. None
  5080. }
  5081. std::collections::hash_map::Entry::Occupied(mut o) => {
  5082. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5083. (before != wanted).then_some((texture, before))
  5084. }
  5085. }
  5086. }
  5087. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5088. /// as [`HostList::transition`] does a title resource's host copy, and
  5089. /// records the barrier: for textures that are not a title resource's
  5090. /// host copy (colour twins) and for the copies between the two.
  5091. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5092. let wanted = legal_state(&copy.texture, wanted);
  5093. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5094. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5095. std::collections::hash_map::Entry::Vacant(v) => {
  5096. v.insert((wanted, wanted, copy.clone()));
  5097. None
  5098. }
  5099. std::collections::hash_map::Entry::Occupied(mut o) => {
  5100. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5101. (before != wanted).then_some(before)
  5102. }
  5103. };
  5104. drop(states);
  5105. if let Some(before) = before {
  5106. let barrier = transition(
  5107. &copy.texture,
  5108. D3D12_RESOURCE_STATES(before as i32),
  5109. D3D12_RESOURCE_STATES(wanted as i32),
  5110. );
  5111. // SAFETY: an open list and a live texture.
  5112. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5113. }
  5114. }
  5115. /// A use of title texture `resource` about to be recorded, if it is a
  5116. /// depth texture with a colour twin (false if it is not): of the twin
  5117. /// (`colour`: unordered access) or of the depth texture (depth target,
  5118. /// clear, shader read, copy, resolve), writing it or only reading. The
  5119. /// side used is first brought up to date: by a copy recorded here if
  5120. /// this list wrote the other side since, by the list's prelude if the
  5121. /// list uses the side as it finds it. The twin is left in the
  5122. /// unordered access state; the caller moves the depth texture to the
  5123. /// state its use needs, as for any texture. A twin still ahead when the
  5124. /// list closes is copied then (`twins_to_depth`).
  5125. /// shortcut: every depth target bound for a draw counts as written
  5126. /// (also when the draw only tests), and every unordered access view a
  5127. /// shader names as written; views a shader picks from the heap by a
  5128. /// computed index are not seen here at all.
  5129. pub(crate) fn twin_use(
  5130. &self,
  5131. resource: crate::object::This,
  5132. colour: bool,
  5133. write: bool,
  5134. ) -> bool {
  5135. const UNORDERED_ACCESS: u32 = 0x8;
  5136. // Asked for every texture a draw reads: most have no twin.
  5137. let Some(twin) = crate::resource::twin(resource) else {
  5138. return false;
  5139. };
  5140. let Some(depth) = crate::resource::host_copy(resource) else {
  5141. return false;
  5142. };
  5143. let side = usize::from(colour);
  5144. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5145. let u = twins
  5146. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5147. .or_insert_with(|| TwinUse {
  5148. depth: depth.clone(),
  5149. twin: twin.clone(),
  5150. needs: [false; 2],
  5151. behind: [None; 2],
  5152. writing: false,
  5153. late: false,
  5154. });
  5155. let copy = match u.behind[side] {
  5156. Some(behind) => behind,
  5157. None => {
  5158. u.needs[side] = true;
  5159. false
  5160. }
  5161. };
  5162. u.behind[side] = Some(false);
  5163. match (write, colour) {
  5164. // Shaders write the twin when the draw or dispatch runs: what
  5165. // the same one reads of the depth texture is prepared before
  5166. // (`twins_written`).
  5167. (true, true) => u.writing = true,
  5168. (true, false) => u.behind[1] = Some(true),
  5169. (false, _) => {}
  5170. }
  5171. // shortcut: the depth plane's twin is not drawn into the plane
  5172. // here: the pass sets a pipeline and a target of ours, which a list
  5173. // still recording the title's commands cannot take. This use sees
  5174. // the plane as it was; the pass runs when the list closes
  5175. // (`twins_to_depth`). Counted.
  5176. if copy && !colour && twin.plane.is_some() {
  5177. u.late = true;
  5178. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5179. }
  5180. drop(twins);
  5181. if copy {
  5182. self.twin_copy(&depth, &twin, colour);
  5183. } else if colour {
  5184. self.settle(&twin.colour, UNORDERED_ACCESS);
  5185. }
  5186. // The depth plane's twin is written through unordered access too.
  5187. if colour && let Some(plane) = &twin.plane {
  5188. self.settle(plane, UNORDERED_ACCESS);
  5189. }
  5190. true
  5191. }
  5192. /// Records the pass that draws the twin of the depth plane of `depth`
  5193. /// into the plane, if `twin` has one, with the moves to the states the
  5194. /// pass needs; the twin is left in the unordered access state. Only
  5195. /// for a list that records nothing of the title's afterwards
  5196. /// (`record_plane_pass`).
  5197. fn pass_plane(
  5198. &self,
  5199. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5200. twin: &crate::resource::Twin,
  5201. ) {
  5202. const UNORDERED_ACCESS: u32 = 0x8;
  5203. const DEPTH_WRITE: u32 = 0x10;
  5204. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5205. let Some(plane) = &twin.plane else { return };
  5206. self.settle(depth, DEPTH_WRITE);
  5207. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5208. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5209. self.settle(plane, UNORDERED_ACCESS);
  5210. }
  5211. /// Records the copy of a depth texture into its colour twin (`colour`)
  5212. /// or of the twin into the depth texture, with the moves to the copy
  5213. /// states. The twin is left in the unordered access state.
  5214. fn twin_copy(
  5215. &self,
  5216. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5217. twin: &crate::resource::Twin,
  5218. colour: bool,
  5219. ) {
  5220. const UNORDERED_ACCESS: u32 = 0x8;
  5221. const COPY_DEST: u32 = 0x400;
  5222. const COPY_SOURCE: u32 = 0x800;
  5223. let (from, to) = if colour {
  5224. (depth, &twin.colour)
  5225. } else {
  5226. (&twin.colour, depth)
  5227. };
  5228. self.settle(from, COPY_SOURCE);
  5229. self.settle(to, COPY_DEST);
  5230. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5231. self.settle(&twin.colour, UNORDERED_ACCESS);
  5232. }
  5233. /// Before the list closes: the depth textures whose twins it wrote last
  5234. /// are given what was written, and left readable by shaders. Shaders
  5235. /// that pick a view from the heap by a computed index are not seen by
  5236. /// `twin_use` and read the depth texture in lists that never name it
  5237. /// (in a captured frame of the title no table names a shadow
  5238. /// map for reading but the pass that fills the next one).
  5239. fn twins_to_depth(&self) {
  5240. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5241. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5242. let written: Vec<_> = twins
  5243. .values_mut()
  5244. .filter(|u| u.behind[0] == Some(true) || u.late)
  5245. .map(|u| {
  5246. // Not copied again if the list copied since the last write
  5247. // and only the depth plane's pass is left.
  5248. let copy = u.behind[0] == Some(true);
  5249. u.behind[0] = Some(false);
  5250. u.late = false;
  5251. (u.depth.clone(), u.twin.clone(), copy)
  5252. })
  5253. .collect();
  5254. drop(twins);
  5255. for (depth, twin, copy) in &written {
  5256. if *copy {
  5257. self.twin_copy(depth, twin, false);
  5258. }
  5259. // Nothing of the title's is recorded after this: the pass may
  5260. // leave its own pipeline and target set.
  5261. self.pass_plane(depth, twin);
  5262. self.settle(depth, SHADER_RESOURCE);
  5263. }
  5264. }
  5265. /// The draw or dispatch just prepared is recorded: the twins it writes
  5266. /// now hold what their depth textures lack.
  5267. pub(crate) fn twins_written(&self) {
  5268. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5269. for u in twins.values_mut().filter(|u| u.writing) {
  5270. u.writing = false;
  5271. u.behind[0] = Some(true);
  5272. }
  5273. }
  5274. /// At submission: the list that moves each texture this list uses from
  5275. /// its real state to the one the list starts with; the textures' real
  5276. /// states become those the list ends with. For depth textures with a
  5277. /// colour twin it first copies the side the list uses as it finds it
  5278. /// from the other, if a list submitted earlier left it behind.
  5279. fn prelude(&self) -> Option<ID3D12CommandList> {
  5280. const COPY_DEST: u32 = 0x400;
  5281. const COPY_SOURCE: u32 = 0x800;
  5282. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5283. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5284. // The copies (depth texture, twin, whether into the twin); the
  5285. // sides are then as this list leaves them.
  5286. let mut syncs = Vec::new();
  5287. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5288. for u in twins.values() {
  5289. let real = u.twin.behind.load(Ordering::Relaxed);
  5290. let mut behind = [real & 1 != 0, real & 2 != 0];
  5291. for side in [0, 1] {
  5292. if u.needs[side] && behind[side] {
  5293. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5294. behind = [false; 2];
  5295. }
  5296. }
  5297. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5298. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5299. u.twin.behind.store(left, Ordering::Relaxed);
  5300. }
  5301. drop(twins);
  5302. // A copy runs with its textures in the copy states: each moves
  5303. // there from its real state, and from there to the state the list
  5304. // starts with (back to its real state if the list does not use it).
  5305. let mut to_copy = Vec::new();
  5306. let mut barriers = Vec::new();
  5307. let mut copying = std::collections::HashMap::new();
  5308. for (depth, twin, colour) in &syncs {
  5309. let (from, to) = if *colour {
  5310. (depth, &twin.colour)
  5311. } else {
  5312. (&twin.colour, depth)
  5313. };
  5314. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  5315. let key = std::sync::Arc::as_ptr(texture) as usize;
  5316. let real = texture.state.load(Ordering::Relaxed);
  5317. copying.insert(key, state);
  5318. if real != state {
  5319. to_copy.push(transition(
  5320. &texture.texture,
  5321. host_state(real),
  5322. host_state(state),
  5323. ));
  5324. if !states.contains_key(&key) {
  5325. barriers.push(transition(
  5326. &texture.texture,
  5327. host_state(state),
  5328. host_state(real),
  5329. ));
  5330. }
  5331. }
  5332. }
  5333. }
  5334. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5335. let real = copy.state.swap(*last, Ordering::Relaxed);
  5336. let real = copying.get(key).copied().unwrap_or(real);
  5337. (real != *first)
  5338. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5339. }));
  5340. if barriers.is_empty() && syncs.is_empty() {
  5341. return None;
  5342. }
  5343. let Some((allocator, list)) = self
  5344. .prelude
  5345. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5346. .as_ref()
  5347. else {
  5348. fail(format_args!("no host list for a state prelude"));
  5349. };
  5350. // SAFETY: the prelude is not executing (every submission is waited
  5351. // for); the textures are live.
  5352. let recorded = unsafe {
  5353. allocator.Reset().and_then(|()| {
  5354. list.Reset(allocator, None)?;
  5355. if !to_copy.is_empty() {
  5356. list.ResourceBarrier(&to_copy);
  5357. }
  5358. for (depth, twin, colour) in &syncs {
  5359. record_twin_copy(list, &depth.texture, twin, *colour);
  5360. }
  5361. if !barriers.is_empty() {
  5362. list.ResourceBarrier(&barriers);
  5363. }
  5364. list.Close()
  5365. })
  5366. };
  5367. if let Err(e) = recorded {
  5368. fail(format_args!("a host state prelude did not record ({e})"));
  5369. }
  5370. list.cast().ok()
  5371. }
  5372. /// Notes what the command about to be recorded does, as a marker
  5373. /// command whose text the list keeps (diagnostics, with device-removed
  5374. /// data on): the report pairs the breadcrumbs' marker commands with the
  5375. /// texts in order and names the commands a fault stopped among.
  5376. #[cfg(feature = "diagnostics")]
  5377. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5378. self.note(what, None);
  5379. }
  5380. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5381. /// `(address, bytes)`: the report places the faulting address in it.
  5382. #[cfg(feature = "diagnostics")]
  5383. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5384. self.note(what, Some(range));
  5385. }
  5386. #[cfg(feature = "diagnostics")]
  5387. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5388. if !dred_on() {
  5389. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5390. return;
  5391. }
  5392. {
  5393. let started = std::time::Instant::now();
  5394. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5395. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5396. // SAFETY: an open list and our query heap.
  5397. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5398. }
  5399. let what = what();
  5400. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5401. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5402. const UNICODE: u32 = 0;
  5403. // SAFETY: an open list; the marker is copied when recorded.
  5404. unsafe {
  5405. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5406. };
  5407. self.notes
  5408. .lock()
  5409. .unwrap_or_else(|e| e.into_inner())
  5410. .push((what, range));
  5411. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5412. }
  5413. }
  5414. /// Whether nothing recorded since the list was opened does any work:
  5415. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5416. /// upload or resolve (they defer a step or move a texture's state), no
  5417. /// bottom-of-pipe write. State set on the list does not count.
  5418. pub(crate) fn untouched(&self) -> bool {
  5419. {
  5420. let deferred = self.deferred();
  5421. if !(deferred.copies.is_empty()
  5422. && deferred.uploads.is_empty()
  5423. && deferred.kept.is_empty()
  5424. && deferred.textures.is_empty()
  5425. && deferred.writes.is_empty()
  5426. && deferred.backs.is_empty())
  5427. {
  5428. return false;
  5429. }
  5430. }
  5431. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5432. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5433. }
  5434. /// Notes a pipeline the list binds.
  5435. pub(crate) fn used_pipeline(&self, name: &str) {
  5436. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5437. if !pipelines.contains(name) {
  5438. pipelines.insert(name.to_owned());
  5439. }
  5440. }
  5441. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5442. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5443. }
  5444. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5445. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5446. let mut deferred = self.deferred();
  5447. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5448. // A copy that goes on where the one recorded just before it ended,
  5449. // source and destination both: with `join_copies` the two are one
  5450. // step.
  5451. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5452. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5453. {
  5454. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5455. if join_copies() {
  5456. *n += len;
  5457. return;
  5458. }
  5459. }
  5460. deferred
  5461. .copies
  5462. .push(Step::Copy(dst as usize, src as usize, len));
  5463. deferred.refreshed.clear();
  5464. }
  5465. /// Copies `len` bytes of title memory at `src` into the list's upload
  5466. /// memory at `dst` when the list is submitted.
  5467. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5468. self.deferred()
  5469. .copies
  5470. .push(Step::Fill(dst as usize, src as usize, len, None));
  5471. }
  5472. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5473. /// title heap's address, and the slot) shows.
  5474. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5475. self.deferred()
  5476. .copies
  5477. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  5478. }
  5479. /// As [`HostList::defer_fill`], for the beginning of a buffer
  5480. /// [`HostList::upload`] made.
  5481. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  5482. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  5483. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  5484. }
  5485. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5486. /// when the list is submitted (once per range until a title copy
  5487. /// intervenes), keeping the copy alive until the list is reset.
  5488. pub(crate) fn defer_refresh(
  5489. &self,
  5490. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5491. address: usize,
  5492. len: usize,
  5493. ) {
  5494. let mut deferred = self.deferred();
  5495. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5496. if deferred.refreshed.insert(key) {
  5497. deferred
  5498. .copies
  5499. .push(Step::Refresh(shadow.clone(), address, len));
  5500. }
  5501. }
  5502. /// Shaders of the list write `[address, address + len)` of a buffer's
  5503. /// host copy: copied back into title memory once the list has run.
  5504. pub(crate) fn defer_gpu_write(
  5505. &self,
  5506. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5507. address: usize,
  5508. len: usize,
  5509. ) {
  5510. self.deferred()
  5511. .copies
  5512. .push(Step::GpuWrite(shadow.clone(), address, len));
  5513. }
  5514. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5515. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5516. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5517. /// the list is reset.
  5518. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5519. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5520. }
  5521. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5522. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5523. self.deferred().writes.push((dst as usize, what, bytes));
  5524. }
  5525. /// A mapped upload buffer of `size` bytes, alive until the list is
  5526. /// reset.
  5527. ///
  5528. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5529. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5530. // With [`card_steps`] the card may be the one that fills it.
  5531. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  5532. name(&buffer, || format!("list upload {size:#x}"));
  5533. self.deferred().hold_upload(buffer.clone(), size);
  5534. Some((buffer, data))
  5535. }
  5536. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5537. /// reset: the host GPU address and the CPU pointer.
  5538. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5539. let host = host()?;
  5540. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5541. let len = len.max(1).next_multiple_of(256);
  5542. if len > SCRATCH_CHUNK {
  5543. let (buffer, data) = host.upload_buffer(len)?;
  5544. name(&buffer, || format!("list scratch {len:#x}"));
  5545. // SAFETY: a live buffer.
  5546. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  5547. self.deferred().hold_upload(buffer, len);
  5548. return Some((gpu, data));
  5549. }
  5550. // The chunk in use while `len` fits in what is left of it, else the
  5551. // next one (a list's first chunk may be a small one).
  5552. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5553. (s.current, s.used) = (s.current + 1, 0);
  5554. }
  5555. if s.current == s.chunks.len() {
  5556. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  5557. SCRATCH_FIRST
  5558. } else {
  5559. SCRATCH_CHUNK
  5560. };
  5561. let chunk = take_chunk(host, size)?;
  5562. s.chunks.push((chunk, size));
  5563. s.used = 0;
  5564. }
  5565. let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu);
  5566. let at = s.used;
  5567. s.used += len;
  5568. Some((gpu + at, (data + at as usize) as *mut u8))
  5569. }
  5570. /// The bytes of scratch chunks the list holds now (after a reset:
  5571. /// none while lists share their chunks).
  5572. pub(crate) fn scratch_kept(&self) -> u64 {
  5573. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5574. scratch.chunks.iter().map(|c| c.1).sum()
  5575. }
  5576. /// The host address of the list's indirect-work budget, zeroed at each
  5577. /// submission of the list from the first use after a reset on.
  5578. pub(crate) fn budget(&self) -> Option<u64> {
  5579. let (buffer, data) = self
  5580. .budget
  5581. .get_or_init(|| {
  5582. let (b, d) = host()?.shared_buffer(256)?;
  5583. Some((b, d as usize))
  5584. })
  5585. .as_ref()?;
  5586. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5587. let mut deferred = self.deferred();
  5588. if !deferred.budget_zeroed {
  5589. deferred.budget_zeroed = true;
  5590. let at = *data;
  5591. // SAFETY: the list's own mapped words, written before it runs.
  5592. // The words after the budget hold what the clamp noted about the
  5593. // list's last run (mesh dispatches: the largest group count
  5594. // asked for, the groups asked in all; with the card's copy, as
  5595. // the list's end copied them here): taken, then zeroed.
  5596. let notes = Box::new(move || unsafe {
  5597. let words = at as *mut u32;
  5598. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  5599. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  5600. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  5601. for k in 0..3 {
  5602. words.add(k).write_volatile(0);
  5603. }
  5604. });
  5605. deferred.copies.push(Step::Host(notes, (0, 0)));
  5606. drop(deferred);
  5607. if let Some(card) = card {
  5608. self.zero_card_budget(card);
  5609. }
  5610. }
  5611. // SAFETY: a live buffer.
  5612. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  5613. }
  5614. /// The budget's words in the card's own memory ([`card_budget`]), if
  5615. /// the list can zero them itself (`WriteBufferImmediate`).
  5616. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  5617. if !card_budget() {
  5618. return None;
  5619. }
  5620. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  5621. let buffer = host()?.uav_buffer(256)?;
  5622. name(&buffer, || "indirect budget".to_owned());
  5623. Some(buffer)
  5624. }
  5625. /// Records, before the list's first clamp, the zeroing of the card's
  5626. /// copy of the budget: common, written as a copy, then left for
  5627. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  5628. fn zero_card_budget(&self, card: &ID3D12Resource) {
  5629. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  5630. return;
  5631. };
  5632. // SAFETY: a live buffer.
  5633. let at = unsafe { card.GetGPUVirtualAddress() };
  5634. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  5635. Dest: at + offset,
  5636. Value: 0,
  5637. });
  5638. // SAFETY: an open list; the buffer is the list's own and in the
  5639. // common state at the start of every recording.
  5640. unsafe {
  5641. self.list.ResourceBarrier(&[transition(
  5642. card,
  5643. D3D12_RESOURCE_STATE_COMMON,
  5644. D3D12_RESOURCE_STATE_COPY_DEST,
  5645. )]);
  5646. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  5647. self.list.ResourceBarrier(&[transition(
  5648. card,
  5649. D3D12_RESOURCE_STATE_COPY_DEST,
  5650. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5651. )]);
  5652. }
  5653. }
  5654. /// Before the list closes, if this recording charged the card's copy
  5655. /// of the budget: its notes on mesh records go to the mapped words
  5656. /// (read at the next submission), and it goes back to common.
  5657. fn card_budget_out(&self) {
  5658. if !self.deferred().budget_zeroed {
  5659. return;
  5660. }
  5661. let (Some(Some(card)), Some(Some((mapped, _)))) =
  5662. (self.card_budget.get(), self.budget.get())
  5663. else {
  5664. return;
  5665. };
  5666. // SAFETY: an open list; both buffers are the list's own. The
  5667. // mapped one is promoted from common to the copy destination.
  5668. unsafe {
  5669. self.list.ResourceBarrier(&[transition(
  5670. card,
  5671. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5672. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5673. )]);
  5674. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  5675. self.list.ResourceBarrier(&[transition(
  5676. card,
  5677. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5678. D3D12_RESOURCE_STATE_COMMON,
  5679. )]);
  5680. }
  5681. }
  5682. /// A device-local unordered-access buffer of at least `size` bytes for
  5683. /// clamped indirect arguments, reused across executions and resets of the
  5684. /// list. Smaller buffers replaced mid-list stay alive until
  5685. /// [`HostList::reset`].
  5686. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  5687. let needed = size.max(64 << 10);
  5688. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  5689. if let Some((buffer, cap)) = &*slot
  5690. && *cap >= needed
  5691. {
  5692. return Some(buffer.clone());
  5693. }
  5694. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  5695. let alloc = prev
  5696. .saturating_mul(2)
  5697. .max(needed)
  5698. .next_multiple_of(64 << 10);
  5699. let buffer = host()?.uav_buffer(alloc)?;
  5700. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  5701. let old = slot.replace((buffer.clone(), alloc));
  5702. drop(slot);
  5703. if let Some((old_buf, _)) = old {
  5704. // It ends the list common, as every scratch buffer does.
  5705. self.indirect_common(&old_buf);
  5706. self.keep(&old_buf);
  5707. }
  5708. Some(buffer)
  5709. }
  5710. /// Where the next batch of clamped records goes: a device-local buffer
  5711. /// the list keeps from recording to recording, the batch's place in it
  5712. /// and the state the buffer is in. Every batch of a recording has a place
  5713. /// of its own: the executions before it may still read theirs.
  5714. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  5715. use crate::indirect::batch::{JOBS, SLOT};
  5716. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5717. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  5718. if buffer == args.0.len() {
  5719. let size = u64::from(BATCHES * JOBS * SLOT);
  5720. let made = host()?.uav_buffer(size)?;
  5721. name(&made, || format!("indirect batches {size:#x}"));
  5722. args.0.push(made);
  5723. }
  5724. args.1 += 1;
  5725. // (Its first batch finds it as the recording before left it:
  5726. // `batches_common`.)
  5727. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  5728. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  5729. }
  5730. /// Before the list closes: the scratch buffers of the batched clamps go
  5731. /// back to the common state, where the next recording expects them.
  5732. fn batches_common(&self) {
  5733. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5734. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  5735. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  5736. .iter()
  5737. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  5738. .collect();
  5739. if !barriers.is_empty() {
  5740. // SAFETY: an open list and live buffers this recording left in
  5741. // `INDIRECT_ARGUMENT`.
  5742. unsafe { self.list.ResourceBarrier(&barriers) };
  5743. }
  5744. }
  5745. /// Moves `scratch` back to the common state if a clamp left it readable
  5746. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  5747. /// list's first clamp expects it. Done before the list closes and before
  5748. /// a bigger scratch buffer replaces it: one barrier per list (where
  5749. /// there was one per indirect execution), and the list ends as it
  5750. /// begins however it is submitted.
  5751. fn indirect_common(&self, scratch: &ID3D12Resource) {
  5752. {
  5753. let mut deferred = self.deferred();
  5754. if deferred.indirect_readable != scratch.as_raw() as usize {
  5755. return;
  5756. }
  5757. deferred.indirect_readable = 0;
  5758. }
  5759. let barrier = transition(
  5760. scratch,
  5761. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  5762. D3D12_RESOURCE_STATE_COMMON,
  5763. );
  5764. // SAFETY: an open list and a live buffer this recording left in
  5765. // `INDIRECT_ARGUMENT`.
  5766. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5767. }
  5768. /// The state the list's indirect scratch buffer `scratch` is in at this
  5769. /// point of the recording: indirect arguments if a clamp in this
  5770. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  5771. /// common: the state a buffer is made in, and the one a recording
  5772. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  5773. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  5774. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  5775. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  5776. } else {
  5777. D3D12_RESOURCE_STATE_COMMON
  5778. }
  5779. }
  5780. /// A clamp recorded in this list left `scratch` readable as indirect
  5781. /// arguments. It stays so for every execution that reads it, until the
  5782. /// next clamp moves it back to unordered access.
  5783. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  5784. self.deferred().indirect_readable = scratch.as_raw() as usize;
  5785. }
  5786. /// Keeps `object` alive until the list is reset.
  5787. pub(crate) fn keep(&self, object: &impl Interface) {
  5788. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  5789. self.deferred().kept.push(object);
  5790. }
  5791. }
  5792. /// Whether this is the first time since the reset that the list asks
  5793. /// about `key` (a texture to bring up to date).
  5794. pub(crate) fn first_use(&self, key: usize) -> bool {
  5795. self.deferred().textures.insert(key)
  5796. }
  5797. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  5798. /// reset.
  5799. pub(crate) fn used(&self, key: usize) -> bool {
  5800. self.deferred().textures.contains(&key)
  5801. }
  5802. /// Runs `work` when the list is submitted, in order with its copies.
  5803. /// `work` may write title memory (refreshes after it copy again).
  5804. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  5805. self.deferred().copies.push(Step::Run(Box::new(work)));
  5806. self.deferred().refreshed.clear();
  5807. }
  5808. /// As [`HostList::defer`], for work that writes only host memory.
  5809. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  5810. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  5811. }
  5812. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  5813. /// memory at `from`.
  5814. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  5815. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  5816. }
  5817. /// Brings a texture's staging buffer up to date when the list is
  5818. /// submitted, keeping it alive until the list is reset.
  5819. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  5820. self.deferred().copies.push(Step::Texture(staging));
  5821. }
  5822. /// Runs the list's submission-time steps; refreshes go into `batch`
  5823. /// (the title's big buffers, a 174 MB one among them, are read by most
  5824. /// lists of a submission, through many ranges). Copies and fills that
  5825. /// `taken` names (by their place) are left out: they are done on the
  5826. /// card ([`card_steps`]).
  5827. fn run_deferred(&self, batch: &mut Batch, taken: impl Fn(usize) -> bool) {
  5828. #[cfg(feature = "diagnostics")]
  5829. use crate::copystat::{C, add};
  5830. // The time and the bytes of the copies and fills, some 13,000 a
  5831. // frame between 20,000 refreshes: summed here and added once.
  5832. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  5833. #[cfg(feature = "diagnostics")]
  5834. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  5835. for (i, step) in self.deferred().copies.iter().enumerate() {
  5836. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  5837. continue;
  5838. }
  5839. let (started, copied) = match step {
  5840. &Step::Copy(dst, src, len) => {
  5841. let started = std::time::Instant::now();
  5842. #[cfg(feature = "diagnostics")]
  5843. {
  5844. copies += 1;
  5845. }
  5846. batch.title_written();
  5847. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  5848. // With the submission's one asking: the journal learns it.
  5849. crate::watch::wrote(dst, len);
  5850. (started, len)
  5851. }
  5852. &Step::Fill(dst, src, len, _) => {
  5853. let started = std::time::Instant::now();
  5854. #[cfg(feature = "diagnostics")]
  5855. {
  5856. copies += 1;
  5857. }
  5858. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  5859. (started, len)
  5860. }
  5861. Step::Refresh(shadow, address, len) => {
  5862. #[cfg(feature = "diagnostics")]
  5863. {
  5864. refreshes += 1;
  5865. refreshed += *len as u64;
  5866. }
  5867. batch.add(shadow, *address, *len);
  5868. continue;
  5869. }
  5870. Step::Run(work) | Step::Host(work, _) => {
  5871. #[cfg(feature = "diagnostics")]
  5872. let started = std::time::Instant::now();
  5873. if matches!(step, Step::Run(_)) {
  5874. batch.title_written();
  5875. }
  5876. work();
  5877. // It wrote title memory, where is not known here: the
  5878. // submission's one asking ends, later refreshes ask anew.
  5879. if matches!(step, Step::Run(_)) {
  5880. crate::watch::ask_once_end();
  5881. }
  5882. #[cfg(feature = "diagnostics")]
  5883. {
  5884. add(C::Runs, 1);
  5885. add(C::RunUs, started.elapsed().as_micros() as u64);
  5886. }
  5887. continue;
  5888. }
  5889. Step::GpuWrite(shadow, address, len) => {
  5890. // The shaders start from the title's data: this copy's
  5891. // pending refresh first. The other copies' wait for
  5892. // the next flush of all (flushing all of them at every
  5893. // range a dispatch writes made thousands of write-watch
  5894. // askings a frame).
  5895. batch.flush_one(shadow);
  5896. #[cfg(feature = "diagnostics")]
  5897. let snapshot = std::time::Instant::now();
  5898. shadow.writing(*address, *len);
  5899. #[cfg(feature = "diagnostics")]
  5900. {
  5901. add(C::GpuWrites, 1);
  5902. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  5903. }
  5904. continue;
  5905. }
  5906. Step::Texture(staging) => {
  5907. if batch.texture_due(staging) {
  5908. batch.due.push(staging.clone());
  5909. if !wide_textures() {
  5910. batch.refresh_textures();
  5911. }
  5912. }
  5913. continue;
  5914. }
  5915. };
  5916. us += started.elapsed();
  5917. bytes += copied as u64;
  5918. }
  5919. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  5920. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  5921. #[cfg(feature = "diagnostics")]
  5922. {
  5923. add(C::Copies, copies);
  5924. add(C::CopyBytes, bytes);
  5925. add(C::Refreshes, refreshes);
  5926. add(C::RefreshBytes, refreshed);
  5927. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  5928. }
  5929. }
  5930. }
  5931. /// A table by a copy's address.
  5932. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  5933. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  5934. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  5935. /// but our own.
  5936. #[derive(Default)]
  5937. pub(crate) struct AddressHash(u64);
  5938. impl std::hash::Hasher for AddressHash {
  5939. fn finish(&self) -> u64 {
  5940. self.0
  5941. }
  5942. fn write(&mut self, bytes: &[u8]) {
  5943. for &b in bytes {
  5944. self.write_usize(usize::from(b));
  5945. }
  5946. }
  5947. fn write_usize(&mut self, n: usize) {
  5948. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  5949. self.0 = h ^ (h >> 32);
  5950. }
  5951. }
  5952. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  5953. /// preparing: the write-watch asking for a submission; the title's bytes put
  5954. /// in under flights' writes; the lists' steps, the refreshes among them; the
  5955. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  5956. /// of the steps: the refreshes, and the copies and fills (those with the
  5957. /// refreshes a copy of title memory flushes).
  5958. #[cfg(feature = "diagnostics")]
  5959. static SPLIT: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  5960. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  5961. /// those known to copy nothing, and those done on several threads.
  5962. #[cfg(feature = "diagnostics")]
  5963. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  5964. /// Counts into [`SPLIT`].
  5965. #[cfg(feature = "diagnostics")]
  5966. struct Split(std::cell::Cell<std::time::Instant>);
  5967. #[cfg(feature = "diagnostics")]
  5968. impl Split {
  5969. fn begin() -> Split {
  5970. Split(std::cell::Cell::new(std::time::Instant::now()))
  5971. }
  5972. /// What came since the last part was part `i`.
  5973. fn part(&self, i: usize) {
  5974. let now = std::time::Instant::now();
  5975. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  5976. }
  5977. }
  5978. /// The split of the preparing, per frame, for the frame-rate line.
  5979. #[cfg(feature = "diagnostics")]
  5980. fn split_line(frames: f64) {
  5981. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  5982. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  5983. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  5984. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  5985. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect();
  5986. tracing::info!(
  5987. "preparing per frame, the submitting thread: {:.1} ms asking the write watch, {:.1} putting the title's bytes under flights' \
  5988. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  5989. several threads; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \
  5990. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
  5991. ms[0],
  5992. ms[1],
  5993. ms[2],
  5994. ms[6],
  5995. f[0],
  5996. f[1],
  5997. f[2],
  5998. f[3],
  5999. ms[7],
  6000. ms[3],
  6001. ms[4],
  6002. ms[5],
  6003. if crate::watch::light() { "on" } else { "off" },
  6004. );
  6005. tracing::info!(
  6006. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB; view ranges: {:.0} answered by their \
  6007. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6008. waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \
  6009. as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)",
  6010. a[0],
  6011. a[1] / 1024.0,
  6012. a[2],
  6013. a[3],
  6014. a[4],
  6015. a[5],
  6016. a[6],
  6017. a[7] / 1e6,
  6018. a[8] / 1e6,
  6019. s[0],
  6020. s[1],
  6021. s[2],
  6022. );
  6023. tracing::info!(
  6024. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures",
  6025. h[0],
  6026. h[1],
  6027. h[2],
  6028. );
  6029. }
  6030. /// Whether a submission's refreshes of host copies run on several threads,
  6031. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6032. ///
  6033. /// A submission brings some sixty copies up to date, one after the other
  6034. /// on the submitting thread: for each, the pages the title wrote are asked
  6035. /// for and read through the kernel into the copy. That is the frame line's
  6036. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6037. /// another: each refresh writes its own copy and its own notes, and reads
  6038. /// title memory. With the switch the copies of a flush (four or more) are
  6039. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6040. /// The write-watch journal and the guards are behind their own locks, as
  6041. /// they are for the title's threads.
  6042. fn wide_refresh() -> bool {
  6043. static ON: OnceLock<bool> = OnceLock::new();
  6044. *ON.get_or_init(|| {
  6045. wide_refresh_enabled(
  6046. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6047. std::thread::available_parallelism().ok().map(|n| n.get()),
  6048. )
  6049. })
  6050. }
  6051. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6052. match setting {
  6053. Some("1") => true,
  6054. Some("0") => false,
  6055. _ => logical_cpus.is_some_and(|n| n >= 4),
  6056. }
  6057. }
  6058. #[cfg(test)]
  6059. mod wide_refresh_tests {
  6060. use super::wide_refresh_enabled;
  6061. #[test]
  6062. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6063. assert!(wide_refresh_enabled(None, Some(4)));
  6064. assert!(wide_refresh_enabled(None, Some(16)));
  6065. assert!(!wide_refresh_enabled(None, Some(2)));
  6066. assert!(!wide_refresh_enabled(None, None));
  6067. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6068. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6069. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6070. }
  6071. }
  6072. /// A submission's refreshes not done yet, merged per buffer copy into the
  6073. /// range that covers them: done before a step that writes title memory or
  6074. /// gives a range to shaders, and before the lists run.
  6075. ///
  6076. /// Also the textures brought up to date in the submission so far: most
  6077. /// lists of a world submission sample the same textures, and a texture in
  6078. /// physical-page memory is hashed whole each time it is checked. Checked
  6079. /// once, it is checked again only after a step that writes title memory.
  6080. #[derive(Default)]
  6081. struct Batch {
  6082. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6083. /// Where each copy (by address) is in `refreshes`: the list that makes
  6084. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6085. /// for every refresh of a submission was tens of millions of
  6086. /// comparisons a frame.
  6087. index: ByCopy<usize>,
  6088. /// Staging buffers (by address) refreshed since the last title write,
  6089. /// or due to be.
  6090. textures: std::collections::HashSet<usize>,
  6091. /// Those due ([`Batch::refresh_textures`]).
  6092. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6093. }
  6094. /// Whether a submission's textures are brought up to date on several
  6095. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6096. /// name them, as before).
  6097. ///
  6098. /// They are read, hashed and, if they changed, detiled into their staging
  6099. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6100. /// its own buffer, notes and lock, and is refreshed by the title's own
  6101. /// threads as it is. They are done before the next step that writes title
  6102. /// memory, as the copies' refreshes are, and before the lists go to the
  6103. /// card. What is new: the note of a list that its upload takes what the
  6104. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6105. /// an earlier list of the submission asked for, not behind it. The texture
  6106. /// is then uploaded by a later list too, once more than needed.
  6107. fn wide_textures() -> bool {
  6108. static ON: OnceLock<bool> = OnceLock::new();
  6109. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6110. }
  6111. impl Batch {
  6112. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6113. let end = address + len;
  6114. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6115. match self.index.get(&key) {
  6116. Some(&at) => {
  6117. let r = &mut self.refreshes[at];
  6118. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6119. }
  6120. None => {
  6121. self.index.insert(key, self.refreshes.len());
  6122. self.refreshes.push((shadow.clone(), address, end));
  6123. }
  6124. }
  6125. }
  6126. /// Before shaders are given a range of `shadow`'s copy: its pending
  6127. /// refresh is done, the others stay pending.
  6128. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  6129. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  6130. return;
  6131. };
  6132. let (shadow, from, to) = self.refreshes.swap_remove(at);
  6133. // The last entry took its place.
  6134. if let Some(moved) = self.refreshes.get(at) {
  6135. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  6136. }
  6137. #[cfg(feature = "diagnostics")]
  6138. let started = std::time::Instant::now();
  6139. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  6140. Self::update(&shadow, from, to);
  6141. }
  6142. #[cfg(feature = "diagnostics")]
  6143. SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6144. }
  6145. /// Brings `[from, to)` of a copy up to date, timed.
  6146. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  6147. let started = std::time::Instant::now();
  6148. let copied = shadow.update(from, to - from);
  6149. let us = started.elapsed().as_micros() as u64;
  6150. #[cfg(feature = "diagnostics")]
  6151. crate::copystat::range(from, to - from, us, 0);
  6152. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  6153. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  6154. }
  6155. /// Whether `staging` is still to be refreshed in this submission (and
  6156. /// notes it refreshed).
  6157. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  6158. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  6159. }
  6160. /// Before a step that writes title memory: pending refreshes are done
  6161. /// first, and textures are checked again after it.
  6162. fn title_written(&mut self) {
  6163. self.flush();
  6164. self.textures.clear();
  6165. }
  6166. /// The textures due are brought up to date.
  6167. fn refresh_textures(&mut self) {
  6168. if self.due.len() < 2 || !wide_textures() {
  6169. self.due.drain(..).for_each(|staging| staging.refresh());
  6170. return;
  6171. }
  6172. // The time counted is the time it took, not the threads' sum.
  6173. let started = std::time::Instant::now();
  6174. let before = PREPARING[2].load(Ordering::Relaxed);
  6175. let due = std::mem::take(&mut self.due);
  6176. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  6177. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  6178. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6179. }
  6180. fn flush(&mut self) {
  6181. self.refresh_textures();
  6182. self.index.clear();
  6183. if self.refreshes.is_empty() {
  6184. return;
  6185. }
  6186. #[cfg(feature = "diagnostics")]
  6187. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  6188. self.flush_all();
  6189. #[cfg(feature = "diagnostics")]
  6190. {
  6191. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6192. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  6193. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  6194. }
  6195. }
  6196. fn flush_all(&mut self) {
  6197. // Most of a flush's copies are as they were: they are told so here,
  6198. // from what the submission's asking found, before anything is asked
  6199. // and any thread woken. (Thousands of them, the heap's buffer views
  6200. // once a frame: on the threads, below.)
  6201. const FEW: usize = 256;
  6202. let light = crate::watch::light();
  6203. if light && self.refreshes.len() <= FEW {
  6204. let started = std::time::Instant::now();
  6205. #[cfg(feature = "diagnostics")]
  6206. let all = self.refreshes.len();
  6207. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  6208. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6209. #[cfg(feature = "diagnostics")]
  6210. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  6211. }
  6212. // One write-watch asking for the copies that lie close together,
  6213. // not one per copy.
  6214. let ahead = self.refreshes.len() > 1;
  6215. if ahead {
  6216. let started = std::time::Instant::now();
  6217. let ranges: Vec<(usize, usize)> = self
  6218. .refreshes
  6219. .iter()
  6220. .filter(|r| !r.0.unwatched())
  6221. .map(|r| (r.1, r.2))
  6222. .collect();
  6223. crate::watch::ask_ahead(&ranges);
  6224. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6225. }
  6226. if wide_refresh() && self.refreshes.len() >= 4 {
  6227. // Each copy on its own, several at a time: a copy's refresh
  6228. // writes that copy and reads title memory, nothing of another's.
  6229. // The time counted is the time it took, not the threads' sum.
  6230. let started = std::time::Instant::now();
  6231. let before = PREPARING[0].load(Ordering::Relaxed);
  6232. #[cfg(feature = "diagnostics")]
  6233. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  6234. if light {
  6235. // A number to a free thread, not a job to each copy.
  6236. let refreshes = std::mem::take(&mut self.refreshes);
  6237. crate::shadow::wide_each(refreshes.len(), move |i| {
  6238. let (shadow, from, to) = &refreshes[i];
  6239. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  6240. #[cfg(feature = "diagnostics")]
  6241. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  6242. return;
  6243. }
  6244. Self::update(shadow, *from, *to);
  6245. });
  6246. } else {
  6247. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  6248. .refreshes
  6249. .drain(..)
  6250. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  6251. .collect();
  6252. crate::shadow::wide_run(jobs);
  6253. }
  6254. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6255. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6256. } else {
  6257. for (shadow, from, to) in self.refreshes.drain(..) {
  6258. Self::update(&shadow, from, to);
  6259. }
  6260. }
  6261. if ahead {
  6262. crate::watch::ask_ahead_done();
  6263. }
  6264. }
  6265. }
  6266. /// Copies title memory at submission. The ranges were checked against their
  6267. /// resources when recorded, but the title may since have unmapped pages of
  6268. /// them (tiled memory, page mappings), which read as zeros here; a title
  6269. /// destination (`title_dst`) that is not all mapped is left alone.
  6270. ///
  6271. /// The source is read through the kernel (`ReadProcessMemory`), which
  6272. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  6273. /// cost about 2 ms per copy in the title's big pools (it walks the page
  6274. /// tables to the region's end), which made copies run at 100-200 MB/s.
  6275. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  6276. #[cfg(feature = "diagnostics")]
  6277. match crate::copystat::mode() {
  6278. 1 => {
  6279. // SAFETY: timing only: the caller vouches for the source.
  6280. unsafe { std::ptr::copy(src, dst, len) };
  6281. return;
  6282. }
  6283. 2 => return,
  6284. _ => {}
  6285. }
  6286. if len == 0 {
  6287. return;
  6288. }
  6289. // A title destination that is not all mapped is left alone. Asking
  6290. // Windows first (`VirtualQuery`) walks the page tables to the end of
  6291. // the destination's region: in the title's big blocks that is
  6292. // milliseconds a copy, and it was a seventh of the submitting thread's
  6293. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  6294. // says the same when it fails, so the question is only asked then.
  6295. // `VICTORY_COPY_ASK=1` asks first, as before.
  6296. static ASK: OnceLock<bool> = OnceLock::new();
  6297. let ask_first = title_dst
  6298. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  6299. if ask_first && !crate::texture::committed(dst, len) {
  6300. return;
  6301. }
  6302. if title_dst {
  6303. // The kernel writes the destination: it must not be guarded.
  6304. crate::watch::writing(dst as usize, len);
  6305. }
  6306. #[cfg(feature = "diagnostics")]
  6307. let moved = std::time::Instant::now();
  6308. let whole = read(src, dst, len);
  6309. #[cfg(feature = "diagnostics")]
  6310. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  6311. if whole {
  6312. return;
  6313. }
  6314. // The copy failed: a source page is not there, or the destination is
  6315. // not all mapped. Then the destination stays as it is (the kernel may
  6316. // have written its first pages).
  6317. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  6318. return;
  6319. }
  6320. #[cfg(feature = "diagnostics")]
  6321. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  6322. #[cfg(feature = "diagnostics")]
  6323. let sparse = std::time::Instant::now();
  6324. if !title_dst && len >= 64 << 10 {
  6325. read_sparse(src, dst, len);
  6326. } else {
  6327. read_pieces(src, dst, len);
  6328. }
  6329. #[cfg(feature = "diagnostics")]
  6330. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  6331. }
  6332. /// After a failed bulk read into host memory, skip contiguous holes. Never
  6333. /// cache the query across copies: the title may remap the same address.
  6334. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  6335. use windows_sys::Win32::System::Memory::{
  6336. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  6337. };
  6338. let mut offset = 0;
  6339. while offset < len {
  6340. let at = src.wrapping_add(offset);
  6341. let to = dst.wrapping_add(offset);
  6342. let remaining = len - offset;
  6343. // SAFETY: the query inspects an address and fills a local structure.
  6344. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  6345. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  6346. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  6347. .saturating_sub(at as usize).min(remaining);
  6348. if size != size_of_val(&info) || n == 0 {
  6349. read_pieces(at, to, remaining);
  6350. break;
  6351. }
  6352. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  6353. #[cfg(feature = "diagnostics")]
  6354. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6355. // SAFETY: this path is only used with a writable host destination.
  6356. unsafe { to.write_bytes(0, n) };
  6357. } else if !read(at, to, n) {
  6358. // A mapping may change between query and read.
  6359. read_pieces(at, to, n);
  6360. }
  6361. offset += n;
  6362. }
  6363. }
  6364. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  6365. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  6366. // that fails), zeros for what cannot be read.
  6367. for_pieces(src as usize, len, 64 << 10, |at, n| {
  6368. let to = dst.wrapping_add(at - src as usize);
  6369. if !read(at as *const u8, to, n) {
  6370. for_pieces(at, n, 4 << 10, |at, n| {
  6371. let to = dst.wrapping_add(at - src as usize);
  6372. if !read(at as *const u8, to, n) {
  6373. #[cfg(feature = "diagnostics")]
  6374. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6375. // SAFETY: inside the destination, which is mapped.
  6376. unsafe { to.write_bytes(0, n) };
  6377. }
  6378. });
  6379. }
  6380. });
  6381. }
  6382. /// Reads title memory at `src` into `dst`; false if a page of it is not
  6383. /// readable.
  6384. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  6385. read(src, dst.as_mut_ptr(), dst.len())
  6386. }
  6387. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  6388. /// readable.
  6389. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  6390. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  6391. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6392. if crate::safecopy::on() {
  6393. // SAFETY: the destination is mapped writable memory of `len` bytes;
  6394. // a source page that is not there fails the copy.
  6395. return unsafe { crate::safecopy::copy(dst, src, len) };
  6396. }
  6397. let mut done = 0;
  6398. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  6399. // kernel checks the source.
  6400. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  6401. }
  6402. #[link(name = "ntdll", kind = "raw-dylib")]
  6403. unsafe extern "system" {
  6404. /// The kernel's write into a process's memory, `(process, address,
  6405. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  6406. /// the range is not there or not writable. It changes no protection.
  6407. fn NtWriteVirtualMemory(
  6408. process: *mut std::ffi::c_void,
  6409. base: *mut std::ffi::c_void,
  6410. buffer: *const std::ffi::c_void,
  6411. size: usize,
  6412. written: *mut usize,
  6413. ) -> i32;
  6414. }
  6415. /// Whether title memory is written with the kernel's own call
  6416. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  6417. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  6418. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  6419. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  6420. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  6421. fn direct_writes() -> bool {
  6422. static ON: OnceLock<bool> = OnceLock::new();
  6423. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  6424. }
  6425. /// Copies host memory into title memory after a submission (what shaders
  6426. /// wrote), leaving pages that are not mapped alone.
  6427. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  6428. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  6429. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6430. let direct = direct_writes();
  6431. let write = |at: usize, n: usize| {
  6432. let from = src.wrapping_add(at - dst as usize);
  6433. if crate::safecopy::on() {
  6434. // SAFETY: the source is ours; a destination page that is not
  6435. // there, or not writable, fails the copy.
  6436. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  6437. }
  6438. let mut done = 0;
  6439. if direct {
  6440. // SAFETY: as below; the kernel checks the destination and
  6441. // writes nothing it cannot (the caller opened its guards:
  6442. // `crate::watch::writing`).
  6443. return unsafe {
  6444. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  6445. };
  6446. }
  6447. // SAFETY: the source is our mapped host copy; the kernel checks the
  6448. // destination.
  6449. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  6450. };
  6451. if len == 0 || write(dst as usize, len) {
  6452. return;
  6453. }
  6454. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  6455. if !write(at, n) {
  6456. for_pieces(at, n, 4 << 10, |at, n| {
  6457. write(at, n);
  6458. });
  6459. }
  6460. });
  6461. }
  6462. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  6463. /// `step`.
  6464. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  6465. let end = start + len;
  6466. let mut at = start;
  6467. while at < end {
  6468. let next = ((at / step + 1) * step).min(end);
  6469. f(at, next - at);
  6470. at = next;
  6471. }
  6472. }
  6473. impl Host {
  6474. /// A buffer in the upload heap, mapped for writing.
  6475. /// A buffer of `size` bytes the card writes and we read (a read back),
  6476. /// in the state copies into it need.
  6477. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  6478. let heap = D3D12_HEAP_PROPERTIES {
  6479. Type: D3D12_HEAP_TYPE_READBACK,
  6480. ..Default::default()
  6481. };
  6482. let desc = D3D12_RESOURCE_DESC {
  6483. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6484. Width: size.max(1),
  6485. Height: 1,
  6486. DepthOrArraySize: 1,
  6487. MipLevels: 1,
  6488. SampleDesc: DXGI_SAMPLE_DESC {
  6489. Count: 1,
  6490. Quality: 0,
  6491. },
  6492. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6493. ..Default::default()
  6494. };
  6495. let mut buffer: Option<ID3D12Resource> = None;
  6496. // SAFETY: plain creation of a read-back buffer.
  6497. let made = unsafe {
  6498. self.device.CreateCommittedResource(
  6499. &heap,
  6500. D3D12_HEAP_FLAG_NONE,
  6501. &desc,
  6502. D3D12_RESOURCE_STATE_COPY_DEST,
  6503. None,
  6504. &mut buffer,
  6505. )
  6506. };
  6507. match made {
  6508. Ok(()) => buffer,
  6509. Err(e) => {
  6510. tracing::warn!(error = %e, size, "no read-back buffer");
  6511. None
  6512. }
  6513. }
  6514. }
  6515. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6516. MADE[0].fetch_add(1, Ordering::Relaxed);
  6517. MADE[1].fetch_add(size, Ordering::Relaxed);
  6518. let heap = D3D12_HEAP_PROPERTIES {
  6519. Type: D3D12_HEAP_TYPE_UPLOAD,
  6520. ..Default::default()
  6521. };
  6522. let desc = D3D12_RESOURCE_DESC {
  6523. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6524. Width: size.max(1),
  6525. Height: 1,
  6526. DepthOrArraySize: 1,
  6527. MipLevels: 1,
  6528. SampleDesc: DXGI_SAMPLE_DESC {
  6529. Count: 1,
  6530. Quality: 0,
  6531. },
  6532. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6533. ..Default::default()
  6534. };
  6535. let mut buffer: Option<ID3D12Resource> = None;
  6536. let mut data = std::ptr::null_mut();
  6537. // SAFETY: plain creation and mapping of an upload buffer.
  6538. let made = unsafe {
  6539. self.device
  6540. .CreateCommittedResource(
  6541. &heap,
  6542. D3D12_HEAP_FLAG_NONE,
  6543. &desc,
  6544. D3D12_RESOURCE_STATE_GENERIC_READ,
  6545. None,
  6546. &mut buffer,
  6547. )
  6548. .and_then(|()| {
  6549. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  6550. b.Map(0, None, Some(&mut data))
  6551. })
  6552. };
  6553. match made {
  6554. Ok(()) => Some((buffer?, data.cast())),
  6555. Err(e) => {
  6556. tracing::warn!(error = %e, size, "no upload buffer");
  6557. None
  6558. }
  6559. }
  6560. }
  6561. }
  6562. /// The swap chain formats a presented texture can be copied into: its own
  6563. /// family's.
  6564. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  6565. Some(match format.0 {
  6566. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  6567. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  6568. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  6569. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  6570. _ => return None,
  6571. })
  6572. }
  6573. const BUFFERS: u32 = 2;
  6574. struct Presenter {
  6575. swap_chain: IDXGISwapChain3,
  6576. width: u32,
  6577. height: u32,
  6578. format: DXGI_FORMAT,
  6579. copy: HostList,
  6580. /// With presents sent ahead ([`late_free_present`]): a list for each
  6581. /// present in the air, and the submission it last flew as (it is used
  6582. /// again once that one has finished).
  6583. ahead: Vec<(HostList, u64)>,
  6584. hwnd: HWND,
  6585. meter: Meter,
  6586. }
  6587. /// The frame rate, shown in the window's caption every second and logged
  6588. /// every few seconds.
  6589. struct Meter {
  6590. since: std::time::Instant,
  6591. frames: u32,
  6592. #[cfg(feature = "diagnostics")]
  6593. copy_stats_frames: u64,
  6594. drawn: u64,
  6595. logged: std::time::Instant,
  6596. /// The caption the window had, once read.
  6597. caption: Option<Vec<u16>>,
  6598. }
  6599. impl Meter {
  6600. fn new() -> Self {
  6601. let now = std::time::Instant::now();
  6602. Meter {
  6603. since: now,
  6604. frames: 0,
  6605. #[cfg(feature = "diagnostics")]
  6606. copy_stats_frames: 0,
  6607. drawn: crate::draw::drawn(),
  6608. logged: now,
  6609. caption: None,
  6610. }
  6611. }
  6612. /// Counts a presented frame.
  6613. fn frame(&mut self, hwnd: HWND) {
  6614. #[cfg(feature = "diagnostics")]
  6615. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  6616. #[cfg(feature = "diagnostics")]
  6617. crate::copystat::presented();
  6618. self.frames += 1;
  6619. #[cfg(feature = "diagnostics")]
  6620. {
  6621. self.copy_stats_frames += 1;
  6622. }
  6623. let elapsed = self.since.elapsed();
  6624. if elapsed < std::time::Duration::from_secs(1) {
  6625. return;
  6626. }
  6627. let drawn = crate::draw::drawn();
  6628. let frames = f64::from(self.frames);
  6629. let fps = frames / elapsed.as_secs_f64();
  6630. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  6631. let draws = (drawn - self.drawn) as f64 / frames;
  6632. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  6633. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  6634. let [cpu, gpu] = [0, 1].map(|i| {
  6635. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  6636. });
  6637. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  6638. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  6639. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  6640. });
  6641. let [back_ms, back_mb] = [0, 1].map(|i| {
  6642. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  6643. });
  6644. let dropped = crate::draw::take_dropped() as f64 / frames;
  6645. let indirect = crate::list::take_indirect() as f64 / frames;
  6646. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  6647. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  6648. tracing::info!(
  6649. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  6650. );
  6651. late_line(frames);
  6652. card_clock_line(frames, ms);
  6653. crate::shadow::back_line(frames);
  6654. #[cfg(feature = "diagnostics")]
  6655. split_line(frames);
  6656. {
  6657. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6658. if passes + compares > 0.0 {
  6659. tracing::info!(
  6660. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  6661. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  6662. if rehash_runs() { "on" } else { "off" }
  6663. );
  6664. }
  6665. }
  6666. {
  6667. let [own, asking, still, all] =
  6668. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  6669. if all >= 1.0 {
  6670. tracing::info!(
  6671. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  6672. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  6673. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  6674. );
  6675. }
  6676. let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6677. if through + left > 0.0 {
  6678. tracing::info!(
  6679. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  6680. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there)"
  6681. );
  6682. }
  6683. }
  6684. {
  6685. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6686. if copies > 0.0 {
  6687. tracing::info!(
  6688. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  6689. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  6690. if join_copies() { "on" } else { "off" }
  6691. );
  6692. }
  6693. }
  6694. // Passes over the heap's buffer views for shaders that pick them by index.
  6695. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  6696. let picked_ms =
  6697. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  6698. // Copies between depth textures and their colour twins, each way.
  6699. let [twin_to_depth, twin_to_colour] =
  6700. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6701. // Depth planes drawn from their twins.
  6702. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  6703. // Copies in the card's memory (`crate::shadow::cards`).
  6704. let card = crate::shadow::card_stats();
  6705. #[cfg(feature = "diagnostics")]
  6706. let slow = crate::watch::slow_asks();
  6707. // Over the same frames as the counts above.
  6708. #[cfg(feature = "diagnostics")]
  6709. let drops = crate::pipeline::take_drops();
  6710. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  6711. self.logged = std::time::Instant::now();
  6712. tracing::info!(
  6713. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  6714. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  6715. );
  6716. {
  6717. let [queued, due, away, partly, oldest] =
  6718. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  6719. let [same, parts, tails] =
  6720. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  6721. tracing::info!(
  6722. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  6723. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  6724. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  6725. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  6726. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  6727. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  6728. {} made slots found unmapped and made null",
  6729. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  6730. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  6731. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  6732. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  6733. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  6734. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  6735. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  6736. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  6737. );
  6738. }
  6739. #[cfg(feature = "diagnostics")]
  6740. tracing::info!(
  6741. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  6742. slow[0] as f64 / frames,
  6743. slow[1] as f64 / 1e3 / frames,
  6744. slow[2] as f64 / 1e3
  6745. );
  6746. if crate::shadow::cards() {
  6747. let per_frame = |i: usize| card[i] as f64 / frames;
  6748. tracing::info!(
  6749. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  6750. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  6751. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  6752. card[7],
  6753. card[8] >> 20,
  6754. card[9] >> 20,
  6755. per_frame(0) / 1e6,
  6756. per_frame(1),
  6757. per_frame(2),
  6758. per_frame(3),
  6759. per_frame(4) / 1e6,
  6760. per_frame(5),
  6761. per_frame(6) / 1e3
  6762. );
  6763. }
  6764. tracing::info!(
  6765. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  6766. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  6767. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  6768. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  6769. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  6770. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  6771. {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}",
  6772. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  6773. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  6774. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  6775. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  6776. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  6777. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  6778. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  6779. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  6780. refused = format!(
  6781. "{}; 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",
  6782. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  6783. crate::resource::TWINS[0].load(Ordering::Relaxed),
  6784. crate::resource::TWINS[1].load(Ordering::Relaxed),
  6785. crate::resource::PLANES[1].load(Ordering::Relaxed),
  6786. crate::resource::PLANES[2].load(Ordering::Relaxed)
  6787. ),
  6788. making = crate::pipeline::making(),
  6789. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  6790. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  6791. );
  6792. #[cfg(feature = "diagnostics")]
  6793. {
  6794. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6795. tracing::info!(
  6796. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  6797. put[0],
  6798. put[1],
  6799. put[2] / 1e6,
  6800. put[3]
  6801. );
  6802. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  6803. for (why, n) in drops.iter().take(40) {
  6804. tracing::info!(
  6805. "dropped {:.1}/frame without a host pipeline: {why}",
  6806. *n as f64 / frames
  6807. );
  6808. }
  6809. }
  6810. }
  6811. if self.caption.is_none() {
  6812. // The window's own text, read without a message.
  6813. let mut buffer = vec![0u16; 512];
  6814. // SAFETY: a window handle and a buffer of that length.
  6815. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  6816. buffer.truncate(n.max(0) as usize);
  6817. self.caption = Some(buffer);
  6818. }
  6819. let Some(caption) = &self.caption else { return };
  6820. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  6821. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  6822. text.push(0);
  6823. // Setting the text waits for the window's thread (a title thread,
  6824. // which may not pump for a while), so a thread of ours does it and
  6825. // presenting never waits; it takes the newest text when free.
  6826. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  6827. static SETTER: std::sync::Once = std::sync::Once::new();
  6828. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  6829. SETTER.call_once(|| {
  6830. let _ = std::thread::Builder::new()
  6831. .name("victory-caption".into())
  6832. .spawn(|| {
  6833. loop {
  6834. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  6835. match next {
  6836. // SAFETY: a window handle and a NUL-terminated text.
  6837. Some((hwnd, text)) => unsafe {
  6838. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  6839. },
  6840. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  6841. }
  6842. }
  6843. });
  6844. });
  6845. }
  6846. }
  6847. impl Host {
  6848. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  6849. /// as frame `frame` (saved if captures are on). `None` if nothing was
  6850. /// shown; else, in diagnostics builds, whether the frame was black.
  6851. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  6852. // SAFETY: a live resource.
  6853. let desc = unsafe { texture.GetDesc() };
  6854. let Some(format) = swap_format(desc.Format) else {
  6855. tracing::warn!(format = desc.Format.0, "cannot present this format");
  6856. return None;
  6857. };
  6858. let (width, height) = (desc.Width as u32, desc.Height);
  6859. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  6860. if presenter.is_none() {
  6861. *presenter = match self.presenter(width, height, format) {
  6862. Ok(p) => Some(p),
  6863. Err(e) => {
  6864. tracing::warn!(error = %e, "no swap chain");
  6865. return None;
  6866. }
  6867. };
  6868. }
  6869. let p = presenter.as_mut()?;
  6870. if (p.width, p.height, p.format) != (width, height, format) {
  6871. // Presents sent ahead hold back buffers until they have run.
  6872. settle_now(WHY_SYNC);
  6873. // SAFETY: no back buffer is held; every submission was waited for.
  6874. let resized = unsafe {
  6875. p.swap_chain
  6876. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  6877. };
  6878. match resized {
  6879. Ok(()) => {
  6880. (p.width, p.height, p.format) = (width, height, format);
  6881. tracing::info!(
  6882. width,
  6883. height,
  6884. format = format.0,
  6885. frame,
  6886. "the swap chain's buffers were made again for another size or format"
  6887. );
  6888. self.log_video_memory("right after the swap chain's buffers were made again");
  6889. }
  6890. Err(e) => {
  6891. tracing::warn!(error = %e, width, height, "swap chain not resized");
  6892. return None;
  6893. }
  6894. }
  6895. }
  6896. let state = D3D12_RESOURCE_STATES(state as i32);
  6897. // SAFETY: our swap chain, list and a live source texture.
  6898. unsafe {
  6899. let index = p.swap_chain.GetCurrentBackBufferIndex();
  6900. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  6901. return None;
  6902. };
  6903. // Sent ahead ([`late_free_present`]) unless the frame is to be
  6904. // read back at once (a saved or listed frame): then a list of
  6905. // its own, one whose last flight has finished or a new one.
  6906. #[cfg(feature = "diagnostics")]
  6907. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  6908. #[cfg(not(feature = "diagnostics"))]
  6909. let read_now = false;
  6910. let slot = if late_free_present() && !read_now {
  6911. let finished = FINISHED.load(Ordering::Acquire);
  6912. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  6913. let list = self.new_list().ok()?;
  6914. list.close();
  6915. p.ahead.push((list, 0));
  6916. Some(p.ahead.len() - 1)
  6917. })
  6918. } else {
  6919. None
  6920. };
  6921. let copy = match slot {
  6922. Some(i) => &p.ahead[i].0,
  6923. None => &p.copy,
  6924. };
  6925. copy.reset();
  6926. let list = &copy.list;
  6927. list.ResourceBarrier(&[
  6928. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  6929. transition(
  6930. &back,
  6931. D3D12_RESOURCE_STATE_PRESENT,
  6932. D3D12_RESOURCE_STATE_COPY_DEST,
  6933. ),
  6934. ]);
  6935. list.CopyResource(&back, texture);
  6936. #[cfg(feature = "diagnostics")]
  6937. let capture = crate::capture::wanted(frame)
  6938. .then(|| crate::capture::read_back(&self.device, list, texture))
  6939. .flatten();
  6940. #[cfg(feature = "diagnostics")]
  6941. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  6942. #[cfg(not(feature = "diagnostics"))]
  6943. let _ = frame;
  6944. list.ResourceBarrier(&[
  6945. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  6946. transition(
  6947. &back,
  6948. D3D12_RESOURCE_STATE_COPY_DEST,
  6949. D3D12_RESOURCE_STATE_PRESENT,
  6950. ),
  6951. ]);
  6952. copy.close();
  6953. match slot {
  6954. Some(i) => {
  6955. let flown = self.execute_own(copy);
  6956. p.ahead[i].1 = flown;
  6957. }
  6958. None => self.execute(&[copy]),
  6959. }
  6960. #[cfg(feature = "diagnostics")]
  6961. if let Some((buffer, footprint)) = capture {
  6962. crate::capture::save_read_back(frame, &buffer, &footprint);
  6963. }
  6964. #[cfg(feature = "diagnostics")]
  6965. crate::replay::record::present(texture, state);
  6966. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  6967. p.meter.frame(p.hwnd);
  6968. #[cfg(feature = "diagnostics")]
  6969. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  6970. #[cfg(not(feature = "diagnostics"))]
  6971. Some(false)
  6972. }
  6973. }
  6974. fn presenter(
  6975. &self,
  6976. width: u32,
  6977. height: u32,
  6978. format: DXGI_FORMAT,
  6979. ) -> windows::core::Result<Presenter> {
  6980. let hwnd = match title_window() {
  6981. Some(hwnd) => hwnd,
  6982. None => window(width, height)?,
  6983. };
  6984. self.log_video_memory("right before the swap chain is made");
  6985. // SAFETY: plain object creation for our window.
  6986. unsafe {
  6987. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  6988. let desc = DXGI_SWAP_CHAIN_DESC1 {
  6989. Width: width,
  6990. Height: height,
  6991. Format: format,
  6992. SampleDesc: DXGI_SAMPLE_DESC {
  6993. Count: 1,
  6994. Quality: 0,
  6995. },
  6996. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  6997. BufferCount: BUFFERS,
  6998. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  6999. ..Default::default()
  7000. };
  7001. let swap_chain = factory
  7002. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  7003. .cast::<IDXGISwapChain3>()?;
  7004. let copy = self.new_list()?;
  7005. copy.close();
  7006. tracing::info!(width, height, format = format.0, "presenting to a window");
  7007. self.log_video_memory("right after the swap chain is made");
  7008. Ok(Presenter {
  7009. swap_chain,
  7010. width,
  7011. height,
  7012. format,
  7013. copy,
  7014. ahead: Vec::new(),
  7015. hwnd,
  7016. meter: Meter::new(),
  7017. })
  7018. }
  7019. }
  7020. }
  7021. /// A visible top-level window of this process: the one the title made, if
  7022. /// it made one.
  7023. fn title_window() -> Option<HWND> {
  7024. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  7025. let mut process = 0;
  7026. // SAFETY: a window handle from the enumeration; `found` is ours.
  7027. unsafe {
  7028. GetWindowThreadProcessId(hwnd, Some(&mut process));
  7029. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  7030. && IsWindowVisible(hwnd).as_bool()
  7031. {
  7032. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  7033. return false.into();
  7034. }
  7035. }
  7036. true.into()
  7037. }
  7038. let mut found: Option<HWND> = None;
  7039. // SAFETY: the callback only writes `found`, which outlives the call.
  7040. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  7041. found
  7042. }
  7043. /// `state` without the bits the host texture's flags forbid: the console
  7044. /// lets the title name states its own resources allow (unordered access on
  7045. /// a depth target, whose host copy cannot have both).
  7046. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  7047. // SAFETY: a plain query.
  7048. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  7049. }
  7050. /// [`legal_state`] for a texture with resource flags `flags`.
  7051. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  7052. // (flag, set or clear forbids, state bits): render target, unordered
  7053. // access, depth, denied shader resource.
  7054. const FORBIDDEN: [(u32, bool, u32); 4] = [
  7055. (0x1, false, 0x4),
  7056. (0x4, false, 0x8),
  7057. (0x2, false, 0x10 | 0x20),
  7058. (0x8, true, 0x40 | 0x80),
  7059. ];
  7060. FORBIDDEN
  7061. .iter()
  7062. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  7063. .fold(state, |s, &(_, _, bits)| s & !bits)
  7064. }
  7065. impl Host {
  7066. /// The card's memory as the system accounts it to this process, in
  7067. /// bytes: the budget and the use of the card's own memory, then of the
  7068. /// PC's memory shared with the card (where the system moves what does
  7069. /// not fit on the card).
  7070. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  7071. let adapter = self.adapter.as_ref()?;
  7072. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7073. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7074. // SAFETY: plain queries that fill our structures.
  7075. unsafe {
  7076. adapter
  7077. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7078. .ok()?;
  7079. adapter
  7080. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7081. .ok()?;
  7082. }
  7083. // The card's budget moved by 256 MB or more since the last look:
  7084. // said at once, with what was in use at the last look, so the log
  7085. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  7086. // the first world frame in runs 179 to 185, and the memory line,
  7087. // seconds later, was the first to show it. We reserve nothing
  7088. // and make the swap chain once, at the start.)
  7089. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  7090. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  7091. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  7092. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  7093. tracing::info!(
  7094. "the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use",
  7095. last[0] >> 20,
  7096. own.Budget >> 20,
  7097. crate::frame::current(),
  7098. last[1] >> 20,
  7099. last[2] >> 20
  7100. );
  7101. self.log_video_memory("right after that change");
  7102. }
  7103. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  7104. }
  7105. /// Both of the system's memory groups for this process, in bytes: for
  7106. /// the card's own memory and then for the PC's memory shared with the
  7107. /// card, the budget, the use, what could still be reserved and what
  7108. /// is reserved (the layer reserves none).
  7109. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  7110. let adapter = self.adapter.as_ref()?;
  7111. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7112. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7113. // SAFETY: plain queries that fill our structures.
  7114. unsafe {
  7115. adapter
  7116. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7117. .ok()?;
  7118. adapter
  7119. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7120. .ok()?;
  7121. }
  7122. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  7123. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  7124. };
  7125. Some([all(&own), all(&shared)])
  7126. }
  7127. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  7128. pub(crate) fn log_video_memory(&self, when: &str) {
  7129. let Some([own, shared]) = self.video_memory_groups() else {
  7130. return;
  7131. };
  7132. tracing::info!(
  7133. "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)",
  7134. when,
  7135. own[0] >> 20,
  7136. own[1] >> 20,
  7137. own[2] >> 20,
  7138. own[3] >> 20,
  7139. shared[0] >> 20,
  7140. shared[1] >> 20,
  7141. shared[2] >> 20,
  7142. shared[3] >> 20
  7143. );
  7144. }
  7145. /// A buffer in system memory that the CPU maps (write-back, so reading
  7146. /// it is fast too) and shaders read and write: for host copies of title
  7147. /// memory that shaders write, which upload memory cannot be. Starts in
  7148. /// the common state (buffers move out of it implicitly).
  7149. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7150. MADE[2].fetch_add(1, Ordering::Relaxed);
  7151. MADE[3].fetch_add(size, Ordering::Relaxed);
  7152. let heap = D3D12_HEAP_PROPERTIES {
  7153. Type: D3D12_HEAP_TYPE_CUSTOM,
  7154. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  7155. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  7156. ..Default::default()
  7157. };
  7158. let desc = D3D12_RESOURCE_DESC {
  7159. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7160. Width: size.max(1),
  7161. Height: 1,
  7162. DepthOrArraySize: 1,
  7163. MipLevels: 1,
  7164. SampleDesc: DXGI_SAMPLE_DESC {
  7165. Count: 1,
  7166. Quality: 0,
  7167. },
  7168. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7169. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7170. ..Default::default()
  7171. };
  7172. let mut buffer: Option<ID3D12Resource> = None;
  7173. let mut data = std::ptr::null_mut();
  7174. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7175. let made = unsafe {
  7176. self.device
  7177. .CreateCommittedResource(
  7178. &heap,
  7179. D3D12_HEAP_FLAG_NONE,
  7180. &desc,
  7181. D3D12_RESOURCE_STATE_COMMON,
  7182. None,
  7183. &mut buffer,
  7184. )
  7185. .and_then(|()| {
  7186. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7187. b.Map(0, None, Some(&mut data))
  7188. })
  7189. };
  7190. match made {
  7191. Ok(()) => Some((buffer?, data.cast())),
  7192. Err(e) => {
  7193. tracing::warn!(error = %e, size, "no shared buffer");
  7194. None
  7195. }
  7196. }
  7197. }
  7198. /// A device-local buffer shaders may write (unordered access) and indirect
  7199. /// execution may read, starting in the common state.
  7200. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7201. MADE[4].fetch_add(1, Ordering::Relaxed);
  7202. MADE[5].fetch_add(size, Ordering::Relaxed);
  7203. let heap = D3D12_HEAP_PROPERTIES {
  7204. Type: D3D12_HEAP_TYPE_DEFAULT,
  7205. ..Default::default()
  7206. };
  7207. let desc = D3D12_RESOURCE_DESC {
  7208. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7209. Width: size.max(1),
  7210. Height: 1,
  7211. DepthOrArraySize: 1,
  7212. MipLevels: 1,
  7213. SampleDesc: DXGI_SAMPLE_DESC {
  7214. Count: 1,
  7215. Quality: 0,
  7216. },
  7217. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7218. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7219. ..Default::default()
  7220. };
  7221. let mut buffer: Option<ID3D12Resource> = None;
  7222. // SAFETY: plain creation of a device-local buffer.
  7223. let made = unsafe {
  7224. self.device.CreateCommittedResource(
  7225. &heap,
  7226. D3D12_HEAP_FLAG_NONE,
  7227. &desc,
  7228. D3D12_RESOURCE_STATE_COMMON,
  7229. None,
  7230. &mut buffer,
  7231. )
  7232. };
  7233. match made {
  7234. Ok(()) => buffer,
  7235. Err(e) => {
  7236. tracing::warn!(error = %e, size, "no unordered-access buffer");
  7237. None
  7238. }
  7239. }
  7240. }
  7241. }
  7242. /// For adapters without device-removed data (the software one): the last
  7243. /// commands each list of the failed submission noted (diagnostics, with
  7244. /// `VICTORY_D3D12_DRED`).
  7245. fn last_notes(runs: &[&HostList]) -> String {
  7246. #[cfg(feature = "diagnostics")]
  7247. {
  7248. let mut text = String::new();
  7249. for (i, r) in runs.iter().enumerate() {
  7250. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  7251. for (n, _) in notes.iter().rev().take(6).rev() {
  7252. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  7253. }
  7254. }
  7255. text
  7256. }
  7257. #[cfg(not(feature = "diagnostics"))]
  7258. {
  7259. let _ = runs;
  7260. String::new()
  7261. }
  7262. }
  7263. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  7264. /// command reads (diagnostics).
  7265. #[cfg(feature = "diagnostics")]
  7266. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  7267. let end = start + bytes;
  7268. if va < start {
  7269. format!(" (fault {:#x} below its source)", start - va)
  7270. } else if va < end {
  7271. format!(" (fault at source +{:#x})", va - start)
  7272. } else {
  7273. format!(" (fault {:#x} past its source's end)", va - end)
  7274. }
  7275. }
  7276. /// The commands that may have been running where a list stopped at
  7277. /// command `done`: those between the barriers around it (work between
  7278. /// barriers overlaps on the GPU), by kind, and what the markers just
  7279. /// before them say (`HostList::note_op`: diagnostics builds with
  7280. /// device-removed data on).
  7281. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  7282. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  7283. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  7284. let to = history[done..]
  7285. .iter()
  7286. .position(barrier)
  7287. .map_or(history.len(), |b| (done + b).max(done + 1));
  7288. let mut text = format!(", commands {from}..{to} between its barriers:");
  7289. let mut shown = 0;
  7290. // From just before the command the GPU had not finished: the first
  7291. // twelve after the barrier named draws long done when a list of 79
  7292. // mesh draws stopped at its 45th (run 41).
  7293. for i in from.max(done.saturating_sub(4))..to {
  7294. let op = history[i];
  7295. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  7296. continue;
  7297. }
  7298. shown += 1;
  7299. let marker = i
  7300. .checked_sub(1)
  7301. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  7302. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  7303. .map_or("no marker", |(_, s)| s.as_str());
  7304. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  7305. }
  7306. text
  7307. }
  7308. pub(crate) fn transition(
  7309. resource: &ID3D12Resource,
  7310. before: D3D12_RESOURCE_STATES,
  7311. after: D3D12_RESOURCE_STATES,
  7312. ) -> D3D12_RESOURCE_BARRIER {
  7313. D3D12_RESOURCE_BARRIER {
  7314. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  7315. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  7316. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  7317. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  7318. // SAFETY: a borrowed pointer; the barrier never releases it.
  7319. pResource: unsafe { std::mem::transmute_copy(resource) },
  7320. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  7321. StateBefore: before,
  7322. StateAfter: after,
  7323. }),
  7324. },
  7325. }
  7326. }
  7327. /// A window of the given client size, owned by its own message thread.
  7328. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7329. let (sender, receiver) = std::sync::mpsc::channel();
  7330. std::thread::Builder::new()
  7331. .name("victory-window".into())
  7332. .spawn(move || {
  7333. let made = make_window(width, height);
  7334. let ok = made.is_ok();
  7335. let _ = sender.send(made.map(|h| h.0 as usize));
  7336. if ok {
  7337. pump();
  7338. }
  7339. })
  7340. .map_err(|_| windows::core::Error::empty())?;
  7341. let hwnd = receiver
  7342. .recv()
  7343. .map_err(|_| windows::core::Error::empty())??;
  7344. Ok(HWND(hwnd as *mut _))
  7345. }
  7346. extern "system" fn window_proc(
  7347. hwnd: HWND,
  7348. message: u32,
  7349. wparam: WPARAM,
  7350. lparam: LPARAM,
  7351. ) -> LRESULT {
  7352. // SAFETY: the default handling for our window.
  7353. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  7354. }
  7355. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7356. const CLASS: PCWSTR = w!("VIctory");
  7357. // SAFETY: registers our class once and creates a window of it.
  7358. unsafe {
  7359. let instance = GetModuleHandleW(None)?;
  7360. let class = WNDCLASSEXW {
  7361. cbSize: size_of::<WNDCLASSEXW>() as u32,
  7362. lpfnWndProc: Some(window_proc),
  7363. hInstance: instance.into(),
  7364. lpszClassName: CLASS,
  7365. hCursor: LoadCursorW(None, IDC_ARROW)?,
  7366. ..Default::default()
  7367. };
  7368. RegisterClassExW(&class);
  7369. let mut rect = RECT {
  7370. left: 0,
  7371. top: 0,
  7372. right: width as i32,
  7373. bottom: height as i32,
  7374. };
  7375. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  7376. CreateWindowExW(
  7377. WINDOW_EX_STYLE(0),
  7378. CLASS,
  7379. w!("VIctory"),
  7380. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  7381. CW_USEDEFAULT,
  7382. CW_USEDEFAULT,
  7383. rect.right - rect.left,
  7384. rect.bottom - rect.top,
  7385. None,
  7386. None,
  7387. Some(instance.into()),
  7388. None,
  7389. )
  7390. }
  7391. }
  7392. fn pump() {
  7393. let mut message = MSG::default();
  7394. // SAFETY: the standard message loop of this thread's window.
  7395. unsafe {
  7396. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  7397. let _ = TranslateMessage(&message);
  7398. DispatchMessageW(&message);
  7399. }
  7400. }
  7401. }
  7402. #[cfg(test)]
  7403. mod trail {
  7404. /// The trail keeps the newest things, and the report made when the
  7405. /// host device is removed says them and the pipeline library's state
  7406. /// (no card is asked for any of it).
  7407. #[test]
  7408. fn the_removal_report_says_the_newest_things_done() {
  7409. for n in 0..super::TRAIL_MOST + 5 {
  7410. super::trail(|| format!("thing {n} done"));
  7411. }
  7412. let text = super::removal_context();
  7413. assert!(text.contains("the submitting thread was"));
  7414. assert!(text.contains("pipeline library: no call running"));
  7415. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  7416. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  7417. }
  7418. }
  7419. #[cfg(test)]
  7420. mod spare {
  7421. use super::Spare;
  7422. /// Kept things come back by size, the last given first, and nothing is
  7423. /// kept past the limit.
  7424. #[test]
  7425. fn kept_things_come_back_by_size_within_the_limit() {
  7426. let mut spare: Spare<u32> = Spare::new();
  7427. assert_eq!(spare.take(4), None);
  7428. assert_eq!(spare.give(1, 4, 10), None);
  7429. assert_eq!(spare.give(2, 1, 10), None);
  7430. assert_eq!(spare.give(3, 4, 10), None);
  7431. assert_eq!(spare.bytes, 9);
  7432. // Past the limit: handed back, nothing changes.
  7433. assert_eq!(spare.give(4, 4, 10), Some(4));
  7434. assert_eq!(spare.bytes, 9);
  7435. assert_eq!(spare.take(2), None, "no thing of that size");
  7436. assert_eq!(spare.take(4), Some(3));
  7437. assert_eq!(spare.take(4), Some(1));
  7438. assert_eq!(spare.take(4), None);
  7439. assert_eq!(spare.take(1), Some(2));
  7440. assert_eq!(spare.bytes, 0);
  7441. assert!(spare.kept.is_empty());
  7442. }
  7443. }
  7444. #[cfg(test)]
  7445. mod refresh_tests {
  7446. use super::Batch;
  7447. use crate::shadow::Shadow;
  7448. use std::sync::Arc;
  7449. use windows_sys::Win32::System::Memory::{
  7450. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  7451. VirtualAlloc,
  7452. };
  7453. const PAGE: usize = 64 << 10;
  7454. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  7455. /// Title memory for the tests (never given back: copies of it stay in
  7456. /// the guards): write-watched, or a view of a section.
  7457. fn title(len: usize, view: bool) -> usize {
  7458. // SAFETY: plain allocations.
  7459. let at = unsafe {
  7460. if view {
  7461. let section =
  7462. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  7463. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  7464. // As the runtime tells of it.
  7465. crate::title_memory_section(section as usize, len as u64, true);
  7466. crate::title_memory_remapped(at, len);
  7467. crate::title_memory_view(at, len, section as usize, 0);
  7468. at
  7469. } else {
  7470. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  7471. }
  7472. };
  7473. assert_ne!(at, 0);
  7474. at
  7475. }
  7476. fn memory(len: usize) -> *mut u8 {
  7477. // SAFETY: a plain allocation.
  7478. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  7479. }
  7480. struct Random(u64);
  7481. impl Random {
  7482. fn below(&mut self, n: usize) -> usize {
  7483. self.0 ^= self.0 << 13;
  7484. self.0 ^= self.0 >> 7;
  7485. self.0 ^= self.0 << 17;
  7486. (self.0 >> 11) as usize % n
  7487. }
  7488. }
  7489. /// Prepares as a submission does: one asking for all the ranges, the
  7490. /// refreshes in several flushes, the asking's end.
  7491. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  7492. // One at a time, as submissions are.
  7493. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  7494. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  7495. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  7496. crate::watch::ask_once(&asked);
  7497. let mut batch = Batch::default();
  7498. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  7499. for (shadow, at, len) in part {
  7500. batch.add(shadow, *at, *len);
  7501. }
  7502. batch.flush();
  7503. }
  7504. crate::watch::ask_once_end();
  7505. }
  7506. /// Whatever is written where, by the title or by us, and whichever
  7507. /// copies (of both kinds of memory, over one another, none on a page
  7508. /// line) are refreshed in which ranges: a refreshed range holds what
  7509. /// title memory holds.
  7510. #[test]
  7511. fn refreshed_ranges_hold_title_memory() {
  7512. // SAFETY (all blocks): title memory and copies of the test's own,
  7513. // written by this thread and, in `Batch::flush`, by the threads that
  7514. // refresh, which are done when it returns.
  7515. let mut random = Random(0x1234_5678_9ABC_DEF1);
  7516. const LEN: usize = 24 * PAGE;
  7517. let regions = [title(LEN, false), title(LEN, true)];
  7518. let mut copies = Vec::new();
  7519. for &region in &regions {
  7520. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  7521. let data = memory(to - from);
  7522. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  7523. }
  7524. }
  7525. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  7526. for round in 0..600 {
  7527. for _ in 0..random.below(4) {
  7528. let at = regions[random.below(2)] + random.below(LEN - 64);
  7529. let n = 1 + random.below(60);
  7530. if random.below(3) == 0 {
  7531. // What shaders wrote.
  7532. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  7533. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  7534. Shadow::put(at, &was, &now);
  7535. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  7536. continue;
  7537. }
  7538. for i in 0..n {
  7539. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  7540. }
  7541. }
  7542. let mut ranges = Vec::new();
  7543. for (shadow, _) in &copies {
  7544. if random.below(3) == 0 {
  7545. continue;
  7546. }
  7547. let (start, len) = shadow.span();
  7548. let (start, len) = (start as usize, len as usize);
  7549. // Often the range of the time before, as a list's is.
  7550. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  7551. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  7552. ranges.push((shadow.clone(), start + from, n));
  7553. }
  7554. if ranges.is_empty() {
  7555. continue;
  7556. }
  7557. let flushes = 1 + random.below(3);
  7558. submission(&ranges, flushes);
  7559. for (shadow, at, n) in &ranges {
  7560. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  7561. let start = shadow.span().0 as usize;
  7562. let same = unsafe {
  7563. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  7564. };
  7565. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  7566. }
  7567. }
  7568. }
  7569. /// A copy in the card's memory, with the card's side and the sends to it
  7570. /// played by the test.
  7571. struct Carded {
  7572. shadow: Arc<Shadow>,
  7573. data: usize,
  7574. start: usize,
  7575. len: usize,
  7576. /// The last send, the last send every fetch to come is behind, and
  7577. /// the card's bytes: the queue's order is the order it is locked in.
  7578. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  7579. /// Whether a flight that writes it has not landed.
  7580. flying: std::sync::atomic::AtomicBool,
  7581. /// The dword of each eight its shaders write.
  7582. class: usize,
  7583. }
  7584. impl Carded {
  7585. fn new(start: usize, len: usize, class: usize) -> Carded {
  7586. let data = memory(len);
  7587. Carded {
  7588. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  7589. data: data as usize,
  7590. start,
  7591. len,
  7592. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  7593. flying: std::sync::atomic::AtomicBool::new(false),
  7594. class,
  7595. }
  7596. }
  7597. /// What changed on the CPU's side goes up.
  7598. fn send(&self) {
  7599. let mut card = self.card.lock().unwrap();
  7600. card.0 += 1;
  7601. let (number, merged) = (card.0, card.1);
  7602. for (a, b) in self.shadow.send_up(number, merged) {
  7603. // SAFETY: the copy's bytes; nothing writes those that are to
  7604. // go up.
  7605. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  7606. }
  7607. }
  7608. }
  7609. /// Everything at once: the title writes its memory on two threads, the
  7610. /// submitting thread puts its bytes in under shader writes
  7611. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  7612. /// the card's memory, one not), sends up what changed and declares what
  7613. /// the next flight's shaders write, and what flights wrote is landed
  7614. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  7615. /// still and the copies are refreshed once more, each of them, and the
  7616. /// card's side of those that have one, hold what title memory holds, and
  7617. /// title memory what was written last.
  7618. ///
  7619. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  7620. /// only takes the block out of the guards' clean ones and leaves its bit,
  7621. /// or if a fault leaves the bit; in some thousand rounds,
  7622. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  7623. #[test]
  7624. fn landings_title_writes_and_light_refreshes_at_once() {
  7625. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  7626. assert!(crate::safecopy::on());
  7627. const LEN: usize = 24 * PAGE;
  7628. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  7629. let region = title(LEN, true);
  7630. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  7631. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  7632. let plain = {
  7633. let (start, len) = (region + 700, LEN - 9000);
  7634. let data = memory(len);
  7635. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  7636. };
  7637. let stop = AtomicBool::new(false);
  7638. // Also when an assertion fails on one of the threads.
  7639. struct Stop<'a>(&'a AtomicBool);
  7640. impl Drop for Stop<'_> {
  7641. fn drop(&mut self) {
  7642. self.0.store(true, Ordering::Relaxed);
  7643. }
  7644. }
  7645. // Held shared by who writes title memory, alone while it is looked at.
  7646. let still = std::sync::RwLock::new(());
  7647. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  7648. std::thread::scope(|s| {
  7649. for t in 0..2usize {
  7650. let (stop, still) = (&stop, &still);
  7651. s.spawn(move || {
  7652. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  7653. let mut value = 0u32;
  7654. while !stop.load(Ordering::Relaxed) {
  7655. {
  7656. let _moving = still.read().unwrap();
  7657. for _ in 0..3 {
  7658. value += 1;
  7659. // Of each eight dwords, one a thread.
  7660. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  7661. dword(at).store(value, Ordering::Relaxed);
  7662. }
  7663. }
  7664. std::thread::sleep(std::time::Duration::from_micros(20));
  7665. }
  7666. });
  7667. }
  7668. // Lands flights.
  7669. {
  7670. let (carded, stop) = (&carded, &stop);
  7671. s.spawn(move || {
  7672. let _stop = Stop(stop);
  7673. while let Ok((which, ranges, value)) = flights.recv() {
  7674. let c = &carded[which];
  7675. // Fetched: the card's bytes, behind every send so far.
  7676. let (after, now) = {
  7677. let card = c.card.lock().unwrap();
  7678. (card.0, card.2.clone())
  7679. };
  7680. // By piece: 64 KiB of title memory.
  7681. let mut pieces = Vec::new();
  7682. for &(from, to) in &ranges {
  7683. let mut at = from;
  7684. while at < to {
  7685. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  7686. pieces.push((at, next, now.as_ptr() as usize + at));
  7687. at = next;
  7688. }
  7689. }
  7690. let parts: Vec<_> = pieces.chunks(3).collect();
  7691. crate::land::each(parts.len(), &|i| {
  7692. let mut notes = crate::land::Notes::default();
  7693. // SAFETY: the bytes of `now`; each piece once.
  7694. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  7695. notes.flush();
  7696. });
  7697. for &(from, to) in &ranges {
  7698. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  7699. // (The next fetch may have brought more.)
  7700. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  7701. }
  7702. }
  7703. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  7704. c.shadow.copy_back_done(&done);
  7705. c.card.lock().unwrap().1 = after;
  7706. c.flying.store(false, Ordering::Release);
  7707. }
  7708. });
  7709. }
  7710. let _stop = Stop(&stop);
  7711. let mut random = Random(0xABCD_EF01_2345_6789);
  7712. let check = |round: usize, random: &mut Random, quiet: bool| {
  7713. for c in &carded {
  7714. if c.shadow.writes_pending() {
  7715. let mut runs = usize::MAX;
  7716. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  7717. }
  7718. }
  7719. let mut ranges = Vec::new();
  7720. for (shadow, start, len) in
  7721. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  7722. {
  7723. // All of it, or a part; often the same part.
  7724. let (from, n) = match random.below(3) {
  7725. _ if quiet => (0, len),
  7726. 0 => (0, len),
  7727. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  7728. _ => {
  7729. let from = random.below(len / 4) * 4;
  7730. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  7731. }
  7732. };
  7733. ranges.push((shadow.clone(), start + from, n));
  7734. }
  7735. submission(&ranges, 1 + random.below(3));
  7736. carded.iter().for_each(Carded::send);
  7737. };
  7738. let mut value = 1u32;
  7739. for round in 0..rounds {
  7740. check(round, &mut random, false);
  7741. // The flight of this submission: its shaders' writes.
  7742. for (which, c) in carded.iter().enumerate() {
  7743. if c.flying.swap(true, Ordering::Acquire) {
  7744. continue;
  7745. }
  7746. value += 1;
  7747. let mut ranges: Vec<(usize, usize)> = Vec::new();
  7748. let first = random.below(6) * PAGE / 2;
  7749. for k in 0..2 {
  7750. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  7751. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  7752. if from < to {
  7753. ranges.push((from, to));
  7754. }
  7755. }
  7756. for &(from, to) in &ranges {
  7757. c.shadow.writing(c.start + from, to - from);
  7758. }
  7759. {
  7760. let mut card = c.card.lock().unwrap();
  7761. for &(from, to) in &ranges {
  7762. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  7763. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  7764. }
  7765. }
  7766. }
  7767. fly.send((which, ranges, value)).unwrap();
  7768. }
  7769. if round % 20 != 19 {
  7770. continue;
  7771. }
  7772. // Still: no flight in the air, no title write.
  7773. let _still = still.write().unwrap();
  7774. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  7775. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  7776. std::thread::yield_now();
  7777. }
  7778. check(round, &mut random, true);
  7779. // SAFETY: the test's own memory, written by nobody now.
  7780. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  7781. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  7782. for c in &carded {
  7783. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  7784. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  7785. let card = c.card.lock().unwrap();
  7786. assert_eq!(first(&card.2, there), None, "round {round}: a card copy's card side (class {})", c.class);
  7787. }
  7788. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  7789. }
  7790. drop(fly);
  7791. });
  7792. }
  7793. /// The title's bytes put in under shader writes, for a copy of 174 MB
  7794. /// whose shader writes were declared as 40 ranges that overlap, with 12
  7795. /// pages written since. Run with `--ignored --nocapture`, and with
  7796. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  7797. #[test]
  7798. #[ignore]
  7799. fn bytes_under_overlapping_ranges() {
  7800. const BIG: usize = 174 << 20;
  7801. let big = title(BIG, true);
  7802. // SAFETY (both): the test's own memory.
  7803. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  7804. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  7805. copy.update(big, BIG);
  7806. copy.take_dirty();
  7807. for i in 0..40 {
  7808. copy.writing(big + i * 5920, BIG - i * 5920);
  7809. }
  7810. let mut best = f64::MAX;
  7811. for round in 0..30 {
  7812. for i in 0..12 {
  7813. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  7814. }
  7815. let started = std::time::Instant::now();
  7816. let mut runs = usize::MAX;
  7817. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  7818. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  7819. copy.take_dirty();
  7820. }
  7821. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  7822. }
  7823. /// A range nothing wrote is known to be as it was, at its ends too, and
  7824. /// is so no more once something wrote it.
  7825. #[test]
  7826. fn unchanged_ranges_are_known() {
  7827. for view in [false, true] {
  7828. let region = title(8 * PAGE, view);
  7829. // (A page read for the first time counts as written.)
  7830. // SAFETY: the test's own memory.
  7831. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  7832. let data = memory(8 * PAGE);
  7833. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  7834. // Ends in the middle of pages.
  7835. let (at, len) = (region + 500, 5 * PAGE);
  7836. let look = |expected: bool, what: &str| {
  7837. // The submission's one asking, which takes two ranges. (Again
  7838. // if a submission of another test ended it.)
  7839. let mut known = false;
  7840. for _ in 0..100 {
  7841. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  7842. known = copy.nothing_new(at, len);
  7843. if known || !expected {
  7844. break;
  7845. }
  7846. }
  7847. assert_eq!(known, expected, "view {view}: {what}");
  7848. let copied = copy.update(at, len);
  7849. crate::watch::ask_once_end();
  7850. copied
  7851. };
  7852. assert_eq!(look(false, "never taken"), len);
  7853. assert_eq!(look(true, "taken"), 0);
  7854. assert_eq!(look(true, "taken"), 0);
  7855. // SAFETY: the test's own memory.
  7856. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  7857. assert_eq!(look(false, "written at its end"), PAGE - 500);
  7858. assert_eq!(look(true, "taken again"), 0);
  7859. // Outside the range, on its last page.
  7860. // SAFETY: as above.
  7861. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  7862. assert_eq!(look(false, "written on its last page"), 500);
  7863. // A longer range was never taken whole.
  7864. assert!(!copy.nothing_new(region, 6 * PAGE));
  7865. }
  7866. }
  7867. /// A part of a copy in the card's memory taken again goes up only if it
  7868. /// differs (with `VICTORY_SEND_CHANGED=1`), whole when never taken.
  7869. #[test]
  7870. fn only_what_differs_goes_up() {
  7871. let region = title(4 * PAGE, true);
  7872. let data = memory(4 * PAGE);
  7873. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  7874. copy.update(region, 4 * PAGE);
  7875. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  7876. // What the relay does: shader writes into title memory, and into the
  7877. // CPU's side.
  7878. crate::watch::landing(region + PAGE + 640, 64);
  7879. // SAFETY: the test's own memory.
  7880. unsafe {
  7881. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  7882. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  7883. }
  7884. copy.update(region, 4 * PAGE);
  7885. let again = copy.take_dirty();
  7886. // SAFETY: as above.
  7887. unsafe { ((region + 2 * PAGE + 128) as *mut u8).write_volatile(9) };
  7888. copy.update(region, 4 * PAGE);
  7889. let written = copy.take_dirty();
  7890. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") {
  7891. assert_eq!(again, []);
  7892. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 192)]);
  7893. } else {
  7894. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  7895. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  7896. }
  7897. // SAFETY: as above.
  7898. assert_eq!(unsafe { data.add(2 * PAGE + 128).read() }, 9);
  7899. }
  7900. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  7901. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  7902. /// big copy that 55 landed pieces and 9 title writes opened, while a
  7903. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  7904. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  7905. #[test]
  7906. #[ignore]
  7907. fn frame_of_refreshes() {
  7908. let mut random = Random(0x9876_5432_1234_5671);
  7909. const EACH: usize = 224 << 10;
  7910. const BIG: usize = 174 << 20;
  7911. let watched = title(3000 * EACH, false);
  7912. let views = title(1400 * EACH, true);
  7913. let big = title(BIG, true);
  7914. // SAFETY: the test's own memory.
  7915. unsafe {
  7916. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  7917. std::ptr::write_bytes(views as *mut u8, 1, 1400 * EACH);
  7918. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  7919. }
  7920. let mut small = Vec::new();
  7921. for i in 0..4400 {
  7922. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  7923. let data = memory(EACH);
  7924. // The range views read, not all of the copy.
  7925. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  7926. }
  7927. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  7928. // The same memory, as another copy: what is landed is landed through
  7929. // it, and the refreshes are of the first.
  7930. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  7931. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  7932. let (mut sum, mut landing) = (0.0, 0.0);
  7933. const FRAMES: usize = 12;
  7934. for frame in 0..FRAMES {
  7935. let mut took = [0f64; 2];
  7936. for i in 0..30 {
  7937. // The title's writes, and the relay's beside the submission.
  7938. for _ in 0..9 {
  7939. let at = views + random.below(1400 * EACH / 8) * 8;
  7940. // SAFETY: the test's own memory.
  7941. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  7942. }
  7943. for _ in 0..60 {
  7944. let at = watched + random.below(3000 * EACH / 8) * 8;
  7945. // SAFETY: the test's own memory.
  7946. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  7947. }
  7948. let first = random.below(BIG / PAGE - 60);
  7949. let lands = lands.clone();
  7950. let land = std::thread::spawn(move || {
  7951. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  7952. let started = std::time::Instant::now();
  7953. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  7954. let pieces: Vec<_> =
  7955. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  7956. let mut notes = crate::land::Notes::default();
  7957. // SAFETY: the bytes of `now`; nothing else lands here.
  7958. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  7959. notes.flush();
  7960. }
  7961. started.elapsed().as_secs_f64() * 1e3
  7962. });
  7963. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  7964. small.iter().cloned().chain([heap.clone()]).collect()
  7965. } else {
  7966. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  7967. };
  7968. let started = std::time::Instant::now();
  7969. submission(&ranges, 3);
  7970. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  7971. let put = land.join().unwrap();
  7972. if frame >= 2 {
  7973. landing += put;
  7974. }
  7975. heap.0.take_dirty();
  7976. }
  7977. if frame >= 2 {
  7978. sum += took[0] + took[1];
  7979. for k in 0..2 {
  7980. best[k] = best[k].min(took[k]);
  7981. asking[k] += took[k];
  7982. }
  7983. }
  7984. }
  7985. println!(
  7986. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  7987. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  7988. crate::watch::light(),
  7989. sum / (FRAMES - 2) as f64,
  7990. asking[0] / (FRAMES - 2) as f64,
  7991. best[0],
  7992. asking[1] / (FRAMES - 2) as f64,
  7993. best[1],
  7994. landing / (FRAMES - 2) as f64,
  7995. );
  7996. #[cfg(feature = "diagnostics")]
  7997. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  7998. }
  7999. }
  8000. #[cfg(test)]
  8001. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  8002. use super::Batch;
  8003. use std::sync::Arc;
  8004. #[test]
  8005. fn a_texture_is_checked_once_per_submission() {
  8006. let mut batch = Batch::default();
  8007. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  8008. // The first list sampling each texture checks it ...
  8009. assert!(batch.texture_due(&a));
  8010. assert!(batch.texture_due(&b));
  8011. // ... later lists of the same submission do not.
  8012. assert!(!batch.texture_due(&a));
  8013. assert!(!batch.texture_due(&a.clone()));
  8014. assert!(!batch.texture_due(&b));
  8015. }
  8016. #[test]
  8017. fn title_writes_make_textures_due_again() {
  8018. let mut batch = Batch::default();
  8019. let a = Arc::new(1u32);
  8020. assert!(batch.texture_due(&a));
  8021. assert!(!batch.texture_due(&a));
  8022. // A copy into title memory or work that may write it may have
  8023. // changed the texture's memory.
  8024. batch.title_written();
  8025. assert!(batch.texture_due(&a));
  8026. assert!(!batch.texture_due(&a));
  8027. // A fresh submission starts over.
  8028. let mut next = Batch::default();
  8029. assert!(next.texture_due(&a));
  8030. }
  8031. /// The hashing a submission does for textures in physical-page memory,
  8032. /// with every list checking the textures it samples (before) and with
  8033. /// each checked once (after). Run with
  8034. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  8035. #[test]
  8036. #[ignore = "benchmark"]
  8037. fn texture_checks_per_submission() {
  8038. const TEXTURES: usize = 48;
  8039. const SIZE: usize = 4 << 20;
  8040. const LISTS: usize = 12;
  8041. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  8042. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  8043. .collect();
  8044. let submit = |dedupe: bool| {
  8045. let mut batch = Batch::default();
  8046. let mut hashed = 0usize;
  8047. let started = std::time::Instant::now();
  8048. for _ in 0..LISTS {
  8049. for t in &textures {
  8050. if !dedupe || batch.texture_due(t) {
  8051. std::hint::black_box(blake3::hash(t));
  8052. hashed += 1;
  8053. }
  8054. }
  8055. }
  8056. (started.elapsed(), hashed)
  8057. };
  8058. submit(false); // warm up
  8059. let (before, n_before) = submit(false);
  8060. let (after, n_after) = submit(true);
  8061. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  8062. println!(
  8063. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  8064. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  8065. SIZE >> 20,
  8066. before.as_secs_f64() / after.as_secs_f64()
  8067. );
  8068. }
  8069. #[test]
  8070. fn vram_idle_ms_scales_with_pressure() {
  8071. use super::vram_idle_ms;
  8072. let gib = 1024 * 1024 * 1024;
  8073. // Normal (< 75%)
  8074. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  8075. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  8076. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  8077. // Moderate (75%..85%)
  8078. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  8079. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  8080. // High (>= 85%, including over-budget)
  8081. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  8082. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  8083. // Missing or zero budget falls back to normal
  8084. assert_eq!(vram_idle_ms(None), 5_000);
  8085. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  8086. }
  8087. #[test]
  8088. fn ram_idle_ms_scales_with_pressure() {
  8089. use super::ram_idle_ms;
  8090. let gib = 1024 * 1024 * 1024;
  8091. // Normal (>= 4 GiB)
  8092. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  8093. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  8094. // Moderate (2 GiB..4 GiB)
  8095. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  8096. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  8097. // High (< 2 GiB)
  8098. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  8099. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  8100. // Missing falls back to normal
  8101. assert_eq!(ram_idle_ms(None), 10_000);
  8102. }
  8103. }