host.rs 411 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350
  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. /// How long host copies of textures the title fills must have been idle to
  107. /// be let go, in milliseconds, and how many bytes of them go at most (the
  108. /// longest idle first): none but those of ten minutes while what is in use
  109. /// of the card (`used`: without what our own blocks have free, with what is
  110. /// kept free for others) is under 88 % of its budget, else enough to come
  111. /// down to 85 %. `VICTORY_TEXTURE_KEEP=0`: [`vram_idle_ms`]' older rule,
  112. /// all that are idle; `=1`: that rule with its two longer times.
  113. ///
  114. /// (By those times everything idle for 2.5 s went from 75 % of the budget
  115. /// on: 61,000 of them in the first 300 s of session play-1125-0203, at 78 to
  116. /// 80 %, of which 13,000 were made and uploaded again.)
  117. pub(crate) fn vram_keep(budget: u64, used: u64) -> (u64, u64) {
  118. const KEPT_MS: u64 = 600_000;
  119. const IDLE_MS: u64 = 5_000;
  120. const SHORT_MS: u64 = 1_500;
  121. if budget == 0 {
  122. return (IDLE_MS, u64::MAX);
  123. }
  124. let share = |percent: u64| budget / 100 * percent;
  125. if used < share(88) {
  126. (KEPT_MS, u64::MAX)
  127. } else if used < share(95) {
  128. (IDLE_MS, used - share(85))
  129. } else {
  130. (SHORT_MS, used - share(85))
  131. }
  132. }
  133. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  134. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  135. /// handles not yet recorded into a list or slot remain protected.
  136. ///
  137. /// With room on the card nothing has to go: in session play-1125-0127 88,000
  138. /// of them (31 GB) went after 5 s with 7 GB of the card free, and 24,700
  139. /// (12 GB) had to be made and uploaded again.
  140. /// `VICTORY_TEXTURE_KEEP=0`: 5 s there too, as before.
  141. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  142. static KEEP: OnceLock<bool> = OnceLock::new();
  143. let keep = *KEEP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_KEEP").is_none_or(|v| v != "0"));
  144. vram_idle_for(video_memory, keep)
  145. }
  146. fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 {
  147. const KEPT_MS: u64 = 600_000;
  148. const LONG_MS: u64 = 30_000;
  149. const NORMAL_MS: u64 = 5_000;
  150. const MODERATE_MS: u64 = 2_500;
  151. const HIGH_MS: u64 = 1_000;
  152. let Some([budget, used, ..]) = video_memory else {
  153. return NORMAL_MS;
  154. };
  155. if budget == 0 {
  156. return NORMAL_MS;
  157. }
  158. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  159. if used_pct >= 85 {
  160. HIGH_MS
  161. } else if used_pct >= 75 {
  162. MODERATE_MS
  163. } else if !keep {
  164. NORMAL_MS
  165. } else if used_pct >= 68 {
  166. LONG_MS
  167. } else {
  168. KEPT_MS
  169. }
  170. }
  171. /// Whether memory the card was given stays with it while there is room (on
  172. /// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader
  173. /// that reads past a view (a raw load through a typed, structured or
  174. /// constant buffer view has no end on AMD: `indirect::tests::raw_loads_past_views`)
  175. /// or through a slot that shows wrong data reads whatever lies there, and
  176. /// nothing happens; where memory was given back it is a page fault, and the
  177. /// device is lost. Both losses of 2026-11-25 were reads in memory given back
  178. /// seconds before (a block of textures; a list's scratch and a window of
  179. /// title memory). Kept are: empty blocks of textures ([`crate::pool`]) below
  180. /// 85 % of the card's budget, windows of title memory and staging buffers
  181. /// for five minutes with 12 GiB of the PC's memory free, and 1 GiB of
  182. /// scratch chunks.
  183. pub(crate) fn keep_freed() -> bool {
  184. static ON: OnceLock<bool> = OnceLock::new();
  185. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_FREED").is_none_or(|v| v != "0"))
  186. }
  187. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  188. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  189. /// when free physical RAM is low. Never returns less than 2,000 ms.
  190. /// With plenty of it five minutes ([`keep_freed`]).
  191. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  192. ram_idle_for(avail_phys, keep_freed())
  193. }
  194. fn ram_idle_for(avail_phys: Option<u64>, keep: bool) -> u64 {
  195. const GIB: u64 = 1024 * 1024 * 1024;
  196. const KEPT_MS: u64 = 300_000;
  197. if keep && avail_phys.is_some_and(|avail| avail >= 12 * GIB) {
  198. return KEPT_MS;
  199. }
  200. const NORMAL_MS: u64 = 10_000;
  201. const MODERATE_MS: u64 = 5_000;
  202. const HIGH_MS: u64 = 2_000;
  203. let Some(avail) = avail_phys else {
  204. return NORMAL_MS;
  205. };
  206. if avail < 2 * GIB {
  207. HIGH_MS
  208. } else if avail < 4 * GIB {
  209. MODERATE_MS
  210. } else {
  211. NORMAL_MS
  212. }
  213. }
  214. /// How many references are held on a host object (its COM count): ours
  215. /// all, since the host's views and commands hold none. A buffer or texture
  216. /// with one is held by its owner alone: no descriptor slot keeps it
  217. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  218. pub(crate) fn references(object: &impl Interface) -> u32 {
  219. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  220. let raw = object.as_raw();
  221. // SAFETY: a live COM object, whose first three methods are those of
  222. // `IUnknown` (query, add a reference, release one); the pair leaves the
  223. // count as it was, and the release returns it. The first is not called.
  224. unsafe {
  225. let methods = *raw.cast::<*const [Method; 3]>();
  226. ((*methods)[1])(raw);
  227. ((*methods)[2])(raw)
  228. }
  229. }
  230. /// Once a second, before a submission starts: lets go of what nothing
  231. /// names any more (copies of windows of title memory, staging buffers,
  232. /// host copies of textures the title fills).
  233. /// `VICTORY_SWEEP=0` keeps everything, as before.
  234. fn sweep() {
  235. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  236. crate::inplace::tick();
  237. static ON: OnceLock<bool> = OnceLock::new();
  238. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  239. return;
  240. }
  241. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  242. let now = now_ms();
  243. let last = LAST.load(Ordering::Relaxed);
  244. if now < last + 1000
  245. || LAST
  246. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  247. .is_err()
  248. {
  249. return;
  250. }
  251. crate::pool::room(host().and_then(|h| h.video_memory()));
  252. crate::pipeline::trim_library();
  253. crate::shadow::let_go_idle();
  254. crate::texture::let_go_idle();
  255. crate::resource::let_go_idle();
  256. }
  257. /// The number of the newest submission begun, and of the newest of which all
  258. /// before it have finished too.
  259. pub(crate) fn submissions() -> (u64, u64) {
  260. (STARTED.load(Ordering::Acquire), FINISHED.load(Ordering::Acquire))
  261. }
  262. /// Drops `object` once every submission running now has finished: at once
  263. /// if none is.
  264. pub(crate) fn retire<T: 'static>(object: T) {
  265. // (Those the title made and the host has not begun get the next numbers.)
  266. let queued = crate::queue::queued();
  267. let started = STARTED.load(Ordering::Acquire) + queued;
  268. if started <= FINISHED.load(Ordering::Acquire) {
  269. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  270. drop(object);
  271. return;
  272. }
  273. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  274. RETIRED
  275. .lock()
  276. .unwrap_or_else(|e| e.into_inner())
  277. .push((started, Retired(Box::new(object))));
  278. }
  279. /// Drops what waited for submissions up to `finished`.
  280. fn bury(finished: u64) {
  281. let done: Vec<(u64, Retired)> = {
  282. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  283. if retired.is_empty() {
  284. return;
  285. }
  286. let (done, keep) = std::mem::take(&mut *retired)
  287. .into_iter()
  288. .partition(|(at, _)| *at <= finished);
  289. *retired = keep;
  290. done
  291. };
  292. drop(done);
  293. }
  294. /// Objects [`retire`] dropped at once (no submission was running) and
  295. /// kept until a running submission finished, since the start.
  296. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  297. /// What the layer did to the host's objects lately, newest last (sweeps
  298. /// that let host copies go, pipeline library calls, saves and trims): said
  299. /// once when the host device is removed ([`log_removal_context`]), with
  300. /// what the submitting thread and the pipeline workers were doing at that
  301. /// moment. A device the driver removes "internally" names no command, and
  302. /// the pass that happens to notice first names only the view it was at:
  303. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  304. /// pipeline library call that no line of the log tied to them.
  305. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  306. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  307. /// The entries kept.
  308. const TRAIL_MOST: usize = 96;
  309. fn trail_on() -> bool {
  310. static ON: OnceLock<bool> = OnceLock::new();
  311. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  312. }
  313. /// Microseconds since the first call.
  314. pub(crate) fn now_us() -> u64 {
  315. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  316. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  317. }
  318. /// The calling thread, as the log's other lines name threads.
  319. pub(crate) fn thread_id() -> u32 {
  320. // SAFETY: a plain query.
  321. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  322. }
  323. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  324. /// run when the trail is kept.
  325. pub(crate) fn trail(what: impl FnOnce() -> String) {
  326. if !trail_on() {
  327. return;
  328. }
  329. let entry = (now_us(), thread_id(), what());
  330. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  331. if trail.len() >= TRAIL_MOST {
  332. trail.pop_front();
  333. }
  334. trail.push_back(entry);
  335. }
  336. /// What the submitting thread is doing (0 nothing: between submissions,
  337. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  338. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  339. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  340. fn submitting(phase: u64, lists: usize) {
  341. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  342. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  343. SUBMITTING[0].store(phase, Ordering::Relaxed);
  344. }
  345. /// What was going on when the host device went: whether a submission was
  346. /// on the card, the pipeline library's state and the calls running in it,
  347. /// and the trail.
  348. pub(crate) fn removal_context() -> String {
  349. use std::fmt::Write;
  350. let now = now_us();
  351. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  352. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  353. 0 => "between submissions (nothing of ours was running on the card)",
  354. 1 => "preparing a submission (nothing of ours was running on the card)",
  355. 2 => "waiting for the card to run a submission",
  356. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  357. };
  358. let mut text = format!(
  359. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  360. SUBMITTING[1].load(Ordering::Relaxed),
  361. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  362. crate::pipeline::library_removal_note(),
  363. RETIREMENTS[0].load(Ordering::Relaxed),
  364. RETIREMENTS[1].load(Ordering::Relaxed),
  365. STARTED.load(Ordering::Relaxed),
  366. FINISHED.load(Ordering::Relaxed),
  367. );
  368. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  369. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  370. for (at, thread, what) in trail.iter() {
  371. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  372. }
  373. text
  374. }
  375. /// Says [`removal_context`] in the log, once: called by whoever finds the
  376. /// host device removed.
  377. pub(crate) fn log_removal_context() {
  378. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  379. if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) {
  380. return;
  381. }
  382. tracing::error!("when the host device went: {}", removal_context());
  383. if dred_any() {
  384. let data = host().map(|h| h.removal_data(&[])).unwrap_or_default();
  385. tracing::error!("device-removed data{}", if data.is_empty() { "; none" } else { &data });
  386. }
  387. }
  388. /// Time spent in submissions since the last frame-rate line, in
  389. /// microseconds: preparing them on the CPU (title memory copies, texture
  390. /// detiling), then waiting for the GPU.
  391. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  392. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  393. /// After submissions: shader-written ranges compared and copied back into
  394. /// title memory (microseconds, bytes that differed), since the last
  395. /// frame-rate line.
  396. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  397. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  398. /// The card's clock, for the frame line of every run, in microseconds since
  399. /// the last one: how long the card had nothing of ours queued; how much of
  400. /// that while the thread that holds the submission lock was working (the
  401. /// card idle behind us: preparing and copying back are done with the card
  402. /// standing); and how long that thread stood waiting for the card.
  403. ///
  404. /// Every send of lists to the queue is followed by a signal on a fence of
  405. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  406. /// the newest signal and notes the moment the card reached it with nothing
  407. /// newer sent; the next send ends that idle stretch.
  408. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  409. /// Of the thread that holds the submission lock: the microseconds it has
  410. /// worked so far (preparing, copying back; not its waits for the card), and
  411. /// since when it works now ([`now_us`] plus one; 0: it does not).
  412. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  413. /// The thread that holds the submission lock starts (`on`) or stops
  414. /// working; whether it worked until now.
  415. fn working(on: bool) -> bool {
  416. let now = now_us() + 1;
  417. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  418. if since != 0 {
  419. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  420. }
  421. since != 0
  422. }
  423. /// [`WORKING`] as of now: microseconds worked so far.
  424. fn worked() -> u64 {
  425. let since = WORKING[1].load(Ordering::Relaxed);
  426. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  427. WORKING[0].load(Ordering::Relaxed) + now
  428. }
  429. /// The thread that holds the submission lock stood waiting for the card
  430. /// from `since` until now ([`CARD_CLOCK_US`]).
  431. fn stood(since: std::time::Instant) {
  432. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  433. }
  434. /// What [`CARD_CLOCK_US`] is measured with.
  435. struct CardClock {
  436. fence: ID3D12Fence,
  437. /// Signals sent so far; and, while the card has reached the last of
  438. /// them, since when and what [`worked`] said then.
  439. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  440. sent: std::sync::Condvar,
  441. }
  442. // SAFETY: a fence (free-threaded) behind a lock.
  443. unsafe impl Send for CardClock {}
  444. // SAFETY: as above.
  445. unsafe impl Sync for CardClock {}
  446. /// The clock's thread: waits for the newest signal sent and notes when the
  447. /// card got there with nothing newer behind it.
  448. fn card_clock_watch(clock: &'static CardClock) {
  449. // SAFETY: a plain event of our own.
  450. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  451. return;
  452. };
  453. let mut seen = 0;
  454. loop {
  455. let target = {
  456. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  457. while state.0 == seen {
  458. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  459. }
  460. state.0
  461. };
  462. // SAFETY: the clock's fence and this thread's event.
  463. unsafe {
  464. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  465. WaitForSingleObject(event, INFINITE);
  466. }
  467. }
  468. seen = target;
  469. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  470. if state.0 == target && state.1.is_none() {
  471. state.1 = Some((std::time::Instant::now(), worked()));
  472. }
  473. }
  474. }
  475. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  476. /// frame's time.
  477. fn card_clock_line(frames: f64, ms: f64) {
  478. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  479. tracing::info!(
  480. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  481. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  482. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  483. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  484. );
  485. }
  486. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  487. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  488. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  489. std::sync::atomic::AtomicU64::new(0),
  490. std::sync::atomic::AtomicU64::new(0),
  491. std::sync::atomic::AtomicU64::new(0),
  492. std::sync::atomic::AtomicU64::new(0),
  493. ];
  494. /// Host buffers made since the start, as (count, bytes): in the upload heap
  495. /// (staging, list scratch), shared with the processor (host copies of title
  496. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  497. /// For the memory line: against what is alive, they show what was let go.
  498. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  499. /// What of that is alive now, for the memory line (`MADE` counts what was
  500. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  501. /// and nothing said how many were alive): host lists; the lists' scratch
  502. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  503. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  504. /// instead of made, since the start; and the lists' other upload buffers
  505. /// (texture data copied from buffers, scratch too big for a chunk) and
  506. /// their bytes.
  507. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  508. /// About host lists, for the memory line: lists made by the host since the
  509. /// start; preludes made (a list's second allocator and list, made when it
  510. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  511. /// bytes the process's private memory grew by while lists were being made
  512. /// (what a list costs: host objects with the driver's command memory; 631
  513. /// lists were alive in run 65, each with a prelude it may never use).
  514. /// Then the lists alive that were never reset since they were made: the
  515. /// host sides of title lists the title made and has not used (a host list
  516. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  517. /// makes at its start).
  518. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  519. /// The process's private bytes (diagnostics: around the making of lists).
  520. #[cfg(feature = "diagnostics")]
  521. fn private_bytes() -> u64 {
  522. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  523. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  524. let mut c = PROCESS_MEMORY_COUNTERS {
  525. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  526. ..Default::default()
  527. };
  528. // SAFETY: our own process and a sized structure.
  529. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  530. c.PagefileUsage as u64
  531. }
  532. /// What the runtime does when the host GPU fails for good: report it like a
  533. /// crash and end the run. The console has no such state, and carrying on
  534. /// draws nothing at seconds per frame.
  535. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  536. /// Sets what a host GPU failure does (the runtime's crash report).
  537. pub fn on_failure(report: fn(&str) -> !) {
  538. let _ = ON_FAILURE.set(report);
  539. }
  540. /// Ends the run on a host GPU failure: what failed, the removal reason and
  541. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  542. /// diagnostics build names the command).
  543. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  544. let mut text = what.to_string();
  545. if let Some(host) = host() {
  546. // SAFETY: a plain query.
  547. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  548. text.push_str(&format!("; device removed: {e}"));
  549. log_removal_context();
  550. }
  551. match host.log_messages() {
  552. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  553. None if host.messages.is_none() => text.push_str(
  554. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  555. ),
  556. None => {}
  557. }
  558. }
  559. tracing::error!("{text}");
  560. // Tests have no log: the reason goes to their output.
  561. #[cfg(test)]
  562. eprintln!("host GPU failure: {text}");
  563. match ON_FAILURE.get() {
  564. Some(report) => report(&text),
  565. None => std::process::abort(),
  566. }
  567. }
  568. /// The host GPU, created on first use; `None` without one (a run then
  569. /// behaves as before: nothing executes).
  570. pub(crate) fn host() -> Option<&'static Host> {
  571. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  572. HOST.get_or_init(|| match create() {
  573. Ok(host) => Some(host),
  574. Err(e) => {
  575. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  576. None
  577. }
  578. })
  579. .as_ref()
  580. }
  581. fn create() -> windows::core::Result<Host> {
  582. // SAFETY: plain D3D12 object creation with valid descriptions.
  583. unsafe {
  584. // The debug layer only in builds with diagnostics.
  585. let debug = cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DEBUG");
  586. if debug {
  587. let mut layer: Option<ID3D12Debug> = None;
  588. match D3D12GetDebugInterface(&mut layer) {
  589. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  590. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  591. }
  592. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  593. // descriptor heap indices and the like become messages naming
  594. // the command instead of page faults. Without state tracking
  595. // (directly indexed textures are not transitioned).
  596. if crate::switch::on("VICTORY_D3D12_GBV")
  597. && let Some(l) = &layer
  598. {
  599. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  600. d1.SetEnableGPUBasedValidation(true);
  601. }
  602. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  603. d2.SetGPUBasedValidationFlags(
  604. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  605. );
  606. }
  607. tracing::info!("GPU-based validation on");
  608. }
  609. }
  610. // Diagnostics: device-removed data (the command that faulted, the
  611. // faulting address), read when the device is removed.
  612. if dred_any() {
  613. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  614. if D3D12GetDebugInterface(&mut dred).is_ok()
  615. && let Some(dred) = dred
  616. {
  617. if dred_on() || dred_light() {
  618. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  619. }
  620. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  621. tracing::info!(
  622. breadcrumbs = dred_on() || dred_light(),
  623. markers = dred_on(),
  624. "crash tracing on (device-removed data)"
  625. );
  626. } else {
  627. tracing::warn!("crash tracing asked for and not there: no device-removed data settings");
  628. }
  629. }
  630. let mut device: Option<ID3D12Device> = None;
  631. // Diagnostics: the software adapter, on which a shader's wild access
  632. // is an access violation in this process (a crash report with the
  633. // address and instruction) instead of a GPU fault and driver reset.
  634. if cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_WARP") {
  635. let adapter = warp_adapter()?;
  636. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  637. tracing::info!("host device on the software adapter (WARP)");
  638. } else {
  639. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  640. // Whether a GPU hang ends the run or freezes the PC (#1054).
  641. crate::tdr::log();
  642. }
  643. let device = device.ok_or_else(windows::core::Error::empty)?;
  644. // Before anything is made with it (`VICTORY_RECORD`).
  645. #[cfg(feature = "diagnostics")]
  646. crate::replay::record::from_env(&device);
  647. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  648. // driver compiling shaders again on the "D3D Background Thread"s,
  649. // for minutes after pipelines were made or loaded) is switched off.
  650. // An experiment: while those threads ran, the same shot took
  651. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  652. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  653. // whether the card is slower with the shaders it then keeps is not
  654. // known.
  655. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  656. && let Ok(device6) = device.cast::<ID3D12Device6>()
  657. {
  658. let set = device6.SetBackgroundProcessingMode(
  659. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  660. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  661. None,
  662. None,
  663. );
  664. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  665. }
  666. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  667. // cross-lane code stays in 32-lane halves translated for waves of 32
  668. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  669. if device
  670. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  671. .is_ok()
  672. {
  673. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  674. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  675. }
  676. let messages = debug
  677. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  678. .flatten();
  679. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  680. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  681. ..Default::default()
  682. })?;
  683. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  684. let event = CreateEventW(None, false, false, None)?;
  685. let rtvs: ID3D12DescriptorHeap =
  686. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  687. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  688. NumDescriptors: RTV_RING,
  689. ..Default::default()
  690. })?;
  691. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  692. let dsvs: ID3D12DescriptorHeap =
  693. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  694. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  695. NumDescriptors: RTV_RING,
  696. ..Default::default()
  697. })?;
  698. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  699. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  700. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  701. .ok();
  702. tracing::info!("host D3D12 device ready");
  703. Ok(Host {
  704. device,
  705. queue,
  706. fence,
  707. submitted: Mutex::new(0),
  708. event,
  709. rtvs,
  710. rtv_size,
  711. dsvs,
  712. dsv_size,
  713. next_dsv: AtomicU32::new(0),
  714. messages,
  715. next_rtv: AtomicU32::new(0),
  716. presenter: Mutex::new(None),
  717. adapter,
  718. })
  719. }
  720. }
  721. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  722. /// Reject it before creating a device in diagnostics' software-only mode.
  723. pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  724. // SAFETY: plain DXGI adapter queries.
  725. unsafe {
  726. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  727. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  728. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  729. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  730. tracing::warn!(
  731. vendor = format_args!("{:#x}", desc.VendorId),
  732. flags = format_args!("{:#x}", desc.Flags),
  733. "DXGI did not identify the WARP adapter as software; refusing device"
  734. );
  735. return Err(windows::core::Error::from_hresult(
  736. windows::Win32::Foundation::E_FAIL,
  737. ));
  738. }
  739. Ok(adapter)
  740. }
  741. }
  742. #[cfg(test)]
  743. mod tests {
  744. /// A list of ours is found by its name, with the debug layer's note or not.
  745. #[cfg(feature = "diagnostics")]
  746. #[test]
  747. fn a_list_is_found_by_the_number_in_its_name() {
  748. assert_eq!(super::list_number("victory host list 7"), Some(7));
  749. assert_eq!(super::list_number("victory host list 158 (debug layer indirect)"), Some(158));
  750. assert_eq!(super::list_number("victory host list 7x"), None);
  751. assert_eq!(super::list_number("victory host list 7 x"), None);
  752. assert_eq!(super::list_number("another list 7"), None);
  753. assert_eq!(super::list_number(""), None);
  754. }
  755. /// What is there of a range some of whose pages are not: those bytes,
  756. /// counted, and zeros for the rest, whatever the buffer held.
  757. #[test]
  758. fn what_is_there_is_read_and_the_rest_is_zeros() {
  759. use windows_sys::Win32::System::Memory::*;
  760. const SIZE: usize = 0x8_0000;
  761. // SAFETY: a reservation of ours; only committed pages are written.
  762. unsafe {
  763. let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  764. assert!(!at.is_null());
  765. // 0-0x1_1000 and 0x3_0000-0x4_0000 are there.
  766. for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] {
  767. assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null());
  768. at.add(from).write_bytes(0x5a, len);
  769. }
  770. // From an address inside a page, as textures are packed.
  771. let mut out = vec![0x77u8; SIZE - 0x300];
  772. assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000);
  773. for (i, &b) in out.iter().enumerate() {
  774. let from = i + 0x300;
  775. let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from);
  776. assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}");
  777. }
  778. // All there: one read.
  779. let mut out = vec![0x77u8; 0x1_0000];
  780. assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000);
  781. assert!(out.iter().all(|&b| b == 0x5a));
  782. // Nothing there.
  783. let mut out = vec![0x77u8; 0x1_0000];
  784. assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0);
  785. assert!(out.iter().all(|&b| b == 0));
  786. assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0);
  787. }
  788. }
  789. /// Zeros for a title destination that went meanwhile are no fault.
  790. #[test]
  791. fn zeros_where_nothing_is_are_lost() {
  792. use windows_sys::Win32::System::Memory::*;
  793. // SAFETY: a reservation of ours, its first page committed.
  794. unsafe {
  795. let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  796. assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
  797. at.write_bytes(7, 4096);
  798. super::zero(at, 4096);
  799. assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
  800. super::zero(at.add(4096), 4096);
  801. VirtualFree(at.cast(), 0, MEM_RELEASE);
  802. }
  803. }
  804. #[test]
  805. fn sparse_copies_preserve_islands_and_observe_remaps() {
  806. use windows_sys::Win32::System::Memory::*;
  807. const N: usize = 5 << 16;
  808. // SAFETY: we reserve a private region, commit selected pages inside it,
  809. // and only directly access the pages while they are writable.
  810. unsafe {
  811. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  812. assert!(!base.is_null());
  813. let mut expected = vec![0; N];
  814. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  815. let at = base.add(offset);
  816. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  817. at.write_bytes(value, 4096);
  818. expected[offset..offset + 4096].fill(value);
  819. }
  820. for remap in [false, true] {
  821. if remap {
  822. let mut old = 0;
  823. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  824. expected[..4096].fill(0);
  825. let at = base.add(1 << 16);
  826. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  827. at.write_bytes(0xc7, 4096);
  828. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  829. }
  830. let mut out = vec![0xee; N];
  831. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  832. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  833. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  834. }
  835. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  836. }
  837. }
  838. use super::*;
  839. #[test]
  840. fn warp_adapter_accepts_only_software() {
  841. // This probes DXGI without creating a D3D12 device or running a title.
  842. // SAFETY: plain DXGI adapter queries.
  843. let raw = unsafe {
  844. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  845. else {
  846. return;
  847. };
  848. factory.EnumWarpAdapter::<IDXGIAdapter>()
  849. };
  850. let Ok(raw) = raw else { return };
  851. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  852. // IDXGIAdapter1; `raw` owns that interface.
  853. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  854. eprintln!(
  855. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  856. desc.VendorId, desc.Flags
  857. );
  858. assert_eq!(
  859. warp_adapter().is_ok(),
  860. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  861. );
  862. }
  863. }
  864. /// The batches of clamped records in one scratch buffer
  865. /// ([`HostList::batch_place`]).
  866. const BATCHES: u32 = 8;
  867. /// A host command list and its allocator, always used together.
  868. pub(crate) struct HostList {
  869. allocator: ID3D12CommandAllocator,
  870. pub(crate) list: ID3D12GraphicsCommandList,
  871. /// Work for submission time, in recorded order.
  872. deferred: Mutex<Deferred>,
  873. /// Upload memory for data the list's draws make (expanded vertices),
  874. /// reused after a reset.
  875. scratch: Mutex<Scratch>,
  876. /// Host texture states the list assumes, by host copy: at its start and
  877. /// at its end. Lists are recorded on many threads and run in submission
  878. /// order, so the transitions from a texture's real state are made at
  879. /// submission, in `prelude`. Holding the copies keeps every texture the
  880. /// list names alive until it is reset, even if the title releases the
  881. /// resource first.
  882. states: Mutex<States>,
  883. /// What the list does with depth textures that have a colour twin, by
  884. /// twin ([`TwinUse`]).
  885. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  886. /// The list that runs those transitions just before this one, made
  887. /// when the list first has such transitions ([`lazy_prelude`]).
  888. prelude: OnceLock<Option<Prelude>>,
  889. /// The pipelines the list binds, for reports of slow submissions.
  890. pipelines: std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>,
  891. /// What its indirect executions ran, for the report of a removed device.
  892. #[cfg(feature = "diagnostics")]
  893. indirects: indirects::Shared,
  894. /// The work its indirect executions may still do (`indirect`): a
  895. /// shader-writable word, zeroed when the list is submitted, and after
  896. /// it what the clamp notes about mesh records. In memory the CPU maps.
  897. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  898. /// The same words in the card's own memory ([`card_budget`]), which the
  899. /// clamp uses instead when there is one: zeroed in the list before its
  900. /// first clamp, its notes copied to `budget` when the list closes.
  901. card_budget: OnceLock<Option<ID3D12Resource>>,
  902. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  903. /// grown to the largest indirect execution recorded on the list.
  904. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  905. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  906. /// how many batches of this recording have a place in them.
  907. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  908. /// Refreshes of host copies that a thread of ours is still finding, and
  909. /// where among the list's steps they belong ([`aside`]).
  910. coming: Mutex<Option<(usize, std::sync::Arc<aside::Coming>)>>,
  911. /// Counts the list in [`ALIVE`] while it lives.
  912. _alive: Counted,
  913. /// The texts of the markers `note_op` set, in order (for device-removed
  914. /// data without marker texts), with the host GPU range a copy reads.
  915. #[cfg(feature = "diagnostics")]
  916. notes: std::sync::Arc<Mutex<Vec<Note>>>,
  917. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  918. /// and at the end, and where they are read back.
  919. #[cfg(feature = "diagnostics")]
  920. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  921. }
  922. /// A list's prelude: an allocator and a closed list.
  923. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  924. /// Whether a host list's prelude is made when the list first needs one. A
  925. /// prelude runs the texture transitions and twin copies a list needs before
  926. /// it; lists that name no texture never have one, and every host list was
  927. /// made with one all the same: twice the host objects per list, for the
  928. /// title's 630 lists and for every list made anew.
  929. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  930. fn lazy_prelude() -> bool {
  931. static ON: OnceLock<bool> = OnceLock::new();
  932. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  933. }
  934. /// Timestamps per list (diagnostics); commands past them are not timed.
  935. #[cfg(feature = "diagnostics")]
  936. const STAMPS: u32 = 4096;
  937. /// A marker's text and the host range its command reads (diagnostics).
  938. #[cfg(feature = "diagnostics")]
  939. type Note = (String, Option<(u64, u64)>);
  940. type States = std::collections::HashMap<
  941. usize,
  942. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  943. >;
  944. /// What a list does with a depth texture that has a colour twin
  945. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  946. /// in submission order, so a list cannot know which side an earlier list
  947. /// leaves behind: it notes which sides it uses as it finds them, and its
  948. /// prelude copies one side into the other at submission if that side is
  949. /// behind then. From its first use of a side on, the list knows.
  950. struct TwinUse {
  951. /// The depth texture (the title resource's host copy) and its twin.
  952. depth: std::sync::Arc<crate::resource::HostTexture>,
  953. twin: std::sync::Arc<crate::resource::Twin>,
  954. /// The sides (depth texture, twin) the list uses as it finds them.
  955. needs: [bool; 2],
  956. /// Whether each side lacks what the other was written last, where the
  957. /// list is now; `None`: as the list found it.
  958. behind: [Option<bool>; 2],
  959. /// The draw or dispatch being prepared writes the twin.
  960. writing: bool,
  961. /// The depth plane's twin holds what the plane lacks although the list
  962. /// copied the twins since: the plane's pass waits for the list's close.
  963. late: bool,
  964. }
  965. /// The pass that draws the twin of a depth plane into the plane: one
  966. /// triangle over each mip of each slice, its pixel shader writing the
  967. /// twin's texel as the depth, with the depth test "always" and no stencil
  968. /// (the stencil plane is copied through a buffer and not touched here).
  969. ///
  970. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  971. /// the step times the float nearest 1/65535 (0x37800080). That is how
  972. /// The title's tiled lighting computes the depth of the
  973. /// rectangles it then draws with the test "equal", one class of materials
  974. /// a draw (all six of its vertex shaders multiply the class number by that
  975. /// constant), so the pass and the draw give the host the same float, and
  976. /// the host turns the same float into the same 24 bits. The step divided
  977. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  978. /// and lands in another 24-bit step for 127 of them (none under 385).
  979. const PLANE_CORNERS: &str = r#"
  980. float4 corner(uint i : SV_VertexID) : SV_Position {
  981. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  982. }
  983. "#;
  984. const PLANE_STEPS: &str = r#"
  985. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  986. Texture2DArray<uint> twin : register(t0);
  987. [RootSignature(RS)]
  988. float plane(float4 p : SV_Position) : SV_Depth {
  989. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  990. }
  991. "#;
  992. const PLANE_FLOATS: &str = r#"
  993. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  994. Texture2DArray<float> twin : register(t0);
  995. [RootSignature(RS)]
  996. float plane(float4 p : SV_Position) : SV_Depth {
  997. return twin.Load(int4(int2(p.xy), 0, 0));
  998. }
  999. "#;
  1000. /// Views of twins the pass reads, in a heap of ours used as a ring.
  1001. /// shortcut: a view must last until its list has run; with one or two
  1002. /// passes a frame the ring is far from coming round.
  1003. const PLANE_VIEWS: u32 = 256;
  1004. /// What the pass draws with: the heap of its views of twins, and per kind
  1005. /// of twin (16-bit steps or floats) and depth format the root signature
  1006. /// and pipeline, made when first needed (`None`: the host refused).
  1007. struct PlanePass {
  1008. views: ID3D12DescriptorHeap,
  1009. cpu: usize,
  1010. gpu: u64,
  1011. step: u32,
  1012. next: AtomicU32,
  1013. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  1014. }
  1015. /// The pass's root signature and pipeline for one kind of twin and one
  1016. /// depth format.
  1017. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  1018. // SAFETY: D3D12 objects are free-threaded.
  1019. unsafe impl Send for PlanePass {}
  1020. // SAFETY: as above.
  1021. unsafe impl Sync for PlanePass {}
  1022. fn plane_pass() -> Option<&'static PlanePass> {
  1023. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  1024. PASS.get_or_init(|| {
  1025. let host = host()?;
  1026. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1027. // SAFETY: plain heap creation and queries.
  1028. unsafe {
  1029. let views: ID3D12DescriptorHeap = host
  1030. .device
  1031. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  1032. Type: kind,
  1033. NumDescriptors: PLANE_VIEWS,
  1034. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  1035. NodeMask: 0,
  1036. })
  1037. .ok()?;
  1038. Some(PlanePass {
  1039. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  1040. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  1041. step: host.device.GetDescriptorHandleIncrementSize(kind),
  1042. views,
  1043. next: AtomicU32::new(0),
  1044. made: Mutex::default(),
  1045. })
  1046. }
  1047. })
  1048. .as_ref()
  1049. }
  1050. /// Compiles function `entry` of `source` for `target` with the system's
  1051. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  1052. pub(crate) fn compile(
  1053. source: &str,
  1054. entry: windows::core::PCSTR,
  1055. target: windows::core::PCSTR,
  1056. ) -> windows::core::Result<Vec<u8>> {
  1057. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  1058. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  1059. let mut code: Option<ID3DBlob> = None;
  1060. let mut errors: Option<ID3DBlob> = None;
  1061. // SAFETY: the source and names live through the call; out pointers ours.
  1062. let compiled = unsafe {
  1063. D3DCompile(
  1064. source.as_ptr().cast(),
  1065. source.len(),
  1066. windows::core::s!("victory"),
  1067. None,
  1068. None,
  1069. entry,
  1070. target,
  1071. 0,
  1072. 0,
  1073. &mut code,
  1074. Some(&mut errors),
  1075. )
  1076. };
  1077. if let Err(e) = compiled {
  1078. if let Some(errors) = errors {
  1079. // SAFETY: the blob's own bytes.
  1080. let text = unsafe {
  1081. std::slice::from_raw_parts(
  1082. errors.GetBufferPointer().cast::<u8>(),
  1083. errors.GetBufferSize(),
  1084. )
  1085. };
  1086. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  1087. }
  1088. return Err(e);
  1089. }
  1090. let code = code.ok_or_else(windows::core::Error::empty)?;
  1091. // SAFETY: the blob's own bytes.
  1092. let bytes = unsafe {
  1093. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  1094. };
  1095. Ok(bytes.to_vec())
  1096. }
  1097. impl PlanePass {
  1098. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  1099. /// or of floats and the depth format `format`.
  1100. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  1101. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1102. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  1103. return pipeline.clone();
  1104. }
  1105. let pipeline = match Self::make(steps, format) {
  1106. Ok(pipeline) => Some(pipeline),
  1107. Err(e) => {
  1108. tracing::warn!(
  1109. error = %e,
  1110. steps,
  1111. format = format.0,
  1112. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  1113. );
  1114. None
  1115. }
  1116. };
  1117. made.push((steps, format.0, pipeline.clone()));
  1118. pipeline
  1119. }
  1120. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  1121. use windows::core::s;
  1122. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  1123. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  1124. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  1125. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  1126. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  1127. pShaderBytecode: bytes.as_ptr().cast(),
  1128. BytecodeLength: bytes.len(),
  1129. };
  1130. // SAFETY: the root signature is inside the pixel shader; the
  1131. // description points at live data and never releases its pointer.
  1132. unsafe {
  1133. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  1134. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1135. pRootSignature: std::mem::transmute_copy(&root),
  1136. VS: code(&vs[..]),
  1137. PS: code(&ps[..]),
  1138. SampleMask: u32::MAX,
  1139. RasterizerState: D3D12_RASTERIZER_DESC {
  1140. FillMode: D3D12_FILL_MODE_SOLID,
  1141. CullMode: D3D12_CULL_MODE_NONE,
  1142. DepthClipEnable: true.into(),
  1143. ..Default::default()
  1144. },
  1145. // Every texel is written; stencil stays off.
  1146. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1147. DepthEnable: true.into(),
  1148. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  1149. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1150. ..Default::default()
  1151. },
  1152. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1153. DSVFormat: format,
  1154. SampleDesc: DXGI_SAMPLE_DESC {
  1155. Count: 1,
  1156. Quality: 0,
  1157. },
  1158. ..Default::default()
  1159. };
  1160. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1161. Ok((root, pipeline))
  1162. }
  1163. }
  1164. }
  1165. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1166. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1167. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1168. /// heap, graphics root signature, pipeline, depth target, viewport,
  1169. /// scissor and topology and puts none of them back: it is for a list that
  1170. /// records nothing of the title's after it.
  1171. fn record_plane_pass(
  1172. list: &ID3D12GraphicsCommandList,
  1173. depth: &ID3D12Resource,
  1174. plane: &ID3D12Resource,
  1175. ) {
  1176. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1177. return;
  1178. };
  1179. // SAFETY: live resources.
  1180. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1181. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1182. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1183. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1184. let steps = twin.Format.0 == 53;
  1185. let format = DXGI_FORMAT(match of.Format.0 {
  1186. 44 => 45,
  1187. 19 => 20,
  1188. typed => typed,
  1189. });
  1190. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1191. return;
  1192. };
  1193. for slice in 0..u32::from(of.DepthOrArraySize) {
  1194. for mip in 0..u32::from(of.MipLevels) {
  1195. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1196. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1197. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1198. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1199. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1200. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1201. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1202. MostDetailedMip: mip,
  1203. MipLevels: 1,
  1204. FirstArraySlice: slice,
  1205. ArraySize: 1,
  1206. ..Default::default()
  1207. },
  1208. },
  1209. };
  1210. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1211. Format: format,
  1212. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1213. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1214. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1215. MipSlice: mip,
  1216. FirstArraySlice: slice,
  1217. ArraySize: 1,
  1218. },
  1219. },
  1220. ..Default::default()
  1221. };
  1222. let target = host.dsv(depth, Some(&target));
  1223. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1224. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1225. ptr: pass.cpu + (slot * pass.step) as usize,
  1226. };
  1227. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1228. ptr: pass.gpu + u64::from(slot * pass.step),
  1229. };
  1230. // SAFETY: an open list; a slot of our heap; live resources and
  1231. // objects (the pass's own live as long as the process).
  1232. unsafe {
  1233. host.device
  1234. .CreateShaderResourceView(plane, Some(&view), cpu);
  1235. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1236. list.SetGraphicsRootSignature(&root);
  1237. list.SetPipelineState(&pipeline);
  1238. list.SetGraphicsRootDescriptorTable(0, gpu);
  1239. list.OMSetRenderTargets(0, None, false, Some(&target));
  1240. list.RSSetViewports(&[D3D12_VIEWPORT {
  1241. TopLeftX: 0.0,
  1242. TopLeftY: 0.0,
  1243. Width: width as f32,
  1244. Height: height as f32,
  1245. MinDepth: 0.0,
  1246. MaxDepth: 1.0,
  1247. }]);
  1248. list.RSSetScissorRects(&[RECT {
  1249. left: 0,
  1250. top: 0,
  1251. right: width as i32,
  1252. bottom: height as i32,
  1253. }]);
  1254. list.IASetPrimitiveTopology(
  1255. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1256. );
  1257. list.DrawInstanced(3, 1, 0, 0);
  1258. }
  1259. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1260. }
  1261. }
  1262. }
  1263. /// Records into `list` the copy of a depth texture into its colour twin
  1264. /// (`colour`) or of the twin into the depth texture, both already in their
  1265. /// copy states: whole textures of one size in one format family, which the
  1266. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1267. /// alone, through the twin's buffer.
  1268. fn record_twin_copy(
  1269. list: &ID3D12GraphicsCommandList,
  1270. depth: &ID3D12Resource,
  1271. twin: &crate::resource::Twin,
  1272. colour: bool,
  1273. ) {
  1274. let (from, to) = if colour {
  1275. (depth, &twin.colour.texture)
  1276. } else {
  1277. (&twin.colour.texture, depth)
  1278. };
  1279. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1280. // shortcut: the depth plane's twin is not given the plane (that is a
  1281. // pass the other way: the plane read by a shader, the twin as its
  1282. // target). The twin then lacks what draws and clears wrote to the
  1283. // plane since shaders last wrote the twin. In the title
  1284. // nothing writes that plane but the twin's pass (its 192 draws against
  1285. // it only test, run 29), so the twin lacks nothing. Counted.
  1286. if colour && twin.plane.is_some() {
  1287. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1288. }
  1289. let Some(through) = &twin.through else {
  1290. // SAFETY: an open list and two live textures.
  1291. unsafe { list.CopyResource(to, from) };
  1292. return;
  1293. };
  1294. // A stencil plane and its twin: each mip and slice of the plane goes
  1295. // into the buffer, laid out as the host lays the plane out for copies,
  1296. // and from the buffer into the other texture, whole subresources both
  1297. // times. In the depth texture the stencil plane's subresources follow
  1298. // the depth plane's; the twin has the one plane.
  1299. let Some(host) = host() else { return };
  1300. // SAFETY: a live texture.
  1301. let of = unsafe { depth.GetDesc() };
  1302. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1303. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1304. // SAFETY: a plain query writing `planes` footprints.
  1305. unsafe {
  1306. host.device.GetCopyableFootprints(
  1307. &of,
  1308. planes,
  1309. planes,
  1310. 0,
  1311. Some(rows.as_mut_ptr()),
  1312. None,
  1313. None,
  1314. None,
  1315. );
  1316. }
  1317. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1318. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1319. // SAFETY: a borrowed pointer the location never releases.
  1320. pResource: unsafe { std::mem::transmute_copy(texture) },
  1321. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1322. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1323. SubresourceIndex: index,
  1324. },
  1325. };
  1326. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1327. // SAFETY: as above.
  1328. pResource: unsafe { std::mem::transmute_copy(through) },
  1329. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1330. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1331. PlacedFootprint: *row,
  1332. },
  1333. };
  1334. let (common, source, dest) = (
  1335. D3D12_RESOURCE_STATE_COMMON,
  1336. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1337. D3D12_RESOURCE_STATE_COPY_DEST,
  1338. );
  1339. // SAFETY: an open list and live resources; the buffer was made as big
  1340. // as these footprints, and rests in the common state between copies.
  1341. unsafe {
  1342. list.ResourceBarrier(&[transition(through, common, dest)]);
  1343. for (i, row) in rows.iter().enumerate() {
  1344. let index = first_from + i as u32;
  1345. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1346. }
  1347. list.ResourceBarrier(&[transition(through, dest, source)]);
  1348. for (i, row) in rows.iter().enumerate() {
  1349. let index = first_to + i as u32;
  1350. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1351. }
  1352. list.ResourceBarrier(&[transition(through, source, common)]);
  1353. }
  1354. }
  1355. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1356. /// builds).
  1357. pub(crate) fn dred_on() -> bool {
  1358. static ON: OnceLock<bool> = OnceLock::new();
  1359. *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED") && !dred_faults() && !dred_light())
  1360. }
  1361. /// Breadcrumbs and the faulting address, but no markers and no texts
  1362. /// (`VICTORY_D3D12_DRED=light`): which list a removed device stopped in, at
  1363. /// which of its commands, and the pipelines the list binds; formatting a text
  1364. /// for every command is what makes the whole of it slow.
  1365. pub(crate) fn dred_light() -> bool {
  1366. static ON: OnceLock<bool> = OnceLock::new();
  1367. *ON.get_or_init(|| {
  1368. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "light")
  1369. })
  1370. }
  1371. /// Any of the three.
  1372. pub(crate) fn dred_any() -> bool {
  1373. dred_on() || dred_light() || dred_faults()
  1374. }
  1375. /// Whether only the faulting address of a removed device is kept
  1376. /// (`VICTORY_D3D12_DRED=faults`): no breadcrumbs, no markers and no texts, so
  1377. /// it costs next to nothing and can stay on while the title is played.
  1378. pub(crate) fn dred_faults() -> bool {
  1379. static ON: OnceLock<bool> = OnceLock::new();
  1380. *ON.get_or_init(|| {
  1381. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "faults")
  1382. })
  1383. }
  1384. /// The lists alive while device-removed data is on, by the number their name
  1385. /// ends in, with their marker texts and the pipelines they bind: a report made
  1386. /// on another thread than the one that submits has no lists of its own.
  1387. #[cfg(feature = "diagnostics")]
  1388. #[allow(clippy::type_complexity)]
  1389. static LIST_NOTES: Mutex<
  1390. std::collections::BTreeMap<
  1391. u32,
  1392. (
  1393. std::sync::Weak<Mutex<Vec<Note>>>,
  1394. std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>,
  1395. std::sync::Weak<Mutex<indirects::Indirects>>,
  1396. ),
  1397. >,
  1398. > = Mutex::new(std::collections::BTreeMap::new());
  1399. /// The number in the name of a list of ours ("victory host list 7", which the
  1400. /// debug layer ends with a note of its own in brackets).
  1401. #[cfg(feature = "diagnostics")]
  1402. fn list_number(name: &str) -> Option<u32> {
  1403. let rest = name.strip_prefix("victory host list ")?;
  1404. let digits = rest.split(' ').next()?;
  1405. (rest.len() == digits.len() || rest[digits.len()..].starts_with(" (")).then(|| digits.parse().ok()).flatten()
  1406. }
  1407. /// Indirect mesh dispatches since the last frame line: the largest group
  1408. /// count a record asked for, and the groups asked in all (from the lists'
  1409. /// budget buffers, a run late).
  1410. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1411. /// Whether a list's indirect-work budget lives in the card's own memory
  1412. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1413. /// before). The clamp charges it with atomics, at least two in a row for
  1414. /// every clamp; in mapped memory on a card of its own each of them
  1415. /// crosses the bus.
  1416. fn card_budget() -> bool {
  1417. static ON: OnceLock<bool> = OnceLock::new();
  1418. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1419. }
  1420. /// Whether each list of a submission runs and is timed on its own, slow
  1421. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1422. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1423. #[cfg(feature = "diagnostics")]
  1424. fn timing() -> bool {
  1425. static ON: OnceLock<bool> = OnceLock::new();
  1426. *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING"))
  1427. }
  1428. /// Names a host object for the device-removed report, which names the
  1429. /// allocations a page fault hit (only with device-removed data on), or for
  1430. /// the frame recorder (`VICTORY_RECORD`).
  1431. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1432. #[cfg(feature = "diagnostics")]
  1433. if crate::replay::record::on() {
  1434. let text = text();
  1435. crate::replay::record::name(object, &text);
  1436. if dred_any()
  1437. && let Ok(object) = object.cast::<ID3D12Object>()
  1438. {
  1439. // SAFETY: a plain call on a live object.
  1440. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1441. }
  1442. return;
  1443. }
  1444. if dred_any()
  1445. && let Ok(object) = object.cast::<ID3D12Object>()
  1446. {
  1447. // SAFETY: a plain call on a live object.
  1448. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1449. }
  1450. }
  1451. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1452. /// [`LISTS`]`[3]` until it is first reset.
  1453. struct Counted {
  1454. /// Not reset since it was made.
  1455. fresh: std::sync::atomic::AtomicBool,
  1456. }
  1457. impl Counted {
  1458. fn new() -> Counted {
  1459. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1460. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1461. Counted {
  1462. fresh: std::sync::atomic::AtomicBool::new(true),
  1463. }
  1464. }
  1465. /// The list is reset: it is in use.
  1466. fn used(&self) {
  1467. if self.fresh.swap(false, Ordering::Relaxed) {
  1468. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1469. }
  1470. }
  1471. }
  1472. impl Drop for Counted {
  1473. fn drop(&mut self) {
  1474. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1475. self.used();
  1476. }
  1477. }
  1478. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1479. /// mapping.
  1480. struct Chunk {
  1481. buffer: ID3D12Resource,
  1482. data: usize,
  1483. }
  1484. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1485. // written only by the list that holds the chunk.
  1486. unsafe impl Send for Chunk {}
  1487. /// Upload chunks handed out front to back: the chunks (each with its
  1488. /// bytes), the one in use and the bytes used in it.
  1489. #[derive(Default)]
  1490. struct Scratch {
  1491. chunks: Vec<(Chunk, u64)>,
  1492. current: usize,
  1493. used: u64,
  1494. }
  1495. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1496. unsafe impl Send for Scratch {}
  1497. impl Drop for Scratch {
  1498. fn drop(&mut self) {
  1499. give_chunks(std::mem::take(&mut self.chunks));
  1500. }
  1501. }
  1502. const SCRATCH_CHUNK: u64 = 4 << 20;
  1503. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1504. /// lists put a few constants or a rectangle's corners there, and every
  1505. /// list that did took 4 MiB of the PC's memory for it.
  1506. const SCRATCH_FIRST: u64 = 256 << 10;
  1507. /// The most bytes of chunks kept while no list holds them.
  1508. const SPARE_MOST: u64 = 128 << 20;
  1509. /// The same with [`keep_freed`].
  1510. const SPARE_KEPT: u64 = 1 << 30;
  1511. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1512. /// first needs one, a small one first, and gives all of them back when it
  1513. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1514. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1515. /// host lists of held submissions, which live for one submission, each
  1516. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1517. /// freed per frame of gameplay (run 60).
  1518. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1519. fn scratch_pool() -> bool {
  1520. static ON: OnceLock<bool> = OnceLock::new();
  1521. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1522. }
  1523. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1524. /// for one of the same size.
  1525. struct Spare<T> {
  1526. kept: Vec<(T, u64)>,
  1527. bytes: u64,
  1528. }
  1529. impl<T> Spare<T> {
  1530. const fn new() -> Self {
  1531. Spare { kept: Vec::new(), bytes: 0 }
  1532. }
  1533. /// A kept thing of `size` bytes, the one given last.
  1534. fn take(&mut self, size: u64) -> Option<T> {
  1535. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1536. self.bytes -= size;
  1537. Some(self.kept.remove(at).0)
  1538. }
  1539. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1540. /// `most`: then it comes back.
  1541. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1542. if self.bytes + size > most {
  1543. return Some(thing);
  1544. }
  1545. self.bytes += size;
  1546. self.kept.push((thing, size));
  1547. None
  1548. }
  1549. }
  1550. /// Scratch chunks no list holds.
  1551. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1552. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1553. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1554. if scratch_pool()
  1555. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1556. {
  1557. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1558. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1559. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1560. return Some(chunk);
  1561. }
  1562. let (buffer, data) = host.upload_buffer(size)?;
  1563. name(&buffer, || "list scratch".into());
  1564. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1565. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1566. Some(Chunk {
  1567. buffer,
  1568. data: data as usize,
  1569. })
  1570. }
  1571. /// A list is done with `chunks` (it was reset after its submissions ran,
  1572. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1573. /// without the pool.
  1574. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1575. if chunks.is_empty() {
  1576. return;
  1577. }
  1578. let mut freed = Vec::new();
  1579. {
  1580. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1581. for (chunk, size) in chunks {
  1582. let back = if scratch_pool() {
  1583. spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST })
  1584. } else {
  1585. Some(chunk)
  1586. };
  1587. match back {
  1588. None => {
  1589. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1590. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1591. }
  1592. Some(chunk) => {
  1593. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1594. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1595. freed.push(chunk);
  1596. }
  1597. }
  1598. }
  1599. }
  1600. // Freed outside the lock.
  1601. drop(freed);
  1602. }
  1603. /// What the host keeps for copies in the card's own memory
  1604. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1605. struct CardWork {
  1606. /// Before a submission's lists: what changed on the copies' CPU side
  1607. /// goes to their card side. Those not in use: a plan takes one and
  1608. /// gives it back when its submission has run (`Host::card_done`), so
  1609. /// that submissions sent ahead ([`late`]) each have their own.
  1610. sync: Vec<Prelude>,
  1611. /// After them, in the same submission: the compare of the declared
  1612. /// ranges with their bytes from before. As `sync`.
  1613. check: Vec<Prelude>,
  1614. /// After it ran: the pieces that differ come down.
  1615. fetch: Prelude,
  1616. root: ID3D12RootSignature,
  1617. pso: ID3D12PipelineState,
  1618. /// One dword per piece compared, odd where the piece differs: PC
  1619. /// memory, mapped (buffer, mapping, bytes).
  1620. differs: (ID3D12Resource, usize, u64),
  1621. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1622. fetched: Option<(ID3D12Resource, usize, u64)>,
  1623. /// The dwords of `differs` taken by plans whose results were not read
  1624. /// yet.
  1625. taken: u32,
  1626. /// Plans made and not done with (`Host::card_done`).
  1627. out: u32,
  1628. }
  1629. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1630. // under the submission lock.
  1631. unsafe impl Send for CardWork {}
  1632. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1633. /// The compare of a declared range of a copy in the card's memory with
  1634. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1635. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1636. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1637. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1638. /// byte just outside the range costs a fetch that finds nothing.
  1639. ///
  1640. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1641. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1642. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1643. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1644. /// those steps.
  1645. pub(crate) const CARD_COMPARE: &str = r#"
  1646. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1647. cbuffer Span : register(b0) {
  1648. uint first; // the first piece
  1649. uint skew; // where the copy starts in its piece 0
  1650. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1651. uint pieces;
  1652. uint out_at; // the first piece's dword in `differs`, in bytes
  1653. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1654. };
  1655. ByteAddressBuffer now : register(t0);
  1656. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1657. // last sent up (or hashed whole, the first time).
  1658. RWByteAddressBuffer hashes : register(u0);
  1659. RWByteAddressBuffer differs : register(u1);
  1660. groupshared uint4 parts[64];
  1661. [RootSignature(RS)]
  1662. [numthreads(64, 1, 1)]
  1663. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1664. uint piece = first + id.x;
  1665. uint lo = piece * 65536u;
  1666. lo = lo > skew ? lo - skew : 0u;
  1667. uint hi = min((piece + 1u) * 65536u - skew, size);
  1668. lo = lo & ~15u;
  1669. hi = (hi + 15u) & ~15u;
  1670. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1671. [loop]
  1672. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1673. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1674. h = h.yzwx ^ (h >> 15);
  1675. }
  1676. parts[thread] = h;
  1677. GroupMemoryBarrierWithGroupSync();
  1678. if (thread != 0u) return;
  1679. h = parts[0];
  1680. [loop]
  1681. for (uint i = 1u; i < 64u; ++i) {
  1682. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1683. h = h.yzwx ^ (h >> 15);
  1684. }
  1685. if (compare != 0u) {
  1686. // The flag, and above it 31 bits of the hash (`torn`).
  1687. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1688. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1689. // With the copy-back on its own thread: the next compare of the
  1690. // piece finds what is written from here on.
  1691. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1692. } else {
  1693. hashes.Store4(piece * 16u, h);
  1694. }
  1695. }
  1696. "#;
  1697. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1698. #[cfg(test)]
  1699. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1700. torn::hash(bytes)
  1701. }
  1702. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1703. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1704. /// parts a dispatch can hold.
  1705. ///
  1706. /// # Safety
  1707. /// The list is open with the compare's root signature, pipeline and buffers
  1708. /// set, and the pieces lie in the buffer.
  1709. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1710. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1711. let mut done = 0;
  1712. while done < span.pieces {
  1713. let n = (span.pieces - done).min(MOST);
  1714. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1715. // SAFETY: the caller's.
  1716. unsafe {
  1717. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1718. list.Dispatch(n, 1, 1);
  1719. }
  1720. done += n;
  1721. }
  1722. }
  1723. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1724. /// the card's memory are hashed in runs of pieces that touch, each piece
  1725. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1726. /// per range sent up.
  1727. ///
  1728. /// These passes are ours, they run on the card before every submission's
  1729. /// lists: a pass takes the time of one piece however few its pieces are.
  1730. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1731. /// a piece hashed when it need not be, or not hashed when it should, costs
  1732. /// a fetch that finds nothing and loses no shader write.
  1733. fn rehash_runs() -> bool {
  1734. static ON: OnceLock<bool> = OnceLock::new();
  1735. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1736. }
  1737. /// Since the last frame-rate line, of our own passes over copies in the
  1738. /// card's memory: hash passes after ranges were sent up, the pieces they
  1739. /// hashed, and compare passes after the lists.
  1740. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1741. /// Whether what shaders wrote to copies in the card's memory is merged
  1742. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1743. /// default). The pieces the card's compare found differing come down in
  1744. /// one fetch and were then merged one after the other on the thread that
  1745. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1746. /// with the copy's CPU side byte by byte and put into title memory through
  1747. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1748. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1749. /// landings do not come here: `crate::land` has threads of its own.)
  1750. fn wide_merge() -> bool {
  1751. static ON: OnceLock<bool> = OnceLock::new();
  1752. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1753. }
  1754. /// One declared range of a copy in the card's memory, in a submission.
  1755. struct CardRange {
  1756. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1757. /// As declared (title addresses), for the statistics.
  1758. declared: (usize, usize),
  1759. span: crate::shadow::CardSpan,
  1760. /// Its first piece's dword in the compare's results.
  1761. at: u32,
  1762. /// Whether the card compares it; else every piece is fetched.
  1763. compared: bool,
  1764. /// Looked at by `crate::picked`, and not declared: what is found changed
  1765. /// there was written through a view nobody declared. Not landed.
  1766. picked: bool,
  1767. }
  1768. impl CardPlan {
  1769. /// `crate::picked` is told where what it looked at changed, by the
  1770. /// compare's results.
  1771. fn picked_found(&self, differs: &[u32]) {
  1772. for r in self.ranges.iter().filter(|r| r.picked) {
  1773. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1774. if let Some(p) = changed {
  1775. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1776. }
  1777. }
  1778. }
  1779. }
  1780. /// What a submission does for copies in the card's memory.
  1781. struct CardPlan {
  1782. ranges: Vec<CardRange>,
  1783. /// The compare, run after the submission's lists.
  1784. check: Option<ID3D12CommandList>,
  1785. /// The copies whose card side was brought up to date, alive until the
  1786. /// submission has run.
  1787. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1788. /// The lists of ours the plan recorded (whether the compare, the
  1789. /// list), given back by `Host::card_done`.
  1790. lists: Vec<(bool, Prelude)>,
  1791. /// With [`relay`]: the number of the send to copies in the card's memory
  1792. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1793. sent_as: u64,
  1794. /// With [`upcheck`]: the look at what it sent up.
  1795. looks: Option<upcheck::Looks>,
  1796. /// With [`send`]: the memory its sends come from.
  1797. sends: Option<send::Memory>,
  1798. }
  1799. /// One piece of submission-time work, in recorded order.
  1800. enum Step {
  1801. /// A copy into title memory (destination, source, bytes): the title's
  1802. /// buffer copies, which later refreshes must see.
  1803. Copy(usize, usize, usize),
  1804. /// A copy of title memory into the list's own upload memory, and how
  1805. /// the card could bring the bytes instead.
  1806. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  1807. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1808. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1809. /// intervenes.
  1810. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1811. /// Work that may write title memory.
  1812. Run(Box<dyn Fn() + Send>),
  1813. /// Work that writes host memory only, and the title memory it reads
  1814. /// (from, to; empty for none).
  1815. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1816. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1817. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1818. /// Brings a texture's staging buffer up to date: once per submission,
  1819. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1820. Texture(std::sync::Arc<crate::texture::Staging>),
  1821. /// A title buffer copy that the list does on the card ([`place`]): what
  1822. /// is done on the CPU for it.
  1823. Placed(place::Placed),
  1824. }
  1825. /// What a list does on the CPU when it is submitted: copies between host
  1826. /// memory regions (title buffers, upload buffers and buffer copies), and
  1827. /// the upload buffers its GPU commands read, kept until the list is reset.
  1828. #[derive(Default)]
  1829. struct Deferred {
  1830. /// Destination, source, bytes.
  1831. copies: Vec<Step>,
  1832. uploads: Vec<ID3D12Resource>,
  1833. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1834. upload_bytes: u64,
  1835. /// Host objects the list's commands name (pipelines, root signatures,
  1836. /// descriptor heaps): the title may release its objects before it
  1837. /// submits the list.
  1838. kept: Vec<windows::core::IUnknown>,
  1839. /// Buffer ranges refreshed since the last title copy (host copy,
  1840. /// address, bytes): refreshing them again would find the same bytes.
  1841. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1842. /// Textures whose contents the list brings up to date.
  1843. textures: std::collections::HashSet<usize>,
  1844. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1845. /// bytes.
  1846. writes: Vec<(usize, crate::queue::Written, usize)>,
  1847. /// Textures read back (texture to buffer copies), done once the list
  1848. /// has run: the host buffer the list copies the texels into, the title
  1849. /// memory they go to, the bytes of a row, the rows, the title's row
  1850. /// pitch.
  1851. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1852. /// Whether the indirect-work budget is zeroed for this recording (a
  1853. /// step on the CPU, or in the list for the card's copy).
  1854. budget_zeroed: bool,
  1855. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1856. /// interface pointer) that a clamp in this recording left readable as
  1857. /// indirect arguments; 0 if none. It stays readable until the next
  1858. /// clamp into it ([`HostList::indirect_state`]).
  1859. indirect_readable: usize,
  1860. }
  1861. impl Deferred {
  1862. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1863. /// reset.
  1864. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1865. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1866. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1867. self.upload_bytes += size;
  1868. self.uploads.push(buffer);
  1869. }
  1870. }
  1871. impl Drop for Deferred {
  1872. fn drop(&mut self) {
  1873. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1874. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1875. }
  1876. }
  1877. /// Whether a queue's submissions go to the card without a wait for each
  1878. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1879. /// waits for every list on its own).
  1880. ///
  1881. /// Every submission was prepared, sent, waited for and copied back before
  1882. /// the next one was looked at, so the card stood idle while we prepared
  1883. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1884. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1885. /// other, on the one thread that submits.
  1886. ///
  1887. /// With the switch a queue's submission is sent and joins a line of
  1888. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1889. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1890. /// for the card, what their shaders wrote copied back once per byte, then
  1891. /// their bottom-of-pipe writes and the fence signals behind them, in
  1892. /// order) at the next point where the title, or our own preparing, can
  1893. /// observe what they do. Those points, exactly:
  1894. ///
  1895. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1896. /// read-back or map of a texture, a clear or upload run at once;
  1897. /// 2. the next submission reads title memory that a flight's shaders may
  1898. /// write: a title buffer copy, a fill of upload memory, a texture's
  1899. /// memory, any step that runs code of ours on title memory
  1900. /// ([`late_blocked`]);
  1901. /// 3. the next submission refreshes a range of a host copy that a flight's
  1902. /// shaders may write, and the title wrote a page of it since it was last
  1903. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1904. /// alone until the flight's writes are back, as it always did within a
  1905. /// submission;
  1906. /// 4. a queue stands at a wait for a memory value that no flight's
  1907. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1908. /// write ([`late_met`]);
  1909. /// 5. the title blocks on a fence without an event;
  1910. /// 6. the card has run every flight (a thread of ours waits for that:
  1911. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1912. ///
  1913. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1914. /// when the card has really run the work, later than before and never
  1915. /// earlier; a fence signalled on a queue while flights are in the air is
  1916. /// set behind them. A wait for a memory value that a flight's
  1917. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1918. /// the card behind that flight, which is the order the wait asks for.
  1919. ///
  1920. /// What it assumes beyond today: memory the title rewrites between two of
  1921. /// its submissions, without waiting for the first, may be seen by the
  1922. /// first's shaders (as on the console, where the card reads title memory
  1923. /// when it runs, not when the list is submitted).
  1924. pub(crate) fn late() -> bool {
  1925. late_stage() > 0
  1926. }
  1927. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1928. fn late_stage() -> u8 {
  1929. static STAGE: OnceLock<u8> = OnceLock::new();
  1930. *STAGE.get_or_init(|| {
  1931. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1932. return 0;
  1933. }
  1934. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1935. Ok("1") => 1,
  1936. Ok("2") => 2,
  1937. Ok("3") => 3,
  1938. // The relay alone: on top of stage 3.
  1939. Err(_) if crate::shadow::relay() => 3,
  1940. _ => 0,
  1941. }
  1942. })
  1943. }
  1944. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1945. /// longer a point. Where the title wrote a page that lies in a range a
  1946. /// flight's shaders may write, the bytes the title changed are found (the
  1947. /// page as it is now against what the copy held when the flight was
  1948. /// prepared) and put into the copy, and only those: what the flight's
  1949. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1950. /// flights are settled for it only where that cannot be done: memory that
  1951. /// is not write-watched, or a copy in the card's memory with more changed
  1952. /// runs than a submission should send up one by one.
  1953. ///
  1954. /// In run 92 (stage 1) this point settled the flights five times a frame
  1955. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1956. /// frame of waiting were left of 200.
  1957. ///
  1958. /// What differs from settling first: a byte both the title and a flight's
  1959. /// shader wrote is the title's if the shader wrote it first, the shader's
  1960. /// if it wrote it afterwards; settled first it was always the shader's.
  1961. /// The title writing a byte a shader of its own is writing is a race on
  1962. /// the console too.
  1963. fn late_exact() -> bool {
  1964. late_stage() > 1
  1965. }
  1966. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1967. /// no longer a point where flights are settled). The copy to the back
  1968. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1969. /// its own for each present in the air) and the swap chain is told to
  1970. /// present behind it; the queue's call returns, and the card finishes the
  1971. /// frame while the title records the next one. What the title is told
  1972. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1973. /// has run it, by the settling thread.
  1974. ///
  1975. /// What is left out with it: the look whether the presented frame is black
  1976. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1977. /// or listed is presented the old way. Once every second and a half a
  1978. /// submission settles the flights all the same, for the sweep that lets
  1979. /// idle host objects go (it needs nothing in the air).
  1980. pub(crate) fn late_free_present() -> bool {
  1981. late_stage() > 2
  1982. }
  1983. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1984. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1985. /// and is off with it, in the timing run and with kept snapshots).
  1986. ///
  1987. /// With [`late`] alone every settle does three things on the thread that
  1988. /// holds the submission lock: it waits for everything in the air, copies
  1989. /// back with the card standing, and only then goes on preparing. The frame
  1990. /// stays a relay: the card works about 242 ms of it and one thread
  1991. /// prepares, waits and copies back for about 220.
  1992. ///
  1993. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1994. /// soon as the card has run them, in the order they were sent and without
  1995. /// the submission lock: it fetches and merges what their shaders wrote to
  1996. /// copies in the card's memory, compares and merges the other copies,
  1997. /// frees the flights' ranges, and then does their read-backs, their
  1998. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1999. /// order. The submitting thread meanwhile prepares and sends the next
  2000. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  2001. /// that thread has landed everything in the air, at the same points as
  2002. /// before (the list in [`late`]), so whoever can observe title memory, a
  2003. /// fence or a present still does so only after the flights before it are
  2004. /// merged.
  2005. ///
  2006. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  2007. /// flight; a merge that never stores into memory the card may be writing;
  2008. /// sends to card copies numbered) and here: flights land in the order of
  2009. /// [`LINE`] by one thread, so a later flight's results never reach title
  2010. /// memory before an earlier flight's; the compare on the card stores the
  2011. /// hash it made, so each flight's compare flags exactly what changed since
  2012. /// the compare before it, however late the pieces are fetched; the fetch
  2013. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  2014. /// title bytes the card had received when it ran.
  2015. pub(crate) fn relay() -> bool {
  2016. static ON: OnceLock<bool> = OnceLock::new();
  2017. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  2018. }
  2019. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  2020. /// title memory a flight's shaders may write (a title buffer copy, a fill
  2021. /// of upload memory, a texture) waits only until the flights that declared
  2022. /// that memory have landed, not for everything in the air; and at
  2023. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  2024. /// both wait for everything.
  2025. fn relay_exact() -> bool {
  2026. static ON: OnceLock<bool> = OnceLock::new();
  2027. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  2028. // since the walls of the first room were found drawn in every run with
  2029. // this set and in fewer than half without it).
  2030. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  2031. }
  2032. /// Whether the pieces the relay fetches from the card's memory come over the
  2033. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  2034. /// draws.
  2035. ///
  2036. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  2037. /// and with the relay that is most of a frame: the thread that lands flights
  2038. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  2039. /// a few milliseconds of copying, and everything that waits for a landing
  2040. /// (the title's fences, reads of memory flights may write) waited with it.
  2041. ///
  2042. /// What changes: the fetch runs when its flights are done and beside later
  2043. /// submissions, so of the sends of title bytes it is only known to have run
  2044. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  2045. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  2046. /// the title's, newer than what the flights wrote. A later flight's bytes
  2047. /// may be in what is fetched, as before.
  2048. fn relay_copy() -> bool {
  2049. static ON: OnceLock<bool> = OnceLock::new();
  2050. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  2051. }
  2052. /// Told when something joins [`LINE`], for the thread that lands flights
  2053. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  2054. /// what queues hold.
  2055. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2056. /// Told when flights have landed ([`relay`]): who waits for that looks
  2057. /// again.
  2058. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  2059. /// With [`relay`], the order of what we put on the queue: the number of
  2060. /// sends of changed ranges to copies in the card's memory so far
  2061. /// (`Host::card_before`). Held from the taking of the ranges until their
  2062. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  2063. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  2064. /// later one.
  2065. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  2066. /// Since the last frame-rate line, of the thread that lands flights
  2067. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  2068. /// card with nothing to land, microseconds it waited for fetches of card
  2069. /// copies' pieces, microseconds of landing in all.
  2070. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  2071. /// Of the line's things in order (a flight: the value signalled on the
  2072. /// host's fence behind it; a write or a signal behind a flight: `None`):
  2073. /// how many, from the front, can be landed when the card has reached
  2074. /// `completed`: everything ahead of the first flight it has not run. A
  2075. /// later flight never lands before an earlier one, and what follows a
  2076. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  2077. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  2078. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  2079. }
  2080. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  2081. /// holds, for every piece of every range of the plan, the copy, the
  2082. /// piece's number in the copy and whether the compare flagged it there (or
  2083. /// did not run). The pieces to fetch, under whichever range, in order: all
  2084. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  2085. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  2086. /// the hash, so the second of them may find it stored already and not
  2087. /// flag it.
  2088. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  2089. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  2090. pieces.sort_unstable();
  2091. pieces.dedup();
  2092. pieces
  2093. }
  2094. #[cfg(test)]
  2095. mod relay_tests {
  2096. use super::{flagged_pieces, landable};
  2097. /// Two flights and what follows each: nothing of the second lands
  2098. /// before the card has run it, and nothing behind a flight lands
  2099. /// before the flight.
  2100. #[test]
  2101. fn flights_land_in_the_order_they_were_sent() {
  2102. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  2103. let line = [Some(5), None, None, Some(6), None];
  2104. assert_eq!(landable(&line, 4), 0);
  2105. assert_eq!(landable(&line, 5), 3);
  2106. assert_eq!(landable(&line, 6), 5);
  2107. assert_eq!(landable(&line, u64::MAX), 5);
  2108. // Signals with no flight ahead land at once; behind one they wait.
  2109. assert_eq!(landable(&[None, None], 0), 2);
  2110. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  2111. assert_eq!(landable(&[], 3), 0);
  2112. // After the first three landed, the rest when its turn comes.
  2113. assert_eq!(landable(&line[3..], 5), 0);
  2114. assert_eq!(landable(&line[3..], 6), 2);
  2115. }
  2116. /// A piece flagged under one range of a plan is fetched under every
  2117. /// range that holds a part of it; pieces of other copies are not.
  2118. #[test]
  2119. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  2120. let (a, b) = (0x1000usize, 0x2000usize);
  2121. // Copy a: piece 3 under two ranges, flagged under the first only;
  2122. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  2123. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  2124. let fetch = flagged_pieces(&flags);
  2125. assert!(fetch.contains(&(a, 3)));
  2126. assert!(!fetch.contains(&(a, 4)));
  2127. assert!(!fetch.contains(&(b, 3)));
  2128. assert!(fetch.contains(&(b, 9)));
  2129. assert_eq!(fetch.len(), 2);
  2130. }
  2131. }
  2132. /// The most host lists in the air before the flights are settled
  2133. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  2134. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  2135. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  2136. /// 32 settled the flights three times a
  2137. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  2138. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  2139. /// descriptor slots, upload
  2140. /// memory and scratch chunks are held until then, and a frame's lists held
  2141. /// all at once ran the slots out before (run 45).
  2142. fn late_most() -> usize {
  2143. static MOST: OnceLock<usize> = OnceLock::new();
  2144. *MOST.get_or_init(|| {
  2145. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  2146. })
  2147. }
  2148. /// Whether a submission with bottom-of-pipe writes may fly
  2149. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  2150. /// the title is told at once, as before; for telling a title that polls
  2151. /// such a value from one that does not).
  2152. fn late_writes() -> bool {
  2153. static ON: OnceLock<bool> = OnceLock::new();
  2154. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  2155. }
  2156. /// Per host copy, the ranges a submission's shaders may write, as declared
  2157. /// (address, end).
  2158. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  2159. /// What [`Host::submit`] hands back for a submission it sent and did not
  2160. /// wait for.
  2161. struct Sent {
  2162. /// Its number among the submissions started.
  2163. number: u64,
  2164. card: Option<CardPlan>,
  2165. back: Vec<Declared>,
  2166. /// What was taken off it to be done on the card.
  2167. own: Option<card_steps::Taken>,
  2168. /// Its bottom-of-pipe writes.
  2169. writes: Vec<(usize, crate::queue::Written, usize)>,
  2170. }
  2171. /// A submission on the card that has not been waited for ([`late`]): its
  2172. /// host lists, taken from the title's (which it may reset meanwhile), and
  2173. /// what is to be done once it has run.
  2174. struct Flight {
  2175. number: u64,
  2176. /// The value signalled on the host's fence behind it.
  2177. fence: u64,
  2178. lists: Vec<crate::list::Detached>,
  2179. order: Vec<usize>,
  2180. card: Option<CardPlan>,
  2181. back: Vec<Declared>,
  2182. /// The list of ours that ran ahead of them ([`card_steps`]).
  2183. own: Option<card_steps::Taken>,
  2184. }
  2185. /// One thing in the line of what waits for the card, in order.
  2186. enum Late {
  2187. Run(Flight),
  2188. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  2189. Write(usize, crate::queue::Written, usize),
  2190. /// A fence (its address) signalled behind the flights before it.
  2191. Signal(usize, u64),
  2192. }
  2193. struct Line {
  2194. line: Vec<Late>,
  2195. /// The title memory the flights' shaders may write (address, end), in
  2196. /// order and joined.
  2197. written: Vec<(usize, usize)>,
  2198. /// Host lists in the flights.
  2199. lists: usize,
  2200. /// The value signalled on the host's fence behind the last flight.
  2201. target: u64,
  2202. /// A settle has taken the line and is not done: a signal still goes
  2203. /// behind it.
  2204. settling: bool,
  2205. /// Something was settled away from a queue's own calls: the helper
  2206. /// thread looks at what queues hold.
  2207. poke: bool,
  2208. /// Host lists of settled flights, reset and given back outside the
  2209. /// submission lock ([`land`]: a settle may run under a caller's own
  2210. /// locks).
  2211. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2212. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2213. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2214. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2215. /// With [`card_steps`]: what the flights being landed write.
  2216. landing: Vec<card_steps::Writer>,
  2217. }
  2218. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2219. // into; touched under the lock.
  2220. unsafe impl Send for Line {}
  2221. static LINE: Mutex<Line> = Mutex::new(Line {
  2222. line: Vec::new(),
  2223. written: Vec::new(),
  2224. lists: 0,
  2225. target: 0,
  2226. settling: false,
  2227. poke: false,
  2228. landed: Vec::new(),
  2229. in_hand: Vec::new(),
  2230. landing: Vec::new(),
  2231. });
  2232. /// Told when a flight joins [`LINE`] or it is poked.
  2233. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2234. fn line() -> std::sync::MutexGuard<'static, Line> {
  2235. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2236. }
  2237. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2238. const WHY_SYNC: usize = 2;
  2239. const WHY_CARD_DONE: usize = 3;
  2240. const WHY_VALUE: usize = 4;
  2241. const WHY_STALE: usize = 5;
  2242. const WHY_READ: usize = 6;
  2243. const WHY_RUN: usize = 7;
  2244. const WHY_MOST: usize = 8;
  2245. const WHY_WRITES: usize = 9;
  2246. const WHY_FENCE: usize = 10;
  2247. /// Since the last frame-rate line: submissions sent without a wait;
  2248. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2249. /// microseconds settles waited for the card; value waits met by a flight's
  2250. /// bottom-of-pipe write; fence signals set behind flights.
  2251. /// Then: the settles for title memory read, by what read it (a buffer
  2252. /// copy, a fill of upload memory, a texture).
  2253. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2254. /// Since the last frame-rate line: the microseconds settles waited for the
  2255. /// card, by why they settled (the `WHY_` places).
  2256. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2257. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2258. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2259. if from >= to {
  2260. return false;
  2261. }
  2262. let at = ranges.partition_point(|r| r.1 <= from);
  2263. ranges.get(at).is_some_and(|r| r.0 < to)
  2264. }
  2265. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2266. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2267. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2268. ranges.sort_unstable();
  2269. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2270. for &(from, to) in ranges.iter() {
  2271. match out.last_mut() {
  2272. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2273. _ => out.push((from, to)),
  2274. }
  2275. }
  2276. *ranges = out;
  2277. }
  2278. /// Whether anything is in the air.
  2279. fn flying() -> bool {
  2280. if !late() {
  2281. return false;
  2282. }
  2283. let line = line();
  2284. // (With the relay: also while flights are being landed.)
  2285. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2286. }
  2287. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2288. /// before they are settled, if so. Preparing reads title memory on the
  2289. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2290. /// runs steps of ours that may read or write it anywhere; what the
  2291. /// flights' shaders write is not there yet.
  2292. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2293. let (written, copies) = {
  2294. let line = line();
  2295. if line.written.is_empty() {
  2296. return None;
  2297. }
  2298. (line.written.clone(), card_steps::copies(&line))
  2299. };
  2300. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2301. }
  2302. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2303. /// flights when the title itself wrote the memory since they were given it
  2304. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2305. ///
  2306. /// The title's 174 MB heap is declared written as a whole (a root view has
  2307. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2308. /// bytes a frame, at a new place each time, waited for every flight's
  2309. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2310. /// named). The title writes those bytes just before the draw that reads
  2311. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2312. ///
  2313. /// Or no shader's write went into that page in the last 600 frames
  2314. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2315. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2316. /// before the page was taken.
  2317. ///
  2318. /// What can go wrong: a constant a flight's shader really writes, in a
  2319. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2320. /// for the first time, is read as it was before that flight.
  2321. fn fill_is_titles(src: usize, len: usize) -> bool {
  2322. const SMALL: usize = 64 << 10;
  2323. static ON: OnceLock<bool> = OnceLock::new();
  2324. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2325. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2326. }
  2327. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2328. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2329. /// in (start, bytes).
  2330. #[cfg(feature = "diagnostics")]
  2331. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2332. /// How often and how long, and the address the last one read.
  2333. #[cfg(feature = "diagnostics")]
  2334. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2335. /// What the wait that comes next is for, and why not on the card.
  2336. #[cfg(feature = "diagnostics")]
  2337. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2338. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2339. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2340. /// shaders.
  2341. #[cfg(feature = "diagnostics")]
  2342. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2343. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2344. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2345. /// raw address (1).
  2346. #[cfg(feature = "diagnostics")]
  2347. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2348. if len < 1 << 20 {
  2349. return;
  2350. }
  2351. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2352. let e = all
  2353. .get_or_insert_with(Default::default)
  2354. .entry((address as usize, (address + len) as usize, pipeline))
  2355. .or_insert_with(|| {
  2356. let shaders = match pipeline {
  2357. 0 => "a view in a table".into(),
  2358. 1 => "a raw address".into(),
  2359. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2360. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2361. }),
  2362. };
  2363. (0, shaders)
  2364. });
  2365. e.0 += 1;
  2366. }
  2367. #[cfg(feature = "diagnostics")]
  2368. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2369. let i = written.partition_point(|r| r.1 <= at);
  2370. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2371. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2372. let why = blamed.1;
  2373. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2374. }
  2375. /// Why [`card_steps`] left the submission to the wait that comes next.
  2376. #[cfg(feature = "diagnostics")]
  2377. fn refused(why: &'static str) {
  2378. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2379. }
  2380. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2381. #[cfg(feature = "diagnostics")]
  2382. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2383. if let Some((shadow, from, _)) = stale.first() {
  2384. let (start, len) = shadow.span();
  2385. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2386. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2387. }
  2388. }
  2389. /// The wait for what [`blame`] last named, or a wait of another reason than
  2390. /// title memory read, took `us`.
  2391. #[cfg(feature = "diagnostics")]
  2392. fn blamed(why: usize, us: u64) {
  2393. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2394. let (key, at) = match (why, named) {
  2395. (WHY_READ | WHY_STALE, Some(named)) => named,
  2396. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2397. _ => {
  2398. let kind = match why {
  2399. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2400. WHY_VALUE => "a memory value",
  2401. WHY_STALE => "title memory changed under shader writes",
  2402. WHY_RUN => "a step of ours",
  2403. WHY_MOST => "lists in the air",
  2404. WHY_FENCE => "a blocking fence wait",
  2405. _ => "another reason",
  2406. };
  2407. ((kind, "", 0, 0, 0), 0)
  2408. }
  2409. };
  2410. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2411. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2412. *e = (e.0 + 1, e.1 + us, at);
  2413. }
  2414. /// For the frame-rate line: the five that waited longest.
  2415. #[cfg(feature = "diagnostics")]
  2416. fn log_blame(frames: f64) {
  2417. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2418. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2419. let mut all: Vec<_> = all.into_iter().collect();
  2420. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2421. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2422. // The passes that declare it written, the ones that do so most.
  2423. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2424. for ((a, b, _), (n, shaders)) in &wide {
  2425. if *a < at + len && at < *b {
  2426. *passes.entry(shaders).or_default() += n;
  2427. }
  2428. }
  2429. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2430. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2431. let passes: Vec<String> =
  2432. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2433. tracing::info!(
  2434. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2435. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2436. us as f64 / 1e3 / frames,
  2437. n as f64 / frames,
  2438. passes.join(", "),
  2439. match (why.is_empty(), kind) {
  2440. (true, _) => "",
  2441. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2442. _ => "; not done on the card: ",
  2443. },
  2444. );
  2445. }
  2446. }
  2447. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2448. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2449. touches(written, src, src + len) && !fill_is_titles(src, len)
  2450. }
  2451. /// Whether they stop a title buffer copy, and if so whether by its source.
  2452. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2453. let read = read_blocked(written, src, len);
  2454. (read || touches(written, dst, dst + len)).then_some(read)
  2455. }
  2456. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2457. /// may write (in order, joined); `count` whether the kind of read is
  2458. /// counted for the frame line.
  2459. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2460. if written.is_empty() {
  2461. return None;
  2462. }
  2463. // Destinations of copies at their place, if a step reads them.
  2464. let mut placed: Vec<(usize, usize)> = Vec::new();
  2465. for list in runs {
  2466. for step in &list.deferred().copies {
  2467. match step {
  2468. &Step::Copy(dst, src, len) => {
  2469. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2470. if count {
  2471. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2472. #[cfg(feature = "diagnostics")]
  2473. if _read {
  2474. blame("a buffer copy's source", written, src, len);
  2475. } else {
  2476. blame("a buffer copy's destination", written, dst, len);
  2477. }
  2478. }
  2479. return Some(WHY_READ);
  2480. }
  2481. }
  2482. &Step::Fill(_, src, len, _) => {
  2483. if read_blocked(written, src, len) {
  2484. if count {
  2485. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2486. #[cfg(feature = "diagnostics")]
  2487. blame("a fill of upload memory", written, src, len);
  2488. }
  2489. return Some(WHY_READ);
  2490. }
  2491. }
  2492. Step::Texture(staging) => {
  2493. let (at, len) = staging.memory();
  2494. if touches(written, at, at + len) {
  2495. if count {
  2496. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2497. #[cfg(feature = "diagnostics")]
  2498. blame("a texture", written, at, len);
  2499. }
  2500. return Some(WHY_READ);
  2501. }
  2502. }
  2503. Step::Run(_) => return Some(WHY_RUN),
  2504. Step::Placed(p) => match p.waits(written) {
  2505. place::Waits::No => {}
  2506. place::Waits::ForReaders => placed.push((p.dst, p.dst + p.len)),
  2507. place::Waits::Yes => {
  2508. if count {
  2509. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2510. #[cfg(feature = "diagnostics")]
  2511. blame("a buffer copy at its place", written, p.src, p.len);
  2512. }
  2513. return Some(WHY_READ);
  2514. }
  2515. },
  2516. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2517. }
  2518. }
  2519. }
  2520. (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ)
  2521. }
  2522. /// With flights in the air, after the submission's write-watch asking:
  2523. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2524. /// may write and that the title wrote since it was last copied. The
  2525. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2526. /// the title's bytes there would reach the card a submission late.
  2527. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2528. use std::sync::Arc;
  2529. // Per copy, the span of what is refreshed (a flush brings that much
  2530. // up to date at most).
  2531. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2532. // Where each copy is in it, if shaders may be writing it (none begins to
  2533. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2534. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2535. for list in runs {
  2536. for step in &list.deferred().copies {
  2537. if let Step::Refresh(shadow, address, len) = step {
  2538. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2539. shadow.writes_pending().then(|| {
  2540. spans.push((shadow.clone(), *address, *address + *len));
  2541. spans.len() - 1
  2542. })
  2543. });
  2544. if let Some(i) = *place {
  2545. let s = &mut spans[i];
  2546. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2547. }
  2548. }
  2549. }
  2550. }
  2551. if late_exact() {
  2552. // The title's bytes are put in beside the flights' writes; a
  2553. // settle is still due where that could not be done. At most this
  2554. // many changed runs go up to copies in the card's memory, each a
  2555. // copy of its own there. With [`card_steps`] the pages of the
  2556. // title's ring of constants come here too, which were waited for
  2557. // before: hundreds of short runs each, at about 1.5 us a run.
  2558. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2559. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2560. return spans;
  2561. }
  2562. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2563. spans
  2564. }
  2565. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2566. /// air, if there are any, and is set when they are settled. Whether it
  2567. /// did; if not the caller sets the fence now.
  2568. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2569. if !late() {
  2570. return false;
  2571. }
  2572. let mut line = line();
  2573. if line.line.is_empty() && !line.settling {
  2574. return false;
  2575. }
  2576. line.line.push(Late::Signal(fence, value));
  2577. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2578. drop(line);
  2579. // A signal alone (behind a settle under way) has no flight to wake
  2580. // the helper thread for it.
  2581. LINE_MOVED.notify_one();
  2582. RELAY_MOVED.notify_one();
  2583. true
  2584. }
  2585. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2586. /// whether it is met once the flights in the air have run. A flight's
  2587. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2588. /// for the card: the part behind the wait goes to the card behind that
  2589. /// flight, which is the order the wait asks for. If the flights may write
  2590. /// the value in a way not known here (shaders, a timestamp, another
  2591. /// width), they are settled and memory is asked again.
  2592. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2593. let (address, bytes) = wait.place();
  2594. {
  2595. let line = line();
  2596. if line.line.is_empty() && line.in_hand.is_empty() {
  2597. return false;
  2598. }
  2599. let mut unsure = touches(&line.written, address, address + bytes);
  2600. // (With the relay: first the writes of flights being landed.)
  2601. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2602. Late::Write(at, what, n) => Some((at, what, n)),
  2603. _ => None,
  2604. }));
  2605. for (at, what, n) in writes {
  2606. if *at >= address + bytes || address >= *at + *n {
  2607. continue;
  2608. }
  2609. match what {
  2610. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2611. if wait.holds_for(*v) {
  2612. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2613. return true;
  2614. }
  2615. }
  2616. _ => unsure = true,
  2617. }
  2618. }
  2619. if !unsure {
  2620. return false;
  2621. }
  2622. }
  2623. settle_now(WHY_VALUE);
  2624. wait.met()
  2625. }
  2626. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2627. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2628. pub(crate) fn settle_now(why: usize) {
  2629. if !late() {
  2630. return;
  2631. }
  2632. let Some(host) = host() else {
  2633. return;
  2634. };
  2635. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2636. host.settle(&mut submitted, why);
  2637. }
  2638. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2639. pub(crate) fn settle_for_present() {
  2640. settle_now(WHY_SYNC);
  2641. }
  2642. pub(crate) fn settle_for_fence() {
  2643. settle_now(WHY_FENCE);
  2644. }
  2645. /// Resets the host lists of settled flights and keeps them for reuse, as
  2646. /// a queue does for the lists it ran (`crate::list::recycle`).
  2647. fn land() {
  2648. let landed = std::mem::take(&mut line().landed);
  2649. for (lists, order) in landed {
  2650. crate::list::recycle(lists, &order);
  2651. }
  2652. }
  2653. /// The thread that settles the flights once the card has run them all
  2654. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2655. /// at the next call that settles, and a title thread that polls such a
  2656. /// value while the submitting thread waits for that thread would never
  2657. /// see it.
  2658. fn late_helper() {
  2659. let Some(host) = host() else {
  2660. return;
  2661. };
  2662. // SAFETY: a plain event of our own.
  2663. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2664. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2665. return;
  2666. };
  2667. loop {
  2668. let target = {
  2669. let mut line = line();
  2670. loop {
  2671. if line.poke {
  2672. line.poke = false;
  2673. break None;
  2674. }
  2675. // (With the relay the flights are another thread's.)
  2676. if !relay() && !line.line.is_empty() && !line.settling {
  2677. break Some(line.target);
  2678. }
  2679. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2680. }
  2681. };
  2682. let Some(target) = target else {
  2683. land();
  2684. crate::queue::release_held(false);
  2685. continue;
  2686. };
  2687. // The card first, without the submission lock: the submitting
  2688. // thread prepares and sends meanwhile.
  2689. // SAFETY: our fence and event.
  2690. unsafe {
  2691. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2692. WaitForSingleObject(event, INFINITE);
  2693. }
  2694. }
  2695. {
  2696. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2697. // Something newer went up meanwhile: the card is waited for
  2698. // again, the submitting thread is not held up for it.
  2699. if line().target != target {
  2700. continue;
  2701. }
  2702. host.settle(&mut submitted, WHY_CARD_DONE);
  2703. }
  2704. land();
  2705. crate::queue::release_held(false);
  2706. }
  2707. }
  2708. /// Starts the threads of [`late`], once: the one that settles flights when
  2709. /// the card has run them and looks at what queues hold, and with [`relay`]
  2710. /// the one that lands flights.
  2711. fn late_threads() {
  2712. static HELPER: std::sync::Once = std::sync::Once::new();
  2713. HELPER.call_once(|| {
  2714. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2715. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2716. }
  2717. tracing::info!(
  2718. most = late_most(),
  2719. writes = late_writes(),
  2720. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2721. );
  2722. if relay() {
  2723. // Without it nothing would ever land.
  2724. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2725. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2726. }
  2727. tracing::info!(
  2728. exact = relay_exact(),
  2729. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2730. );
  2731. }
  2732. });
  2733. }
  2734. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2735. /// time flights have landed. Counted as a settle for `why`, and its time
  2736. /// as waiting for the card. The caller may hold the submission lock: the
  2737. /// thread that lands flights never takes it.
  2738. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2739. let mut line = line();
  2740. if done(&line) {
  2741. return;
  2742. }
  2743. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2744. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2745. let was_working = working(false);
  2746. let waiting = std::time::Instant::now();
  2747. while !done(&line) {
  2748. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2749. }
  2750. drop(line);
  2751. stood(waiting);
  2752. working(was_working);
  2753. let us = waiting.elapsed().as_micros() as u64;
  2754. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2755. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2756. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2757. #[cfg(feature = "diagnostics")]
  2758. blamed(why, us);
  2759. }
  2760. /// What the thread that lands flights fetches card copies' pieces with
  2761. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2762. /// behind the submission lock), and the memory the pieces come down to.
  2763. struct RelayFetch {
  2764. list: Prelude,
  2765. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2766. queue: Option<ID3D12CommandQueue>,
  2767. fence: ID3D12Fence,
  2768. event: HANDLE,
  2769. /// The last value signalled on `fence`.
  2770. sent: u64,
  2771. /// Buffer, mapping, bytes.
  2772. buffer: Option<(ID3D12Resource, usize, u64)>,
  2773. /// Pieces caught while a later flight was writing them.
  2774. suspects: torn::Suspects,
  2775. /// What earlier fetches brought of flights not landed yet.
  2776. had: crate::land::Had,
  2777. }
  2778. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2779. /// the first flights of the line it takes them, with what follows them,
  2780. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2781. /// the card, or for a flight. It takes neither the submission lock nor
  2782. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2783. /// lists and looking at what queues hold are left to [`late_helper`].
  2784. fn relay_worker() {
  2785. let Some(host) = host() else {
  2786. return;
  2787. };
  2788. // SAFETY: a plain event of our own.
  2789. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2790. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2791. };
  2792. let mut fetch: Option<RelayFetch> = None;
  2793. loop {
  2794. let next = {
  2795. let mut line = line();
  2796. loop {
  2797. if line.line.is_empty() {
  2798. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2799. continue;
  2800. }
  2801. let fences: Vec<Option<u64>> = line
  2802. .line
  2803. .iter()
  2804. .map(|l| match l {
  2805. Late::Run(flight) => Some(flight.fence),
  2806. _ => None,
  2807. })
  2808. .collect();
  2809. // SAFETY: a plain query.
  2810. let completed = unsafe { host.fence.GetCompletedValue() };
  2811. let n = landable(&fences, completed);
  2812. if n == 0 {
  2813. // The first thing is a flight the card has not run.
  2814. break Err(fences[0].unwrap_or(0));
  2815. }
  2816. line.settling = true;
  2817. let items: Vec<Late> = line.line.drain(..n).collect();
  2818. line.in_hand = items
  2819. .iter()
  2820. .filter_map(|l| match l {
  2821. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2822. _ => None,
  2823. })
  2824. .collect();
  2825. if card_steps::stage() > 0 {
  2826. line.landing = card_steps::writers(&items);
  2827. }
  2828. break Ok(items);
  2829. }
  2830. };
  2831. match next {
  2832. Ok(items) => host.relay_land(items, &mut fetch),
  2833. Err(target) => {
  2834. let waiting = std::time::Instant::now();
  2835. // SAFETY: the host's fence and this thread's event.
  2836. let waited = unsafe {
  2837. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2838. WaitForSingleObject(event, INFINITE);
  2839. })
  2840. };
  2841. if waited.is_err() {
  2842. std::thread::sleep(std::time::Duration::from_millis(1));
  2843. }
  2844. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2845. }
  2846. }
  2847. }
  2848. }
  2849. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2850. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2851. /// once, the pieces that differ found on several threads; but the merge is
  2852. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2853. /// are not done with here (each flight's are, afterwards). In two steps:
  2854. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  2855. /// which needs nothing that the fetch from the card's memory brings), and
  2856. /// the merge.
  2857. struct RelayBack {
  2858. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  2859. found: Option<Vec<Vec<(usize, usize)>>>,
  2860. }
  2861. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  2862. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2863. for (shadow, declared) in back {
  2864. if shadow.carded() {
  2865. continue;
  2866. }
  2867. let mut spans: Vec<(usize, usize)> = Vec::new();
  2868. join_ranges(&mut spans, declared.iter().copied());
  2869. for &(from, to) in &spans {
  2870. shadow.relay_compared(from, to - from);
  2871. }
  2872. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2873. }
  2874. RelayBack { work, found: None }
  2875. }
  2876. impl RelayBack {
  2877. /// Looks the ranges through, once; its time counts as `stat`.
  2878. fn look(&mut self, stat: usize) {
  2879. if self.work.is_empty() || self.found.is_some() {
  2880. return;
  2881. }
  2882. let scanning = std::time::Instant::now();
  2883. // Looked through without a lock: a piece that changes meanwhile (a
  2884. // later flight writing, the title's bytes going in) is found now or
  2885. // by that flight's landing, and the merge looks again under the
  2886. // lock.
  2887. self.found = Some(crate::shadow::find_all(&self.work));
  2888. crate::land::spent(stat, scanning);
  2889. #[cfg(feature = "diagnostics")]
  2890. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2891. }
  2892. /// What differs goes into title memory.
  2893. fn merge(mut self) {
  2894. use crate::land;
  2895. self.look(land::stat::SCAN);
  2896. let Some(found) = self.found else {
  2897. return;
  2898. };
  2899. let merging = std::time::Instant::now();
  2900. let mut written: Vec<u64> = Vec::new();
  2901. if land::on() {
  2902. // Pieces in the same block of title memory in one job, in order.
  2903. let pieces: Vec<(usize, usize, usize)> =
  2904. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  2905. let start = |i: usize| self.work[i].0.span().0 as usize;
  2906. let mut order: Vec<usize> = (0..pieces.len()).collect();
  2907. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  2908. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  2909. let jobs = land::jobs(&cut);
  2910. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  2911. land::each(jobs.len(), &|j| {
  2912. let working = std::time::Instant::now();
  2913. let mut notes = land::Notes::default();
  2914. for &p in &order[jobs[j].clone()] {
  2915. let (i, at, n) = pieces[p];
  2916. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  2917. }
  2918. notes.flush();
  2919. land::spent(land::stat::BACK_ALL, working);
  2920. });
  2921. land::count(land::stat::JOBS, jobs.len() as u64);
  2922. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  2923. } else {
  2924. let (mut now, mut title) = (Vec::new(), Vec::new());
  2925. for ((shadow, ..), found) in self.work.iter().zip(found) {
  2926. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  2927. written.push(found.into_iter().map(merge).sum());
  2928. }
  2929. }
  2930. land::spent(land::stat::BACK, merging);
  2931. for ((_, from, to), written) in self.work.iter().zip(written) {
  2932. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  2933. #[cfg(feature = "diagnostics")]
  2934. crate::copystat::compared(*from, to - from, written as usize);
  2935. let _ = (from, to);
  2936. }
  2937. }
  2938. }
  2939. /// For the frame-rate line, with [`late`]: what the line of flights did
  2940. /// per frame since the last one.
  2941. fn late_line(frames: f64) {
  2942. if !late() {
  2943. return;
  2944. }
  2945. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2946. tracing::info!(
  2947. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2948. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2949. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2950. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2951. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2952. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2953. s[0],
  2954. s[1],
  2955. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2956. s[12] / 1000.0,
  2957. s[WHY_SYNC],
  2958. s[WHY_CARD_DONE],
  2959. s[WHY_VALUE],
  2960. s[WHY_STALE],
  2961. s[WHY_READ],
  2962. s[15],
  2963. s[16],
  2964. s[17],
  2965. s[WHY_RUN],
  2966. late_most(),
  2967. s[WHY_MOST],
  2968. s[WHY_WRITES],
  2969. s[WHY_FENCE],
  2970. s[13],
  2971. s[14],
  2972. );
  2973. {
  2974. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2975. tracing::info!(
  2976. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2977. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2978. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2979. w[WHY_SYNC],
  2980. w[WHY_CARD_DONE],
  2981. w[WHY_VALUE],
  2982. w[WHY_STALE],
  2983. w[WHY_READ],
  2984. w[WHY_RUN],
  2985. w[WHY_MOST],
  2986. w[WHY_WRITES],
  2987. w[WHY_FENCE],
  2988. );
  2989. }
  2990. if relay() {
  2991. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2992. tracing::info!(
  2993. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2994. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2995. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2996. \"settles\" above are waits of other threads for it)",
  2997. r[1],
  2998. r[0],
  2999. r[2] / 1000.0,
  3000. r[3] / 1000.0,
  3001. r[4] / 1000.0,
  3002. );
  3003. if send::own() {
  3004. let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3005. tracing::info!(
  3006. "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
  3007. taking them out of the CPU sides",
  3008. t[0] / (1 << 20) as f64,
  3009. t[1],
  3010. t[2],
  3011. t[3] / 1000.0,
  3012. );
  3013. }
  3014. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3015. if t[0] > 0.0 {
  3016. tracing::info!(
  3017. "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",
  3018. t[0],
  3019. t[1],
  3020. t[2],
  3021. );
  3022. }
  3023. }
  3024. crate::land::log(frames);
  3025. if place::on() {
  3026. let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3027. tracing::info!(
  3028. "title buffer copies at their place in the lists, per frame (VICTORY_COPIES_IN_PLACE): {:.1} of {:.1} KB, {:.1} of them out of what shaders wrote; {:.2} copies into textures out of what shaders wrote",
  3029. t[0],
  3030. t[1] / 1024.0,
  3031. t[2],
  3032. t[3],
  3033. );
  3034. }
  3035. card_steps::log(frames);
  3036. crate::picked::log(frames);
  3037. #[cfg(feature = "diagnostics")]
  3038. log_blame(frames);
  3039. if late_exact() {
  3040. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  3041. tracing::info!(
  3042. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  3043. {runs:.0} changed runs, {:.2} MB",
  3044. bytes / (1 << 20) as f64
  3045. );
  3046. }
  3047. }
  3048. pub(crate) mod aside;
  3049. mod card_steps;
  3050. pub(crate) mod indirects;
  3051. mod place;
  3052. mod send;
  3053. pub(crate) use send::{goes_as_words, words_under};
  3054. mod torn;
  3055. pub(crate) mod upcheck;
  3056. #[cfg(test)]
  3057. mod late_tests {
  3058. use super::{continues, join_ranges, touches};
  3059. /// Copies join only when both ends continue and the whole does not
  3060. /// overlap itself.
  3061. #[test]
  3062. fn copies_join_only_end_to_end_and_apart() {
  3063. // (destination, source, bytes)
  3064. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  3065. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  3066. // A gap, or only one side continues.
  3067. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  3068. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  3069. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  3070. // Together they would overlap: the second reads what the first wrote.
  3071. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  3072. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  3073. // They touch without overlapping.
  3074. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  3075. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  3076. }
  3077. /// Ranges are found by what they hold, not by where they start, and a
  3078. /// range that only touches another's end does not touch it.
  3079. #[test]
  3080. fn ranges_touch_where_they_overlap() {
  3081. let mut ranges = Vec::new();
  3082. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  3083. assert_eq!(ranges, [(10, 25), (40, 60)]);
  3084. join_ranges(&mut ranges, [(25, 40)]);
  3085. assert_eq!(ranges, [(10, 60)]);
  3086. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  3087. for (from, to, hit) in [
  3088. (0, 10, false),
  3089. (0, 11, true),
  3090. (24, 25, true),
  3091. (25, 40, false),
  3092. (25, 41, true),
  3093. (59, 200, true),
  3094. (60, 100, false),
  3095. (100, 101, true),
  3096. (101, 500, false),
  3097. (30, 30, false),
  3098. (50, 50, false),
  3099. ] {
  3100. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  3101. }
  3102. assert!(!touches(&[], 0, usize::MAX));
  3103. }
  3104. }
  3105. /// Whether a title buffer copy that continues the one recorded before it
  3106. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  3107. /// default).
  3108. ///
  3109. /// Each copy is done at submission through the kernel, which reports a
  3110. /// page that is not there instead of faulting (`copy_mapped`), tells the
  3111. /// write watch and the guards, and ends the refreshes gathered so far: a
  3112. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  3113. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  3114. /// continue the one before is counted either way and said on its own line
  3115. /// with the frame rate; the switch is worth that many kernel calls.
  3116. ///
  3117. /// Joined, the same bytes move: [`continues`] joins only copies whose
  3118. /// ranges, taken together, do not overlap, and nothing is recorded between
  3119. /// two steps that follow each other. What differs: a page that is not
  3120. /// mapped now fails the joined copy as a whole (it then goes page by page,
  3121. /// zeros for what cannot be read, as a single copy does), where before
  3122. /// only the copy that held it did.
  3123. fn join_copies() -> bool {
  3124. static ON: OnceLock<bool> = OnceLock::new();
  3125. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  3126. }
  3127. /// Since the last frame-rate line: title buffer copies recorded, and those
  3128. /// that continue the one before ([`join_copies`]).
  3129. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  3130. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  3131. /// where `last` ended, source and destination both, and the two as one do
  3132. /// not overlap (source over destination): then one copy of both moves the
  3133. /// bytes the two would move in turn.
  3134. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  3135. let ((d, s, n), (dst, src, len)) = (last, next);
  3136. let Some(all) = n.checked_add(len) else {
  3137. return false;
  3138. };
  3139. d.checked_add(n) == Some(dst)
  3140. && s.checked_add(n) == Some(src)
  3141. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  3142. }
  3143. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  3144. /// One list's lock at a time: a submission may name a list twice.
  3145. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  3146. let mut back: Vec<Declared> = Vec::new();
  3147. // Where each copy is in it, and the ranges seen: dispatches declare the
  3148. // same ranges thousands of times a frame.
  3149. let mut places: ByCopy<usize> = ByCopy::default();
  3150. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  3151. for list in runs {
  3152. for step in &list.deferred().copies {
  3153. if let Step::GpuWrite(shadow, address, len) = step {
  3154. let key = std::sync::Arc::as_ptr(shadow) as usize;
  3155. if !seen.insert((key, *address, *len)) {
  3156. continue;
  3157. }
  3158. let i = *places.entry(key).or_insert_with(|| {
  3159. back.push((shadow.clone(), Vec::new()));
  3160. back.len() - 1
  3161. });
  3162. back[i].1.push((*address, *address + *len));
  3163. }
  3164. }
  3165. }
  3166. back
  3167. }
  3168. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  3169. /// lines that say what the title's CPU was given while it decided whether
  3170. /// the camera is in a room. The values of the small read-backs
  3171. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  3172. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  3173. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  3174. /// copies found stale after their refresh (`shadow.rs`; only with
  3175. /// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
  3176. /// runtime, the read requests that fail (with 2: every request).
  3177. pub(crate) fn walls_trace() -> bool {
  3178. static ON: OnceLock<bool> = OnceLock::new();
  3179. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  3180. }
  3181. /// After `list` has run: the texels its read-backs copied into host
  3182. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  3183. ///
  3184. /// A submission that is waited for did this itself. One sent ahead
  3185. /// ([`late`]) did not, at any stage: the flights' lists were settled
  3186. /// without it, so the title read a buffer nobody wrote, as before read-backs
  3187. /// were made (the exposure metering's two small float targets, every frame).
  3188. fn read_backs(list: &HostList) {
  3189. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  3190. let mut data = std::ptr::null_mut();
  3191. // SAFETY: a read-back buffer of ours, written by the list that has
  3192. // run; the title's destination holds every row (checked when the
  3193. // copy was recorded).
  3194. unsafe {
  3195. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  3196. let from = data.cast::<u8>().cast_const();
  3197. for line in 0..*rows {
  3198. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  3199. }
  3200. // The walls trace: what the title is handed (one row of at
  3201. // most 24 values: its 5x1 and 1x1 float targets).
  3202. if walls_trace() && *rows == 1 && *row <= 96 {
  3203. let mut values = [0f32; 24];
  3204. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  3205. tracing::info!(
  3206. frame = crate::frame::current(),
  3207. to = format_args!("{:#x}", *at),
  3208. bytes = *row,
  3209. values = ?&values[..*row / 4],
  3210. "walls trace: a read-back lands in title memory"
  3211. );
  3212. }
  3213. buffer.Unmap(0, None);
  3214. }
  3215. }
  3216. }
  3217. }
  3218. /// After the card ran what declared `back`: what shaders wrote there goes
  3219. /// into title memory, and the ranges are done with.
  3220. fn hand_back(back: &[Declared]) {
  3221. if crate::shadow::wide_back() {
  3222. // Every range first (the pieces that differ, found on several
  3223. // threads), then the merges, in order, as below.
  3224. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3225. for (shadow, declared) in back {
  3226. if shadow.carded() {
  3227. continue;
  3228. }
  3229. let mut sorted = declared.clone();
  3230. sorted.sort_unstable();
  3231. let mut spans: Vec<(usize, usize)> = Vec::new();
  3232. for (from, to) in sorted {
  3233. match spans.last_mut() {
  3234. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3235. _ => spans.push((from, to)),
  3236. }
  3237. }
  3238. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3239. }
  3240. #[cfg(feature = "diagnostics")]
  3241. let scanning = std::time::Instant::now();
  3242. let found = crate::shadow::find_all(&work);
  3243. #[cfg(feature = "diagnostics")]
  3244. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3245. for ((shadow, from, to), found) in work.iter().zip(found) {
  3246. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3247. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3248. #[cfg(feature = "diagnostics")]
  3249. crate::copystat::compared(*from, to - from, written);
  3250. }
  3251. for (shadow, declared) in back {
  3252. shadow.copy_back_done(declared);
  3253. }
  3254. return;
  3255. }
  3256. for (shadow, declared) in back {
  3257. if shadow.carded() {
  3258. // Done before (`Host::card_back`).
  3259. shadow.copy_back_done(declared);
  3260. continue;
  3261. }
  3262. // Each byte compared once: the world declares dozens of views
  3263. // of its 174 MB heap that overlap almost entirely, and comparing
  3264. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3265. // MB shaders wrote. Only ranges that overlap or touch are
  3266. // joined: what lies between two was not given to shaders (the
  3267. // snapshot does not hold it).
  3268. let mut sorted = declared.clone();
  3269. sorted.sort_unstable();
  3270. let mut spans: Vec<(usize, usize)> = Vec::new();
  3271. for (from, to) in sorted {
  3272. match spans.last_mut() {
  3273. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3274. _ => spans.push((from, to)),
  3275. }
  3276. }
  3277. for (from, to) in spans {
  3278. let written = shadow.copy_back(from, to - from);
  3279. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3280. #[cfg(feature = "diagnostics")]
  3281. crate::copystat::compared(from, to - from, written);
  3282. }
  3283. shadow.copy_back_done(declared);
  3284. }
  3285. }
  3286. impl Host {
  3287. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3288. /// mesh shaders need both); logged once.
  3289. pub(crate) fn mesh_shaders(&self) -> bool {
  3290. static MESH: OnceLock<bool> = OnceLock::new();
  3291. *MESH.get_or_init(|| {
  3292. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3293. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3294. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3295. };
  3296. // SAFETY: each query writes its own structure of the given size.
  3297. let ok = unsafe {
  3298. self.device
  3299. .CheckFeatureSupport(
  3300. D3D12_FEATURE_D3D12_OPTIONS7,
  3301. (&raw mut options).cast(),
  3302. size_of_val(&options) as u32,
  3303. )
  3304. .is_ok()
  3305. && self
  3306. .device
  3307. .CheckFeatureSupport(
  3308. D3D12_FEATURE_SHADER_MODEL,
  3309. (&raw mut model).cast(),
  3310. size_of_val(&model) as u32,
  3311. )
  3312. .is_ok()
  3313. };
  3314. let mesh = ok
  3315. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3316. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3317. tracing::info!(mesh, "host mesh shader support");
  3318. mesh
  3319. })
  3320. }
  3321. /// Whether the host GPU supports the depth bounds test; logged once.
  3322. pub(crate) fn depth_bounds(&self) -> bool {
  3323. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3324. *BOUNDS.get_or_init(|| {
  3325. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3326. // SAFETY: writes `options` of the given size.
  3327. let ok = unsafe {
  3328. self.device
  3329. .CheckFeatureSupport(
  3330. D3D12_FEATURE_D3D12_OPTIONS2,
  3331. (&raw mut options).cast(),
  3332. size_of_val(&options) as u32,
  3333. )
  3334. .is_ok()
  3335. };
  3336. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3337. tracing::info!(supported, "host depth bounds support");
  3338. supported
  3339. })
  3340. }
  3341. /// A new list, open for recording.
  3342. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3343. #[cfg(feature = "diagnostics")]
  3344. let started = std::time::Instant::now();
  3345. #[cfg(feature = "diagnostics")]
  3346. let before = private_bytes();
  3347. let list = self.make_list();
  3348. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3349. // (May shrink while a list is made, on another thread's account:
  3350. // added as it is, the sum is what counts.)
  3351. #[cfg(feature = "diagnostics")]
  3352. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3353. #[cfg(feature = "diagnostics")]
  3354. {
  3355. use crate::copystat::{C, add};
  3356. add(C::HostLists, 1);
  3357. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3358. }
  3359. list
  3360. }
  3361. /// An allocator and a closed list for a prelude.
  3362. fn make_prelude(&self) -> Option<Prelude> {
  3363. // SAFETY: plain object creation.
  3364. let made: windows::core::Result<Prelude> = unsafe {
  3365. (|| {
  3366. let allocator: ID3D12CommandAllocator =
  3367. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3368. let list: ID3D12GraphicsCommandList =
  3369. self.device
  3370. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3371. list.Close()?;
  3372. Ok((allocator, list))
  3373. })()
  3374. };
  3375. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3376. match made {
  3377. Ok(prelude) => Some(prelude),
  3378. Err(e) => {
  3379. tracing::warn!(error = %e, "no host list for a prelude");
  3380. None
  3381. }
  3382. }
  3383. }
  3384. fn make_list(&self) -> windows::core::Result<HostList> {
  3385. // SAFETY: plain object creation.
  3386. unsafe {
  3387. let allocator: ID3D12CommandAllocator = self
  3388. .device
  3389. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3390. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3391. 0,
  3392. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3393. &allocator,
  3394. None,
  3395. )?;
  3396. let prelude = OnceLock::new();
  3397. if !lazy_prelude() {
  3398. let _ = prelude.set(self.make_prelude());
  3399. }
  3400. #[cfg(feature = "diagnostics")]
  3401. let notes = std::sync::Arc::<Mutex<Vec<Note>>>::default();
  3402. let pipelines = std::sync::Arc::<Mutex<std::collections::BTreeSet<String>>>::default();
  3403. #[cfg(feature = "diagnostics")]
  3404. let indirects = indirects::Shared::default();
  3405. #[cfg(feature = "diagnostics")]
  3406. if dred_on() || dred_light() {
  3407. static NUMBER: AtomicU32 = AtomicU32::new(0);
  3408. let number = NUMBER.fetch_add(1, Ordering::Relaxed);
  3409. name(&list, || format!("victory host list {number}"));
  3410. let mut all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  3411. if number.is_multiple_of(256) {
  3412. all.retain(|_, l| l.0.strong_count() > 0);
  3413. }
  3414. all.insert(
  3415. number,
  3416. (
  3417. std::sync::Arc::downgrade(&notes),
  3418. std::sync::Arc::downgrade(&pipelines),
  3419. std::sync::Arc::downgrade(&indirects),
  3420. ),
  3421. );
  3422. }
  3423. Ok(HostList {
  3424. allocator,
  3425. list,
  3426. deferred: Mutex::default(),
  3427. scratch: Mutex::default(),
  3428. states: Mutex::default(),
  3429. twins: Mutex::default(),
  3430. prelude,
  3431. pipelines,
  3432. #[cfg(feature = "diagnostics")]
  3433. indirects,
  3434. budget: OnceLock::new(),
  3435. card_budget: OnceLock::new(),
  3436. indirect_args: Mutex::default(),
  3437. batch_args: Mutex::default(),
  3438. coming: Mutex::default(),
  3439. _alive: Counted::new(),
  3440. #[cfg(feature = "diagnostics")]
  3441. notes,
  3442. #[cfg(feature = "diagnostics")]
  3443. stamps: OnceLock::new(),
  3444. })
  3445. }
  3446. }
  3447. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3448. fn card_clock(&self) -> Option<&'static CardClock> {
  3449. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3450. static WATCH: std::sync::Once = std::sync::Once::new();
  3451. let clock = CLOCK
  3452. .get_or_init(|| {
  3453. // SAFETY: a plain fence on our device.
  3454. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3455. Some(CardClock {
  3456. fence,
  3457. state: Mutex::new((0, None)),
  3458. sent: std::sync::Condvar::new(),
  3459. })
  3460. })
  3461. .as_ref()?;
  3462. WATCH.call_once(|| {
  3463. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3464. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3465. }
  3466. });
  3467. Some(clock)
  3468. }
  3469. /// Lists of ours just went to the queue: the clock's signal goes
  3470. /// behind them, and an idle stretch of the card, if one was under way,
  3471. /// ends here ([`CARD_CLOCK_US`]).
  3472. fn card_sent(&self) {
  3473. let Some(clock) = self.card_clock() else {
  3474. return;
  3475. };
  3476. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3477. state.0 += 1;
  3478. // SAFETY: our queue and the clock's fence.
  3479. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3480. if let Some((since, worked_then)) = state.1.take() {
  3481. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3482. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3483. }
  3484. drop(state);
  3485. clock.sent.notify_one();
  3486. }
  3487. /// Whether the host has what copies in the card's memory need (three
  3488. /// lists and the compare); made at the first ask. A copy goes to the
  3489. /// card's memory only if it has.
  3490. pub(crate) fn card_ready(&self) -> bool {
  3491. static READY: OnceLock<bool> = OnceLock::new();
  3492. *READY.get_or_init(|| match self.make_card_work() {
  3493. Ok(work) => {
  3494. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3495. true
  3496. }
  3497. Err(e) => {
  3498. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3499. false
  3500. }
  3501. })
  3502. }
  3503. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3504. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3505. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3506. let mut code: Option<ID3DBlob> = None;
  3507. // SAFETY: the source and names live through the call; the out
  3508. // pointer is ours.
  3509. unsafe {
  3510. D3DCompile(
  3511. CARD_COMPARE.as_ptr().cast(),
  3512. CARD_COMPARE.len(),
  3513. windows::core::s!("card compare"),
  3514. None,
  3515. None,
  3516. windows::core::s!("main"),
  3517. windows::core::s!("cs_5_1"),
  3518. 0,
  3519. 0,
  3520. &mut code,
  3521. None,
  3522. )?;
  3523. }
  3524. let code = code.ok_or_else(windows::core::Error::empty)?;
  3525. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3526. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3527. // in one submission.
  3528. const RESULTS: u64 = 1 << 20;
  3529. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3530. name(&differs, || "card compare results".into());
  3531. // SAFETY: the blob's own bytes; the root signature is inside the
  3532. // shader.
  3533. unsafe {
  3534. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3535. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3536. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3537. pRootSignature: std::mem::transmute_copy(&root),
  3538. CS: D3D12_SHADER_BYTECODE {
  3539. pShaderBytecode: bytes.as_ptr().cast(),
  3540. BytecodeLength: bytes.len(),
  3541. },
  3542. ..Default::default()
  3543. })?;
  3544. #[cfg(feature = "diagnostics")]
  3545. name(&pso, || crate::replay::play::COMPARE.into());
  3546. Ok(CardWork {
  3547. sync: vec![list()?],
  3548. check: vec![list()?],
  3549. fetch: list()?,
  3550. root,
  3551. pso,
  3552. differs: (differs, data as usize, RESULTS),
  3553. fetched: None,
  3554. taken: 0,
  3555. out: 0,
  3556. })
  3557. }
  3558. }
  3559. /// Before a submission's lists run, for copies in the card's memory
  3560. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3561. /// the last submission goes to their card side (a list of ours, run
  3562. /// now; the submission's lists follow it on the queue), and the ranges
  3563. /// this submission's shaders may write get a compare to run after its
  3564. /// lists. `None` if there is nothing to do.
  3565. ///
  3566. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3567. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3568. /// `relay`).
  3569. /// `picked`: ranges that may be written too, and ranges to look at
  3570. /// (`crate::picked`).
  3571. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3572. use std::sync::Arc;
  3573. if !crate::shadow::cards() {
  3574. return None;
  3575. }
  3576. // The ranges this submission's shaders may write, per copy.
  3577. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3578. for list in runs {
  3579. for step in &list.deferred().copies {
  3580. if let Step::GpuWrite(shadow, address, len) = step
  3581. && shadow.carded()
  3582. {
  3583. let range = (*address, *address + *len);
  3584. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3585. Some((_, ranges)) => {
  3586. if !ranges.contains(&range) {
  3587. ranges.push(range);
  3588. }
  3589. }
  3590. None => declared.push((shadow.clone(), vec![range])),
  3591. }
  3592. }
  3593. }
  3594. }
  3595. let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
  3596. // (Of a copy with a declared range here, that says it.)
  3597. let looked: Vec<&crate::picked::Range> =
  3598. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3599. // With the relay: the order of the queue is held from here until
  3600. // what is taken is on the queue, and the taking is numbered.
  3601. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3602. let sent_as = match order.as_mut() {
  3603. Some(order) => {
  3604. **order += 1;
  3605. **order
  3606. }
  3607. None => 0,
  3608. };
  3609. let mut dirty = crate::shadow::card_dirty(sent_as);
  3610. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3611. return None;
  3612. }
  3613. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3614. let work = work.as_mut()?;
  3615. // A copy whose shader writes are declared for the first time gets
  3616. // its bytes from before, whole.
  3617. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3618. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3619. if shadow.card_make_before(|size| {
  3620. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3621. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3622. Some(before)
  3623. }) {
  3624. whole.push(shadow.clone());
  3625. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3626. dirty.push((shadow.clone(), Vec::new()));
  3627. }
  3628. }
  3629. }
  3630. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3631. let mut looks = None;
  3632. // The bytes as they are now, whatever later submissions put there.
  3633. let own = if send::own() { send::take(self, &dirty) } else { None };
  3634. if !dirty.is_empty() {
  3635. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3636. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3637. };
  3638. let (allocator, list) = &sync;
  3639. // SAFETY: the list's last run finished (it ran ahead of a
  3640. // submission that was waited for, and came back after that);
  3641. // live buffers, and the ranges lie in them.
  3642. let recorded = unsafe {
  3643. (|| -> windows::core::Result<()> {
  3644. allocator.Reset()?;
  3645. list.Reset(allocator, None)?;
  3646. if upcheck::on() {
  3647. looks = upcheck::record(self, list, &dirty);
  3648. }
  3649. // Every copy first, then one barrier call, then every
  3650. // pass: a wait between each copy and its pass had the
  3651. // card do them one after the other.
  3652. let mut sent = Vec::new();
  3653. if let Some(own) = &own {
  3654. own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
  3655. }
  3656. for (shadow, ranges) in &dirty {
  3657. let Some((staging, before, _)) = shadow.card_sides() else {
  3658. continue;
  3659. };
  3660. for &(a, b) in ranges {
  3661. if own.is_none() {
  3662. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3663. }
  3664. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3665. }
  3666. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3667. if own.is_none() && before.is_some() && !ranges.is_empty() {
  3668. sent.push(transition(
  3669. &shadow.buffer,
  3670. D3D12_RESOURCE_STATE_COPY_DEST,
  3671. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3672. ));
  3673. }
  3674. }
  3675. if !sent.is_empty() {
  3676. list.ResourceBarrier(&sent);
  3677. }
  3678. list.SetComputeRootSignature(&work.root);
  3679. list.SetPipelineState(&work.pso);
  3680. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3681. for (shadow, ranges) in &dirty {
  3682. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3683. continue;
  3684. };
  3685. // No twin (it cost the card the copy's size again,
  3686. // 399 MB in run 75): `before` holds a 128-bit hash
  3687. // of each 64 KiB piece. The pieces just sent up are
  3688. // hashed again, all of them the first time; the
  3689. // compare after the lists hashes the declared
  3690. // pieces and flags those whose hash is another.
  3691. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3692. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3693. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3694. vec![shadow.card_run(0, usize::MAX)]
  3695. } else {
  3696. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3697. };
  3698. // The same pieces in fewer passes (`rehash_runs`).
  3699. let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3700. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3701. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3702. for run in runs {
  3703. card_pass(list, &run, size as u32, 0, 0);
  3704. }
  3705. }
  3706. list.Close()?;
  3707. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3708. Ok(())
  3709. })()
  3710. };
  3711. if let Err(e) = recorded {
  3712. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3713. }
  3714. used.push((false, sync));
  3715. }
  3716. drop(order);
  3717. let mut plan = CardPlan {
  3718. ranges: Vec::new(),
  3719. check: None,
  3720. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3721. lists: used,
  3722. sent_as,
  3723. looks,
  3724. sends: own.map(send::Own::memory),
  3725. };
  3726. // Each byte once, as the copy-back joins the declared ranges. The
  3727. // results go behind those of plans still in the air.
  3728. let mut at = work.taken;
  3729. for (shadow, ranges) in &declared {
  3730. let mut sorted = ranges.clone();
  3731. sorted.sort_unstable();
  3732. let mut spans: Vec<(usize, usize)> = Vec::new();
  3733. for (from, to) in sorted {
  3734. match spans.last_mut() {
  3735. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3736. _ => spans.push((from, to)),
  3737. }
  3738. }
  3739. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3740. for (from, to) in spans {
  3741. let Some(span) = shadow.card_span(from, to) else {
  3742. continue;
  3743. };
  3744. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3745. plan.ranges.push(CardRange {
  3746. shadow: shadow.clone(),
  3747. declared: (from, to),
  3748. span,
  3749. at,
  3750. compared,
  3751. picked: false,
  3752. });
  3753. if compared {
  3754. at += span.pieces;
  3755. }
  3756. }
  3757. }
  3758. for (shadow, from, len) in looked {
  3759. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3760. if let Some(span) = shadow.card_span(*from, from + len)
  3761. && twin
  3762. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3763. {
  3764. plan.ranges.push(CardRange {
  3765. shadow: shadow.clone(),
  3766. declared: (*from, from + len),
  3767. span,
  3768. at,
  3769. compared: true,
  3770. picked: true,
  3771. });
  3772. at += span.pieces;
  3773. }
  3774. }
  3775. work.taken = at;
  3776. if plan.ranges.iter().any(|r| r.compared) {
  3777. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3778. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3779. };
  3780. let (allocator, list) = &check;
  3781. // SAFETY: the list's last run finished (its submission was
  3782. // waited for, and it came back after that); live buffers; the
  3783. // compare's own root signature.
  3784. let recorded = unsafe {
  3785. (|| -> windows::core::Result<ID3D12CommandList> {
  3786. allocator.Reset()?;
  3787. list.Reset(allocator, None)?;
  3788. // What the submission's shaders wrote, first.
  3789. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3790. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3791. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3792. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3793. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3794. pResource: std::mem::ManuallyDrop::new(None),
  3795. }),
  3796. },
  3797. }]);
  3798. list.SetComputeRootSignature(&work.root);
  3799. list.SetPipelineState(&work.pso);
  3800. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3801. for r in plan.ranges.iter().filter(|r| r.compared) {
  3802. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3803. continue;
  3804. };
  3805. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3806. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3807. // (What is only looked at keeps its hashes: what
  3808. // changed there is the next declared range's to land.)
  3809. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  3810. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3811. }
  3812. list.Close()?;
  3813. list.cast()
  3814. })()
  3815. };
  3816. match recorded {
  3817. Ok(list) => plan.check = Some(list),
  3818. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3819. }
  3820. plan.lists.push((true, check));
  3821. }
  3822. work.out += 1;
  3823. Some(plan)
  3824. }
  3825. /// With [`relay`]: whether the compare's result area is half taken by
  3826. /// plans in the air. It starts from the beginning only when no plan is
  3827. /// out, so the caller lets the flights land first.
  3828. fn card_results_low(&self) -> bool {
  3829. CARD_WORK
  3830. .lock()
  3831. .unwrap_or_else(|e| e.into_inner())
  3832. .as_ref()
  3833. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3834. }
  3835. /// The plan's submission has run and its results were read
  3836. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3837. /// when nothing of ours is on the card, so the compare's results start
  3838. /// from the beginning again.
  3839. fn card_done(&self, plan: CardPlan) {
  3840. if let Some(looks) = plan.looks {
  3841. looks.read();
  3842. }
  3843. if let Some(memory) = plan.sends {
  3844. send::give_back(memory);
  3845. }
  3846. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3847. let Some(work) = work.as_mut() else {
  3848. return;
  3849. };
  3850. for (check, list) in plan.lists {
  3851. if check { work.check.push(list) } else { work.sync.push(list) }
  3852. }
  3853. work.out = work.out.saturating_sub(1);
  3854. // With the relay other plans may be on the card, their results
  3855. // not read yet: the area starts again only when none is out.
  3856. if !relay() || work.out == 0 {
  3857. work.taken = 0;
  3858. }
  3859. }
  3860. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3861. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3862. // SAFETY: plain object creation.
  3863. let copying = relay_copy().then(|| unsafe {
  3864. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3865. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3866. let list: ID3D12GraphicsCommandList =
  3867. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3868. list.Close()?;
  3869. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3870. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3871. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3872. ..Default::default()
  3873. })?;
  3874. Ok(((allocator, list), queue))
  3875. })()
  3876. });
  3877. let (list, queue) = match copying {
  3878. Some(Ok((list, queue))) => (list, Some(queue)),
  3879. Some(Err(e)) => {
  3880. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3881. (self.make_prelude()?, None)
  3882. }
  3883. None => (self.make_prelude()?, None),
  3884. };
  3885. // SAFETY: plain objects of our own.
  3886. unsafe {
  3887. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3888. let event = CreateEventW(None, false, false, None).ok()?;
  3889. Some(RelayFetch {
  3890. list,
  3891. queue,
  3892. fence,
  3893. event,
  3894. sent: 0,
  3895. buffer: None,
  3896. suspects: torn::Suspects::default(),
  3897. had: crate::land::Had::default(),
  3898. })
  3899. }
  3900. }
  3901. /// [`relay`], on the thread that lands flights: for the plans of the
  3902. /// flights being landed (the card has run them), the pieces their
  3903. /// compares flagged are fetched, once each, with a list and a wait of
  3904. /// this thread's own, and what shaders wrote in them goes into title
  3905. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3906. /// no submission lock; a piece flagged under one range of a plan is
  3907. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3908. /// whatever was sent meanwhile, so it may bring a later flight's
  3909. /// bytes, which that flight's landing then finds merged already; and
  3910. /// nothing is sent back up. `plans` come with the value signalled behind
  3911. /// their flight. `meanwhile` is called while the fetch is on its way, if
  3912. /// there is one.
  3913. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  3914. use crate::land;
  3915. let gathering = std::time::Instant::now();
  3916. let differs = {
  3917. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3918. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3919. };
  3920. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3921. let mut total = 0u64;
  3922. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  3923. fetch.had.landing(first);
  3924. }
  3925. // SAFETY: the mapping of the results. The compares of these plans
  3926. // have run, and their dwords are given to no other plan before these
  3927. // are done with (`card_done`).
  3928. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  3929. if let Some(differs) = differs {
  3930. // Pieces caught while a later flight was at them (`torn`).
  3931. let suspects = fetch.as_ref().map(|f| &f.suspects);
  3932. let mut seen = std::collections::HashSet::new();
  3933. for &(plan, behind) in plans {
  3934. plan.picked_found(differs);
  3935. let flags: Vec<(usize, u32, bool)> = plan
  3936. .ranges
  3937. .iter()
  3938. .filter(|r| !r.picked)
  3939. .flat_map(|r| {
  3940. (0..r.span.pieces).map(move |p| {
  3941. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  3942. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  3943. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  3944. })
  3945. })
  3946. .collect();
  3947. let fetched = flagged_pieces(&flags);
  3948. for r in plan.ranges.iter().filter(|r| !r.picked) {
  3949. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3950. if upcheck::on() {
  3951. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  3952. }
  3953. for p in 0..r.span.pieces {
  3954. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  3955. continue;
  3956. }
  3957. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3958. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  3959. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  3960. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  3961. land::count(land::stat::HAD, 1);
  3962. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  3963. if land::skip_on() {
  3964. continue;
  3965. }
  3966. }
  3967. if upcheck::on() {
  3968. upcheck::fetched(r.shadow.id(), lo);
  3969. }
  3970. seen.insert((copy, lo, hi));
  3971. pieces.push((r.shadow.clone(), lo, hi, total));
  3972. total += (hi - lo) as u64;
  3973. }
  3974. }
  3975. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3976. }
  3977. }
  3978. }
  3979. if land::on() {
  3980. // In the order they are landed, each byte of a copy once.
  3981. let keys: Vec<land::Piece> =
  3982. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  3983. total = 0;
  3984. pieces = land::ordered(&keys)
  3985. .into_iter()
  3986. .map(|(i, title, len)| {
  3987. let shadow = &pieces[i].0;
  3988. let lo = title - shadow.span().0 as usize;
  3989. let at = total;
  3990. total += len as u64;
  3991. (shadow.clone(), lo, lo + len, at)
  3992. })
  3993. .collect();
  3994. }
  3995. land::spent(land::stat::GATHER, gathering);
  3996. if fetch.is_none() {
  3997. *fetch = self.make_relay_fetch();
  3998. }
  3999. // On the copy queue a later flight may be at a piece while it is
  4000. // fetched: the pieces come down whole, to be hashed.
  4001. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  4002. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  4003. if let Some(check) = &check {
  4004. total = check.total;
  4005. }
  4006. // The sends these flights ran behind, all a fetch on the copy queue
  4007. // is known to have run behind.
  4008. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  4009. if pieces.is_empty() {
  4010. // Nothing to fetch: every send so far is older than the next
  4011. // fetch, if that goes to the queue the sends went to.
  4012. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  4013. true => behind,
  4014. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  4015. };
  4016. crate::shadow::relay_fetched(after);
  4017. return;
  4018. }
  4019. let Some(f) = fetch.as_mut() else {
  4020. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  4021. };
  4022. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  4023. let size = total.next_multiple_of(16 << 20);
  4024. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4025. }
  4026. let Some((buffer, data, _)) = f.buffer.clone() else {
  4027. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  4028. };
  4029. f.sent += 1;
  4030. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  4031. let copy_queue = f.queue.clone();
  4032. let waiting = std::time::Instant::now();
  4033. // The flights the fetch runs behind: those in the line by now have
  4034. // been given to the queue. On the copy queue, those landed here.
  4035. let ahead = match copy_queue {
  4036. Some(_) => 0,
  4037. None => line().target,
  4038. };
  4039. // SAFETY: the list's last run was waited for by this thread; live
  4040. // buffers (the copies are held by the plans); the fence and the
  4041. // event are this thread's.
  4042. let ran = unsafe {
  4043. (|| -> windows::core::Result<u64> {
  4044. allocator.Reset()?;
  4045. list.Reset(&allocator, None)?;
  4046. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  4047. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  4048. }
  4049. list.Close()?;
  4050. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  4051. if let Some(queue) = &copy_queue {
  4052. queue.ExecuteCommandLists(&lists);
  4053. queue.Signal(&fence, sent)?;
  4054. meanwhile();
  4055. fence.SetEventOnCompletion(sent, event)?;
  4056. WaitForSingleObject(event, INFINITE);
  4057. return Ok(behind);
  4058. }
  4059. // In the order of the queue: the sends of title bytes so
  4060. // far are ahead of this fetch, every later one behind it.
  4061. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  4062. self.queue.ExecuteCommandLists(&lists);
  4063. let after = *order;
  4064. drop(order);
  4065. self.card_sent();
  4066. self.queue.Signal(&fence, sent)?;
  4067. meanwhile();
  4068. fence.SetEventOnCompletion(sent, event)?;
  4069. WaitForSingleObject(event, INFINITE);
  4070. Ok(after)
  4071. })()
  4072. };
  4073. let after = match ran {
  4074. Ok(after) => after,
  4075. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  4076. };
  4077. let us = waiting.elapsed().as_micros() as u64;
  4078. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  4079. {
  4080. use crate::shadow::CARD_STATS;
  4081. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4082. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4083. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4084. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  4085. }
  4086. let merging = std::time::Instant::now();
  4087. let mut written = 0;
  4088. if land::on() {
  4089. let titles: Vec<(usize, usize)> =
  4090. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  4091. let jobs = land::jobs(&titles);
  4092. let put = std::sync::atomic::AtomicU64::new(0);
  4093. land::each(jobs.len(), &|j| {
  4094. let working = std::time::Instant::now();
  4095. if let Some(check) = &check {
  4096. for i in jobs[j].clone() {
  4097. // SAFETY: as below.
  4098. unsafe { check.look(i, data) };
  4099. }
  4100. }
  4101. let mut notes = land::Notes::default();
  4102. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  4103. let addressed: Vec<(usize, usize, usize)> =
  4104. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  4105. // SAFETY: the mapping of the fetched bytes, `total` of
  4106. // them; the copy into it has run, and the next waits
  4107. // for this call.
  4108. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  4109. }
  4110. notes.flush();
  4111. land::spent(land::stat::CARD_ALL, working);
  4112. });
  4113. land::count(land::stat::JOBS, jobs.len() as u64);
  4114. written = put.into_inner();
  4115. } else {
  4116. let mut title = Vec::new();
  4117. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  4118. if let Some(check) = &check {
  4119. // SAFETY: as below.
  4120. unsafe { check.look(i, data) };
  4121. }
  4122. // SAFETY: the mapping of the fetched bytes, `total` of them;
  4123. // the copy into it has run.
  4124. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  4125. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  4126. shadow.walls_merged(gpu.len(), merged);
  4127. written += merged as u64;
  4128. }
  4129. }
  4130. land::spent(land::stat::CARD, merging);
  4131. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  4132. if let Some(f) = fetch.as_mut() {
  4133. if let Some(check) = &check {
  4134. check.done(&mut f.suspects);
  4135. }
  4136. f.had.fetched(
  4137. ahead,
  4138. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  4139. );
  4140. }
  4141. // Sends up to `after` are of no use to any later merge.
  4142. crate::shadow::relay_fetched(after);
  4143. }
  4144. /// [`relay`], on the thread that lands flights: `items` are the first
  4145. /// things of the line, flights the card has run and what follows them.
  4146. /// What their shaders wrote goes into title memory (copies in the
  4147. /// card's memory first, then the others, each byte once whichever
  4148. /// flights declared it); then every flight's ranges are done with;
  4149. /// then, in the line's order, each flight's read-backs, its
  4150. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  4151. /// is complete before the title is told anything.
  4152. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  4153. let landing = std::time::Instant::now();
  4154. {
  4155. let flights: Vec<&Flight> = items
  4156. .iter()
  4157. .filter_map(|l| match l {
  4158. Late::Run(flight) => Some(flight),
  4159. _ => None,
  4160. })
  4161. .collect();
  4162. if !flights.is_empty() {
  4163. // SAFETY: a plain query.
  4164. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4165. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  4166. fail(format_args!(
  4167. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  4168. flights.len(),
  4169. runs.len(),
  4170. self.removal_data(&runs),
  4171. last_notes(&runs)
  4172. ));
  4173. }
  4174. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  4175. // (Each byte once: the ranges are joined.)
  4176. let mut back: Vec<Declared> = Vec::new();
  4177. for flight in &flights {
  4178. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  4179. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4180. Some((_, all)) => all.extend_from_slice(ranges),
  4181. None => back.push((shadow.clone(), ranges.clone())),
  4182. }
  4183. }
  4184. }
  4185. let mut hand_back = relay_hand_back(&back);
  4186. self.relay_card_back(&plans, fetch, &mut || {
  4187. if crate::land::on() {
  4188. hand_back.look(crate::land::stat::SCAN_BESIDE);
  4189. }
  4190. });
  4191. hand_back.merge();
  4192. let finishing = std::time::Instant::now();
  4193. // Only now, and flight by flight: a range another flight
  4194. // in the air declared too stays closed to refreshes.
  4195. for flight in &flights {
  4196. for (shadow, ranges) in &flight.back {
  4197. shadow.copy_back_done(ranges);
  4198. }
  4199. }
  4200. crate::land::spent(crate::land::stat::DONE, finishing);
  4201. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4202. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  4203. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  4204. }
  4205. }
  4206. // In the order given: what tells the title the card is done.
  4207. let mut last = 0;
  4208. let mut landed = Vec::new();
  4209. let mut telling = std::time::Instant::now();
  4210. for item in items {
  4211. telling = match item {
  4212. Late::Run(flight) => {
  4213. last = flight.number;
  4214. for &i in &flight.order {
  4215. read_backs(flight.lists[i].host());
  4216. }
  4217. if let Some(card) = flight.card {
  4218. self.card_done(card);
  4219. }
  4220. if let Some(own) = flight.own {
  4221. own.landed();
  4222. }
  4223. landed.push((flight.lists, flight.order));
  4224. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  4225. }
  4226. Late::Write(at, what, bytes) => {
  4227. what.write(at as *mut u8, bytes);
  4228. crate::land::spent(crate::land::stat::TOLD, telling)
  4229. }
  4230. Late::Signal(fence, value) => {
  4231. crate::fence::set(fence as crate::object::This, value);
  4232. crate::land::spent(crate::land::stat::TOLD, telling)
  4233. }
  4234. };
  4235. }
  4236. if last > 0 {
  4237. FINISHED.store(last, Ordering::Release);
  4238. bury(last);
  4239. }
  4240. self.log_messages();
  4241. crate::land::spent(crate::land::stat::REST, telling);
  4242. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4243. {
  4244. let mut line = line();
  4245. let Line {
  4246. line: items,
  4247. written,
  4248. lists,
  4249. settling,
  4250. poke,
  4251. landed: kept,
  4252. in_hand,
  4253. landing,
  4254. ..
  4255. } = &mut *line;
  4256. kept.extend(landed);
  4257. in_hand.clear();
  4258. landing.clear();
  4259. // What is still in the air, from the flights that are.
  4260. written.clear();
  4261. *lists = 0;
  4262. let mut ranges = Vec::new();
  4263. for item in items.iter() {
  4264. if let Late::Run(flight) = item {
  4265. *lists += flight.order.len().max(1);
  4266. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  4267. }
  4268. }
  4269. join_ranges(written, ranges);
  4270. *settling = false;
  4271. // The landed lists are reset, and what queues hold looked at,
  4272. // by the helper thread (they take locks a waiter may hold).
  4273. *poke = true;
  4274. }
  4275. LINE_MOVED.notify_all();
  4276. LINE_LANDED.notify_all();
  4277. }
  4278. /// After a submission ran, for copies in the card's memory: the pieces
  4279. /// of the declared ranges that the compare found differing (all of a
  4280. /// range it did not compare) are fetched, with one more wait for the
  4281. /// card, and what shaders wrote in them goes into title memory.
  4282. /// `submitted` is the last value signalled on the fence. `seen` holds
  4283. /// the pieces fetched already since the card was last waited for
  4284. /// (several submissions settled together name the same ones).
  4285. fn card_back(
  4286. &self,
  4287. plan: &CardPlan,
  4288. submitted: &mut u64,
  4289. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4290. ) {
  4291. if plan.ranges.is_empty() {
  4292. return;
  4293. }
  4294. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4295. let Some(work) = work.as_mut() else {
  4296. return;
  4297. };
  4298. // SAFETY: the mapping of the results, which the compare (it has
  4299. // run) wrote.
  4300. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4301. // The pieces to fetch: the range, the offsets in its copy, and
  4302. // where the bytes come down.
  4303. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4304. let mut total = 0u64;
  4305. plan.picked_found(differs);
  4306. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4307. for p in 0..r.span.pieces {
  4308. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4309. continue;
  4310. }
  4311. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4312. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4313. pieces.push((i, lo, hi, total));
  4314. total += (hi - lo) as u64;
  4315. }
  4316. }
  4317. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4318. }
  4319. let mut written = vec![0usize; plan.ranges.len()];
  4320. if !pieces.is_empty() {
  4321. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4322. let size = total.next_multiple_of(16 << 20);
  4323. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4324. }
  4325. let Some((fetched, data, _)) = &work.fetched else {
  4326. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4327. };
  4328. let waiting = std::time::Instant::now();
  4329. let (allocator, list) = &work.fetch;
  4330. // SAFETY: the list's last run was waited for; live buffers; the
  4331. // fence and event are ours, under the submission lock.
  4332. let ran = unsafe {
  4333. (|| -> windows::core::Result<()> {
  4334. allocator.Reset()?;
  4335. list.Reset(allocator, None)?;
  4336. for &(i, lo, hi, at) in &pieces {
  4337. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4338. }
  4339. list.Close()?;
  4340. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4341. self.card_sent();
  4342. *submitted += 1;
  4343. self.queue.Signal(&self.fence, *submitted)?;
  4344. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4345. let was_working = working(false);
  4346. WaitForSingleObject(self.event, INFINITE);
  4347. stood(waiting);
  4348. working(was_working);
  4349. Ok(())
  4350. })()
  4351. };
  4352. if let Err(e) = ran {
  4353. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4354. }
  4355. {
  4356. use crate::shadow::CARD_STATS;
  4357. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4358. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4359. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4360. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4361. }
  4362. if wide_merge() && pieces.len() >= 8 {
  4363. // The pieces are apart from one another (each its own bytes
  4364. // of its copy and of title memory): several at a time.
  4365. let fetched = *data;
  4366. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4367. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4368. let each = pieces.len().div_ceil(8);
  4369. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4370. .chunks(each)
  4371. .map(|chunk| {
  4372. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4373. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4374. let counts = counts.clone();
  4375. Box::new(move || {
  4376. let mut title = Vec::new();
  4377. for (shadow, i, lo, hi, at) in chunk {
  4378. // SAFETY: the mapping of the fetched bytes;
  4379. // the copy into it has run, and the caller
  4380. // waits for this job.
  4381. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4382. let merged = shadow.card_merge(lo, gpu, &mut title);
  4383. shadow.walls_merged(gpu.len(), merged);
  4384. counts[i].fetch_add(merged, Ordering::Relaxed);
  4385. }
  4386. }) as Box<dyn FnOnce() + Send>
  4387. })
  4388. .collect();
  4389. crate::shadow::wide_run(jobs);
  4390. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4391. *written += count.load(Ordering::Relaxed);
  4392. }
  4393. } else {
  4394. let mut title = Vec::new();
  4395. for &(i, lo, hi, at) in &pieces {
  4396. // SAFETY: the mapping of the fetched bytes, `total` of
  4397. // them; the copy into it has run.
  4398. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4399. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4400. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4401. written[i] += merged;
  4402. }
  4403. }
  4404. }
  4405. for (r, written) in plan.ranges.iter().zip(written) {
  4406. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4407. let (from, to) = r.declared;
  4408. #[cfg(feature = "diagnostics")]
  4409. crate::copystat::compared(from, to - from, written);
  4410. let _ = (from, to);
  4411. }
  4412. }
  4413. /// Runs closed lists and waits for them, and with [`late`] for
  4414. /// everything sent to the card before them, which is settled first.
  4415. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4416. // Behind what the title's queues were given before it.
  4417. crate::queue::before_sync();
  4418. let _ = self.submit(runs, false);
  4419. }
  4420. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4421. /// from the title's, go to the card in `order` and are not waited for.
  4422. /// They join the line of flights and are settled, with the others in
  4423. /// the air, at the next point where what they do can be observed
  4424. /// ([`late`] lists those points); their host lists are reset and kept
  4425. /// for reuse then, as a queue does for the lists it ran.
  4426. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4427. if order.is_empty() {
  4428. crate::list::recycle(lists, &order);
  4429. return;
  4430. }
  4431. late_threads();
  4432. let sent = {
  4433. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4434. self.submit(&runs, true)
  4435. };
  4436. let Some((mut submitted, sent)) = sent else {
  4437. // (Not reached: a submission sent ahead always comes back.)
  4438. crate::list::recycle(lists, &order);
  4439. return;
  4440. };
  4441. let told = !sent.writes.is_empty();
  4442. let most = {
  4443. let mut line = line();
  4444. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4445. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4446. *flying += order.len();
  4447. *target = *submitted;
  4448. items.push(Late::Run(Flight {
  4449. number: sent.number,
  4450. fence: *target,
  4451. lists,
  4452. order,
  4453. card: sent.card,
  4454. back: sent.back,
  4455. own: sent.own,
  4456. }));
  4457. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4458. *flying >= late_most()
  4459. };
  4460. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4461. RELAY_MOVED.notify_one();
  4462. if told && !late_writes() {
  4463. self.settle(&mut submitted, WHY_WRITES);
  4464. } else if most && relay_exact() {
  4465. // Until there are fewer, not until there are none.
  4466. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4467. } else if most {
  4468. self.settle(&mut submitted, WHY_MOST);
  4469. } else {
  4470. LINE_MOVED.notify_one();
  4471. }
  4472. drop(submitted);
  4473. land();
  4474. }
  4475. /// Sends `list`, a closed list of ours (the present's copy), as a
  4476. /// flight ([`late_free_present`]): not waited for, settled with the
  4477. /// others. The caller keeps the list and does not reset it before the
  4478. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4479. /// it ran and was waited for after all.
  4480. fn execute_own(&self, list: &HostList) -> u64 {
  4481. late_threads();
  4482. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4483. return 0;
  4484. };
  4485. let number = sent.number;
  4486. {
  4487. let mut line = line();
  4488. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4489. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4490. *flying += 1;
  4491. *target = *submitted;
  4492. items.push(Late::Run(Flight {
  4493. number,
  4494. fence: *target,
  4495. lists: Vec::new(),
  4496. order: Vec::new(),
  4497. card: sent.card,
  4498. back: sent.back,
  4499. own: sent.own,
  4500. }));
  4501. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4502. }
  4503. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4504. LINE_MOVED.notify_one();
  4505. RELAY_MOVED.notify_one();
  4506. drop(submitted);
  4507. number
  4508. }
  4509. /// Waits for the card to run every flight in the air ([`late`]) and
  4510. /// does what they left to do, as [`Host::execute`] does for one
  4511. /// submission after its wait: the pieces their shaders wrote in copies
  4512. /// in the card's memory are fetched and merged (each once), the ranges
  4513. /// they declared in the other copies are compared and copied back
  4514. /// (each byte once, whichever flights declared it), and then, in the
  4515. /// order they were given: their bottom-of-pipe writes and the fence
  4516. /// signals behind them. `submitted` is the submission lock's value;
  4517. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4518. ///
  4519. /// Everything in the air is settled, never the first flights alone:
  4520. /// the merge writes the copies' CPU side, which a flight still on the
  4521. /// card may be writing too.
  4522. fn settle(&self, submitted: &mut u64, why: usize) {
  4523. if !late() {
  4524. return;
  4525. }
  4526. if relay() {
  4527. // Nothing is settled here: the thread that lands flights does
  4528. // it, in order, and this waits until nothing is in the air and
  4529. // nothing is being landed. Every point that settled before
  4530. // comes here, so each still sees title memory, fences and
  4531. // bottom-of-pipe values as after a settle.
  4532. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4533. return;
  4534. }
  4535. let was_working = working(true);
  4536. let mut counted = false;
  4537. loop {
  4538. let items = {
  4539. let mut line = line();
  4540. if line.line.is_empty() {
  4541. line.settling = false;
  4542. break;
  4543. }
  4544. line.settling = true;
  4545. line.written.clear();
  4546. line.lists = 0;
  4547. std::mem::take(&mut line.line)
  4548. };
  4549. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4550. if !counted {
  4551. counted = true;
  4552. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4553. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4554. }
  4555. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4556. if flights > 0 {
  4557. submitting(2, flights);
  4558. let waiting = std::time::Instant::now();
  4559. // SAFETY: the fence and event are ours, under the
  4560. // submission lock; `submitted` is the last value signalled.
  4561. unsafe {
  4562. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4563. Ok(()) => {
  4564. working(false);
  4565. WaitForSingleObject(self.event, INFINITE);
  4566. stood(waiting);
  4567. working(true);
  4568. }
  4569. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4570. }
  4571. }
  4572. let gpu = waiting.elapsed();
  4573. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4574. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4575. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4576. #[cfg(feature = "diagnostics")]
  4577. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4578. format!("{flights} submissions sent ahead, settled together")
  4579. });
  4580. // SAFETY: a plain query.
  4581. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4582. let runs: Vec<&HostList> = items
  4583. .iter()
  4584. .filter_map(|i| match i {
  4585. Late::Run(f) => Some(f),
  4586. _ => None,
  4587. })
  4588. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4589. .collect();
  4590. fail(format_args!(
  4591. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4592. runs.len(),
  4593. self.removal_data(&runs),
  4594. last_notes(&runs)
  4595. ));
  4596. }
  4597. submitting(3, flights);
  4598. let copying = std::time::Instant::now();
  4599. let mut seen = std::collections::HashSet::new();
  4600. let mut back: Vec<Declared> = Vec::new();
  4601. for item in &items {
  4602. let Late::Run(flight) = item else {
  4603. continue;
  4604. };
  4605. if let Some(card) = &flight.card {
  4606. self.card_back(card, submitted, &mut seen);
  4607. }
  4608. for (shadow, ranges) in &flight.back {
  4609. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4610. Some((_, all)) => {
  4611. for range in ranges {
  4612. if !all.contains(range) {
  4613. all.push(*range);
  4614. }
  4615. }
  4616. }
  4617. None => back.push((shadow.clone(), ranges.clone())),
  4618. }
  4619. }
  4620. }
  4621. hand_back(&back);
  4622. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4623. }
  4624. // In the order given: what tells the title the card is done.
  4625. let mut last = 0;
  4626. let mut landed = Vec::new();
  4627. for item in items {
  4628. match item {
  4629. Late::Run(flight) => {
  4630. last = flight.number;
  4631. for &i in &flight.order {
  4632. read_backs(flight.lists[i].host());
  4633. }
  4634. if let Some(card) = flight.card {
  4635. self.card_done(card);
  4636. }
  4637. landed.push((flight.lists, flight.order));
  4638. }
  4639. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4640. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4641. }
  4642. }
  4643. if last > 0 {
  4644. FINISHED.store(last, Ordering::Release);
  4645. bury(last);
  4646. }
  4647. line().landed.extend(landed);
  4648. }
  4649. if counted {
  4650. self.log_messages();
  4651. submitting(0, 0);
  4652. // What was settled may be what a queue stands at, and the
  4653. // caller may not be one that looks (a read-back, a present).
  4654. if why != WHY_CARD_DONE {
  4655. line().poke = true;
  4656. LINE_MOVED.notify_one();
  4657. }
  4658. }
  4659. working(was_working);
  4660. }
  4661. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4662. /// copies, which flights may be writing and the title wrote too
  4663. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4664. /// those of the submission's one asking, which is made again.
  4665. ///
  4666. /// With [`card_steps`] only the flights that declared them: a range of
  4667. /// a copy nobody declared any more is refreshed like any other. What
  4668. /// they landed is title memory written, so everything is asked and
  4669. /// looked at again; what is left after three times waits as before.
  4670. fn settle_stale(
  4671. &self,
  4672. submitted: &mut u64,
  4673. runs: &[&HostList],
  4674. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4675. ranges: &[(usize, usize)],
  4676. ) {
  4677. if relay_exact() && card_steps::stage() > 0 {
  4678. for _ in 0..3 {
  4679. #[cfg(feature = "diagnostics")]
  4680. blame_stale(&stale);
  4681. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4682. crate::watch::ask_once(ranges);
  4683. stale = stale_under_flights(runs);
  4684. if stale.is_empty() {
  4685. return;
  4686. }
  4687. }
  4688. }
  4689. #[cfg(feature = "diagnostics")]
  4690. blame_stale(&stale);
  4691. self.settle(submitted, WHY_STALE);
  4692. crate::watch::ask_once(ranges);
  4693. }
  4694. /// [`Host::execute`], or with `late` the first half of
  4695. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4696. /// to be done once they have run comes back with the submission lock
  4697. /// still held.
  4698. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4699. #[cfg(feature = "diagnostics")]
  4700. let called = std::time::Instant::now();
  4701. #[cfg(feature = "diagnostics")]
  4702. crate::copystat::submission_begins();
  4703. // One submission at a time from preparation to copy-back: snapshots
  4704. // and the ranges shaders write are per host copy, not per submission.
  4705. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4706. let was_working = working(true);
  4707. submitting(1, runs.len());
  4708. #[cfg(feature = "diagnostics")]
  4709. let ahead = Split::begin();
  4710. #[cfg(feature = "diagnostics")]
  4711. SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed);
  4712. // Flights in the air ([`late`]): a submission that is waited for
  4713. // settles them first, one sent ahead only if preparing it reads
  4714. // what they write.
  4715. // Or the reads are done on the card, behind the flights.
  4716. let own = if late { self.card_steps(runs) } else { None };
  4717. #[cfg(feature = "diagnostics")]
  4718. ahead.part(12);
  4719. if !late {
  4720. self.settle(&mut submitted, WHY_SYNC);
  4721. } else if own.is_none()
  4722. && let Some(why) = late_blocked(runs)
  4723. {
  4724. if relay_exact() && why == WHY_READ {
  4725. // Only until the flights that may write what is read have
  4726. // landed: their copy-back's end, not the card's other work.
  4727. relay_wait(why, |line| {
  4728. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4729. });
  4730. } else {
  4731. self.settle(&mut submitted, why);
  4732. }
  4733. }
  4734. #[cfg(feature = "diagnostics")]
  4735. ahead.part(13);
  4736. // Descriptors the title copied into placed heaps directly, before
  4737. // command lists that index those slots are submitted.
  4738. let heaps_synced = crate::descriptor::begin_sync_heaps();
  4739. // That list runs first, and is one of the submission's from here on.
  4740. let with: Vec<&HostList>;
  4741. let runs = match &own {
  4742. Some(own) => {
  4743. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4744. &with[..]
  4745. }
  4746. None => runs,
  4747. };
  4748. let behind = late && flying();
  4749. // Before this submission counts as started: what the sweep lets go
  4750. // of is named by no list, and nothing runs now (behind flights the
  4751. // sweep waits for a submission that finds none in the air: there is
  4752. // one at every present).
  4753. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4754. if !behind {
  4755. if upcheck::on() {
  4756. upcheck::at_rest(self);
  4757. }
  4758. sweep();
  4759. SWEPT.store(now_ms(), Ordering::Relaxed);
  4760. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4761. // With the present sent ahead nothing else brings a moment
  4762. // with nothing in the air: one is made for the sweep.
  4763. self.settle(&mut submitted, WHY_SYNC);
  4764. if upcheck::on() {
  4765. upcheck::at_rest(self);
  4766. }
  4767. sweep();
  4768. SWEPT.store(now_ms(), Ordering::Relaxed);
  4769. }
  4770. let behind = late && flying();
  4771. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4772. // The ranges shaders write are counted for it (with the relay).
  4773. crate::shadow::preparing(this_submission);
  4774. let started = std::time::Instant::now();
  4775. #[cfg(feature = "diagnostics")]
  4776. ahead.part(14);
  4777. #[cfg(feature = "diagnostics")]
  4778. let lock = (started - called).as_micros() as u64;
  4779. #[cfg(feature = "diagnostics")]
  4780. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4781. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4782. // Where each run's lists start in `lists`.
  4783. let mut firsts = Vec::with_capacity(runs.len());
  4784. let mut batch = Batch::default();
  4785. #[cfg(feature = "diagnostics")]
  4786. let split = Split::begin();
  4787. // The time a settle of flights takes inside this preparing: the
  4788. // wait for the card and the copy-back have their own places on the
  4789. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4790. let mut settled = std::time::Duration::ZERO;
  4791. // One write-watch asking for everything the submission refreshes
  4792. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4793. if crate::watch::once() {
  4794. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  4795. for list in runs {
  4796. for step in &list.deferred().copies {
  4797. if let Step::Refresh(shadow, address, len) = step
  4798. && shadow.asked_ahead()
  4799. {
  4800. let span = spans
  4801. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4802. .or_insert((*address, *address + *len));
  4803. *span = (span.0.min(*address), span.1.max(*address + *len));
  4804. }
  4805. }
  4806. }
  4807. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4808. #[cfg(feature = "diagnostics")]
  4809. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  4810. crate::watch::ask_once(&ranges);
  4811. #[cfg(feature = "diagnostics")]
  4812. split.part(0);
  4813. // Behind flights: the title wrote memory that a flight's shaders
  4814. // may write too, and this submission refreshes it. The flights
  4815. // are settled, and the asking made again: the copy-back wrote
  4816. // title memory, which other copies of it must see.
  4817. if upcheck::on() {
  4818. upcheck::order(runs);
  4819. if behind {
  4820. upcheck::reads(runs);
  4821. }
  4822. }
  4823. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  4824. if !stale.is_empty() {
  4825. let settling = std::time::Instant::now();
  4826. self.settle_stale(&mut submitted, runs, stale, &ranges);
  4827. settled += settling.elapsed();
  4828. }
  4829. } else if behind && !stale_under_flights(runs).is_empty() {
  4830. let settling = std::time::Instant::now();
  4831. self.settle(&mut submitted, WHY_STALE);
  4832. settled += settling.elapsed();
  4833. }
  4834. #[cfg(feature = "diagnostics")]
  4835. split.part(1);
  4836. // What flights in the air may write.
  4837. let air = line().written.clone();
  4838. if ahead_of_writes() {
  4839. batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4840. }
  4841. for list in runs {
  4842. list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4843. firsts.push(lists.len());
  4844. if let Some(prelude) = list.prelude() {
  4845. lists.push(Some(prelude));
  4846. }
  4847. lists.push(list.list.cast().ok());
  4848. }
  4849. batch.fill();
  4850. batch.flush();
  4851. crate::watch::ask_once_end();
  4852. #[cfg(feature = "diagnostics")]
  4853. split.part(2);
  4854. // The snapshots of the ranges shaders may write, if they were left
  4855. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4856. // lists have not gone to the card.
  4857. {
  4858. #[cfg(feature = "diagnostics")]
  4859. let snapshots = std::time::Instant::now();
  4860. crate::shadow::take_snapshots();
  4861. #[cfg(feature = "diagnostics")]
  4862. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4863. }
  4864. #[cfg(feature = "diagnostics")]
  4865. split.part(3);
  4866. // Copies in the card's memory: what changed on their CPU side goes
  4867. // up ahead of the lists, and a compare of what the shaders may
  4868. // write follows them in the same submission.
  4869. let flown = late && relay();
  4870. if flown && self.card_results_low() {
  4871. let settling = std::time::Instant::now();
  4872. self.settle(&mut submitted, WHY_MOST);
  4873. settled += settling.elapsed();
  4874. }
  4875. // What shaders may write through views they pick: last, so that no
  4876. // refresh of this submission leaves it alone.
  4877. let picked = crate::picked::declare(runs);
  4878. for (shadow, at, len) in &picked.written {
  4879. shadow.writing(*at, *len);
  4880. }
  4881. let card = self.card_before(runs, &picked, flown);
  4882. // The sends are taken: from here on the references hold what the
  4883. // copies in the lists put.
  4884. for (shadow, at, bytes) in batch.placed.drain(..) {
  4885. shadow.placed_copy(at, &bytes);
  4886. }
  4887. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4888. lists.push(Some(check));
  4889. }
  4890. #[cfg(feature = "diagnostics")]
  4891. split.part(4);
  4892. drop(heaps_synced);
  4893. // The slots that waited for a texture's host copy, before the
  4894. // lists that may read them run.
  4895. crate::descriptor::make_waiting();
  4896. #[cfg(feature = "diagnostics")]
  4897. split.part(15);
  4898. let prepared = std::time::Instant::now();
  4899. if late {
  4900. *submitted += 1;
  4901. // SAFETY: closed lists; the fence is ours.
  4902. let signalled = unsafe {
  4903. self.queue.ExecuteCommandLists(&lists);
  4904. self.queue.Signal(&self.fence, *submitted)
  4905. };
  4906. self.card_sent();
  4907. if let Err(e) = signalled {
  4908. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4909. }
  4910. #[cfg(feature = "diagnostics")]
  4911. split.part(5);
  4912. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4913. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4914. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4915. submitting(0, 0);
  4916. #[cfg(feature = "diagnostics")]
  4917. crate::copystat::submission_ends(lock);
  4918. let sent = Sent {
  4919. number: this_submission,
  4920. card,
  4921. back,
  4922. own,
  4923. writes,
  4924. };
  4925. working(was_working);
  4926. return Some((submitted, sent));
  4927. }
  4928. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4929. #[cfg(feature = "diagnostics")]
  4930. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4931. firsts
  4932. .iter()
  4933. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4934. .map(|(&a, &b)| &lists[a..b])
  4935. .collect()
  4936. } else {
  4937. vec![&lists[..]]
  4938. };
  4939. #[cfg(not(feature = "diagnostics"))]
  4940. let groups = [&lists[..]];
  4941. submitting(2, runs.len());
  4942. for (i, group) in groups.iter().enumerate() {
  4943. *submitted += 1;
  4944. let started = std::time::Instant::now();
  4945. // SAFETY: closed lists; the fence and event are ours.
  4946. unsafe {
  4947. self.queue.ExecuteCommandLists(group);
  4948. self.card_sent();
  4949. let waited = self
  4950. .queue
  4951. .Signal(&self.fence, *submitted)
  4952. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4953. match waited {
  4954. Ok(()) => {
  4955. working(false);
  4956. WaitForSingleObject(self.event, INFINITE);
  4957. stood(started);
  4958. working(true);
  4959. }
  4960. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4961. }
  4962. }
  4963. // With timing on each group is one of `runs` (and the compare
  4964. // of copies in the card's memory, with the last): every
  4965. // command's time on the card goes to the sums by pipeline.
  4966. #[cfg(feature = "diagnostics")]
  4967. if timing() {
  4968. // SAFETY: a plain query.
  4969. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4970. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4971. crate::copystat::command_took(&op, ms);
  4972. }
  4973. }
  4974. // A submission of one list was never named here (`groups.len()
  4975. // > 1` was the test): the two 50 ms lists of the gameplay
  4976. // frame, each a submission of its own, printed nothing.
  4977. #[cfg(feature = "diagnostics")]
  4978. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4979. // SAFETY: a plain query.
  4980. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4981. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4982. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4983. for (ms, op) in runs[i].slowest(frequency, 6) {
  4984. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4985. }
  4986. }
  4987. let _ = (i, started);
  4988. }
  4989. let _ = &firsts;
  4990. FINISHED.store(this_submission, Ordering::Release);
  4991. bury(this_submission);
  4992. let gpu = prepared.elapsed();
  4993. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4994. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4995. #[cfg(feature = "diagnostics")]
  4996. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4997. let pipelines: std::collections::BTreeSet<String> = runs
  4998. .iter()
  4999. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  5000. .collect();
  5001. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  5002. text.chars().take(1200).collect()
  5003. });
  5004. // The host resets a device whose submission runs for about 2 s.
  5005. if gpu > std::time::Duration::from_millis(250) {
  5006. let pipelines: std::collections::BTreeSet<String> = runs
  5007. .iter()
  5008. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  5009. .collect();
  5010. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  5011. }
  5012. // SAFETY: a plain query.
  5013. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  5014. fail(format_args!(
  5015. "host GPU device removed after a submission of {} lists{}{}",
  5016. runs.len(),
  5017. self.removal_data(runs),
  5018. last_notes(runs)
  5019. ));
  5020. }
  5021. submitting(3, runs.len());
  5022. // What shaders wrote goes back before the bottom-of-pipe writes,
  5023. // which tell the title the GPU is done; each range once per
  5024. // submission, however many dispatches declared it (the world's
  5025. // passes declare the same big ranges dozens of times).
  5026. let copying = std::time::Instant::now();
  5027. // For copies in the card's memory the compare has run there: the
  5028. // pieces that differ are fetched and merged.
  5029. if let Some(card) = &card {
  5030. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  5031. }
  5032. let back = crate::picked::with(declared_writes(runs), &picked.written);
  5033. hand_back(&back);
  5034. if let Some(card) = card {
  5035. self.card_done(card);
  5036. }
  5037. #[cfg(feature = "diagnostics")]
  5038. if !back.is_empty() {
  5039. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  5040. }
  5041. // Nothing of this submission goes back to the title: no range of
  5042. // shader writes, no value written when it is done. The wait for
  5043. // such a one is only for order and for what the card still holds.
  5044. #[cfg(feature = "diagnostics")]
  5045. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  5046. use crate::copystat::{C, add};
  5047. add(C::NothingBack, 1);
  5048. add(C::NothingBackUs, gpu.as_micros() as u64);
  5049. }
  5050. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  5051. for list in runs {
  5052. // Read backs first: a value written at the bottom of the pipe
  5053. // may be what tells the title that they are there.
  5054. read_backs(list);
  5055. for &(at, what, bytes) in &list.deferred().writes {
  5056. what.write(at as *mut u8, bytes);
  5057. }
  5058. }
  5059. self.log_messages();
  5060. submitting(0, 0);
  5061. #[cfg(feature = "diagnostics")]
  5062. crate::copystat::submission_ends(lock);
  5063. // With the relay: nothing is in the air now, so no fetch still to
  5064. // be merged is older than the sends to card copies so far, and
  5065. // their notes can go.
  5066. if relay() {
  5067. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  5068. }
  5069. working(was_working);
  5070. None
  5071. }
  5072. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  5073. /// it lies in (by the names we give them) or the title memory copy just
  5074. /// below it; for each list that did not finish, the command it stopped
  5075. /// at and what the draws and dispatches in flight there run (or, in
  5076. /// lists that never started, the pipelines they bind).
  5077. fn removal_data(&self, runs: &[&HostList]) -> String {
  5078. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  5079. return String::new();
  5080. };
  5081. let mut text = String::new();
  5082. let mut fault_va = None;
  5083. // SAFETY: the outputs are the runtime's, valid while the device
  5084. // lives; nodes are walked as linked, histories have their counts.
  5085. unsafe {
  5086. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  5087. && fault.PageFaultVA != 0
  5088. {
  5089. let va = fault.PageFaultVA;
  5090. fault_va = Some(va);
  5091. text.push_str(&format!("; page fault at {va:#x}"));
  5092. for (what, head) in [
  5093. ("inside", fault.pHeadExistingAllocationNode),
  5094. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  5095. ] {
  5096. let mut names = Vec::new();
  5097. let mut node = head;
  5098. while let Some(n) = node.as_ref()
  5099. && names.len() < 8
  5100. {
  5101. let name = if n.ObjectNameW.is_null() {
  5102. "unnamed".to_owned()
  5103. } else {
  5104. n.ObjectNameW.to_string().unwrap_or_default()
  5105. };
  5106. names.push(format!("{name} (type {})", n.AllocationType.0));
  5107. node = n.pNext;
  5108. }
  5109. if !names.is_empty() {
  5110. text.push_str(&format!("; {what} {names:?}"));
  5111. }
  5112. }
  5113. text.push_str(&crate::shadow::near(va));
  5114. text.push_str(&crate::descriptor::host::near_heaps(va));
  5115. }
  5116. // The plain output: the extended one (with marker texts) came
  5117. // back without stopped lists on this host.
  5118. if dred_faults() {
  5119. return text;
  5120. }
  5121. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  5122. Ok(crumbs) => crumbs,
  5123. Err(e) => {
  5124. text.push_str(&format!("; no breadcrumbs ({e})"));
  5125. return text;
  5126. }
  5127. };
  5128. // Every list's progress (done/count), in the runtime's order.
  5129. let mut progress = Vec::new();
  5130. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  5131. while let Some(p) = node.as_ref() {
  5132. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5133. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  5134. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  5135. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  5136. node = p.pNext;
  5137. }
  5138. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  5139. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  5140. while let Some(p) = plain.as_ref() {
  5141. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5142. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  5143. let history =
  5144. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  5145. text.push_str(&format!(
  5146. "; a list stopped at command {done} of {} (op {})",
  5147. p.BreadcrumbCount, history[done as usize].0
  5148. ));
  5149. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  5150. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  5151. let named = [
  5152. (!p.pCommandListDebugNameW.is_null()).then(|| p.pCommandListDebugNameW.to_string().unwrap_or_default()),
  5153. (!p.pCommandListDebugNameA.is_null()).then(|| {
  5154. std::ffi::CStr::from_ptr(p.pCommandListDebugNameA.cast()).to_string_lossy().into_owned()
  5155. }),
  5156. ]
  5157. .into_iter()
  5158. .flatten()
  5159. .next()
  5160. .unwrap_or_default();
  5161. text.push_str(&format!(" of \"{named}\""));
  5162. // Not one of the caller's: by the name.
  5163. #[cfg(feature = "diagnostics")]
  5164. let by_name = list_number(&named).and_then(|n| {
  5165. let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  5166. all.get(&n).map(|(notes, pipelines, _)| (notes.upgrade(), pipelines.upgrade()))
  5167. });
  5168. #[cfg(feature = "diagnostics")]
  5169. let indirects = run.map(|r| r.indirects.clone()).or_else(|| {
  5170. let n = list_number(&named)?;
  5171. LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()).get(&n)?.2.upgrade()
  5172. });
  5173. #[cfg(not(feature = "diagnostics"))]
  5174. #[allow(clippy::type_complexity)]
  5175. let by_name: Option<(Option<()>, Option<std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>>)> = None;
  5176. #[cfg(feature = "diagnostics")]
  5177. let noted = run.map(|r| r.notes.clone()).or_else(|| by_name.as_ref().and_then(|b| b.0.clone()));
  5178. let bound = run.map(|r| r.pipelines.clone()).or_else(|| by_name.as_ref().and_then(|b| b.1.clone()));
  5179. // The k-th marker command is the k-th note.
  5180. #[cfg(feature = "diagnostics")]
  5181. let markers: Vec<(u32, String)> = noted.map_or_else(Vec::new, |notes| {
  5182. let notes = notes.lock().unwrap_or_else(|e| e.into_inner());
  5183. history
  5184. .iter()
  5185. .enumerate()
  5186. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  5187. .zip(notes.iter())
  5188. .map(|((at, _), (note, range))| {
  5189. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  5190. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  5191. })
  5192. .collect()
  5193. });
  5194. #[cfg(not(feature = "diagnostics"))]
  5195. let markers: Vec<(u32, String)> = Vec::new();
  5196. #[cfg(not(feature = "diagnostics"))]
  5197. let _ = fault_va;
  5198. if done > 0 {
  5199. text.push_str(&in_flight(history, &markers, done as usize));
  5200. }
  5201. #[cfg(feature = "diagnostics")]
  5202. if let Some(indirects) = indirects {
  5203. text.push_str(&indirects_around(history, done as usize, &indirects));
  5204. }
  5205. // (Without markers a list that stopped midway says what
  5206. // it may have been at only by what it binds.)
  5207. if (done == 0 || markers.is_empty())
  5208. && let Some(bound) = bound
  5209. {
  5210. let pipelines = bound.lock().unwrap_or_else(|e| e.into_inner());
  5211. text.push_str(&format!(", its pipelines {pipelines:?}"));
  5212. }
  5213. }
  5214. plain = p.pNext;
  5215. }
  5216. }
  5217. text
  5218. }
  5219. /// Moves the debug layer's messages into our log; returns the first
  5220. /// error among them.
  5221. pub(crate) fn log_messages(&self) -> Option<String> {
  5222. let Some(queue) = &self.messages else {
  5223. return None;
  5224. };
  5225. let mut first_error = None;
  5226. // SAFETY: each message is read into a buffer of the size the queue
  5227. // reports, then the queue is emptied.
  5228. unsafe {
  5229. for i in 0..queue.GetNumStoredMessages() {
  5230. let mut size = 0;
  5231. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  5232. continue;
  5233. }
  5234. let mut buffer = vec![0u64; size.div_ceil(8)];
  5235. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  5236. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  5237. let m = &*message;
  5238. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  5239. let text = String::from_utf8_lossy(text);
  5240. let text = text.trim_end_matches('\0');
  5241. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  5242. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  5243. first_error = Some(text.to_owned());
  5244. }
  5245. }
  5246. }
  5247. queue.ClearStoredMessages();
  5248. }
  5249. first_error
  5250. }
  5251. /// A host render target view of `resource`, valid until it is recorded.
  5252. pub(crate) fn rtv(
  5253. &self,
  5254. resource: Option<&ID3D12Resource>,
  5255. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  5256. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5257. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5258. // SAFETY: a slot of our heap and a live resource, or none with a
  5259. // description (a typed null view).
  5260. unsafe {
  5261. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  5262. handle.ptr += (slot * self.rtv_size) as usize;
  5263. self.device
  5264. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  5265. handle
  5266. }
  5267. }
  5268. /// A host depth view of `resource`, valid until it is recorded.
  5269. pub(crate) fn dsv(
  5270. &self,
  5271. resource: &ID3D12Resource,
  5272. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  5273. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5274. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5275. // SAFETY: a slot of our heap and a live resource.
  5276. unsafe {
  5277. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  5278. handle.ptr += (slot * self.dsv_size) as usize;
  5279. self.device
  5280. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  5281. handle
  5282. }
  5283. }
  5284. }
  5285. impl HostList {
  5286. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  5287. #[cfg(feature = "diagnostics")]
  5288. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  5289. if !timing() {
  5290. return None;
  5291. }
  5292. self.stamps
  5293. .get_or_init(|| {
  5294. let device = &host()?.device;
  5295. let mut heap: Option<ID3D12QueryHeap> = None;
  5296. let mut back: Option<ID3D12Resource> = None;
  5297. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  5298. let desc = D3D12_RESOURCE_DESC {
  5299. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5300. Width: u64::from(STAMPS) * 8,
  5301. Height: 1,
  5302. DepthOrArraySize: 1,
  5303. MipLevels: 1,
  5304. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  5305. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5306. ..Default::default()
  5307. };
  5308. // SAFETY: plain object creation.
  5309. unsafe {
  5310. device
  5311. .CreateQueryHeap(
  5312. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  5313. &mut heap,
  5314. )
  5315. .ok()?;
  5316. device
  5317. .CreateCommittedResource(
  5318. &readback,
  5319. D3D12_HEAP_FLAG_NONE,
  5320. &desc,
  5321. D3D12_RESOURCE_STATE_COPY_DEST,
  5322. None,
  5323. &mut back,
  5324. )
  5325. .ok()?;
  5326. }
  5327. Some((heap?, back?))
  5328. })
  5329. .as_ref()
  5330. }
  5331. /// The noted commands that took longest on the GPU, longest first, as
  5332. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  5333. #[cfg(feature = "diagnostics")]
  5334. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  5335. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  5336. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  5337. return Vec::new();
  5338. };
  5339. let mut data = std::ptr::null_mut();
  5340. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  5341. // SAFETY: a read-back buffer the finished list resolved into.
  5342. let stamps: Vec<u64> = unsafe {
  5343. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  5344. return Vec::new();
  5345. }
  5346. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  5347. back.Unmap(0, None);
  5348. s
  5349. };
  5350. let mut times: Vec<(f64, String)> = (0..count)
  5351. .map(|i| {
  5352. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5353. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5354. })
  5355. .collect();
  5356. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5357. times.truncate(n);
  5358. times
  5359. }
  5360. pub(crate) fn close(&self) {
  5361. self.twins_to_depth();
  5362. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5363. if let Some((scratch, _)) = scratch {
  5364. self.indirect_common(&scratch);
  5365. }
  5366. self.batches_common();
  5367. self.card_budget_out();
  5368. self.take_coming();
  5369. #[cfg(feature = "diagnostics")]
  5370. if let Some((heap, back)) = self.stamps() {
  5371. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5372. // SAFETY: an open list, our heap and read-back buffer.
  5373. unsafe {
  5374. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5375. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5376. }
  5377. }
  5378. // SAFETY: our list.
  5379. if let Err(e) = unsafe { self.list.Close() } {
  5380. fail(format_args!(
  5381. "a host command list did not close ({e}): a command recorded into it was invalid"
  5382. ));
  5383. }
  5384. }
  5385. /// `work` finds, on a thread of ours, refreshes that belong at this
  5386. /// place among the list's steps; they are there when the list is closed.
  5387. pub(crate) fn refreshes_coming(&self, work: impl FnOnce() -> Vec<aside::Refresh> + Send + 'static) {
  5388. self.take_coming();
  5389. let at = self.deferred().copies.len();
  5390. let coming = aside::begin(work);
  5391. *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = Some((at, coming));
  5392. }
  5393. /// The refreshes that were still to come are put among the steps.
  5394. fn take_coming(&self) {
  5395. let Some((at, coming)) = self.coming.lock().unwrap_or_else(|e| e.into_inner()).take() else {
  5396. return;
  5397. };
  5398. let found = coming.wait();
  5399. let mut deferred = self.deferred();
  5400. let at = at.min(deferred.copies.len());
  5401. deferred
  5402. .copies
  5403. .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize)));
  5404. }
  5405. /// Only after the list's last submission finished (every one is waited
  5406. /// for).
  5407. pub(crate) fn reset(&self) {
  5408. #[cfg(feature = "diagnostics")]
  5409. let started = std::time::Instant::now();
  5410. self._alive.used();
  5411. *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None;
  5412. *self.deferred() = Deferred::default();
  5413. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5414. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5415. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5416. #[cfg(feature = "diagnostics")]
  5417. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5418. #[cfg(feature = "diagnostics")]
  5419. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5420. {
  5421. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5422. (scratch.current, scratch.used) = (0, 0);
  5423. // Every submission of the list has run: nothing reads its
  5424. // scratch memory any more, and the next list to ask takes it.
  5425. if scratch_pool() {
  5426. give_chunks(std::mem::take(&mut scratch.chunks));
  5427. }
  5428. }
  5429. // SAFETY: the list is not executing.
  5430. let reset = unsafe {
  5431. self.allocator
  5432. .Reset()
  5433. .and_then(|()| self.list.Reset(&self.allocator, None))
  5434. };
  5435. if let Err(e) = reset {
  5436. fail(format_args!("a host command list did not reset ({e})"));
  5437. }
  5438. #[cfg(feature = "diagnostics")]
  5439. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5440. }
  5441. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5442. /// list: the host texture and the state it leaves, if that is a change.
  5443. /// The list's first use of a texture records nothing: its prelude brings
  5444. /// the texture there at submission.
  5445. pub(crate) fn transition(
  5446. &self,
  5447. resource: crate::object::This,
  5448. wanted: u32,
  5449. ) -> Option<(&'static ID3D12Resource, u32)> {
  5450. let copy = crate::resource::host_copy(resource)?;
  5451. // SAFETY: as in `crate::resource::host_resource`; the list's states
  5452. // hold the copy from here on.
  5453. let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(&copy.texture) };
  5454. let wanted = legal_state(texture, wanted);
  5455. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5456. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5457. std::collections::hash_map::Entry::Vacant(v) => {
  5458. v.insert((wanted, wanted, copy));
  5459. None
  5460. }
  5461. std::collections::hash_map::Entry::Occupied(mut o) => {
  5462. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5463. (before != wanted).then_some((texture, before))
  5464. }
  5465. }
  5466. }
  5467. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5468. /// as [`HostList::transition`] does a title resource's host copy, and
  5469. /// records the barrier: for textures that are not a title resource's
  5470. /// host copy (colour twins) and for the copies between the two.
  5471. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5472. let wanted = legal_state(&copy.texture, wanted);
  5473. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5474. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5475. std::collections::hash_map::Entry::Vacant(v) => {
  5476. v.insert((wanted, wanted, copy.clone()));
  5477. None
  5478. }
  5479. std::collections::hash_map::Entry::Occupied(mut o) => {
  5480. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5481. (before != wanted).then_some(before)
  5482. }
  5483. };
  5484. drop(states);
  5485. if let Some(before) = before {
  5486. let barrier = transition(
  5487. &copy.texture,
  5488. D3D12_RESOURCE_STATES(before as i32),
  5489. D3D12_RESOURCE_STATES(wanted as i32),
  5490. );
  5491. // SAFETY: an open list and a live texture.
  5492. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5493. }
  5494. }
  5495. /// A use of title texture `resource` about to be recorded, if it is a
  5496. /// depth texture with a colour twin (false if it is not): of the twin
  5497. /// (`colour`: unordered access) or of the depth texture (depth target,
  5498. /// clear, shader read, copy, resolve), writing it or only reading. The
  5499. /// side used is first brought up to date: by a copy recorded here if
  5500. /// this list wrote the other side since, by the list's prelude if the
  5501. /// list uses the side as it finds it. The twin is left in the
  5502. /// unordered access state; the caller moves the depth texture to the
  5503. /// state its use needs, as for any texture. A twin still ahead when the
  5504. /// list closes is copied then (`twins_to_depth`).
  5505. /// shortcut: every depth target bound for a draw counts as written
  5506. /// (also when the draw only tests), and every unordered access view a
  5507. /// shader names as written; views a shader picks from the heap by a
  5508. /// computed index are not seen here at all.
  5509. pub(crate) fn twin_use(
  5510. &self,
  5511. resource: crate::object::This,
  5512. colour: bool,
  5513. write: bool,
  5514. ) -> bool {
  5515. const UNORDERED_ACCESS: u32 = 0x8;
  5516. // Asked for every texture a draw reads: most have no twin.
  5517. let Some(twin) = crate::resource::twin(resource) else {
  5518. return false;
  5519. };
  5520. let Some(depth) = crate::resource::host_copy(resource) else {
  5521. return false;
  5522. };
  5523. let side = usize::from(colour);
  5524. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5525. let u = twins
  5526. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5527. .or_insert_with(|| TwinUse {
  5528. depth: depth.clone(),
  5529. twin: twin.clone(),
  5530. needs: [false; 2],
  5531. behind: [None; 2],
  5532. writing: false,
  5533. late: false,
  5534. });
  5535. let copy = match u.behind[side] {
  5536. Some(behind) => behind,
  5537. None => {
  5538. u.needs[side] = true;
  5539. false
  5540. }
  5541. };
  5542. u.behind[side] = Some(false);
  5543. match (write, colour) {
  5544. // Shaders write the twin when the draw or dispatch runs: what
  5545. // the same one reads of the depth texture is prepared before
  5546. // (`twins_written`).
  5547. (true, true) => u.writing = true,
  5548. (true, false) => u.behind[1] = Some(true),
  5549. (false, _) => {}
  5550. }
  5551. // shortcut: the depth plane's twin is not drawn into the plane
  5552. // here: the pass sets a pipeline and a target of ours, which a list
  5553. // still recording the title's commands cannot take. This use sees
  5554. // the plane as it was; the pass runs when the list closes
  5555. // (`twins_to_depth`). Counted.
  5556. if copy && !colour && twin.plane.is_some() {
  5557. u.late = true;
  5558. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5559. }
  5560. drop(twins);
  5561. if copy {
  5562. self.twin_copy(&depth, &twin, colour);
  5563. } else if colour {
  5564. self.settle(&twin.colour, UNORDERED_ACCESS);
  5565. }
  5566. // The depth plane's twin is written through unordered access too.
  5567. if colour && let Some(plane) = &twin.plane {
  5568. self.settle(plane, UNORDERED_ACCESS);
  5569. }
  5570. true
  5571. }
  5572. /// Records the pass that draws the twin of the depth plane of `depth`
  5573. /// into the plane, if `twin` has one, with the moves to the states the
  5574. /// pass needs; the twin is left in the unordered access state. Only
  5575. /// for a list that records nothing of the title's afterwards
  5576. /// (`record_plane_pass`).
  5577. fn pass_plane(
  5578. &self,
  5579. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5580. twin: &crate::resource::Twin,
  5581. ) {
  5582. const UNORDERED_ACCESS: u32 = 0x8;
  5583. const DEPTH_WRITE: u32 = 0x10;
  5584. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5585. let Some(plane) = &twin.plane else { return };
  5586. self.settle(depth, DEPTH_WRITE);
  5587. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5588. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5589. self.settle(plane, UNORDERED_ACCESS);
  5590. }
  5591. /// Records the copy of a depth texture into its colour twin (`colour`)
  5592. /// or of the twin into the depth texture, with the moves to the copy
  5593. /// states. The twin is left in the unordered access state.
  5594. fn twin_copy(
  5595. &self,
  5596. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5597. twin: &crate::resource::Twin,
  5598. colour: bool,
  5599. ) {
  5600. const UNORDERED_ACCESS: u32 = 0x8;
  5601. const COPY_DEST: u32 = 0x400;
  5602. const COPY_SOURCE: u32 = 0x800;
  5603. let (from, to) = if colour {
  5604. (depth, &twin.colour)
  5605. } else {
  5606. (&twin.colour, depth)
  5607. };
  5608. self.settle(from, COPY_SOURCE);
  5609. self.settle(to, COPY_DEST);
  5610. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5611. self.settle(&twin.colour, UNORDERED_ACCESS);
  5612. }
  5613. /// Before the list closes: the depth textures whose twins it wrote last
  5614. /// are given what was written, and left readable by shaders. Shaders
  5615. /// that pick a view from the heap by a computed index are not seen by
  5616. /// `twin_use` and read the depth texture in lists that never name it
  5617. /// (in a captured frame of the title no table names a shadow
  5618. /// map for reading but the pass that fills the next one).
  5619. fn twins_to_depth(&self) {
  5620. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5621. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5622. let written: Vec<_> = twins
  5623. .values_mut()
  5624. .filter(|u| u.behind[0] == Some(true) || u.late)
  5625. .map(|u| {
  5626. // Not copied again if the list copied since the last write
  5627. // and only the depth plane's pass is left.
  5628. let copy = u.behind[0] == Some(true);
  5629. u.behind[0] = Some(false);
  5630. u.late = false;
  5631. (u.depth.clone(), u.twin.clone(), copy)
  5632. })
  5633. .collect();
  5634. drop(twins);
  5635. for (depth, twin, copy) in &written {
  5636. if *copy {
  5637. self.twin_copy(depth, twin, false);
  5638. }
  5639. // Nothing of the title's is recorded after this: the pass may
  5640. // leave its own pipeline and target set.
  5641. self.pass_plane(depth, twin);
  5642. self.settle(depth, SHADER_RESOURCE);
  5643. }
  5644. }
  5645. /// The draw or dispatch just prepared is recorded: the twins it writes
  5646. /// now hold what their depth textures lack.
  5647. pub(crate) fn twins_written(&self) {
  5648. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5649. for u in twins.values_mut().filter(|u| u.writing) {
  5650. u.writing = false;
  5651. u.behind[0] = Some(true);
  5652. }
  5653. }
  5654. /// At submission: the list that moves each texture this list uses from
  5655. /// its real state to the one the list starts with; the textures' real
  5656. /// states become those the list ends with. For depth textures with a
  5657. /// colour twin it first copies the side the list uses as it finds it
  5658. /// from the other, if a list submitted earlier left it behind.
  5659. fn prelude(&self) -> Option<ID3D12CommandList> {
  5660. const COPY_DEST: u32 = 0x400;
  5661. const COPY_SOURCE: u32 = 0x800;
  5662. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5663. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5664. // The copies (depth texture, twin, whether into the twin); the
  5665. // sides are then as this list leaves them.
  5666. let mut syncs = Vec::new();
  5667. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5668. for u in twins.values() {
  5669. let real = u.twin.behind.load(Ordering::Relaxed);
  5670. let mut behind = [real & 1 != 0, real & 2 != 0];
  5671. for side in [0, 1] {
  5672. if u.needs[side] && behind[side] {
  5673. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5674. behind = [false; 2];
  5675. }
  5676. }
  5677. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5678. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5679. u.twin.behind.store(left, Ordering::Relaxed);
  5680. }
  5681. drop(twins);
  5682. // A copy runs with its textures in the copy states: each moves
  5683. // there from its real state, and from there to the state the list
  5684. // starts with (back to its real state if the list does not use it).
  5685. let mut to_copy = Vec::new();
  5686. let mut barriers = Vec::new();
  5687. let mut copying = std::collections::HashMap::new();
  5688. for (depth, twin, colour) in &syncs {
  5689. let (from, to) = if *colour {
  5690. (depth, &twin.colour)
  5691. } else {
  5692. (&twin.colour, depth)
  5693. };
  5694. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  5695. let key = std::sync::Arc::as_ptr(texture) as usize;
  5696. let real = texture.state.load(Ordering::Relaxed);
  5697. copying.insert(key, state);
  5698. if real != state {
  5699. to_copy.push(transition(
  5700. &texture.texture,
  5701. host_state(real),
  5702. host_state(state),
  5703. ));
  5704. if !states.contains_key(&key) {
  5705. barriers.push(transition(
  5706. &texture.texture,
  5707. host_state(state),
  5708. host_state(real),
  5709. ));
  5710. }
  5711. }
  5712. }
  5713. }
  5714. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5715. let real = copy.state.swap(*last, Ordering::Relaxed);
  5716. let real = copying.get(key).copied().unwrap_or(real);
  5717. (real != *first)
  5718. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5719. }));
  5720. if barriers.is_empty() && syncs.is_empty() {
  5721. return None;
  5722. }
  5723. let Some((allocator, list)) = self
  5724. .prelude
  5725. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5726. .as_ref()
  5727. else {
  5728. fail(format_args!("no host list for a state prelude"));
  5729. };
  5730. // SAFETY: the prelude is not executing (every submission is waited
  5731. // for); the textures are live.
  5732. let recorded = unsafe {
  5733. allocator.Reset().and_then(|()| {
  5734. list.Reset(allocator, None)?;
  5735. if !to_copy.is_empty() {
  5736. list.ResourceBarrier(&to_copy);
  5737. }
  5738. for (depth, twin, colour) in &syncs {
  5739. record_twin_copy(list, &depth.texture, twin, *colour);
  5740. }
  5741. if !barriers.is_empty() {
  5742. list.ResourceBarrier(&barriers);
  5743. }
  5744. list.Close()
  5745. })
  5746. };
  5747. if let Err(e) = recorded {
  5748. fail(format_args!("a host state prelude did not record ({e})"));
  5749. }
  5750. list.cast().ok()
  5751. }
  5752. /// Notes what the command about to be recorded does, as a marker
  5753. /// command whose text the list keeps (diagnostics, with device-removed
  5754. /// data on): the report pairs the breadcrumbs' marker commands with the
  5755. /// texts in order and names the commands a fault stopped among.
  5756. #[cfg(feature = "diagnostics")]
  5757. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5758. self.note(what, None);
  5759. }
  5760. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5761. /// `(address, bytes)`: the report places the faulting address in it.
  5762. #[cfg(feature = "diagnostics")]
  5763. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5764. self.note(what, Some(range));
  5765. }
  5766. #[cfg(feature = "diagnostics")]
  5767. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5768. if !dred_on() {
  5769. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5770. return;
  5771. }
  5772. {
  5773. let started = std::time::Instant::now();
  5774. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5775. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5776. // SAFETY: an open list and our query heap.
  5777. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5778. }
  5779. let what = what();
  5780. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5781. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5782. const UNICODE: u32 = 0;
  5783. // SAFETY: an open list; the marker is copied when recorded.
  5784. unsafe {
  5785. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5786. };
  5787. self.notes
  5788. .lock()
  5789. .unwrap_or_else(|e| e.into_inner())
  5790. .push((what, range));
  5791. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5792. }
  5793. }
  5794. /// Whether nothing recorded since the list was opened does any work:
  5795. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5796. /// upload or resolve (they defer a step or move a texture's state), no
  5797. /// bottom-of-pipe write. State set on the list does not count.
  5798. pub(crate) fn untouched(&self) -> bool {
  5799. {
  5800. let deferred = self.deferred();
  5801. if !(deferred.copies.is_empty()
  5802. && deferred.uploads.is_empty()
  5803. && deferred.kept.is_empty()
  5804. && deferred.textures.is_empty()
  5805. && deferred.writes.is_empty()
  5806. && deferred.backs.is_empty())
  5807. {
  5808. return false;
  5809. }
  5810. }
  5811. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5812. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5813. }
  5814. /// Notes an indirect execution, while device-removed data is kept
  5815. /// ([`indirects`]).
  5816. #[cfg(feature = "diagnostics")]
  5817. pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) {
  5818. if dred_on() || dred_light() {
  5819. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user);
  5820. }
  5821. }
  5822. /// Notes a pipeline the list binds.
  5823. pub(crate) fn used_pipeline(&self, name: &str) {
  5824. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5825. if !pipelines.contains(name) {
  5826. pipelines.insert(name.to_owned());
  5827. }
  5828. }
  5829. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5830. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5831. }
  5832. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5833. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5834. let mut deferred = self.deferred();
  5835. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5836. // A copy that goes on where the one recorded just before it ended,
  5837. // source and destination both: with `join_copies` the two are one
  5838. // step.
  5839. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5840. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5841. {
  5842. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5843. if join_copies() {
  5844. *n += len;
  5845. return;
  5846. }
  5847. }
  5848. deferred
  5849. .copies
  5850. .push(Step::Copy(dst as usize, src as usize, len));
  5851. deferred.refreshed.clear();
  5852. }
  5853. /// Copies `len` bytes of title memory at `src` into the list's upload
  5854. /// memory at `dst` when the list is submitted.
  5855. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5856. self.deferred()
  5857. .copies
  5858. .push(Step::Fill(dst as usize, src as usize, len, None));
  5859. }
  5860. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5861. /// title heap's address, and the slot) shows.
  5862. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5863. self.deferred()
  5864. .copies
  5865. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  5866. }
  5867. /// As [`HostList::defer_fill`], for the beginning of a buffer
  5868. /// [`HostList::upload`] made.
  5869. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  5870. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  5871. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  5872. }
  5873. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5874. /// when the list is submitted (once per range until a title copy
  5875. /// intervenes), keeping the copy alive until the list is reset.
  5876. pub(crate) fn defer_refresh(
  5877. &self,
  5878. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5879. address: usize,
  5880. len: usize,
  5881. ) {
  5882. let mut deferred = self.deferred();
  5883. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5884. if deferred.refreshed.insert(key) {
  5885. deferred
  5886. .copies
  5887. .push(Step::Refresh(shadow.clone(), address, len));
  5888. }
  5889. }
  5890. /// Shaders of the list write `[address, address + len)` of a buffer's
  5891. /// host copy: copied back into title memory once the list has run.
  5892. pub(crate) fn defer_gpu_write(
  5893. &self,
  5894. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5895. address: usize,
  5896. len: usize,
  5897. ) {
  5898. self.deferred()
  5899. .copies
  5900. .push(Step::GpuWrite(shadow.clone(), address, len));
  5901. }
  5902. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5903. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5904. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5905. /// the list is reset.
  5906. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5907. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5908. }
  5909. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5910. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5911. self.deferred().writes.push((dst as usize, what, bytes));
  5912. }
  5913. /// A mapped upload buffer of `size` bytes, alive until the list is
  5914. /// reset.
  5915. ///
  5916. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5917. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5918. // With [`card_steps`] the card may be the one that fills it.
  5919. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  5920. name(&buffer, || format!("list upload {size:#x}"));
  5921. self.deferred().hold_upload(buffer.clone(), size);
  5922. Some((buffer, data))
  5923. }
  5924. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5925. /// reset: the host GPU address and the CPU pointer.
  5926. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5927. let (buffer, at, data) = self.scratch_at(len)?;
  5928. // SAFETY: a live buffer.
  5929. Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data))
  5930. }
  5931. /// [`HostList::scratch`] and the buffer it lies in, for a descriptor
  5932. /// slot to hold: the slot outlives the list's use of it.
  5933. pub(crate) fn scratch_held(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  5934. let (buffer, at, data) = self.scratch_at(len)?;
  5935. // SAFETY: a live buffer.
  5936. let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at;
  5937. Some((buffer, gpu, data))
  5938. }
  5939. /// [`HostList::scratch`]: the buffer, the offset in it and the CPU
  5940. /// pointer.
  5941. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  5942. let host = host()?;
  5943. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5944. let len = len.max(1).next_multiple_of(256);
  5945. if len > SCRATCH_CHUNK {
  5946. let (buffer, data) = host.upload_buffer(len)?;
  5947. name(&buffer, || format!("list scratch {len:#x}"));
  5948. self.deferred().hold_upload(buffer.clone(), len);
  5949. return Some((buffer, 0, data));
  5950. }
  5951. // The chunk in use while `len` fits in what is left of it, else the
  5952. // next one (a list's first chunk may be a small one).
  5953. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5954. (s.current, s.used) = (s.current + 1, 0);
  5955. }
  5956. if s.current == s.chunks.len() {
  5957. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  5958. SCRATCH_FIRST
  5959. } else {
  5960. SCRATCH_CHUNK
  5961. };
  5962. let chunk = take_chunk(host, size)?;
  5963. s.chunks.push((chunk, size));
  5964. s.used = 0;
  5965. }
  5966. let (data, buffer) = (s.chunks[s.current].0.data, s.chunks[s.current].0.buffer.clone());
  5967. let at = s.used;
  5968. s.used += len;
  5969. Some((buffer, at, (data + at as usize) as *mut u8))
  5970. }
  5971. /// The bytes of scratch chunks the list holds now (after a reset:
  5972. /// none while lists share their chunks).
  5973. pub(crate) fn scratch_kept(&self) -> u64 {
  5974. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5975. scratch.chunks.iter().map(|c| c.1).sum()
  5976. }
  5977. /// The host address of the list's indirect-work budget, zeroed at each
  5978. /// submission of the list from the first use after a reset on.
  5979. pub(crate) fn budget(&self) -> Option<u64> {
  5980. let (buffer, data) = self
  5981. .budget
  5982. .get_or_init(|| {
  5983. let (b, d) = host()?.shared_buffer(256)?;
  5984. Some((b, d as usize))
  5985. })
  5986. .as_ref()?;
  5987. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5988. let mut deferred = self.deferred();
  5989. if !deferred.budget_zeroed {
  5990. deferred.budget_zeroed = true;
  5991. let at = *data;
  5992. // SAFETY: the list's own mapped words, written before it runs.
  5993. // The words after the budget hold what the clamp noted about the
  5994. // list's last run (mesh dispatches: the largest group count
  5995. // asked for, the groups asked in all; with the card's copy, as
  5996. // the list's end copied them here): taken, then zeroed.
  5997. let notes = Box::new(move || unsafe {
  5998. let words = at as *mut u32;
  5999. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  6000. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  6001. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  6002. for k in 0..3 {
  6003. words.add(k).write_volatile(0);
  6004. }
  6005. });
  6006. deferred.copies.push(Step::Host(notes, (0, 0)));
  6007. drop(deferred);
  6008. if let Some(card) = card {
  6009. self.zero_card_budget(card);
  6010. }
  6011. }
  6012. // SAFETY: a live buffer.
  6013. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  6014. }
  6015. /// The budget's words in the card's own memory ([`card_budget`]), if
  6016. /// the list can zero them itself (`WriteBufferImmediate`).
  6017. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  6018. if !card_budget() {
  6019. return None;
  6020. }
  6021. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  6022. let buffer = host()?.uav_buffer(256)?;
  6023. name(&buffer, || "indirect budget".to_owned());
  6024. Some(buffer)
  6025. }
  6026. /// Records, before the list's first clamp, the zeroing of the card's
  6027. /// copy of the budget: common, written as a copy, then left for
  6028. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  6029. fn zero_card_budget(&self, card: &ID3D12Resource) {
  6030. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  6031. return;
  6032. };
  6033. // SAFETY: a live buffer.
  6034. let at = unsafe { card.GetGPUVirtualAddress() };
  6035. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  6036. Dest: at + offset,
  6037. Value: 0,
  6038. });
  6039. // SAFETY: an open list; the buffer is the list's own and in the
  6040. // common state at the start of every recording.
  6041. unsafe {
  6042. self.list.ResourceBarrier(&[transition(
  6043. card,
  6044. D3D12_RESOURCE_STATE_COMMON,
  6045. D3D12_RESOURCE_STATE_COPY_DEST,
  6046. )]);
  6047. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  6048. self.list.ResourceBarrier(&[transition(
  6049. card,
  6050. D3D12_RESOURCE_STATE_COPY_DEST,
  6051. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  6052. )]);
  6053. }
  6054. }
  6055. /// Before the list closes, if this recording charged the card's copy
  6056. /// of the budget: its notes on mesh records go to the mapped words
  6057. /// (read at the next submission), and it goes back to common.
  6058. fn card_budget_out(&self) {
  6059. if !self.deferred().budget_zeroed {
  6060. return;
  6061. }
  6062. let (Some(Some(card)), Some(Some((mapped, _)))) =
  6063. (self.card_budget.get(), self.budget.get())
  6064. else {
  6065. return;
  6066. };
  6067. // SAFETY: an open list; both buffers are the list's own. The
  6068. // mapped one is promoted from common to the copy destination.
  6069. unsafe {
  6070. self.list.ResourceBarrier(&[transition(
  6071. card,
  6072. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  6073. D3D12_RESOURCE_STATE_COPY_SOURCE,
  6074. )]);
  6075. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  6076. self.list.ResourceBarrier(&[transition(
  6077. card,
  6078. D3D12_RESOURCE_STATE_COPY_SOURCE,
  6079. D3D12_RESOURCE_STATE_COMMON,
  6080. )]);
  6081. }
  6082. }
  6083. /// A device-local unordered-access buffer of at least `size` bytes for
  6084. /// clamped indirect arguments, reused across executions and resets of the
  6085. /// list. Smaller buffers replaced mid-list stay alive until
  6086. /// [`HostList::reset`].
  6087. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  6088. let needed = size.max(64 << 10);
  6089. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  6090. if let Some((buffer, cap)) = &*slot
  6091. && *cap >= needed
  6092. {
  6093. return Some(buffer.clone());
  6094. }
  6095. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  6096. let alloc = prev
  6097. .saturating_mul(2)
  6098. .max(needed)
  6099. .next_multiple_of(64 << 10);
  6100. let buffer = host()?.uav_buffer(alloc)?;
  6101. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  6102. let old = slot.replace((buffer.clone(), alloc));
  6103. drop(slot);
  6104. if let Some((old_buf, _)) = old {
  6105. // It ends the list common, as every scratch buffer does.
  6106. self.indirect_common(&old_buf);
  6107. self.keep(&old_buf);
  6108. }
  6109. Some(buffer)
  6110. }
  6111. /// Where the next batch of clamped records goes: a device-local buffer
  6112. /// the list keeps from recording to recording, the batch's place in it
  6113. /// and the state the buffer is in. Every batch of a recording has a place
  6114. /// of its own: the executions before it may still read theirs.
  6115. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  6116. use crate::indirect::batch::{JOBS, SLOT};
  6117. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6118. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  6119. if buffer == args.0.len() {
  6120. let size = u64::from(BATCHES * JOBS * SLOT);
  6121. let made = host()?.uav_buffer(size)?;
  6122. name(&made, || format!("indirect batches {size:#x}"));
  6123. args.0.push(made);
  6124. }
  6125. args.1 += 1;
  6126. // (Its first batch finds it as the recording before left it:
  6127. // `batches_common`.)
  6128. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  6129. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  6130. }
  6131. /// Before the list closes: the scratch buffers of the batched clamps go
  6132. /// back to the common state, where the next recording expects them.
  6133. fn batches_common(&self) {
  6134. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6135. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  6136. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  6137. .iter()
  6138. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  6139. .collect();
  6140. if !barriers.is_empty() {
  6141. // SAFETY: an open list and live buffers this recording left in
  6142. // `INDIRECT_ARGUMENT`.
  6143. unsafe { self.list.ResourceBarrier(&barriers) };
  6144. }
  6145. }
  6146. /// Moves `scratch` back to the common state if a clamp left it readable
  6147. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  6148. /// list's first clamp expects it. Done before the list closes and before
  6149. /// a bigger scratch buffer replaces it: one barrier per list (where
  6150. /// there was one per indirect execution), and the list ends as it
  6151. /// begins however it is submitted.
  6152. fn indirect_common(&self, scratch: &ID3D12Resource) {
  6153. {
  6154. let mut deferred = self.deferred();
  6155. if deferred.indirect_readable != scratch.as_raw() as usize {
  6156. return;
  6157. }
  6158. deferred.indirect_readable = 0;
  6159. }
  6160. let barrier = transition(
  6161. scratch,
  6162. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  6163. D3D12_RESOURCE_STATE_COMMON,
  6164. );
  6165. // SAFETY: an open list and a live buffer this recording left in
  6166. // `INDIRECT_ARGUMENT`.
  6167. unsafe { self.list.ResourceBarrier(&[barrier]) };
  6168. }
  6169. /// The state the list's indirect scratch buffer `scratch` is in at this
  6170. /// point of the recording: indirect arguments if a clamp in this
  6171. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  6172. /// common: the state a buffer is made in, and the one a recording
  6173. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  6174. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  6175. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  6176. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  6177. } else {
  6178. D3D12_RESOURCE_STATE_COMMON
  6179. }
  6180. }
  6181. /// A clamp recorded in this list left `scratch` readable as indirect
  6182. /// arguments. It stays so for every execution that reads it, until the
  6183. /// next clamp moves it back to unordered access.
  6184. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  6185. self.deferred().indirect_readable = scratch.as_raw() as usize;
  6186. }
  6187. /// Keeps `object` alive until the list is reset.
  6188. pub(crate) fn keep(&self, object: &impl Interface) {
  6189. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  6190. self.deferred().kept.push(object);
  6191. }
  6192. }
  6193. /// Whether this is the first time since the reset that the list asks
  6194. /// about `key` (a texture to bring up to date).
  6195. pub(crate) fn first_use(&self, key: usize) -> bool {
  6196. self.deferred().textures.insert(key)
  6197. }
  6198. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  6199. /// reset.
  6200. pub(crate) fn used(&self, key: usize) -> bool {
  6201. self.deferred().textures.contains(&key)
  6202. }
  6203. /// Runs `work` when the list is submitted, in order with its copies.
  6204. /// `work` may write title memory (refreshes after it copy again).
  6205. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  6206. self.deferred().copies.push(Step::Run(Box::new(work)));
  6207. self.deferred().refreshed.clear();
  6208. }
  6209. /// As [`HostList::defer`], for work that writes only host memory.
  6210. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  6211. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  6212. }
  6213. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  6214. /// memory at `from`.
  6215. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  6216. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  6217. }
  6218. /// Brings a texture's staging buffer up to date when the list is
  6219. /// submitted, keeping it alive until the list is reset.
  6220. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  6221. self.deferred().copies.push(Step::Texture(staging));
  6222. }
  6223. /// Runs the list's submission-time steps; refreshes go into `batch`
  6224. /// (the title's big buffers, a 174 MB one among them, are read by most
  6225. /// lists of a submission, through many ranges). Copies and fills that
  6226. /// `taken` names (by their place) are left out: they are done on the
  6227. /// card ([`card_steps`]).
  6228. fn run_deferred(&self, batch: &mut Batch, air: &[(usize, usize)], taken: impl Fn(usize) -> bool) {
  6229. #[cfg(feature = "diagnostics")]
  6230. use crate::copystat::{C, add};
  6231. // The time and the bytes of the copies and fills, some 13,000 a
  6232. // frame between 20,000 refreshes: summed here and added once.
  6233. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  6234. #[cfg(feature = "diagnostics")]
  6235. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  6236. for (i, step) in self.deferred().copies.iter().enumerate() {
  6237. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  6238. continue;
  6239. }
  6240. let (started, copied) = match step {
  6241. &Step::Copy(dst, src, len) => {
  6242. let started = std::time::Instant::now();
  6243. #[cfg(feature = "diagnostics")]
  6244. {
  6245. copies += 1;
  6246. }
  6247. batch.fill();
  6248. batch.title_written();
  6249. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  6250. // With the submission's one asking: the journal learns it.
  6251. crate::watch::wrote(dst, len);
  6252. // What the card holds there may be another value although
  6253. // ours did not change.
  6254. if send::own() {
  6255. crate::shadow::send_copied(dst, len);
  6256. }
  6257. (started, len)
  6258. }
  6259. &Step::Fill(dst, src, len, _) => {
  6260. #[cfg(feature = "diagnostics")]
  6261. {
  6262. copies += 1;
  6263. }
  6264. if wide_fills() {
  6265. batch.fills.push((dst, src, len));
  6266. bytes += len as u64;
  6267. continue;
  6268. }
  6269. let started = std::time::Instant::now();
  6270. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6271. (started, len)
  6272. }
  6273. Step::Placed(p) => {
  6274. let started = std::time::Instant::now();
  6275. let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len);
  6276. batch.fill();
  6277. if free {
  6278. batch.title_written();
  6279. }
  6280. if let Some(bytes) = p.prepare(free) {
  6281. batch.placed.push((p.shadow.clone(), p.dst, bytes));
  6282. }
  6283. (started, p.len)
  6284. }
  6285. Step::Refresh(shadow, address, len) => {
  6286. #[cfg(feature = "diagnostics")]
  6287. {
  6288. refreshes += 1;
  6289. refreshed += *len as u64;
  6290. }
  6291. batch.add(shadow, *address, *len);
  6292. continue;
  6293. }
  6294. Step::Run(work) | Step::Host(work, _) => {
  6295. batch.fill();
  6296. #[cfg(feature = "diagnostics")]
  6297. let started = std::time::Instant::now();
  6298. if matches!(step, Step::Run(_)) {
  6299. batch.title_written();
  6300. }
  6301. work();
  6302. // It wrote title memory, where is not known here: the
  6303. // submission's one asking ends, later refreshes ask anew.
  6304. if matches!(step, Step::Run(_)) {
  6305. crate::watch::ask_once_end();
  6306. }
  6307. #[cfg(feature = "diagnostics")]
  6308. {
  6309. add(C::Runs, 1);
  6310. add(C::RunUs, started.elapsed().as_micros() as u64);
  6311. }
  6312. continue;
  6313. }
  6314. Step::GpuWrite(shadow, address, len) => {
  6315. // The shaders start from the title's data: this copy's
  6316. // pending refresh first. The other copies' wait for
  6317. // the next flush of all (flushing all of them at every
  6318. // range a dispatch writes made thousands of write-watch
  6319. // askings a frame).
  6320. batch.flush_one(shadow);
  6321. #[cfg(feature = "diagnostics")]
  6322. let snapshot = std::time::Instant::now();
  6323. shadow.writing(*address, *len);
  6324. #[cfg(feature = "diagnostics")]
  6325. {
  6326. add(C::GpuWrites, 1);
  6327. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  6328. }
  6329. continue;
  6330. }
  6331. Step::Texture(staging) => {
  6332. if batch.texture_due(staging) {
  6333. batch.due.push(staging.clone());
  6334. if !wide_textures() {
  6335. batch.refresh_textures();
  6336. }
  6337. }
  6338. continue;
  6339. }
  6340. };
  6341. us += started.elapsed();
  6342. bytes += copied as u64;
  6343. }
  6344. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  6345. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  6346. #[cfg(feature = "diagnostics")]
  6347. {
  6348. add(C::Copies, copies);
  6349. add(C::CopyBytes, bytes);
  6350. add(C::Refreshes, refreshes);
  6351. add(C::RefreshBytes, refreshed);
  6352. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  6353. }
  6354. }
  6355. }
  6356. /// A table by a copy's address.
  6357. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  6358. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  6359. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  6360. /// but our own.
  6361. #[derive(Default)]
  6362. pub(crate) struct AddressHash(u64);
  6363. impl std::hash::Hasher for AddressHash {
  6364. fn finish(&self) -> u64 {
  6365. self.0
  6366. }
  6367. fn write(&mut self, bytes: &[u8]) {
  6368. for &b in bytes {
  6369. self.write_usize(usize::from(b));
  6370. }
  6371. }
  6372. fn write_usize(&mut self, n: usize) {
  6373. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  6374. self.0 = h ^ (h >> 32);
  6375. }
  6376. }
  6377. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  6378. /// preparing: the write-watch asking for a submission; the title's bytes put
  6379. /// in under flights' writes; the lists' steps, the refreshes among them; the
  6380. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  6381. /// of the steps: the refreshes, and the copies and fills (those with the
  6382. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  6383. /// is of. Of the refreshes, those before ranges are given to shaders, one
  6384. /// copy at a time: nanoseconds, and how many. Ahead of all that: the wait for
  6385. /// the submission lock, the steps done on the card planned ([`card_steps`]),
  6386. /// the flights waited for, the heaps' records and what is swept; and, at the
  6387. /// end, the wait for the heaps' records.
  6388. #[cfg(feature = "diagnostics")]
  6389. static SPLIT: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16];
  6390. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  6391. /// those known to copy nothing, and those done on several threads.
  6392. #[cfg(feature = "diagnostics")]
  6393. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  6394. /// Counts into [`SPLIT`].
  6395. #[cfg(feature = "diagnostics")]
  6396. struct Split(std::cell::Cell<std::time::Instant>);
  6397. #[cfg(feature = "diagnostics")]
  6398. impl Split {
  6399. fn begin() -> Split {
  6400. Split(std::cell::Cell::new(std::time::Instant::now()))
  6401. }
  6402. /// Nanoseconds since the last part.
  6403. fn so_far(&self) -> u64 {
  6404. self.0.get().elapsed().as_nanos() as u64
  6405. }
  6406. /// What came since the last part was part `i`.
  6407. fn part(&self, i: usize) {
  6408. let now = std::time::Instant::now();
  6409. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  6410. }
  6411. }
  6412. /// The split of the preparing, per frame, for the frame-rate line.
  6413. #[cfg(feature = "diagnostics")]
  6414. fn split_line(frames: f64) {
  6415. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6416. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  6417. let e: Vec<f64> = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect();
  6418. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  6419. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6420. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
  6421. tracing::info!(
  6422. "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \
  6423. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  6424. several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \
  6425. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the submission lock, {:.1} \
  6426. planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is swept; at the end {:.1} waiting \
  6427. for the heaps' records; asked early by a thread of its own {:.0} pieces of 2 MiB, {:.1} ms (VICTORY_ASK_EARLY)",
  6428. ms[0],
  6429. ms[8],
  6430. ms[1],
  6431. ms[2],
  6432. ms[6],
  6433. f[0],
  6434. f[1],
  6435. f[2],
  6436. f[3],
  6437. ms[9],
  6438. ms[10] * 1e6,
  6439. ms[7],
  6440. ms[3],
  6441. ms[4],
  6442. ms[5],
  6443. if crate::watch::light() { "on" } else { "off" },
  6444. ms[11],
  6445. ms[12],
  6446. ms[13],
  6447. ms[14],
  6448. ms[15],
  6449. e[0],
  6450. e[1] / 1e3,
  6451. );
  6452. tracing::info!(
  6453. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6454. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6455. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6456. waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
  6457. as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
  6458. a[0],
  6459. a[1] / 1024.0,
  6460. a[11] / 1e6,
  6461. a[12],
  6462. a[10],
  6463. a[9],
  6464. a[2],
  6465. a[3],
  6466. a[4],
  6467. a[5],
  6468. a[6],
  6469. a[7] / 1e6,
  6470. a[8] / 1e6,
  6471. s[0] / 1048576.0,
  6472. s[1] / 1048576.0,
  6473. s[2] / 1048576.0,
  6474. s[3],
  6475. );
  6476. tracing::info!(
  6477. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures; the \
  6478. first two beside the recording (VICTORY_HEAP_PASS_ASIDE), {:.1} ms waited for at the lists' close",
  6479. h[0],
  6480. h[1],
  6481. h[2],
  6482. aside::WAITED.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames,
  6483. );
  6484. }
  6485. /// Whether a submission's refreshes of host copies run on several threads,
  6486. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6487. ///
  6488. /// A submission brings some sixty copies up to date, one after the other
  6489. /// on the submitting thread: for each, the pages the title wrote are asked
  6490. /// for and read through the kernel into the copy. That is the frame line's
  6491. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6492. /// another: each refresh writes its own copy and its own notes, and reads
  6493. /// title memory. With the switch the copies of a flush (four or more) are
  6494. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6495. /// The write-watch journal and the guards are behind their own locks, as
  6496. /// they are for the title's threads.
  6497. fn wide_refresh() -> bool {
  6498. static ON: OnceLock<bool> = OnceLock::new();
  6499. *ON.get_or_init(|| {
  6500. wide_refresh_enabled(
  6501. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6502. std::thread::available_parallelism().ok().map(|n| n.get()),
  6503. )
  6504. })
  6505. }
  6506. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6507. match setting {
  6508. Some("1") => true,
  6509. Some("0") => false,
  6510. _ => logical_cpus.is_some_and(|n| n >= 4),
  6511. }
  6512. }
  6513. #[cfg(test)]
  6514. mod wide_refresh_tests {
  6515. use super::wide_refresh_enabled;
  6516. #[test]
  6517. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6518. assert!(wide_refresh_enabled(None, Some(4)));
  6519. assert!(wide_refresh_enabled(None, Some(16)));
  6520. assert!(!wide_refresh_enabled(None, Some(2)));
  6521. assert!(!wide_refresh_enabled(None, None));
  6522. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6523. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6524. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6525. }
  6526. }
  6527. /// A submission's refreshes not done yet, merged per buffer copy into the
  6528. /// range that covers them: done before a step that writes title memory or
  6529. /// gives a range to shaders, and before the lists run.
  6530. ///
  6531. /// Also the textures brought up to date in the submission so far: most
  6532. /// lists of a world submission sample the same textures, and a texture in
  6533. /// physical-page memory is hashed whole each time it is checked. Checked
  6534. /// once, it is checked again only after a step that writes title memory.
  6535. #[derive(Default)]
  6536. struct Batch {
  6537. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6538. /// Where each copy (by address) is in `refreshes`: the list that makes
  6539. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6540. /// for every refresh of a submission was tens of millions of
  6541. /// comparisons a frame.
  6542. index: ByCopy<usize>,
  6543. /// Staging buffers (by address) refreshed since the last title write,
  6544. /// or due to be.
  6545. textures: std::collections::HashSet<usize>,
  6546. /// Those due ([`Batch::refresh_textures`]).
  6547. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6548. /// What copies at their place in the submission's lists put into title
  6549. /// memory ([`place`]): the host copy, the title address, the bytes.
  6550. placed: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, Vec<u8>)>,
  6551. /// Fills not done yet (destination, source, bytes): [`wide_fills`].
  6552. fills: Vec<(usize, usize, usize)>,
  6553. /// Copies (by address) brought up to date ahead of the steps, and the
  6554. /// range (from, to) ([`Batch::refresh_ahead`]).
  6555. ahead: ByCopy<(usize, usize)>,
  6556. }
  6557. /// Whether the copies that a submission's shaders write are brought up to
  6558. /// date together, on several threads, ahead of its steps
  6559. /// (`VICTORY_REFRESH_AHEAD=0`: each before the step that gives it to them).
  6560. ///
  6561. /// 580 copies a frame, one after the other on the submitting thread, 3.4 to
  6562. /// 6.5 ms (session play-1125-0203).
  6563. fn ahead_of_writes() -> bool {
  6564. static ON: OnceLock<bool> = OnceLock::new();
  6565. *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_AHEAD").is_none_or(|v| v != "0") && wide_refresh() && crate::watch::light())
  6566. }
  6567. /// What a step is to the copies' refreshes, for [`written_spans`].
  6568. enum Touch {
  6569. /// A refresh of a copy (by address), from, to.
  6570. Refresh(usize, usize, usize),
  6571. /// The copy is given to shaders.
  6572. Write(usize),
  6573. /// Title memory is written.
  6574. Title,
  6575. Nothing,
  6576. }
  6577. /// Of `steps`, up to the first that writes title memory: the copies given to
  6578. /// shaders, each with the range its refreshes before that cover.
  6579. fn written_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> {
  6580. // (From, to, given to shaders.)
  6581. let mut spans: ByCopy<(usize, usize, bool)> = ByCopy::default();
  6582. for step in steps {
  6583. match step {
  6584. Touch::Refresh(copy, from, to) => {
  6585. let span = spans.entry(copy).or_insert((from, to, false));
  6586. if !span.2 {
  6587. (span.0, span.1) = (span.0.min(from), span.1.max(to));
  6588. }
  6589. }
  6590. // (Not refreshed before: nothing of it is due.)
  6591. Touch::Write(copy) => {
  6592. if let Some(span) = spans.get_mut(&copy) {
  6593. span.2 = true;
  6594. }
  6595. }
  6596. Touch::Title => break,
  6597. Touch::Nothing => {}
  6598. }
  6599. }
  6600. spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect()
  6601. }
  6602. #[cfg(test)]
  6603. mod written_spans_tests {
  6604. use super::{Touch, written_spans};
  6605. #[test]
  6606. fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() {
  6607. use Touch::{Nothing, Refresh, Title, Write};
  6608. let mut found = written_spans(
  6609. [
  6610. Refresh(1, 10, 20),
  6611. Refresh(2, 0, 5),
  6612. Nothing,
  6613. Refresh(1, 30, 40),
  6614. Write(1),
  6615. Refresh(1, 0, 100),
  6616. Write(3),
  6617. Refresh(3, 1, 2),
  6618. Refresh(4, 7, 9),
  6619. Write(4),
  6620. Title,
  6621. Write(2),
  6622. ]
  6623. .into_iter(),
  6624. );
  6625. found.sort_unstable();
  6626. assert_eq!(found, [(1, 10, 40), (4, 7, 9)]);
  6627. }
  6628. }
  6629. /// Whether the fills of a submission's upload memory are done together on
  6630. /// several threads (`VICTORY_WIDE_FILLS=0`: one after the other, where the
  6631. /// lists name them).
  6632. ///
  6633. /// They are 7,000 to 12,000 a frame, some 500 bytes each, 5 ms of the
  6634. /// submitting thread. Each reads title memory and writes memory of its own
  6635. /// that the card alone reads, when the lists run; they are done before the
  6636. /// next step that writes title memory or runs code of ours, and before the
  6637. /// submission goes on from its steps.
  6638. fn wide_fills() -> bool {
  6639. static ON: OnceLock<bool> = OnceLock::new();
  6640. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_FILLS").is_none_or(|v| v != "0") && wide_refresh())
  6641. }
  6642. /// Whether a submission's textures are brought up to date on several
  6643. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6644. /// name them, as before).
  6645. ///
  6646. /// They are read, hashed and, if they changed, detiled into their staging
  6647. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6648. /// its own buffer, notes and lock, and is refreshed by the title's own
  6649. /// threads as it is. They are done before the next step that writes title
  6650. /// memory, as the copies' refreshes are, and before the lists go to the
  6651. /// card. What is new: the note of a list that its upload takes what the
  6652. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6653. /// an earlier list of the submission asked for, not behind it. The texture
  6654. /// is then uploaded by a later list too, once more than needed.
  6655. fn wide_textures() -> bool {
  6656. static ON: OnceLock<bool> = OnceLock::new();
  6657. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6658. }
  6659. impl Batch {
  6660. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6661. let end = address + len;
  6662. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6663. if self.ahead.get(&key).is_some_and(|&(from, to)| from <= address && end <= to) {
  6664. return;
  6665. }
  6666. match self.index.get(&key) {
  6667. Some(&at) => {
  6668. let r = &mut self.refreshes[at];
  6669. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6670. }
  6671. None => {
  6672. self.index.insert(key, self.refreshes.len());
  6673. self.refreshes.push((shadow.clone(), address, end));
  6674. }
  6675. }
  6676. }
  6677. /// Before shaders are given a range of `shadow`'s copy: its pending
  6678. /// refresh is done, the others stay pending.
  6679. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  6680. // From here on it is refreshed around what the shaders write.
  6681. self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize));
  6682. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  6683. return;
  6684. };
  6685. let (shadow, from, to) = self.refreshes.swap_remove(at);
  6686. // The last entry took its place.
  6687. if let Some(moved) = self.refreshes.get(at) {
  6688. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  6689. }
  6690. #[cfg(feature = "diagnostics")]
  6691. let started = std::time::Instant::now();
  6692. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  6693. Self::update(&shadow, from, to);
  6694. }
  6695. #[cfg(feature = "diagnostics")]
  6696. {
  6697. let ns = started.elapsed().as_nanos() as u64;
  6698. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6699. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6700. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  6701. }
  6702. }
  6703. /// Brings `[from, to)` of a copy up to date, timed.
  6704. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  6705. let started = std::time::Instant::now();
  6706. let copied = shadow.update(from, to - from);
  6707. let us = started.elapsed().as_micros() as u64;
  6708. #[cfg(feature = "diagnostics")]
  6709. crate::copystat::range(from, to - from, us, 0);
  6710. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  6711. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  6712. }
  6713. /// Whether `staging` is still to be refreshed in this submission (and
  6714. /// notes it refreshed).
  6715. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  6716. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  6717. }
  6718. /// Before a step that writes title memory: pending refreshes are done
  6719. /// first, and textures are checked again after it.
  6720. fn title_written(&mut self) {
  6721. self.flush();
  6722. self.ahead.clear();
  6723. self.textures.clear();
  6724. }
  6725. /// Before the steps of `runs` ([`ahead_of_writes`]); copies and fills
  6726. /// that `taken` names are not done on the CPU.
  6727. fn refresh_ahead(&mut self, runs: &[&HostList], taken: impl Fn(&HostList, usize) -> bool) {
  6728. let mut copies: ByCopy<std::sync::Arc<crate::shadow::Shadow>> = ByCopy::default();
  6729. let mut touches = Vec::new();
  6730. 'steps: for list in runs {
  6731. for (i, step) in list.deferred().copies.iter().enumerate() {
  6732. touches.push(match step {
  6733. Step::Refresh(shadow, at, len) => {
  6734. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6735. copies.entry(key).or_insert_with(|| shadow.clone());
  6736. Touch::Refresh(key, *at, *at + *len)
  6737. }
  6738. Step::GpuWrite(shadow, ..) => Touch::Write(std::sync::Arc::as_ptr(shadow) as usize),
  6739. Step::Copy(..) if taken(list, i) => Touch::Nothing,
  6740. Step::Copy(..) | Step::Run(_) | Step::Placed(_) => break 'steps,
  6741. _ => Touch::Nothing,
  6742. });
  6743. }
  6744. }
  6745. let due: Vec<_> = written_spans(touches.into_iter())
  6746. .into_iter()
  6747. .filter_map(|(key, from, to)| Some((copies.get(&key)?.clone(), from, to)))
  6748. .collect();
  6749. for (shadow, from, to) in &due {
  6750. self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to));
  6751. }
  6752. #[cfg(feature = "diagnostics")]
  6753. let began = std::time::Instant::now();
  6754. let started = std::time::Instant::now();
  6755. let before = PREPARING[0].load(Ordering::Relaxed);
  6756. crate::shadow::wide_each(due.len(), move |i| {
  6757. let (shadow, from, to) = &due[i];
  6758. if !shadow.nothing_new(*from, *to - *from) {
  6759. Self::update(shadow, *from, *to);
  6760. }
  6761. });
  6762. // The time counted is the time it took, not the threads' sum.
  6763. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6764. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6765. #[cfg(feature = "diagnostics")]
  6766. {
  6767. let ns = began.elapsed().as_nanos() as u64;
  6768. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6769. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6770. }
  6771. }
  6772. /// The fills noted are done.
  6773. fn fill(&mut self) {
  6774. // Below this many the threads cost more than they save.
  6775. const FEW: usize = 96;
  6776. const PART: usize = 64;
  6777. if self.fills.is_empty() {
  6778. return;
  6779. }
  6780. let started = std::time::Instant::now();
  6781. if self.fills.len() < FEW {
  6782. for (dst, src, len) in self.fills.drain(..) {
  6783. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6784. }
  6785. } else {
  6786. let fills = std::mem::take(&mut self.fills);
  6787. crate::shadow::wide_each(fills.len().div_ceil(PART), move |i| {
  6788. for &(dst, src, len) in fills.iter().skip(i * PART).take(PART) {
  6789. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6790. }
  6791. });
  6792. }
  6793. let took = started.elapsed();
  6794. PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed);
  6795. #[cfg(feature = "diagnostics")]
  6796. SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed);
  6797. }
  6798. /// The textures due are brought up to date.
  6799. fn refresh_textures(&mut self) {
  6800. if self.due.len() < 2 || !wide_textures() {
  6801. self.due.drain(..).for_each(|staging| staging.refresh());
  6802. return;
  6803. }
  6804. // The time counted is the time it took, not the threads' sum.
  6805. let started = std::time::Instant::now();
  6806. let before = PREPARING[2].load(Ordering::Relaxed);
  6807. let due = std::mem::take(&mut self.due);
  6808. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  6809. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  6810. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6811. }
  6812. fn flush(&mut self) {
  6813. self.refresh_textures();
  6814. self.index.clear();
  6815. if self.refreshes.is_empty() {
  6816. return;
  6817. }
  6818. #[cfg(feature = "diagnostics")]
  6819. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  6820. self.flush_all();
  6821. #[cfg(feature = "diagnostics")]
  6822. {
  6823. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6824. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  6825. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  6826. }
  6827. }
  6828. fn flush_all(&mut self) {
  6829. // Most of a flush's copies are as they were: they are told so here,
  6830. // from what the submission's asking found, before anything is asked
  6831. // and any thread woken. (Thousands of them, the heap's buffer views
  6832. // once a frame: on the threads, below.)
  6833. const FEW: usize = 256;
  6834. let light = crate::watch::light();
  6835. if light && self.refreshes.len() <= FEW {
  6836. let started = std::time::Instant::now();
  6837. #[cfg(feature = "diagnostics")]
  6838. let all = self.refreshes.len();
  6839. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  6840. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6841. #[cfg(feature = "diagnostics")]
  6842. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  6843. }
  6844. // One write-watch asking for the copies that lie close together,
  6845. // not one per copy.
  6846. let ahead = self.refreshes.len() > 1;
  6847. if ahead {
  6848. let started = std::time::Instant::now();
  6849. let ranges: Vec<(usize, usize)> = self
  6850. .refreshes
  6851. .iter()
  6852. .filter(|r| r.0.asked_ahead())
  6853. .map(|r| (r.1, r.2))
  6854. .collect();
  6855. crate::watch::ask_ahead(&ranges);
  6856. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6857. }
  6858. if wide_refresh() && self.refreshes.len() >= 4 {
  6859. // Each copy on its own, several at a time: a copy's refresh
  6860. // writes that copy and reads title memory, nothing of another's.
  6861. // The time counted is the time it took, not the threads' sum.
  6862. let started = std::time::Instant::now();
  6863. let before = PREPARING[0].load(Ordering::Relaxed);
  6864. #[cfg(feature = "diagnostics")]
  6865. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  6866. if light {
  6867. // A number to a free thread, not a job to each copy.
  6868. let refreshes = std::mem::take(&mut self.refreshes);
  6869. crate::shadow::wide_each(refreshes.len(), move |i| {
  6870. let (shadow, from, to) = &refreshes[i];
  6871. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  6872. #[cfg(feature = "diagnostics")]
  6873. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  6874. return;
  6875. }
  6876. Self::update(shadow, *from, *to);
  6877. });
  6878. } else {
  6879. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  6880. .refreshes
  6881. .drain(..)
  6882. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  6883. .collect();
  6884. crate::shadow::wide_run(jobs);
  6885. }
  6886. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6887. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6888. } else {
  6889. for (shadow, from, to) in self.refreshes.drain(..) {
  6890. Self::update(&shadow, from, to);
  6891. }
  6892. }
  6893. if ahead {
  6894. crate::watch::ask_ahead_done();
  6895. }
  6896. }
  6897. }
  6898. /// Copies title memory at submission. The ranges were checked against their
  6899. /// resources when recorded, but the title may since have unmapped pages of
  6900. /// them (tiled memory, page mappings), which read as zeros here; a title
  6901. /// destination (`title_dst`) that is not all mapped is left alone.
  6902. ///
  6903. /// The source is read through the kernel (`ReadProcessMemory`), which
  6904. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  6905. /// cost about 2 ms per copy in the title's big pools (it walks the page
  6906. /// tables to the region's end), which made copies run at 100-200 MB/s.
  6907. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  6908. #[cfg(feature = "diagnostics")]
  6909. match crate::copystat::mode() {
  6910. 1 => {
  6911. // SAFETY: timing only: the caller vouches for the source.
  6912. unsafe { std::ptr::copy(src, dst, len) };
  6913. return;
  6914. }
  6915. 2 => return,
  6916. _ => {}
  6917. }
  6918. if len == 0 {
  6919. return;
  6920. }
  6921. // A title destination that is not all mapped is left alone. Asking
  6922. // Windows first (`VirtualQuery`) walks the page tables to the end of
  6923. // the destination's region: in the title's big blocks that is
  6924. // milliseconds a copy, and it was a seventh of the submitting thread's
  6925. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  6926. // says the same when it fails, so the question is only asked then.
  6927. // `VICTORY_COPY_ASK=1` asks first, as before.
  6928. static ASK: OnceLock<bool> = OnceLock::new();
  6929. let ask_first = title_dst
  6930. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  6931. if ask_first && !crate::texture::committed(dst, len) {
  6932. return;
  6933. }
  6934. if title_dst {
  6935. // The kernel writes the destination: it must not be guarded.
  6936. crate::watch::writing(dst as usize, len);
  6937. }
  6938. #[cfg(feature = "diagnostics")]
  6939. let moved = std::time::Instant::now();
  6940. let since = crate::watch::changes();
  6941. // (A title destination that is away only while the runtime changes a
  6942. // mapping beside it is written when that is done.)
  6943. let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
  6944. #[cfg(feature = "diagnostics")]
  6945. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  6946. if whole {
  6947. return;
  6948. }
  6949. // The copy failed: a source page is not there, or the destination is
  6950. // not all mapped. Then the destination stays as it is (the kernel may
  6951. // have written its first pages).
  6952. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  6953. crate::watch::lost("a copy of the title's", dst as usize, len);
  6954. return;
  6955. }
  6956. #[cfg(feature = "diagnostics")]
  6957. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  6958. #[cfg(feature = "diagnostics")]
  6959. let sparse = std::time::Instant::now();
  6960. if !title_dst && len >= 64 << 10 {
  6961. read_sparse(src, dst, len);
  6962. } else {
  6963. read_pieces(src, dst, len);
  6964. }
  6965. #[cfg(feature = "diagnostics")]
  6966. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  6967. }
  6968. /// After a failed bulk read into host memory, skip contiguous holes. Never
  6969. /// cache the query across copies: the title may remap the same address.
  6970. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  6971. use windows_sys::Win32::System::Memory::{
  6972. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  6973. };
  6974. let mut offset = 0;
  6975. while offset < len {
  6976. let at = src.wrapping_add(offset);
  6977. let to = dst.wrapping_add(offset);
  6978. let remaining = len - offset;
  6979. // SAFETY: the query inspects an address and fills a local structure.
  6980. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  6981. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  6982. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  6983. .saturating_sub(at as usize).min(remaining);
  6984. if size != size_of_val(&info) || n == 0 {
  6985. read_pieces(at, to, remaining);
  6986. break;
  6987. }
  6988. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  6989. #[cfg(feature = "diagnostics")]
  6990. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6991. // SAFETY: this path is only used with a writable host destination.
  6992. unsafe { to.write_bytes(0, n) };
  6993. } else if !read(at, to, n) {
  6994. // A mapping may change between query and read.
  6995. read_pieces(at, to, n);
  6996. }
  6997. offset += n;
  6998. }
  6999. }
  7000. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  7001. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  7002. // that fails), zeros for what cannot be read.
  7003. for_pieces(src as usize, len, 64 << 10, |at, n| {
  7004. let to = dst.wrapping_add(at - src as usize);
  7005. if !read(at as *const u8, to, n) {
  7006. for_pieces(at, n, 4 << 10, |at, n| {
  7007. let to = dst.wrapping_add(at - src as usize);
  7008. if !read(at as *const u8, to, n) {
  7009. #[cfg(feature = "diagnostics")]
  7010. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  7011. zero(to, n);
  7012. }
  7013. });
  7014. }
  7015. });
  7016. }
  7017. /// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
  7018. /// destination of a title's copy), which can go between the question whether
  7019. /// it is there and this.
  7020. fn zero(to: *mut u8, n: usize) {
  7021. static ZEROS: [u8; 4096] = [0; 4096];
  7022. if n <= ZEROS.len() && crate::safecopy::on() {
  7023. // SAFETY: a destination that is not there fails the copy.
  7024. if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
  7025. crate::watch::lost("zeros", to as usize, n);
  7026. }
  7027. return;
  7028. }
  7029. // SAFETY: inside the destination, which is mapped.
  7030. unsafe { to.write_bytes(0, n) };
  7031. }
  7032. /// Reads title memory at `src` into `dst`; false if a page of it is not
  7033. /// readable.
  7034. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  7035. read(src, dst.as_mut_ptr(), dst.len())
  7036. }
  7037. /// Reads what is there of the `dst.len()` bytes of title memory at `src`,
  7038. /// zeros for the rest; returns how many bytes were there. Safe while the
  7039. /// runtime remaps title memory (the kernel, or a copy that takes the fault,
  7040. /// reads). What the runtime's record says is mapped is read in one go each,
  7041. /// and by pieces where that fails; memory it has no record of by pieces.
  7042. pub(crate) fn read_there(src: *const u8, dst: &mut [u8]) -> usize {
  7043. dst.fill(0);
  7044. let (start, len) = (src as usize, dst.len());
  7045. let mut got = 0;
  7046. let mut runs = crate::inplace::shown_runs(start, len);
  7047. if runs.is_empty() {
  7048. runs.push((start, len));
  7049. }
  7050. for (at, n) in runs {
  7051. let piece = &mut dst[at - start..at - start + n];
  7052. if read_into(at as *const u8, piece) {
  7053. got += n;
  7054. continue;
  7055. }
  7056. // (What failed may have written its first pages.)
  7057. piece.fill(0);
  7058. for_pieces(at, n, 64 << 10, |from, n| {
  7059. let piece = &mut dst[from - start..from - start + n];
  7060. if read_into(from as *const u8, piece) {
  7061. got += n;
  7062. return;
  7063. }
  7064. piece.fill(0);
  7065. for_pieces(from, n, 4 << 10, |from, n| {
  7066. let piece = &mut dst[from - start..from - start + n];
  7067. if read_into(from as *const u8, piece) {
  7068. got += n;
  7069. } else {
  7070. piece.fill(0);
  7071. }
  7072. });
  7073. });
  7074. }
  7075. got
  7076. }
  7077. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  7078. /// readable.
  7079. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  7080. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  7081. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7082. if crate::safecopy::on() {
  7083. // SAFETY: the destination is mapped writable memory of `len` bytes;
  7084. // a source page that is not there fails the copy.
  7085. return unsafe { crate::safecopy::copy(dst, src, len) };
  7086. }
  7087. let mut done = 0;
  7088. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  7089. // kernel checks the source.
  7090. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  7091. }
  7092. #[link(name = "ntdll", kind = "raw-dylib")]
  7093. unsafe extern "system" {
  7094. /// The kernel's write into a process's memory, `(process, address,
  7095. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  7096. /// the range is not there or not writable. It changes no protection.
  7097. fn NtWriteVirtualMemory(
  7098. process: *mut std::ffi::c_void,
  7099. base: *mut std::ffi::c_void,
  7100. buffer: *const std::ffi::c_void,
  7101. size: usize,
  7102. written: *mut usize,
  7103. ) -> i32;
  7104. }
  7105. /// Whether title memory is written with the kernel's own call
  7106. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  7107. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  7108. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  7109. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  7110. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  7111. fn direct_writes() -> bool {
  7112. static ON: OnceLock<bool> = OnceLock::new();
  7113. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  7114. }
  7115. /// Copies host memory into title memory after a submission (what shaders
  7116. /// wrote), leaving pages that are not mapped alone.
  7117. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  7118. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  7119. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7120. let direct = direct_writes();
  7121. let since = crate::watch::changes();
  7122. let write = |at: usize, n: usize| {
  7123. let from = src.wrapping_add(at - dst as usize);
  7124. if crate::safecopy::on() {
  7125. // SAFETY: the source is ours; a destination page that is not
  7126. // there, or not writable, fails the copy.
  7127. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  7128. }
  7129. let mut done = 0;
  7130. if direct {
  7131. // SAFETY: as below; the kernel checks the destination and
  7132. // writes nothing it cannot (the caller opened its guards:
  7133. // `crate::watch::writing`).
  7134. return unsafe {
  7135. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  7136. };
  7137. }
  7138. // SAFETY: the source is our mapped host copy; the kernel checks the
  7139. // destination.
  7140. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  7141. };
  7142. if len == 0 || write(dst as usize, len) {
  7143. return;
  7144. }
  7145. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  7146. if !write(at, n) {
  7147. for_pieces(at, n, 4 << 10, |at, n| {
  7148. if write(at, n) {
  7149. return;
  7150. }
  7151. // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
  7152. // refresh guarded the block again since the caller opened
  7153. // it; and any where the runtime was changing a mapping.
  7154. crate::watch::writing(at, n);
  7155. if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
  7156. crate::watch::lost("a host copy's bytes", at, n);
  7157. }
  7158. });
  7159. }
  7160. });
  7161. }
  7162. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  7163. /// `step`.
  7164. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  7165. let end = start + len;
  7166. let mut at = start;
  7167. while at < end {
  7168. let next = ((at / step + 1) * step).min(end);
  7169. f(at, next - at);
  7170. at = next;
  7171. }
  7172. }
  7173. impl Host {
  7174. /// The queue everything of ours runs on, for a call that must go to it
  7175. /// in order with the lists (`crate::tiles`: a texture's levels are
  7176. /// given memory ahead of the list that uploads them).
  7177. pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
  7178. &self.queue
  7179. }
  7180. /// A buffer in the upload heap, mapped for writing.
  7181. /// A buffer of `size` bytes the card writes and we read (a read back),
  7182. /// in the state copies into it need.
  7183. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7184. let heap = D3D12_HEAP_PROPERTIES {
  7185. Type: D3D12_HEAP_TYPE_READBACK,
  7186. ..Default::default()
  7187. };
  7188. let desc = D3D12_RESOURCE_DESC {
  7189. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7190. Width: size.max(1),
  7191. Height: 1,
  7192. DepthOrArraySize: 1,
  7193. MipLevels: 1,
  7194. SampleDesc: DXGI_SAMPLE_DESC {
  7195. Count: 1,
  7196. Quality: 0,
  7197. },
  7198. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7199. ..Default::default()
  7200. };
  7201. let mut buffer: Option<ID3D12Resource> = None;
  7202. // SAFETY: plain creation of a read-back buffer.
  7203. let made = unsafe {
  7204. self.device.CreateCommittedResource(
  7205. &heap,
  7206. D3D12_HEAP_FLAG_NONE,
  7207. &desc,
  7208. D3D12_RESOURCE_STATE_COPY_DEST,
  7209. None,
  7210. &mut buffer,
  7211. )
  7212. };
  7213. match made {
  7214. Ok(()) => buffer,
  7215. Err(e) => {
  7216. tracing::warn!(error = %e, size, "no read-back buffer");
  7217. None
  7218. }
  7219. }
  7220. }
  7221. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7222. MADE[0].fetch_add(1, Ordering::Relaxed);
  7223. MADE[1].fetch_add(size, Ordering::Relaxed);
  7224. let heap = D3D12_HEAP_PROPERTIES {
  7225. Type: D3D12_HEAP_TYPE_UPLOAD,
  7226. ..Default::default()
  7227. };
  7228. let desc = D3D12_RESOURCE_DESC {
  7229. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7230. Width: size.max(1),
  7231. Height: 1,
  7232. DepthOrArraySize: 1,
  7233. MipLevels: 1,
  7234. SampleDesc: DXGI_SAMPLE_DESC {
  7235. Count: 1,
  7236. Quality: 0,
  7237. },
  7238. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7239. ..Default::default()
  7240. };
  7241. let mut buffer: Option<ID3D12Resource> = None;
  7242. let mut data = std::ptr::null_mut();
  7243. // SAFETY: plain creation and mapping of an upload buffer.
  7244. let made = unsafe {
  7245. self.device
  7246. .CreateCommittedResource(
  7247. &heap,
  7248. D3D12_HEAP_FLAG_NONE,
  7249. &desc,
  7250. D3D12_RESOURCE_STATE_GENERIC_READ,
  7251. None,
  7252. &mut buffer,
  7253. )
  7254. .and_then(|()| {
  7255. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7256. b.Map(0, None, Some(&mut data))
  7257. })
  7258. };
  7259. match made {
  7260. Ok(()) => Some((buffer?, data.cast())),
  7261. Err(e) => {
  7262. tracing::warn!(error = %e, size, "no upload buffer");
  7263. None
  7264. }
  7265. }
  7266. }
  7267. }
  7268. /// The swap chain formats a presented texture can be copied into: its own
  7269. /// family's.
  7270. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  7271. Some(match format.0 {
  7272. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  7273. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  7274. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  7275. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  7276. _ => return None,
  7277. })
  7278. }
  7279. const BUFFERS: u32 = 2;
  7280. struct Presenter {
  7281. swap_chain: IDXGISwapChain3,
  7282. width: u32,
  7283. height: u32,
  7284. format: DXGI_FORMAT,
  7285. copy: HostList,
  7286. /// With presents sent ahead ([`late_free_present`]): a list for each
  7287. /// present in the air, and the submission it last flew as (it is used
  7288. /// again once that one has finished).
  7289. ahead: Vec<(HostList, u64)>,
  7290. hwnd: HWND,
  7291. meter: Meter,
  7292. }
  7293. /// The frame rate, shown in the window's caption every second and logged
  7294. /// every few seconds.
  7295. struct Meter {
  7296. since: std::time::Instant,
  7297. frames: u32,
  7298. #[cfg(feature = "diagnostics")]
  7299. copy_stats_frames: u64,
  7300. drawn: u64,
  7301. logged: std::time::Instant,
  7302. /// The caption the window had, once read.
  7303. caption: Option<Vec<u16>>,
  7304. }
  7305. impl Meter {
  7306. fn new() -> Self {
  7307. let now = std::time::Instant::now();
  7308. Meter {
  7309. since: now,
  7310. frames: 0,
  7311. #[cfg(feature = "diagnostics")]
  7312. copy_stats_frames: 0,
  7313. drawn: crate::draw::drawn(),
  7314. logged: now,
  7315. caption: None,
  7316. }
  7317. }
  7318. /// Counts a presented frame.
  7319. fn frame(&mut self, hwnd: HWND) {
  7320. #[cfg(feature = "diagnostics")]
  7321. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  7322. #[cfg(feature = "diagnostics")]
  7323. crate::copystat::presented();
  7324. self.frames += 1;
  7325. #[cfg(feature = "diagnostics")]
  7326. {
  7327. self.copy_stats_frames += 1;
  7328. }
  7329. let elapsed = self.since.elapsed();
  7330. if elapsed < std::time::Duration::from_secs(1) {
  7331. return;
  7332. }
  7333. let drawn = crate::draw::drawn();
  7334. let frames = f64::from(self.frames);
  7335. let fps = frames / elapsed.as_secs_f64();
  7336. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  7337. let draws = (drawn - self.drawn) as f64 / frames;
  7338. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  7339. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  7340. let [cpu, gpu] = [0, 1].map(|i| {
  7341. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  7342. });
  7343. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  7344. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  7345. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  7346. });
  7347. let [back_ms, back_mb] = [0, 1].map(|i| {
  7348. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  7349. });
  7350. let dropped = crate::draw::take_dropped() as f64 / frames;
  7351. let indirect = crate::list::take_indirect() as f64 / frames;
  7352. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  7353. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  7354. tracing::info!(
  7355. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  7356. );
  7357. crate::shadow::exact_line(frames);
  7358. crate::descriptor::sync_line(frames);
  7359. late_line(frames);
  7360. crate::queue::behind_line(frames);
  7361. card_clock_line(frames, ms);
  7362. crate::shadow::back_line(frames);
  7363. #[cfg(feature = "diagnostics")]
  7364. split_line(frames);
  7365. {
  7366. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7367. if passes + compares > 0.0 {
  7368. tracing::info!(
  7369. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  7370. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  7371. if rehash_runs() { "on" } else { "off" }
  7372. );
  7373. }
  7374. }
  7375. {
  7376. let [own, asking, still, all] =
  7377. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  7378. if all >= 1.0 {
  7379. tracing::info!(
  7380. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  7381. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  7382. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  7383. );
  7384. }
  7385. let [through, left, filled, short] =
  7386. [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7387. if through + left + filled > 0.0 {
  7388. tracing::info!(
  7389. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  7390. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \
  7391. {filled:.1} first fillings from the pages there (VICTORY_TEXTURE_FILL=0: left empty), {short:.1} of them \
  7392. with less than was mapped (looked at again)"
  7393. );
  7394. }
  7395. }
  7396. {
  7397. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7398. if copies > 0.0 {
  7399. tracing::info!(
  7400. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  7401. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  7402. if join_copies() { "on" } else { "off" }
  7403. );
  7404. }
  7405. }
  7406. // Passes over the heap's buffer views for shaders that pick them by index.
  7407. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  7408. let picked_ms =
  7409. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  7410. // Copies between depth textures and their colour twins, each way.
  7411. let [twin_to_depth, twin_to_colour] =
  7412. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7413. // Depth planes drawn from their twins.
  7414. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  7415. // Copies in the card's memory (`crate::shadow::cards`).
  7416. let card = crate::shadow::card_stats();
  7417. #[cfg(feature = "diagnostics")]
  7418. let slow = crate::watch::slow_asks();
  7419. // Over the same frames as the counts above.
  7420. #[cfg(feature = "diagnostics")]
  7421. let drops = crate::pipeline::take_drops();
  7422. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  7423. self.logged = std::time::Instant::now();
  7424. tracing::info!(
  7425. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  7426. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  7427. );
  7428. crate::tiles::status();
  7429. {
  7430. let [queued, due, away, partly, oldest] =
  7431. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  7432. let [same, parts, tails] =
  7433. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  7434. tracing::info!(
  7435. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  7436. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  7437. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  7438. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  7439. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  7440. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  7441. {} made slots found unmapped and made null",
  7442. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  7443. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  7444. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  7445. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  7446. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  7447. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  7448. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  7449. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  7450. );
  7451. }
  7452. if crate::resource::held_only() {
  7453. let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed));
  7454. let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed));
  7455. tracing::info!(
  7456. "textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \
  7457. levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \
  7458. {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \
  7459. out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free",
  7460. bytes >> 20,
  7461. whole >> 20,
  7462. crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed),
  7463. crate::pool::texture_room() >> 20
  7464. );
  7465. }
  7466. {
  7467. let mode = crate::watch::page_writes();
  7468. let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
  7469. let [kept, dropped, slots, uploaded] =
  7470. [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
  7471. tracing::info!(
  7472. "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset or guards opens the guarded blocks, 0 counts only, 1, slots, all)",
  7473. bytes >> 20,
  7474. if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
  7475. if mode & 4 != 0 { "told as well" } else { "counted only" },
  7476. if mode & 2 != 0 { "made due again" } else { "left as they were" }
  7477. );
  7478. }
  7479. #[cfg(feature = "diagnostics")]
  7480. tracing::info!(
  7481. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  7482. slow[0] as f64 / frames,
  7483. slow[1] as f64 / 1e3 / frames,
  7484. slow[2] as f64 / 1e3
  7485. );
  7486. if crate::shadow::cards() {
  7487. let per_frame = |i: usize| card[i] as f64 / frames;
  7488. tracing::info!(
  7489. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  7490. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  7491. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  7492. card[7],
  7493. card[8] >> 20,
  7494. card[9] >> 20,
  7495. per_frame(0) / 1e6,
  7496. per_frame(1),
  7497. per_frame(2),
  7498. per_frame(3),
  7499. per_frame(4) / 1e6,
  7500. per_frame(5),
  7501. per_frame(6) / 1e3
  7502. );
  7503. }
  7504. tracing::info!(
  7505. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  7506. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  7507. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  7508. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  7509. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  7510. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  7511. {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}",
  7512. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  7513. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  7514. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  7515. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  7516. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  7517. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  7518. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  7519. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  7520. refused = format!(
  7521. "{} ({} copies made of views off their buffer's elements); depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass",
  7522. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  7523. crate::shadow::OWN_MADE.load(Ordering::Relaxed),
  7524. crate::resource::TWINS[0].load(Ordering::Relaxed),
  7525. crate::resource::TWINS[1].load(Ordering::Relaxed),
  7526. crate::resource::PLANES[1].load(Ordering::Relaxed),
  7527. crate::resource::PLANES[2].load(Ordering::Relaxed)
  7528. ),
  7529. making = crate::pipeline::making(),
  7530. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  7531. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  7532. );
  7533. #[cfg(feature = "diagnostics")]
  7534. {
  7535. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7536. tracing::info!(
  7537. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  7538. put[0],
  7539. put[1],
  7540. put[2] / 1e6,
  7541. put[3]
  7542. );
  7543. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  7544. for (why, n) in drops.iter().take(40) {
  7545. tracing::info!(
  7546. "dropped {:.1}/frame without a host pipeline: {why}",
  7547. *n as f64 / frames
  7548. );
  7549. }
  7550. }
  7551. }
  7552. if self.caption.is_none() {
  7553. // The window's own text, read without a message.
  7554. let mut buffer = vec![0u16; 512];
  7555. // SAFETY: a window handle and a buffer of that length.
  7556. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  7557. buffer.truncate(n.max(0) as usize);
  7558. self.caption = Some(buffer);
  7559. }
  7560. let Some(caption) = &self.caption else { return };
  7561. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  7562. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  7563. text.push(0);
  7564. // Setting the text waits for the window's thread (a title thread,
  7565. // which may not pump for a while), so a thread of ours does it and
  7566. // presenting never waits; it takes the newest text when free.
  7567. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  7568. static SETTER: std::sync::Once = std::sync::Once::new();
  7569. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  7570. SETTER.call_once(|| {
  7571. let _ = std::thread::Builder::new()
  7572. .name("victory-caption".into())
  7573. .spawn(|| {
  7574. loop {
  7575. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  7576. match next {
  7577. // SAFETY: a window handle and a NUL-terminated text.
  7578. Some((hwnd, text)) => unsafe {
  7579. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  7580. },
  7581. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  7582. }
  7583. }
  7584. });
  7585. });
  7586. }
  7587. }
  7588. impl Host {
  7589. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  7590. /// as frame `frame` (saved if captures are on). `None` if nothing was
  7591. /// shown; else, in diagnostics builds, whether the frame was black.
  7592. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  7593. // SAFETY: a live resource.
  7594. let desc = unsafe { texture.GetDesc() };
  7595. let Some(format) = swap_format(desc.Format) else {
  7596. tracing::warn!(format = desc.Format.0, "cannot present this format");
  7597. return None;
  7598. };
  7599. let (width, height) = (desc.Width as u32, desc.Height);
  7600. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  7601. if presenter.is_none() {
  7602. *presenter = match self.presenter(width, height, format) {
  7603. Ok(p) => Some(p),
  7604. Err(e) => {
  7605. tracing::warn!(error = %e, "no swap chain");
  7606. return None;
  7607. }
  7608. };
  7609. }
  7610. let p = presenter.as_mut()?;
  7611. if (p.width, p.height, p.format) != (width, height, format) {
  7612. // Presents sent ahead hold back buffers until they have run.
  7613. settle_now(WHY_SYNC);
  7614. // SAFETY: no back buffer is held; every submission was waited for.
  7615. let resized = unsafe {
  7616. p.swap_chain
  7617. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  7618. };
  7619. match resized {
  7620. Ok(()) => {
  7621. (p.width, p.height, p.format) = (width, height, format);
  7622. tracing::info!(
  7623. width,
  7624. height,
  7625. format = format.0,
  7626. frame,
  7627. "the swap chain's buffers were made again for another size or format"
  7628. );
  7629. self.log_video_memory("right after the swap chain's buffers were made again");
  7630. }
  7631. Err(e) => {
  7632. tracing::warn!(error = %e, width, height, "swap chain not resized");
  7633. return None;
  7634. }
  7635. }
  7636. }
  7637. let state = D3D12_RESOURCE_STATES(state as i32);
  7638. // SAFETY: our swap chain, list and a live source texture.
  7639. unsafe {
  7640. let index = p.swap_chain.GetCurrentBackBufferIndex();
  7641. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  7642. return None;
  7643. };
  7644. // Sent ahead ([`late_free_present`]) unless the frame is to be
  7645. // read back at once (a saved or listed frame): then a list of
  7646. // its own, one whose last flight has finished or a new one.
  7647. #[cfg(feature = "diagnostics")]
  7648. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  7649. #[cfg(not(feature = "diagnostics"))]
  7650. let read_now = false;
  7651. let slot = if late_free_present() && !read_now {
  7652. let finished = FINISHED.load(Ordering::Acquire);
  7653. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  7654. let list = self.new_list().ok()?;
  7655. list.close();
  7656. p.ahead.push((list, 0));
  7657. Some(p.ahead.len() - 1)
  7658. })
  7659. } else {
  7660. None
  7661. };
  7662. let copy = match slot {
  7663. Some(i) => &p.ahead[i].0,
  7664. None => &p.copy,
  7665. };
  7666. copy.reset();
  7667. let list = &copy.list;
  7668. list.ResourceBarrier(&[
  7669. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  7670. transition(
  7671. &back,
  7672. D3D12_RESOURCE_STATE_PRESENT,
  7673. D3D12_RESOURCE_STATE_COPY_DEST,
  7674. ),
  7675. ]);
  7676. list.CopyResource(&back, texture);
  7677. #[cfg(feature = "diagnostics")]
  7678. let capture = crate::capture::wanted(frame)
  7679. .then(|| crate::capture::read_back(&self.device, list, texture))
  7680. .flatten();
  7681. #[cfg(feature = "diagnostics")]
  7682. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  7683. #[cfg(not(feature = "diagnostics"))]
  7684. let _ = frame;
  7685. list.ResourceBarrier(&[
  7686. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  7687. transition(
  7688. &back,
  7689. D3D12_RESOURCE_STATE_COPY_DEST,
  7690. D3D12_RESOURCE_STATE_PRESENT,
  7691. ),
  7692. ]);
  7693. copy.close();
  7694. match slot {
  7695. Some(i) => {
  7696. let flown = self.execute_own(copy);
  7697. p.ahead[i].1 = flown;
  7698. }
  7699. None => self.execute(&[copy]),
  7700. }
  7701. #[cfg(feature = "diagnostics")]
  7702. if let Some((buffer, footprint)) = capture {
  7703. crate::capture::save_read_back(frame, &buffer, &footprint);
  7704. }
  7705. #[cfg(feature = "diagnostics")]
  7706. crate::replay::record::present(texture, state);
  7707. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  7708. p.meter.frame(p.hwnd);
  7709. #[cfg(feature = "diagnostics")]
  7710. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  7711. #[cfg(not(feature = "diagnostics"))]
  7712. Some(false)
  7713. }
  7714. }
  7715. fn presenter(
  7716. &self,
  7717. width: u32,
  7718. height: u32,
  7719. format: DXGI_FORMAT,
  7720. ) -> windows::core::Result<Presenter> {
  7721. let hwnd = match title_window() {
  7722. Some(hwnd) => hwnd,
  7723. None => window(width, height)?,
  7724. };
  7725. self.log_video_memory("right before the swap chain is made");
  7726. // SAFETY: plain object creation for our window.
  7727. unsafe {
  7728. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  7729. let desc = DXGI_SWAP_CHAIN_DESC1 {
  7730. Width: width,
  7731. Height: height,
  7732. Format: format,
  7733. SampleDesc: DXGI_SAMPLE_DESC {
  7734. Count: 1,
  7735. Quality: 0,
  7736. },
  7737. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  7738. BufferCount: BUFFERS,
  7739. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  7740. ..Default::default()
  7741. };
  7742. let swap_chain = factory
  7743. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  7744. .cast::<IDXGISwapChain3>()?;
  7745. let copy = self.new_list()?;
  7746. copy.close();
  7747. tracing::info!(width, height, format = format.0, "presenting to a window");
  7748. self.log_video_memory("right after the swap chain is made");
  7749. Ok(Presenter {
  7750. swap_chain,
  7751. width,
  7752. height,
  7753. format,
  7754. copy,
  7755. ahead: Vec::new(),
  7756. hwnd,
  7757. meter: Meter::new(),
  7758. })
  7759. }
  7760. }
  7761. }
  7762. /// A visible top-level window of this process: the one the title made, if
  7763. /// it made one.
  7764. fn title_window() -> Option<HWND> {
  7765. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  7766. let mut process = 0;
  7767. // SAFETY: a window handle from the enumeration; `found` is ours.
  7768. unsafe {
  7769. GetWindowThreadProcessId(hwnd, Some(&mut process));
  7770. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  7771. && IsWindowVisible(hwnd).as_bool()
  7772. {
  7773. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  7774. return false.into();
  7775. }
  7776. }
  7777. true.into()
  7778. }
  7779. let mut found: Option<HWND> = None;
  7780. // SAFETY: the callback only writes `found`, which outlives the call.
  7781. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  7782. found
  7783. }
  7784. /// `state` without the bits the host texture's flags forbid: the console
  7785. /// lets the title name states its own resources allow (unordered access on
  7786. /// a depth target, whose host copy cannot have both).
  7787. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  7788. // SAFETY: a plain query.
  7789. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  7790. }
  7791. /// [`legal_state`] for a texture with resource flags `flags`.
  7792. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  7793. // (flag, set or clear forbids, state bits): render target, unordered
  7794. // access, depth, denied shader resource.
  7795. const FORBIDDEN: [(u32, bool, u32); 4] = [
  7796. (0x1, false, 0x4),
  7797. (0x4, false, 0x8),
  7798. (0x2, false, 0x10 | 0x20),
  7799. (0x8, true, 0x40 | 0x80),
  7800. ];
  7801. FORBIDDEN
  7802. .iter()
  7803. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  7804. .fold(state, |s, &(_, _, bits)| s & !bits)
  7805. }
  7806. impl Host {
  7807. /// The card's memory as the system accounts it to this process, in
  7808. /// bytes: the budget and the use of the card's own memory, then of the
  7809. /// PC's memory shared with the card (where the system moves what does
  7810. /// not fit on the card).
  7811. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  7812. let adapter = self.adapter.as_ref()?;
  7813. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7814. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7815. // SAFETY: plain queries that fill our structures.
  7816. unsafe {
  7817. adapter
  7818. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7819. .ok()?;
  7820. adapter
  7821. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7822. .ok()?;
  7823. }
  7824. // The card's budget moved by 256 MB or more since the last look:
  7825. // said at once, with what was in use at the last look, so the log
  7826. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  7827. // the first world frame in runs 179 to 185, and the memory line,
  7828. // seconds later, was the first to show it. We reserve nothing
  7829. // and make the swap chain once, at the start.)
  7830. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  7831. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  7832. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  7833. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  7834. tracing::info!(
  7835. "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",
  7836. last[0] >> 20,
  7837. own.Budget >> 20,
  7838. crate::frame::current(),
  7839. last[1] >> 20,
  7840. last[2] >> 20
  7841. );
  7842. self.log_video_memory("right after that change");
  7843. }
  7844. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  7845. }
  7846. /// Both of the system's memory groups for this process, in bytes: for
  7847. /// the card's own memory and then for the PC's memory shared with the
  7848. /// card, the budget, the use, what could still be reserved and what
  7849. /// is reserved (the layer reserves none).
  7850. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  7851. let adapter = self.adapter.as_ref()?;
  7852. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7853. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7854. // SAFETY: plain queries that fill our structures.
  7855. unsafe {
  7856. adapter
  7857. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7858. .ok()?;
  7859. adapter
  7860. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7861. .ok()?;
  7862. }
  7863. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  7864. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  7865. };
  7866. Some([all(&own), all(&shared)])
  7867. }
  7868. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  7869. pub(crate) fn log_video_memory(&self, when: &str) {
  7870. let Some([own, shared]) = self.video_memory_groups() else {
  7871. return;
  7872. };
  7873. tracing::info!(
  7874. "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)",
  7875. when,
  7876. own[0] >> 20,
  7877. own[1] >> 20,
  7878. own[2] >> 20,
  7879. own[3] >> 20,
  7880. shared[0] >> 20,
  7881. shared[1] >> 20,
  7882. shared[2] >> 20,
  7883. shared[3] >> 20
  7884. );
  7885. }
  7886. /// A buffer in system memory that the CPU maps (write-back, so reading
  7887. /// it is fast too) and shaders read and write: for host copies of title
  7888. /// memory that shaders write, which upload memory cannot be. Starts in
  7889. /// the common state (buffers move out of it implicitly).
  7890. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7891. MADE[2].fetch_add(1, Ordering::Relaxed);
  7892. MADE[3].fetch_add(size, Ordering::Relaxed);
  7893. let heap = D3D12_HEAP_PROPERTIES {
  7894. Type: D3D12_HEAP_TYPE_CUSTOM,
  7895. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  7896. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  7897. ..Default::default()
  7898. };
  7899. let desc = D3D12_RESOURCE_DESC {
  7900. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7901. Width: size.max(1),
  7902. Height: 1,
  7903. DepthOrArraySize: 1,
  7904. MipLevels: 1,
  7905. SampleDesc: DXGI_SAMPLE_DESC {
  7906. Count: 1,
  7907. Quality: 0,
  7908. },
  7909. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7910. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7911. ..Default::default()
  7912. };
  7913. let mut buffer: Option<ID3D12Resource> = None;
  7914. let mut data = std::ptr::null_mut();
  7915. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7916. let made = unsafe {
  7917. self.device
  7918. .CreateCommittedResource(
  7919. &heap,
  7920. D3D12_HEAP_FLAG_NONE,
  7921. &desc,
  7922. D3D12_RESOURCE_STATE_COMMON,
  7923. None,
  7924. &mut buffer,
  7925. )
  7926. .and_then(|()| {
  7927. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7928. b.Map(0, None, Some(&mut data))
  7929. })
  7930. };
  7931. match made {
  7932. Ok(()) => Some((buffer?, data.cast())),
  7933. Err(e) => {
  7934. tracing::warn!(error = %e, size, "no shared buffer");
  7935. None
  7936. }
  7937. }
  7938. }
  7939. /// A device-local buffer shaders may write (unordered access) and indirect
  7940. /// execution may read, starting in the common state.
  7941. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7942. MADE[4].fetch_add(1, Ordering::Relaxed);
  7943. MADE[5].fetch_add(size, Ordering::Relaxed);
  7944. let heap = D3D12_HEAP_PROPERTIES {
  7945. Type: D3D12_HEAP_TYPE_DEFAULT,
  7946. ..Default::default()
  7947. };
  7948. let desc = D3D12_RESOURCE_DESC {
  7949. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7950. Width: size.max(1),
  7951. Height: 1,
  7952. DepthOrArraySize: 1,
  7953. MipLevels: 1,
  7954. SampleDesc: DXGI_SAMPLE_DESC {
  7955. Count: 1,
  7956. Quality: 0,
  7957. },
  7958. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7959. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7960. ..Default::default()
  7961. };
  7962. let mut buffer: Option<ID3D12Resource> = None;
  7963. // SAFETY: plain creation of a device-local buffer.
  7964. let made = unsafe {
  7965. self.device.CreateCommittedResource(
  7966. &heap,
  7967. D3D12_HEAP_FLAG_NONE,
  7968. &desc,
  7969. D3D12_RESOURCE_STATE_COMMON,
  7970. None,
  7971. &mut buffer,
  7972. )
  7973. };
  7974. match made {
  7975. Ok(()) => buffer,
  7976. Err(e) => {
  7977. tracing::warn!(error = %e, size, "no unordered-access buffer");
  7978. None
  7979. }
  7980. }
  7981. }
  7982. }
  7983. /// For adapters without device-removed data (the software one): the last
  7984. /// commands each list of the failed submission noted (diagnostics, with
  7985. /// `VICTORY_D3D12_DRED`).
  7986. fn last_notes(runs: &[&HostList]) -> String {
  7987. #[cfg(feature = "diagnostics")]
  7988. {
  7989. let mut text = String::new();
  7990. for (i, r) in runs.iter().enumerate() {
  7991. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  7992. for (n, _) in notes.iter().rev().take(6).rev() {
  7993. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  7994. }
  7995. }
  7996. text
  7997. }
  7998. #[cfg(not(feature = "diagnostics"))]
  7999. {
  8000. let _ = runs;
  8001. String::new()
  8002. }
  8003. }
  8004. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  8005. /// command reads (diagnostics).
  8006. #[cfg(feature = "diagnostics")]
  8007. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  8008. let end = start + bytes;
  8009. if va < start {
  8010. format!(" (fault {:#x} below its source)", start - va)
  8011. } else if va < end {
  8012. format!(" (fault at source +{:#x})", va - start)
  8013. } else {
  8014. format!(" (fault {:#x} past its source's end)", va - end)
  8015. }
  8016. }
  8017. /// The commands that may have been running where a list stopped at
  8018. /// command `done`: those between the barriers around it (work between
  8019. /// barriers overlaps on the GPU), by kind, and what the markers just
  8020. /// before them say (`HostList::note_op`: diagnostics builds with
  8021. /// device-removed data on).
  8022. /// For a list that stopped at command `done`: what the indirect executions
  8023. /// there ran, from the one before it to the next barrier (four at most), and
  8024. /// what the heap slots their user data names hold now.
  8025. #[cfg(feature = "diagnostics")]
  8026. fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &indirects::Shared) -> String {
  8027. let indirect = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT;
  8028. let all = all.lock().unwrap_or_else(|e| e.into_inner());
  8029. let mut text = String::new();
  8030. let mut shown = 0;
  8031. for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) {
  8032. if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) {
  8033. break;
  8034. }
  8035. if !indirect(op) {
  8036. continue;
  8037. }
  8038. shown += 1;
  8039. let Some((what, words)) = all.nth(indirects::before(history, at, indirect)) else {
  8040. continue;
  8041. };
  8042. text.push_str(&format!("; command {at} ran {what}"));
  8043. for (word, slot, what) in crate::descriptor::host::describe_slots(words) {
  8044. text.push_str(&format!(", word {word} slot {slot}: {what}"));
  8045. }
  8046. }
  8047. text
  8048. }
  8049. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  8050. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  8051. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  8052. let to = history[done..]
  8053. .iter()
  8054. .position(barrier)
  8055. .map_or(history.len(), |b| (done + b).max(done + 1));
  8056. let mut text = format!(", commands {from}..{to} between its barriers:");
  8057. let mut shown = 0;
  8058. // From just before the command the GPU had not finished: the first
  8059. // twelve after the barrier named draws long done when a list of 79
  8060. // mesh draws stopped at its 45th (run 41).
  8061. for i in from.max(done.saturating_sub(4))..to {
  8062. let op = history[i];
  8063. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  8064. continue;
  8065. }
  8066. shown += 1;
  8067. let marker = i
  8068. .checked_sub(1)
  8069. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  8070. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  8071. .map_or("no marker", |(_, s)| s.as_str());
  8072. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  8073. }
  8074. text
  8075. }
  8076. pub(crate) fn transition(
  8077. resource: &ID3D12Resource,
  8078. before: D3D12_RESOURCE_STATES,
  8079. after: D3D12_RESOURCE_STATES,
  8080. ) -> D3D12_RESOURCE_BARRIER {
  8081. D3D12_RESOURCE_BARRIER {
  8082. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  8083. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  8084. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  8085. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  8086. // SAFETY: a borrowed pointer; the barrier never releases it.
  8087. pResource: unsafe { std::mem::transmute_copy(resource) },
  8088. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  8089. StateBefore: before,
  8090. StateAfter: after,
  8091. }),
  8092. },
  8093. }
  8094. }
  8095. /// A window of the given client size, owned by its own message thread.
  8096. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  8097. let (sender, receiver) = std::sync::mpsc::channel();
  8098. std::thread::Builder::new()
  8099. .name("victory-window".into())
  8100. .spawn(move || {
  8101. let made = make_window(width, height);
  8102. let ok = made.is_ok();
  8103. let _ = sender.send(made.map(|h| h.0 as usize));
  8104. if ok {
  8105. pump();
  8106. }
  8107. })
  8108. .map_err(|_| windows::core::Error::empty())?;
  8109. let hwnd = receiver
  8110. .recv()
  8111. .map_err(|_| windows::core::Error::empty())??;
  8112. Ok(HWND(hwnd as *mut _))
  8113. }
  8114. extern "system" fn window_proc(
  8115. hwnd: HWND,
  8116. message: u32,
  8117. wparam: WPARAM,
  8118. lparam: LPARAM,
  8119. ) -> LRESULT {
  8120. // SAFETY: the default handling for our window.
  8121. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  8122. }
  8123. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  8124. const CLASS: PCWSTR = w!("VIctory");
  8125. // SAFETY: registers our class once and creates a window of it.
  8126. unsafe {
  8127. let instance = GetModuleHandleW(None)?;
  8128. let class = WNDCLASSEXW {
  8129. cbSize: size_of::<WNDCLASSEXW>() as u32,
  8130. lpfnWndProc: Some(window_proc),
  8131. hInstance: instance.into(),
  8132. lpszClassName: CLASS,
  8133. hCursor: LoadCursorW(None, IDC_ARROW)?,
  8134. ..Default::default()
  8135. };
  8136. RegisterClassExW(&class);
  8137. let mut rect = RECT {
  8138. left: 0,
  8139. top: 0,
  8140. right: width as i32,
  8141. bottom: height as i32,
  8142. };
  8143. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  8144. CreateWindowExW(
  8145. WINDOW_EX_STYLE(0),
  8146. CLASS,
  8147. w!("VIctory"),
  8148. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  8149. CW_USEDEFAULT,
  8150. CW_USEDEFAULT,
  8151. rect.right - rect.left,
  8152. rect.bottom - rect.top,
  8153. None,
  8154. None,
  8155. Some(instance.into()),
  8156. None,
  8157. )
  8158. }
  8159. }
  8160. fn pump() {
  8161. let mut message = MSG::default();
  8162. // SAFETY: the standard message loop of this thread's window.
  8163. unsafe {
  8164. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  8165. let _ = TranslateMessage(&message);
  8166. DispatchMessageW(&message);
  8167. }
  8168. }
  8169. }
  8170. #[cfg(test)]
  8171. mod trail {
  8172. /// The trail keeps the newest things, and the report made when the
  8173. /// host device is removed says them and the pipeline library's state
  8174. /// (no card is asked for any of it).
  8175. #[test]
  8176. fn the_removal_report_says_the_newest_things_done() {
  8177. for n in 0..super::TRAIL_MOST + 5 {
  8178. super::trail(|| format!("thing {n} done"));
  8179. }
  8180. let text = super::removal_context();
  8181. assert!(text.contains("the submitting thread was"));
  8182. assert!(text.contains("pipeline library: no call running"));
  8183. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  8184. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  8185. }
  8186. }
  8187. #[cfg(test)]
  8188. mod spare {
  8189. use super::Spare;
  8190. /// Kept things come back by size, the last given first, and nothing is
  8191. /// kept past the limit.
  8192. #[test]
  8193. fn kept_things_come_back_by_size_within_the_limit() {
  8194. let mut spare: Spare<u32> = Spare::new();
  8195. assert_eq!(spare.take(4), None);
  8196. assert_eq!(spare.give(1, 4, 10), None);
  8197. assert_eq!(spare.give(2, 1, 10), None);
  8198. assert_eq!(spare.give(3, 4, 10), None);
  8199. assert_eq!(spare.bytes, 9);
  8200. // Past the limit: handed back, nothing changes.
  8201. assert_eq!(spare.give(4, 4, 10), Some(4));
  8202. assert_eq!(spare.bytes, 9);
  8203. assert_eq!(spare.take(2), None, "no thing of that size");
  8204. assert_eq!(spare.take(4), Some(3));
  8205. assert_eq!(spare.take(4), Some(1));
  8206. assert_eq!(spare.take(4), None);
  8207. assert_eq!(spare.take(1), Some(2));
  8208. assert_eq!(spare.bytes, 0);
  8209. assert!(spare.kept.is_empty());
  8210. }
  8211. }
  8212. #[cfg(test)]
  8213. mod refresh_tests {
  8214. use super::Batch;
  8215. use crate::shadow::Shadow;
  8216. use std::sync::Arc;
  8217. use windows_sys::Win32::System::Memory::{
  8218. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  8219. VirtualAlloc,
  8220. };
  8221. const PAGE: usize = 64 << 10;
  8222. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  8223. /// Title memory for the tests (never given back: copies of it stay in
  8224. /// the guards): write-watched, or a view of a section.
  8225. fn title(len: usize, view: bool) -> usize {
  8226. // SAFETY: plain allocations.
  8227. let at = unsafe {
  8228. if view {
  8229. let section =
  8230. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  8231. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  8232. // As the runtime tells of it.
  8233. crate::title_memory_section(section as usize, len as u64, true);
  8234. crate::title_memory_remapped(at, len);
  8235. crate::title_memory_view(at, len, section as usize, 0);
  8236. at
  8237. } else {
  8238. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  8239. }
  8240. };
  8241. assert_ne!(at, 0);
  8242. at
  8243. }
  8244. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  8245. /// and every fourth page not there: as a title that streams has it.
  8246. fn with_holes(blocks: usize) -> usize {
  8247. use windows_sys::Win32::System::Memory::{
  8248. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  8249. VirtualAlloc2, VirtualFree,
  8250. };
  8251. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  8252. // SAFETY: a placeholder and a section of our own.
  8253. unsafe {
  8254. let at = VirtualAlloc2(
  8255. GetCurrentProcess(),
  8256. std::ptr::null(),
  8257. blocks * PAGE,
  8258. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  8259. PAGE_NOACCESS,
  8260. std::ptr::null_mut(),
  8261. 0,
  8262. ) as usize;
  8263. assert_ne!(at, 0);
  8264. let len = blocks * PAGE;
  8265. let section =
  8266. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  8267. for block in (0..blocks).filter(|b| b % 4 != 3) {
  8268. let to = at + block * PAGE;
  8269. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  8270. let view = MapViewOfFile3(
  8271. section,
  8272. GetCurrentProcess(),
  8273. to as *const _,
  8274. (block * PAGE) as u64,
  8275. PAGE,
  8276. MEM_REPLACE_PLACEHOLDER,
  8277. PAGE_READWRITE,
  8278. std::ptr::null_mut(),
  8279. 0,
  8280. );
  8281. assert_eq!(view.Value as usize, to);
  8282. crate::title_memory_remapped(to, PAGE);
  8283. }
  8284. at
  8285. }
  8286. }
  8287. fn memory(len: usize) -> *mut u8 {
  8288. // SAFETY: a plain allocation.
  8289. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  8290. }
  8291. struct Random(u64);
  8292. impl Random {
  8293. fn below(&mut self, n: usize) -> usize {
  8294. self.0 ^= self.0 << 13;
  8295. self.0 ^= self.0 >> 7;
  8296. self.0 ^= self.0 << 17;
  8297. (self.0 >> 11) as usize % n
  8298. }
  8299. }
  8300. /// Prepares as a submission does: one asking for all the ranges, the
  8301. /// refreshes in several flushes, the asking's end.
  8302. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  8303. // One at a time, as submissions are.
  8304. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  8305. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  8306. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  8307. crate::watch::ask_once(&asked);
  8308. let mut batch = Batch::default();
  8309. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  8310. for (shadow, at, len) in part {
  8311. batch.add(shadow, *at, *len);
  8312. }
  8313. batch.flush();
  8314. }
  8315. crate::watch::ask_once_end();
  8316. }
  8317. /// Whatever is written where, by the title or by us, and whichever
  8318. /// copies (of both kinds of memory, over one another, none on a page
  8319. /// line) are refreshed in which ranges: a refreshed range holds what
  8320. /// title memory holds.
  8321. #[test]
  8322. fn refreshed_ranges_hold_title_memory() {
  8323. // SAFETY (all blocks): title memory and copies of the test's own,
  8324. // written by this thread and, in `Batch::flush`, by the threads that
  8325. // refresh, which are done when it returns.
  8326. let mut random = Random(0x1234_5678_9ABC_DEF1);
  8327. const LEN: usize = 24 * PAGE;
  8328. let regions = [title(LEN, false), title(LEN, true)];
  8329. let mut copies = Vec::new();
  8330. for &region in &regions {
  8331. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  8332. let data = memory(to - from);
  8333. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  8334. }
  8335. }
  8336. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  8337. for round in 0..600 {
  8338. for _ in 0..random.below(4) {
  8339. let at = regions[random.below(2)] + random.below(LEN - 64);
  8340. let n = 1 + random.below(60);
  8341. if random.below(3) == 0 {
  8342. // What shaders wrote.
  8343. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  8344. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  8345. Shadow::put(at, &was, &now);
  8346. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  8347. continue;
  8348. }
  8349. for i in 0..n {
  8350. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  8351. }
  8352. }
  8353. let mut ranges = Vec::new();
  8354. for (shadow, _) in &copies {
  8355. if random.below(3) == 0 {
  8356. continue;
  8357. }
  8358. let (start, len) = shadow.span();
  8359. let (start, len) = (start as usize, len as usize);
  8360. // Often the range of the time before, as a list's is.
  8361. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  8362. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  8363. ranges.push((shadow.clone(), start + from, n));
  8364. }
  8365. if ranges.is_empty() {
  8366. continue;
  8367. }
  8368. let flushes = 1 + random.below(3);
  8369. submission(&ranges, flushes);
  8370. for (shadow, at, n) in &ranges {
  8371. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  8372. let start = shadow.span().0 as usize;
  8373. let same = unsafe {
  8374. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  8375. };
  8376. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  8377. }
  8378. }
  8379. }
  8380. /// A copy in the card's memory, with the card's side and the sends to it
  8381. /// played by the test.
  8382. struct Carded {
  8383. shadow: Arc<Shadow>,
  8384. data: usize,
  8385. start: usize,
  8386. len: usize,
  8387. /// The last send, the last send every fetch to come is behind, and
  8388. /// the card's bytes: the queue's order is the order it is locked in.
  8389. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  8390. /// Whether a flight that writes it has not landed.
  8391. flying: std::sync::atomic::AtomicBool,
  8392. /// The dword of each eight its shaders write.
  8393. class: usize,
  8394. }
  8395. impl Carded {
  8396. fn new(start: usize, len: usize, class: usize) -> Carded {
  8397. let data = memory(len);
  8398. Carded {
  8399. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  8400. data: data as usize,
  8401. start,
  8402. len,
  8403. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  8404. flying: std::sync::atomic::AtomicBool::new(false),
  8405. class,
  8406. }
  8407. }
  8408. /// What changed on the CPU's side goes up.
  8409. fn send(&self) {
  8410. let mut card = self.card.lock().unwrap();
  8411. card.0 += 1;
  8412. let (number, merged) = (card.0, card.1);
  8413. for (a, b) in self.shadow.send_up(number, merged) {
  8414. // SAFETY: the copy's bytes; nothing writes those that are to
  8415. // go up.
  8416. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  8417. }
  8418. }
  8419. }
  8420. /// Everything at once: the title writes its memory on two threads, the
  8421. /// submitting thread puts its bytes in under shader writes
  8422. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  8423. /// the card's memory, one not), sends up what changed and declares what
  8424. /// the next flight's shaders write, and what flights wrote is landed
  8425. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  8426. /// still and the copies are refreshed once more, each of them, and the
  8427. /// card's side of those that have one, hold what title memory holds, and
  8428. /// title memory what was written last.
  8429. ///
  8430. /// Into the first copy shaders write besides through a view nobody
  8431. /// declared, words the title does not write: nothing that goes up ever
  8432. /// puts an older value over those.
  8433. ///
  8434. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  8435. /// only takes the block out of the guards' clean ones and leaves its bit,
  8436. /// or if a fault leaves the bit; in some thousand rounds,
  8437. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  8438. #[test]
  8439. fn landings_title_writes_and_light_refreshes_at_once() {
  8440. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  8441. assert!(crate::safecopy::on());
  8442. const LEN: usize = 24 * PAGE;
  8443. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  8444. let region = title(LEN, true);
  8445. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  8446. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  8447. let plain = {
  8448. let (start, len) = (region + 700, LEN - 9000);
  8449. let data = memory(len);
  8450. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  8451. };
  8452. // What was last written so, by offset.
  8453. let mut undeclared = std::collections::HashMap::new();
  8454. let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0");
  8455. let stop = AtomicBool::new(false);
  8456. // Also when an assertion fails on one of the threads.
  8457. struct Stop<'a>(&'a AtomicBool);
  8458. impl Drop for Stop<'_> {
  8459. fn drop(&mut self) {
  8460. self.0.store(true, Ordering::Relaxed);
  8461. }
  8462. }
  8463. // Held shared by who writes title memory, alone while it is looked at.
  8464. let still = std::sync::RwLock::new(());
  8465. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  8466. std::thread::scope(|s| {
  8467. for t in 0..2usize {
  8468. let (stop, still) = (&stop, &still);
  8469. s.spawn(move || {
  8470. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  8471. let mut value = 0u32;
  8472. while !stop.load(Ordering::Relaxed) {
  8473. {
  8474. let _moving = still.read().unwrap();
  8475. for _ in 0..3 {
  8476. value += 1;
  8477. // Of each eight dwords, one a thread.
  8478. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  8479. dword(at).store(value, Ordering::Relaxed);
  8480. }
  8481. }
  8482. std::thread::sleep(std::time::Duration::from_micros(20));
  8483. }
  8484. });
  8485. }
  8486. // Lands flights.
  8487. {
  8488. let (carded, stop) = (&carded, &stop);
  8489. s.spawn(move || {
  8490. let _stop = Stop(stop);
  8491. while let Ok((which, ranges, value)) = flights.recv() {
  8492. let c = &carded[which];
  8493. // Fetched: the card's bytes, behind every send so far.
  8494. let (after, now) = {
  8495. let card = c.card.lock().unwrap();
  8496. (card.0, card.2.clone())
  8497. };
  8498. // By piece: 64 KiB of title memory.
  8499. let mut pieces = Vec::new();
  8500. for &(from, to) in &ranges {
  8501. let mut at = from;
  8502. while at < to {
  8503. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  8504. pieces.push((at, next, now.as_ptr() as usize + at));
  8505. at = next;
  8506. }
  8507. }
  8508. let parts: Vec<_> = pieces.chunks(3).collect();
  8509. crate::land::each(parts.len(), &|i| {
  8510. let mut notes = crate::land::Notes::default();
  8511. // SAFETY: the bytes of `now`; each piece once.
  8512. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  8513. notes.flush();
  8514. });
  8515. for &(from, to) in &ranges {
  8516. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8517. // (The next fetch may have brought more.)
  8518. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  8519. }
  8520. }
  8521. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  8522. c.shadow.copy_back_done(&done);
  8523. c.card.lock().unwrap().1 = after;
  8524. c.flying.store(false, Ordering::Release);
  8525. }
  8526. });
  8527. }
  8528. let _stop = Stop(&stop);
  8529. let mut random = Random(0xABCD_EF01_2345_6789);
  8530. let check = |round: usize, random: &mut Random, quiet: bool| {
  8531. for c in &carded {
  8532. if c.shadow.writes_pending() {
  8533. let mut runs = usize::MAX;
  8534. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  8535. }
  8536. }
  8537. let mut ranges = Vec::new();
  8538. for (shadow, start, len) in
  8539. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  8540. {
  8541. // All of it, or a part; often the same part.
  8542. let (from, n) = match random.below(3) {
  8543. _ if quiet => (0, len),
  8544. 0 => (0, len),
  8545. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  8546. _ => {
  8547. let from = random.below(len / 4) * 4;
  8548. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  8549. }
  8550. };
  8551. ranges.push((shadow.clone(), start + from, n));
  8552. }
  8553. submission(&ranges, 1 + random.below(3));
  8554. carded.iter().for_each(Carded::send);
  8555. };
  8556. let mut value = 1u32;
  8557. for round in 0..rounds {
  8558. check(round, &mut random, false);
  8559. if exact {
  8560. let c = &carded[0];
  8561. let mut card = c.card.lock().unwrap();
  8562. for _ in 0..40 {
  8563. value += 1;
  8564. let at = random.below(LEN / 32) * 32 + 4 * 6;
  8565. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8566. undeclared.insert(at, value);
  8567. }
  8568. }
  8569. // The flight of this submission: its shaders' writes.
  8570. for (which, c) in carded.iter().enumerate() {
  8571. if c.flying.swap(true, Ordering::Acquire) {
  8572. continue;
  8573. }
  8574. value += 1;
  8575. let mut ranges: Vec<(usize, usize)> = Vec::new();
  8576. let first = random.below(6) * PAGE / 2;
  8577. for k in 0..2 {
  8578. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  8579. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  8580. if from < to {
  8581. ranges.push((from, to));
  8582. }
  8583. }
  8584. for &(from, to) in &ranges {
  8585. c.shadow.writing(c.start + from, to - from);
  8586. }
  8587. {
  8588. let mut card = c.card.lock().unwrap();
  8589. for &(from, to) in &ranges {
  8590. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8591. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8592. }
  8593. }
  8594. }
  8595. fly.send((which, ranges, value)).unwrap();
  8596. }
  8597. if round % 20 != 19 {
  8598. continue;
  8599. }
  8600. // Still: no flight in the air, no title write.
  8601. let _still = still.write().unwrap();
  8602. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  8603. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  8604. std::thread::yield_now();
  8605. }
  8606. check(round, &mut random, true);
  8607. // SAFETY: the test's own memory, written by nobody now.
  8608. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  8609. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  8610. for c in &carded {
  8611. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  8612. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  8613. let card = c.card.lock().unwrap();
  8614. let mut side = card.2.clone();
  8615. if c.class == carded[0].class {
  8616. // (They may have been landed meanwhile, by a flight
  8617. // that declared their range, and may not.)
  8618. for (&at, &value) in &undeclared {
  8619. let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
  8620. assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
  8621. side[at..at + 4].copy_from_slice(&there[at..at + 4]);
  8622. }
  8623. }
  8624. assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
  8625. }
  8626. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  8627. }
  8628. drop(fly);
  8629. });
  8630. }
  8631. /// The title's bytes put in under shader writes, for a copy of 174 MB
  8632. /// whose shader writes were declared as 40 ranges that overlap, with 12
  8633. /// pages written since. Run with `--ignored --nocapture`, and with
  8634. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8635. #[test]
  8636. #[ignore]
  8637. fn bytes_under_overlapping_ranges() {
  8638. const BIG: usize = 174 << 20;
  8639. let big = title(BIG, true);
  8640. // SAFETY (both): the test's own memory.
  8641. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  8642. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8643. copy.update(big, BIG);
  8644. copy.take_dirty();
  8645. for i in 0..40 {
  8646. copy.writing(big + i * 5920, BIG - i * 5920);
  8647. }
  8648. let mut best = f64::MAX;
  8649. for round in 0..30 {
  8650. for i in 0..12 {
  8651. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  8652. }
  8653. let started = std::time::Instant::now();
  8654. let mut runs = usize::MAX;
  8655. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  8656. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  8657. copy.take_dirty();
  8658. }
  8659. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  8660. }
  8661. /// A range nothing wrote is known to be as it was, at its ends too, and
  8662. /// is so no more once something wrote it.
  8663. #[test]
  8664. fn unchanged_ranges_are_known() {
  8665. for view in [false, true] {
  8666. let region = title(8 * PAGE, view);
  8667. // (A page read for the first time counts as written.)
  8668. // SAFETY: the test's own memory.
  8669. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  8670. let data = memory(8 * PAGE);
  8671. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  8672. // Ends in the middle of pages.
  8673. let (at, len) = (region + 500, 5 * PAGE);
  8674. let look = |expected: bool, what: &str| {
  8675. // The submission's one asking, which takes two ranges. (Again
  8676. // if a submission of another test ended it.)
  8677. let mut known = false;
  8678. for _ in 0..100 {
  8679. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  8680. known = copy.nothing_new(at, len);
  8681. if known || !expected {
  8682. break;
  8683. }
  8684. }
  8685. assert_eq!(known, expected, "view {view}: {what}");
  8686. let copied = copy.update(at, len);
  8687. crate::watch::ask_once_end();
  8688. copied
  8689. };
  8690. assert_eq!(look(false, "never taken"), len);
  8691. assert_eq!(look(true, "taken"), 0);
  8692. assert_eq!(look(true, "taken"), 0);
  8693. // SAFETY: the test's own memory.
  8694. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  8695. // (The kernel names the 4 KiB, the guards only the block.)
  8696. assert_eq!(look(false, "written at its end"), if view { PAGE } else { 4096 } - 500);
  8697. assert_eq!(look(true, "taken again"), 0);
  8698. // Outside the range, on its last page.
  8699. // SAFETY: as above.
  8700. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  8701. assert_eq!(look(false, "written on its last page"), 500);
  8702. // A longer range was never taken whole.
  8703. assert!(!copy.nothing_new(region, 6 * PAGE));
  8704. }
  8705. }
  8706. /// Of a copy in the card's memory only the dwords title memory changed go
  8707. /// up, and none beside them, not even between two in 64 bytes; a page
  8708. /// never taken goes up whole.
  8709. #[test]
  8710. fn only_what_differs_goes_up() {
  8711. let region = title(4 * PAGE, true);
  8712. let data = memory(4 * PAGE);
  8713. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  8714. copy.update(region, 4 * PAGE);
  8715. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  8716. // What the relay does: shader writes into title memory, and into the
  8717. // CPU's side.
  8718. crate::watch::landing(region + PAGE + 640, 64);
  8719. // SAFETY: the test's own memory.
  8720. unsafe {
  8721. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  8722. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  8723. }
  8724. copy.update(region, 4 * PAGE);
  8725. let again = copy.take_dirty();
  8726. // SAFETY: as above.
  8727. unsafe {
  8728. ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
  8729. ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
  8730. ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
  8731. // The value that was there.
  8732. ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
  8733. }
  8734. copy.update(region, 4 * PAGE);
  8735. let written = copy.take_dirty();
  8736. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") {
  8737. assert_eq!(again, []);
  8738. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
  8739. } else {
  8740. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  8741. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  8742. }
  8743. // SAFETY: as above.
  8744. assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
  8745. }
  8746. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  8747. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  8748. /// big copy that 55 landed pieces and 9 title writes opened, while a
  8749. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  8750. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8751. #[test]
  8752. #[ignore]
  8753. fn frame_of_refreshes() {
  8754. let mut random = Random(0x9876_5432_1234_5671);
  8755. const EACH: usize = 224 << 10;
  8756. const BIG: usize = 174 << 20;
  8757. let watched = title(3000 * EACH, false);
  8758. // `VICTORY_BENCH_HOLES=0`: views without holes.
  8759. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  8760. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  8761. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  8762. let big = title(BIG, true);
  8763. // SAFETY: the test's own memory.
  8764. unsafe {
  8765. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  8766. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  8767. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  8768. }
  8769. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  8770. }
  8771. let mut small = Vec::new();
  8772. for i in 0..4400 {
  8773. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  8774. let data = memory(EACH);
  8775. // The range views read, not all of the copy.
  8776. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  8777. }
  8778. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  8779. // The same memory, as another copy: what is landed is landed through
  8780. // it, and the refreshes are of the first.
  8781. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8782. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  8783. let (mut sum, mut landing) = (0.0, 0.0);
  8784. const FRAMES: usize = 12;
  8785. for frame in 0..FRAMES {
  8786. let mut took = [0f64; 2];
  8787. for i in 0..30 {
  8788. // The title's writes, and the relay's beside the submission.
  8789. for _ in 0..9 {
  8790. let at = views + random.below(1400 * EACH / 8) * 8;
  8791. if there(at) {
  8792. // SAFETY: the test's own memory.
  8793. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8794. }
  8795. }
  8796. for _ in 0..60 {
  8797. let at = watched + random.below(3000 * EACH / 8) * 8;
  8798. // SAFETY: the test's own memory.
  8799. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8800. }
  8801. let first = random.below(BIG / PAGE - 60);
  8802. let lands = lands.clone();
  8803. let land = std::thread::spawn(move || {
  8804. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  8805. let started = std::time::Instant::now();
  8806. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  8807. let pieces: Vec<_> =
  8808. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  8809. let mut notes = crate::land::Notes::default();
  8810. // SAFETY: the bytes of `now`; nothing else lands here.
  8811. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  8812. notes.flush();
  8813. }
  8814. started.elapsed().as_secs_f64() * 1e3
  8815. });
  8816. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  8817. small.iter().cloned().chain([heap.clone()]).collect()
  8818. } else {
  8819. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  8820. };
  8821. let started = std::time::Instant::now();
  8822. submission(&ranges, 3);
  8823. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  8824. let put = land.join().unwrap();
  8825. if frame >= 2 {
  8826. landing += put;
  8827. }
  8828. heap.0.take_dirty();
  8829. }
  8830. if frame >= 2 {
  8831. sum += took[0] + took[1];
  8832. for k in 0..2 {
  8833. best[k] = best[k].min(took[k]);
  8834. asking[k] += took[k];
  8835. }
  8836. }
  8837. }
  8838. println!(
  8839. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  8840. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  8841. crate::watch::light(),
  8842. sum / (FRAMES - 2) as f64,
  8843. asking[0] / (FRAMES - 2) as f64,
  8844. best[0],
  8845. asking[1] / (FRAMES - 2) as f64,
  8846. best[1],
  8847. landing / (FRAMES - 2) as f64,
  8848. );
  8849. #[cfg(feature = "diagnostics")]
  8850. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  8851. }
  8852. }
  8853. #[cfg(test)]
  8854. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  8855. use super::Batch;
  8856. use std::sync::Arc;
  8857. #[test]
  8858. fn a_texture_is_checked_once_per_submission() {
  8859. let mut batch = Batch::default();
  8860. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  8861. // The first list sampling each texture checks it ...
  8862. assert!(batch.texture_due(&a));
  8863. assert!(batch.texture_due(&b));
  8864. // ... later lists of the same submission do not.
  8865. assert!(!batch.texture_due(&a));
  8866. assert!(!batch.texture_due(&a.clone()));
  8867. assert!(!batch.texture_due(&b));
  8868. }
  8869. #[test]
  8870. fn title_writes_make_textures_due_again() {
  8871. let mut batch = Batch::default();
  8872. let a = Arc::new(1u32);
  8873. assert!(batch.texture_due(&a));
  8874. assert!(!batch.texture_due(&a));
  8875. // A copy into title memory or work that may write it may have
  8876. // changed the texture's memory.
  8877. batch.title_written();
  8878. assert!(batch.texture_due(&a));
  8879. assert!(!batch.texture_due(&a));
  8880. // A fresh submission starts over.
  8881. let mut next = Batch::default();
  8882. assert!(next.texture_due(&a));
  8883. }
  8884. /// The hashing a submission does for textures in physical-page memory,
  8885. /// with every list checking the textures it samples (before) and with
  8886. /// each checked once (after). Run with
  8887. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  8888. #[test]
  8889. #[ignore = "benchmark"]
  8890. fn texture_checks_per_submission() {
  8891. const TEXTURES: usize = 48;
  8892. const SIZE: usize = 4 << 20;
  8893. const LISTS: usize = 12;
  8894. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  8895. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  8896. .collect();
  8897. let submit = |dedupe: bool| {
  8898. let mut batch = Batch::default();
  8899. let mut hashed = 0usize;
  8900. let started = std::time::Instant::now();
  8901. for _ in 0..LISTS {
  8902. for t in &textures {
  8903. if !dedupe || batch.texture_due(t) {
  8904. std::hint::black_box(blake3::hash(t));
  8905. hashed += 1;
  8906. }
  8907. }
  8908. }
  8909. (started.elapsed(), hashed)
  8910. };
  8911. submit(false); // warm up
  8912. let (before, n_before) = submit(false);
  8913. let (after, n_after) = submit(true);
  8914. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  8915. println!(
  8916. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  8917. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  8918. SIZE >> 20,
  8919. before.as_secs_f64() / after.as_secs_f64()
  8920. );
  8921. }
  8922. #[test]
  8923. fn vram_idle_ms_scales_with_pressure() {
  8924. let vram_idle_ms = |memory| super::vram_idle_for(memory, false);
  8925. let keeps = |memory| super::vram_idle_for(memory, true);
  8926. let gib = 1024 * 1024 * 1024;
  8927. assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000);
  8928. assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000);
  8929. assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500);
  8930. assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000);
  8931. assert_eq!(keeps(None), 5_000);
  8932. // Normal (< 75%)
  8933. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  8934. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  8935. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  8936. // Moderate (75%..85%)
  8937. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  8938. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  8939. // High (>= 85%, including over-budget)
  8940. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  8941. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  8942. // Missing or zero budget falls back to normal
  8943. assert_eq!(vram_idle_ms(None), 5_000);
  8944. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  8945. }
  8946. #[test]
  8947. fn textures_are_kept_while_the_card_has_room() {
  8948. use super::vram_keep;
  8949. let gib = 1 << 30;
  8950. assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000);
  8951. // Past it: the longest idle ones, enough to come down to 85 %.
  8952. let (ms, bytes) = vram_keep(100 * gib, 90 * gib);
  8953. assert_eq!((ms, bytes), (5_000, 5 * gib));
  8954. assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib));
  8955. assert_eq!(vram_keep(0, 7).0, 5_000);
  8956. }
  8957. #[test]
  8958. fn ram_idle_ms_scales_with_pressure() {
  8959. let ram_idle_ms = |avail| super::ram_idle_for(avail, false);
  8960. assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000);
  8961. assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000);
  8962. assert_eq!(super::ram_idle_for(None, true), 10_000);
  8963. let gib = 1024 * 1024 * 1024;
  8964. // Normal (>= 4 GiB)
  8965. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  8966. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  8967. // Moderate (2 GiB..4 GiB)
  8968. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  8969. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  8970. // High (< 2 GiB)
  8971. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  8972. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  8973. // Missing falls back to normal
  8974. assert_eq!(ram_idle_ms(None), 10_000);
  8975. }
  8976. }