host.rs 448 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178
  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<std::collections::VecDeque<(u64, Retired)>> = Mutex::new(std::collections::VecDeque::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. #[allow(dead_code)]
  72. enum Retired {
  73. Any(Box<dyn std::any::Any>),
  74. /// What a descriptor slot showed: 20,000 a frame, without a box each.
  75. Resource(ID3D12Resource),
  76. }
  77. // SAFETY: what is retired is D3D12 objects (free-threaded) and the
  78. // reference-counted wrappers holding them, dropped once.
  79. unsafe impl Send for Retired {}
  80. /// Milliseconds since the first call.
  81. pub(crate) fn now_ms() -> u64 {
  82. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  83. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  84. }
  85. /// [`now_ms`] to the system's tick (16 ms): a few nanoseconds, where the
  86. /// performance counter's are 25. For what is noted tens of thousands of
  87. /// times a frame and read in tenths of a second.
  88. pub(crate) fn coarse_ms() -> u64 {
  89. use windows_sys::Win32::System::SystemInformation::GetTickCount64;
  90. // The same beginning as `now_ms`.
  91. static BEGAN: OnceLock<u64> = OnceLock::new();
  92. // SAFETY: a plain query.
  93. let now = unsafe { GetTickCount64() };
  94. now.saturating_sub(*BEGAN.get_or_init(|| now.saturating_sub(now_ms())))
  95. }
  96. /// This moment, for telling later how long ago it was ([`long_ago`]): the
  97. /// frames begun so far (high half, `crate::frame::current`) and tenths of a
  98. /// second since the start. Host copies of title memory, staging buffers and
  99. /// host textures note when they were last used with it.
  100. pub(crate) fn moment() -> u64 {
  101. (crate::frame::current() << 32) | ((coarse_ms() / 100) & 0xffff_ffff)
  102. }
  103. /// Whether `moment` lies at least `ms` milliseconds and `frames` frames
  104. /// back. Both: at seconds per frame, what every frame uses is not touched
  105. /// for seconds, and at many frames per second not for many frames. (A title
  106. /// that never waits for frames has no frame count: nothing is then idle.)
  107. pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
  108. let now = self::moment();
  109. let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
  110. (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
  111. }
  112. /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
  113. pub(crate) fn available_physical_ram() -> Option<u64> {
  114. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  115. // SAFETY: plain data the call fills in.
  116. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  117. m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
  118. // SAFETY: a sized structure.
  119. let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
  120. ok.then_some(m.ullAvailPhys)
  121. }
  122. /// How long host copies of textures the title fills must have been idle to
  123. /// be let go, in milliseconds, and how many bytes of them go at most (the
  124. /// longest idle first): none but those of ten minutes while what is in use
  125. /// of the card (`used`: without what our own blocks have free, with what is
  126. /// kept free for others) is under 88 % of its budget, else enough to come
  127. /// down to 85 %. `VICTORY_TEXTURE_KEEP=0`: [`vram_idle_ms`]' older rule,
  128. /// all that are idle; `=1`: that rule with its two longer times.
  129. ///
  130. /// (By those times everything idle for 2.5 s went from 75 % of the budget
  131. /// on: 61,000 of them in the first 300 s of session play-1125-0203, at 78 to
  132. /// 80 %, of which 13,000 were made and uploaded again.)
  133. pub(crate) fn vram_keep(budget: u64, used: u64) -> (u64, u64) {
  134. const KEPT_MS: u64 = 600_000;
  135. const IDLE_MS: u64 = 5_000;
  136. const SHORT_MS: u64 = 1_500;
  137. if budget == 0 {
  138. return (IDLE_MS, u64::MAX);
  139. }
  140. let share = |percent: u64| budget / 100 * percent;
  141. if used < share(88) {
  142. (KEPT_MS, u64::MAX)
  143. } else if used < share(95) {
  144. (IDLE_MS, used - share(85))
  145. } else {
  146. (SHORT_MS, used - share(85))
  147. }
  148. }
  149. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  150. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  151. /// handles not yet recorded into a list or slot remain protected.
  152. ///
  153. /// With room on the card nothing has to go: in session play-1125-0127 88,000
  154. /// of them (31 GB) went after 5 s with 7 GB of the card free, and 24,700
  155. /// (12 GB) had to be made and uploaded again.
  156. /// `VICTORY_TEXTURE_KEEP=0`: 5 s there too, as before.
  157. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  158. static KEEP: OnceLock<bool> = OnceLock::new();
  159. let keep = *KEEP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_KEEP").is_none_or(|v| v != "0"));
  160. vram_idle_for(video_memory, keep)
  161. }
  162. fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 {
  163. const KEPT_MS: u64 = 600_000;
  164. const LONG_MS: u64 = 30_000;
  165. const NORMAL_MS: u64 = 5_000;
  166. const MODERATE_MS: u64 = 2_500;
  167. const HIGH_MS: u64 = 1_000;
  168. let Some([budget, used, ..]) = video_memory else {
  169. return NORMAL_MS;
  170. };
  171. if budget == 0 {
  172. return NORMAL_MS;
  173. }
  174. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  175. if used_pct >= 85 {
  176. HIGH_MS
  177. } else if used_pct >= 75 {
  178. MODERATE_MS
  179. } else if !keep {
  180. NORMAL_MS
  181. } else if used_pct >= 68 {
  182. LONG_MS
  183. } else {
  184. KEPT_MS
  185. }
  186. }
  187. /// Whether new memory is made resident, and waited for, before anything can
  188. /// name it (on by default; `VICTORY_WAIT_RESIDENT=0`: as before). A heap or
  189. /// resource of the default kind is resident once it is made, but its
  190. /// mapping into the card's address space is work of the system's that runs
  191. /// later: only lists sent after it wait for it. Lists sent before run on,
  192. /// and read our descriptor heaps as they are: a slot that shows a texture
  193. /// in a new block is a page fault for them until the block is mapped. The
  194. /// device losses of the night of 2026-11-25 were that (run n08: the fault
  195. /// lay in a texture made in the same tenth of a second, in a new block).
  196. fn wait_resident() -> bool {
  197. static ON: OnceLock<bool> = OnceLock::new();
  198. *ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_RESIDENT").is_none_or(|v| v != "0"))
  199. }
  200. /// The flag memory is made with that [`resident`] waits for.
  201. pub(crate) fn not_resident() -> D3D12_HEAP_FLAGS {
  202. if wait_resident() { D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT } else { D3D12_HEAP_FLAG_NONE }
  203. }
  204. /// A queue of its own that new memory is waited for with ([`mapped`]).
  205. struct Aside {
  206. queue: ID3D12CommandQueue,
  207. list: ID3D12CommandList,
  208. fence: ID3D12Fence,
  209. event: windows::Win32::Foundation::HANDLE,
  210. value: u64,
  211. _keep: (ID3D12CommandAllocator, [ID3D12Resource; 2]),
  212. }
  213. // SAFETY: D3D12 objects are free-threaded, the event is waited on by one
  214. // thread at a time (the lock).
  215. unsafe impl Send for Aside {}
  216. /// New memory of the card is mapped into its address space when this
  217. /// returns: a copy of a few bytes is sent to a queue of ours after the
  218. /// memory was made, which the system starts only when all mappings asked
  219. /// for so far are done, and waited for. (`MakeResident` came back before
  220. /// that: run n11 was lost as n08 was with it alone.) Best done off a hot
  221. /// path: a tenth of a millisecond to some.
  222. pub(crate) fn mapped(device: &ID3D12Device) -> windows::core::Result<()> {
  223. static ASIDE: Mutex<Option<Aside>> = Mutex::new(None);
  224. if !wait_resident() {
  225. return Ok(());
  226. }
  227. let started = std::time::Instant::now();
  228. let mut aside = ASIDE.lock().unwrap_or_else(|e| e.into_inner());
  229. // SAFETY: plain object creation; the objects the list names are kept.
  230. unsafe {
  231. if aside.is_none() {
  232. let buffer = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| -> windows::core::Result<ID3D12Resource> {
  233. let mut made: Option<ID3D12Resource> = None;
  234. device.CreateCommittedResource(
  235. &D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() },
  236. D3D12_HEAP_FLAG_NONE,
  237. &D3D12_RESOURCE_DESC {
  238. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  239. Width: 256,
  240. Height: 1,
  241. DepthOrArraySize: 1,
  242. MipLevels: 1,
  243. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  244. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  245. ..Default::default()
  246. },
  247. state,
  248. None,
  249. &mut made,
  250. )?;
  251. made.ok_or_else(windows::core::Error::empty)
  252. };
  253. let from = buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ)?;
  254. let to = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST)?;
  255. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  256. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  257. ..Default::default()
  258. })?;
  259. let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  260. let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  261. list.CopyBufferRegion(&to, 0, &from, 0, 16);
  262. list.Close()?;
  263. *aside = Some(Aside {
  264. queue,
  265. list: list.cast()?,
  266. fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?,
  267. event: CreateEventW(None, false, false, None)?,
  268. value: 0,
  269. _keep: (allocator, [from, to]),
  270. });
  271. }
  272. let Some(a) = aside.as_mut() else { return Ok(()) };
  273. a.queue.ExecuteCommandLists(&[Some(a.list.clone())]);
  274. a.value += 1;
  275. a.queue.Signal(&a.fence, a.value)?;
  276. if a.fence.GetCompletedValue() < a.value {
  277. a.fence.SetEventOnCompletion(a.value, a.event)?;
  278. WaitForSingleObject(a.event, INFINITE);
  279. }
  280. }
  281. let us = started.elapsed().as_micros() as u64;
  282. MAPPED[0].fetch_add(1, Ordering::Relaxed);
  283. MAPPED[1].fetch_add(us, Ordering::Relaxed);
  284. MAPPED[2].fetch_max(us, Ordering::Relaxed);
  285. let n = MAPPED[0].load(Ordering::Relaxed);
  286. if n == 1 || n.is_multiple_of(200) {
  287. tracing::info!(
  288. "new card memory waited for until it is mapped (VICTORY_WAIT_RESIDENT=0: not), since the start: {n} times, {:.1} ms, the longest {:.1} ms",
  289. MAPPED[1].load(Ordering::Relaxed) as f64 / 1000.0,
  290. MAPPED[2].load(Ordering::Relaxed) as f64 / 1000.0
  291. );
  292. }
  293. Ok(())
  294. }
  295. /// Times, microseconds and the longest of [`mapped`].
  296. static MAPPED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  297. /// New memory (made with [`not_resident`]) is resident when this returns.
  298. pub(crate) fn resident(device: &ID3D12Device, object: &impl Interface) -> windows::core::Result<()> {
  299. if !wait_resident() {
  300. return Ok(());
  301. }
  302. let started = std::time::Instant::now();
  303. let object: ID3D12Pageable = object.cast()?;
  304. // SAFETY: a live heap or resource of the device's.
  305. let made = unsafe { device.MakeResident(&[Some(object)]) };
  306. let us = started.elapsed().as_micros() as u64;
  307. RESIDENT[0].fetch_add(1, Ordering::Relaxed);
  308. RESIDENT[1].fetch_add(us, Ordering::Relaxed);
  309. RESIDENT[2].fetch_max(us, Ordering::Relaxed);
  310. static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  311. let n = RESIDENT[0].load(Ordering::Relaxed);
  312. if n >= 1000 * (SAID.load(Ordering::Relaxed) + 1) {
  313. SAID.store(n / 1000, Ordering::Relaxed);
  314. tracing::info!(
  315. "new memory waited for (VICTORY_WAIT_RESIDENT=0: not), since the start: {n} times, {:.1} ms, the longest {:.1} ms",
  316. RESIDENT[1].load(Ordering::Relaxed) as f64 / 1000.0,
  317. RESIDENT[2].load(Ordering::Relaxed) as f64 / 1000.0
  318. );
  319. }
  320. made
  321. }
  322. /// Times, microseconds and the longest of [`resident`].
  323. static RESIDENT: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  324. /// Whether memory the card was given stays with it while there is room (on
  325. /// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader
  326. /// that reads past a view (a raw load through a typed, structured or
  327. /// constant buffer view has no end on AMD: `indirect::tests::raw_loads_past_views`)
  328. /// or through a slot that shows wrong data reads whatever lies there, and
  329. /// nothing happens; where memory was given back it is a page fault, and the
  330. /// device is lost. Both losses of 2026-11-25 were reads in memory given back
  331. /// seconds before (a block of textures; a list's scratch and a window of
  332. /// title memory). Kept are: empty blocks of textures ([`crate::pool`]) below
  333. /// 85 % of the card's budget, windows of title memory and staging buffers
  334. /// for five minutes with 12 GiB of the PC's memory free, and 1 GiB of
  335. /// scratch chunks.
  336. pub(crate) fn keep_freed() -> bool {
  337. static ON: OnceLock<bool> = OnceLock::new();
  338. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_FREED").is_none_or(|v| v != "0"))
  339. }
  340. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  341. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  342. /// when free physical RAM is low. Never returns less than 2,000 ms.
  343. /// With plenty of it five minutes ([`keep_freed`]).
  344. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  345. ram_idle_for(avail_phys, keep_freed())
  346. }
  347. fn ram_idle_for(avail_phys: Option<u64>, keep: bool) -> u64 {
  348. const GIB: u64 = 1024 * 1024 * 1024;
  349. const KEPT_MS: u64 = 300_000;
  350. if keep && avail_phys.is_some_and(|avail| avail >= 12 * GIB) {
  351. return KEPT_MS;
  352. }
  353. const NORMAL_MS: u64 = 10_000;
  354. const MODERATE_MS: u64 = 5_000;
  355. const HIGH_MS: u64 = 2_000;
  356. let Some(avail) = avail_phys else {
  357. return NORMAL_MS;
  358. };
  359. if avail < 2 * GIB {
  360. HIGH_MS
  361. } else if avail < 4 * GIB {
  362. MODERATE_MS
  363. } else {
  364. NORMAL_MS
  365. }
  366. }
  367. /// How many references are held on a host object (its COM count): ours
  368. /// all, since the host's views and commands hold none. A buffer or texture
  369. /// with one is held by its owner alone: no descriptor slot keeps it
  370. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  371. pub(crate) fn references(object: &impl Interface) -> u32 {
  372. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  373. let raw = object.as_raw();
  374. // SAFETY: a live COM object, whose first three methods are those of
  375. // `IUnknown` (query, add a reference, release one); the pair leaves the
  376. // count as it was, and the release returns it. The first is not called.
  377. unsafe {
  378. let methods = *raw.cast::<*const [Method; 3]>();
  379. ((*methods)[1])(raw);
  380. ((*methods)[2])(raw)
  381. }
  382. }
  383. /// Once a second, before a submission starts: lets go of what nothing
  384. /// names any more (copies of windows of title memory, staging buffers,
  385. /// host copies of textures the title fills).
  386. /// `VICTORY_SWEEP=0` keeps everything, as before.
  387. fn sweep() {
  388. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  389. crate::inplace::tick();
  390. static ON: OnceLock<bool> = OnceLock::new();
  391. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  392. return;
  393. }
  394. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  395. let now = now_ms();
  396. let last = LAST.load(Ordering::Relaxed);
  397. if now < last + 1000
  398. || LAST
  399. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  400. .is_err()
  401. {
  402. return;
  403. }
  404. #[cfg(feature = "diagnostics")]
  405. crate::book::check();
  406. crate::pool::room(host().and_then(|h| h.video_memory()));
  407. crate::pipeline::trim_library();
  408. crate::shadow::let_go_idle();
  409. crate::texture::let_go_idle();
  410. crate::resource::let_go_idle();
  411. }
  412. /// The number of the newest submission begun, and of the newest of which all
  413. /// before it have finished too.
  414. pub(crate) fn submissions() -> (u64, u64) {
  415. (STARTED.load(Ordering::Acquire), FINISHED.load(Ordering::Acquire))
  416. }
  417. /// Drops `object` once every submission running now has finished: at once
  418. /// if none is.
  419. pub(crate) fn retire<T: 'static>(object: T) {
  420. // (Those the title made and the host has not begun get the next numbers.)
  421. let queued = crate::queue::queued();
  422. let started = STARTED.load(Ordering::Acquire) + queued;
  423. if bury_lag() == 0 && started <= FINISHED.load(Ordering::Acquire) {
  424. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  425. drop(object);
  426. return;
  427. }
  428. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  429. RETIRED
  430. .lock()
  431. .unwrap_or_else(|e| e.into_inner())
  432. .push_back((started, Retired::Any(Box::new(object))));
  433. }
  434. /// [`retire`] for a resource.
  435. pub(crate) fn retire_resource(object: ID3D12Resource) {
  436. let queued = crate::queue::queued();
  437. let started = STARTED.load(Ordering::Acquire) + queued;
  438. if bury_lag() == 0 && started <= FINISHED.load(Ordering::Acquire) {
  439. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  440. drop(object);
  441. return;
  442. }
  443. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  444. RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object)));
  445. }
  446. /// How many submissions later than it could (the last one that may use it
  447. /// has finished) an object let go is dropped, and a host list that has run
  448. /// is reset, about two frames: the device losses of the night of 2026-11-25
  449. /// were page faults in memory nothing of ours named any more, at no command
  450. /// in particular. Objects let go while nothing runs wait as well: lists
  451. /// recorded and not yet sent may name them. `VICTORY_BURY_LAG=0`: not.
  452. fn bury_lag() -> u64 {
  453. static LAG: OnceLock<u64> = OnceLock::new();
  454. *LAG.get_or_init(|| std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(64))
  455. }
  456. /// Drops what waited for submissions up to `finished` ([`bury_lag`]). The
  457. /// numbers come in order, but for threads that overtake each other: one of
  458. /// those is dropped a little later than it could be.
  459. fn bury(finished: u64) {
  460. let finished = finished.saturating_sub(bury_lag());
  461. let done: Vec<(u64, Retired)> = {
  462. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  463. let n = retired.iter().take_while(|(at, _)| *at <= finished).count();
  464. if n == 0 {
  465. return;
  466. }
  467. retired.drain(..n).collect()
  468. };
  469. drop(done);
  470. }
  471. /// Objects [`retire`] dropped at once (no submission was running) and
  472. /// kept until a running submission finished, since the start.
  473. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  474. /// What the layer did to the host's objects lately, newest last (sweeps
  475. /// that let host copies go, pipeline library calls, saves and trims): said
  476. /// once when the host device is removed ([`log_removal_context`]), with
  477. /// what the submitting thread and the pipeline workers were doing at that
  478. /// moment. A device the driver removes "internally" names no command, and
  479. /// the pass that happens to notice first names only the view it was at:
  480. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  481. /// pipeline library call that no line of the log tied to them.
  482. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  483. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  484. /// The entries kept.
  485. const TRAIL_MOST: usize = 96;
  486. fn trail_on() -> bool {
  487. static ON: OnceLock<bool> = OnceLock::new();
  488. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  489. }
  490. /// Microseconds since the first call.
  491. pub(crate) fn now_us() -> u64 {
  492. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  493. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  494. }
  495. /// The calling thread, as the log's other lines name threads.
  496. pub(crate) fn thread_id() -> u32 {
  497. // SAFETY: a plain query.
  498. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  499. }
  500. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  501. /// run when the trail is kept.
  502. pub(crate) fn trail(what: impl FnOnce() -> String) {
  503. if !trail_on() {
  504. return;
  505. }
  506. let entry = (now_us(), thread_id(), what());
  507. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  508. if trail.len() >= TRAIL_MOST {
  509. trail.pop_front();
  510. }
  511. trail.push_back(entry);
  512. }
  513. /// What the submitting thread is doing (0 nothing: between submissions,
  514. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  515. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  516. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  517. fn submitting(phase: u64, lists: usize) {
  518. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  519. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  520. SUBMITTING[0].store(phase, Ordering::Relaxed);
  521. }
  522. /// What was going on when the host device went: whether a submission was
  523. /// on the card, the pipeline library's state and the calls running in it,
  524. /// and the trail.
  525. pub(crate) fn removal_context() -> String {
  526. use std::fmt::Write;
  527. let now = now_us();
  528. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  529. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  530. 0 => "between submissions (nothing of ours was running on the card)",
  531. 1 => "preparing a submission (nothing of ours was running on the card)",
  532. 2 => "waiting for the card to run a submission",
  533. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  534. };
  535. let mut text = format!(
  536. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  537. SUBMITTING[1].load(Ordering::Relaxed),
  538. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  539. crate::pipeline::library_removal_note(),
  540. RETIREMENTS[0].load(Ordering::Relaxed),
  541. RETIREMENTS[1].load(Ordering::Relaxed),
  542. STARTED.load(Ordering::Relaxed),
  543. FINISHED.load(Ordering::Relaxed),
  544. );
  545. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  546. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  547. for (at, thread, what) in trail.iter() {
  548. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  549. }
  550. text
  551. }
  552. /// Says [`removal_context`] in the log, once: called by whoever finds the
  553. /// host device removed.
  554. pub(crate) fn log_removal_context() {
  555. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  556. if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) {
  557. return;
  558. }
  559. tracing::error!("when the host device went: {}", removal_context());
  560. if dred_any() {
  561. let data = host().map(|h| h.removal_data(&[])).unwrap_or_default();
  562. tracing::error!("device-removed data{}", if data.is_empty() { "; none" } else { &data });
  563. }
  564. }
  565. /// Time spent in submissions since the last frame-rate line, in
  566. /// microseconds: preparing them on the CPU (title memory copies, texture
  567. /// detiling), then waiting for the GPU.
  568. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  569. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  570. /// After submissions: shader-written ranges compared and copied back into
  571. /// title memory (microseconds, bytes that differed), since the last
  572. /// frame-rate line.
  573. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  574. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  575. /// The card's clock, for the frame line of every run, in microseconds since
  576. /// the last one: how long the card had nothing of ours queued; how much of
  577. /// that while the thread that holds the submission lock was working (the
  578. /// card idle behind us: preparing and copying back are done with the card
  579. /// standing); and how long that thread stood waiting for the card.
  580. ///
  581. /// Every send of lists to the queue is followed by a signal on a fence of
  582. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  583. /// the newest signal and notes the moment the card reached it with nothing
  584. /// newer sent; the next send ends that idle stretch.
  585. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  586. /// Of the thread that holds the submission lock: the microseconds it has
  587. /// worked so far (preparing, copying back; not its waits for the card), and
  588. /// since when it works now ([`now_us`] plus one; 0: it does not).
  589. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  590. /// The thread that holds the submission lock starts (`on`) or stops
  591. /// working; whether it worked until now.
  592. fn working(on: bool) -> bool {
  593. let now = now_us() + 1;
  594. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  595. if since != 0 {
  596. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  597. }
  598. since != 0
  599. }
  600. /// [`WORKING`] as of now: microseconds worked so far.
  601. fn worked() -> u64 {
  602. let since = WORKING[1].load(Ordering::Relaxed);
  603. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  604. WORKING[0].load(Ordering::Relaxed) + now
  605. }
  606. /// The thread that holds the submission lock stood waiting for the card
  607. /// from `since` until now ([`CARD_CLOCK_US`]).
  608. fn stood(since: std::time::Instant) {
  609. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  610. }
  611. /// What [`CARD_CLOCK_US`] is measured with.
  612. struct CardClock {
  613. fence: ID3D12Fence,
  614. /// Signals sent so far; and, while the card has reached the last of
  615. /// them, since when and what [`worked`] said then.
  616. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  617. sent: std::sync::Condvar,
  618. }
  619. // SAFETY: a fence (free-threaded) behind a lock.
  620. unsafe impl Send for CardClock {}
  621. // SAFETY: as above.
  622. unsafe impl Sync for CardClock {}
  623. /// The clock's thread: waits for the newest signal sent and notes when the
  624. /// card got there with nothing newer behind it.
  625. fn card_clock_watch(clock: &'static CardClock) {
  626. // SAFETY: a plain event of our own.
  627. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  628. return;
  629. };
  630. let mut seen = 0;
  631. loop {
  632. let target = {
  633. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  634. while state.0 == seen {
  635. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  636. }
  637. state.0
  638. };
  639. // SAFETY: the clock's fence and this thread's event.
  640. unsafe {
  641. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  642. WaitForSingleObject(event, INFINITE);
  643. }
  644. }
  645. seen = target;
  646. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  647. if state.0 == target && state.1.is_none() {
  648. state.1 = Some((std::time::Instant::now(), worked()));
  649. }
  650. }
  651. }
  652. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  653. /// frame's time.
  654. fn card_clock_line(frames: f64, ms: f64) {
  655. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  656. tracing::info!(
  657. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  658. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  659. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  660. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  661. );
  662. }
  663. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  664. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  665. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  666. std::sync::atomic::AtomicU64::new(0),
  667. std::sync::atomic::AtomicU64::new(0),
  668. std::sync::atomic::AtomicU64::new(0),
  669. std::sync::atomic::AtomicU64::new(0),
  670. ];
  671. /// Host buffers made since the start, as (count, bytes): in the upload heap
  672. /// (staging, list scratch), shared with the processor (host copies of title
  673. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  674. /// For the memory line: against what is alive, they show what was let go.
  675. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  676. /// What of that is alive now, for the memory line (`MADE` counts what was
  677. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  678. /// and nothing said how many were alive): host lists; the lists' scratch
  679. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  680. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  681. /// instead of made, since the start; and the lists' other upload buffers
  682. /// (texture data copied from buffers, scratch too big for a chunk) and
  683. /// their bytes.
  684. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  685. /// About host lists, for the memory line: lists made by the host since the
  686. /// start; preludes made (a list's second allocator and list, made when it
  687. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  688. /// bytes the process's private memory grew by while lists were being made
  689. /// (what a list costs: host objects with the driver's command memory; 631
  690. /// lists were alive in run 65, each with a prelude it may never use).
  691. /// Then the lists alive that were never reset since they were made: the
  692. /// host sides of title lists the title made and has not used (a host list
  693. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  694. /// makes at its start).
  695. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  696. /// The process's private bytes (diagnostics: around the making of lists).
  697. #[cfg(feature = "diagnostics")]
  698. fn private_bytes() -> u64 {
  699. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  700. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  701. let mut c = PROCESS_MEMORY_COUNTERS {
  702. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  703. ..Default::default()
  704. };
  705. // SAFETY: our own process and a sized structure.
  706. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  707. c.PagefileUsage as u64
  708. }
  709. /// What the runtime does when the host GPU fails for good: report it like a
  710. /// crash and end the run. The console has no such state, and carrying on
  711. /// draws nothing at seconds per frame.
  712. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  713. /// Sets what a host GPU failure does (the runtime's crash report).
  714. pub fn on_failure(report: fn(&str) -> !) {
  715. let _ = ON_FAILURE.set(report);
  716. }
  717. /// Ends the run on a host GPU failure: what failed, the removal reason and
  718. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  719. /// diagnostics build names the command).
  720. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  721. let mut text = what.to_string();
  722. if let Some(host) = host() {
  723. // SAFETY: a plain query.
  724. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  725. text.push_str(&format!("; device removed: {e}"));
  726. log_removal_context();
  727. }
  728. match host.log_messages() {
  729. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  730. None if host.messages.is_none() => text.push_str(
  731. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  732. ),
  733. None => {}
  734. }
  735. }
  736. tracing::error!("{text}");
  737. // Tests have no log: the reason goes to their output.
  738. #[cfg(test)]
  739. eprintln!("host GPU failure: {text}");
  740. match ON_FAILURE.get() {
  741. Some(report) => report(&text),
  742. None => std::process::abort(),
  743. }
  744. }
  745. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  746. /// The host GPU if it is made already.
  747. #[cfg(feature = "diagnostics")]
  748. pub(crate) fn made_host() -> Option<&'static Host> {
  749. HOST.get()?.as_ref()
  750. }
  751. /// The host GPU, created on first use; `None` without one (a run then
  752. /// behaves as before: nothing executes).
  753. pub(crate) fn host() -> Option<&'static Host> {
  754. HOST.get_or_init(|| match create() {
  755. Ok(host) => Some(host),
  756. Err(e) => {
  757. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  758. None
  759. }
  760. })
  761. .as_ref()
  762. }
  763. fn create() -> windows::core::Result<Host> {
  764. // SAFETY: plain D3D12 object creation with valid descriptions.
  765. unsafe {
  766. // The debug layer only in builds with diagnostics.
  767. let debug = cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DEBUG");
  768. if debug {
  769. let mut layer: Option<ID3D12Debug> = None;
  770. match D3D12GetDebugInterface(&mut layer) {
  771. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  772. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  773. }
  774. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  775. // descriptor heap indices and the like become messages naming
  776. // the command instead of page faults. Without state tracking
  777. // (directly indexed textures are not transitioned).
  778. if crate::switch::on("VICTORY_D3D12_GBV")
  779. && let Some(l) = &layer
  780. {
  781. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  782. d1.SetEnableGPUBasedValidation(true);
  783. }
  784. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  785. d2.SetGPUBasedValidationFlags(
  786. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  787. );
  788. }
  789. tracing::info!("GPU-based validation on");
  790. }
  791. }
  792. // Diagnostics: device-removed data (the command that faulted, the
  793. // faulting address), read when the device is removed.
  794. if dred_any() {
  795. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  796. if D3D12GetDebugInterface(&mut dred).is_ok()
  797. && let Some(dred) = dred
  798. {
  799. if dred_on() || dred_light() {
  800. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  801. }
  802. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  803. tracing::info!(
  804. breadcrumbs = dred_on() || dred_light(),
  805. markers = dred_on(),
  806. "crash tracing on (device-removed data)"
  807. );
  808. } else {
  809. tracing::warn!("crash tracing asked for and not there: no device-removed data settings");
  810. }
  811. }
  812. let mut device: Option<ID3D12Device> = None;
  813. // Diagnostics: the software adapter, on which a shader's wild access
  814. // is an access violation in this process (a crash report with the
  815. // address and instruction) instead of a GPU fault and driver reset.
  816. if cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_WARP") {
  817. let adapter = warp_adapter()?;
  818. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  819. tracing::info!("host device on the software adapter (WARP)");
  820. } else {
  821. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  822. // Whether a GPU hang ends the run or freezes the PC (#1054).
  823. crate::tdr::log();
  824. }
  825. let device = device.ok_or_else(windows::core::Error::empty)?;
  826. // Before anything is made with it (`VICTORY_RECORD`).
  827. #[cfg(feature = "diagnostics")]
  828. crate::replay::record::from_env(&device);
  829. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  830. // driver compiling shaders again on the "D3D Background Thread"s,
  831. // for minutes after pipelines were made or loaded) is switched off.
  832. // An experiment: while those threads ran, the same shot took
  833. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  834. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  835. // whether the card is slower with the shaders it then keeps is not
  836. // known.
  837. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  838. && let Ok(device6) = device.cast::<ID3D12Device6>()
  839. {
  840. let set = device6.SetBackgroundProcessingMode(
  841. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  842. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  843. None,
  844. None,
  845. );
  846. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  847. }
  848. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  849. // cross-lane code stays in 32-lane halves translated for waves of 32
  850. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  851. if device
  852. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  853. .is_ok()
  854. {
  855. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  856. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  857. // (RDNA has waves of 32 and 64, the vendor's older cards of 64 alone.)
  858. let amd = crate::indirect::amd(&device);
  859. victory_shader::emit::set_host_rdna(amd && o1.WaveLaneCountMin == 32 && o1.WaveLaneCountMax == 64);
  860. }
  861. let messages = debug
  862. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  863. .flatten();
  864. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  865. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  866. ..Default::default()
  867. })?;
  868. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  869. let event = CreateEventW(None, false, false, None)?;
  870. let rtvs: ID3D12DescriptorHeap =
  871. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  872. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  873. NumDescriptors: RTV_RING,
  874. ..Default::default()
  875. })?;
  876. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  877. let dsvs: ID3D12DescriptorHeap =
  878. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  879. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  880. NumDescriptors: RTV_RING,
  881. ..Default::default()
  882. })?;
  883. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  884. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  885. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  886. .ok();
  887. tracing::info!("host D3D12 device ready");
  888. Ok(Host {
  889. device,
  890. queue,
  891. fence,
  892. submitted: Mutex::new(0),
  893. event,
  894. rtvs,
  895. rtv_size,
  896. dsvs,
  897. dsv_size,
  898. next_dsv: AtomicU32::new(0),
  899. messages,
  900. next_rtv: AtomicU32::new(0),
  901. presenter: Mutex::new(None),
  902. adapter,
  903. })
  904. }
  905. }
  906. impl Host {
  907. /// The driver's version, as the system counts it (0: not known).
  908. pub(crate) fn driver(&self) -> i64 {
  909. let adapter = self.adapter.as_ref();
  910. // SAFETY: a plain query.
  911. adapter.map_or(0, |a| unsafe { a.CheckInterfaceSupport(&IDXGIDevice::IID) }.unwrap_or(0))
  912. }
  913. }
  914. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  915. /// Reject it before creating a device in diagnostics' software-only mode.
  916. pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  917. // SAFETY: plain DXGI adapter queries.
  918. unsafe {
  919. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  920. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  921. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  922. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  923. tracing::warn!(
  924. vendor = format_args!("{:#x}", desc.VendorId),
  925. flags = format_args!("{:#x}", desc.Flags),
  926. "DXGI did not identify the WARP adapter as software; refusing device"
  927. );
  928. return Err(windows::core::Error::from_hresult(
  929. windows::Win32::Foundation::E_FAIL,
  930. ));
  931. }
  932. Ok(adapter)
  933. }
  934. }
  935. #[cfg(test)]
  936. mod tests {
  937. /// A list of ours is found by its name, with the debug layer's note or not.
  938. #[cfg(feature = "diagnostics")]
  939. #[test]
  940. fn a_list_is_found_by_the_number_in_its_name() {
  941. assert_eq!(super::list_number("victory host list 7"), Some(7));
  942. assert_eq!(super::list_number("victory host list 158 (debug layer indirect)"), Some(158));
  943. assert_eq!(super::list_number("victory host list 7x"), None);
  944. assert_eq!(super::list_number("victory host list 7 x"), None);
  945. assert_eq!(super::list_number("another list 7"), None);
  946. assert_eq!(super::list_number(""), None);
  947. }
  948. /// What is there of a range some of whose pages are not: those bytes,
  949. /// counted, and zeros for the rest, whatever the buffer held.
  950. #[test]
  951. fn what_is_there_is_read_and_the_rest_is_zeros() {
  952. use windows_sys::Win32::System::Memory::*;
  953. const SIZE: usize = 0x8_0000;
  954. // SAFETY: a reservation of ours; only committed pages are written.
  955. unsafe {
  956. let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  957. assert!(!at.is_null());
  958. // 0-0x1_1000 and 0x3_0000-0x4_0000 are there.
  959. for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] {
  960. assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null());
  961. at.add(from).write_bytes(0x5a, len);
  962. }
  963. // From an address inside a page, as textures are packed.
  964. let mut out = vec![0x77u8; SIZE - 0x300];
  965. assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000);
  966. for (i, &b) in out.iter().enumerate() {
  967. let from = i + 0x300;
  968. let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from);
  969. assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}");
  970. }
  971. // All there: one read.
  972. let mut out = vec![0x77u8; 0x1_0000];
  973. assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000);
  974. assert!(out.iter().all(|&b| b == 0x5a));
  975. // Nothing there.
  976. let mut out = vec![0x77u8; 0x1_0000];
  977. assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0);
  978. assert!(out.iter().all(|&b| b == 0));
  979. assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0);
  980. }
  981. }
  982. /// Zeros for a title destination that went meanwhile are no fault.
  983. #[test]
  984. fn zeros_where_nothing_is_are_lost() {
  985. use windows_sys::Win32::System::Memory::*;
  986. // SAFETY: a reservation of ours, its first page committed.
  987. unsafe {
  988. let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  989. assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
  990. at.write_bytes(7, 4096);
  991. super::zero(at, 4096);
  992. assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
  993. super::zero(at.add(4096), 4096);
  994. VirtualFree(at.cast(), 0, MEM_RELEASE);
  995. }
  996. }
  997. #[test]
  998. fn sparse_copies_preserve_islands_and_observe_remaps() {
  999. use windows_sys::Win32::System::Memory::*;
  1000. const N: usize = 5 << 16;
  1001. // SAFETY: we reserve a private region, commit selected pages inside it,
  1002. // and only directly access the pages while they are writable.
  1003. unsafe {
  1004. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  1005. assert!(!base.is_null());
  1006. let mut expected = vec![0; N];
  1007. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  1008. let at = base.add(offset);
  1009. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  1010. at.write_bytes(value, 4096);
  1011. expected[offset..offset + 4096].fill(value);
  1012. }
  1013. for remap in [false, true] {
  1014. if remap {
  1015. let mut old = 0;
  1016. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  1017. expected[..4096].fill(0);
  1018. let at = base.add(1 << 16);
  1019. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  1020. at.write_bytes(0xc7, 4096);
  1021. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  1022. }
  1023. let mut out = vec![0xee; N];
  1024. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  1025. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  1026. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  1027. }
  1028. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  1029. }
  1030. }
  1031. use super::*;
  1032. #[test]
  1033. fn warp_adapter_accepts_only_software() {
  1034. // This probes DXGI without creating a D3D12 device or running a title.
  1035. // SAFETY: plain DXGI adapter queries.
  1036. let raw = unsafe {
  1037. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  1038. else {
  1039. return;
  1040. };
  1041. factory.EnumWarpAdapter::<IDXGIAdapter>()
  1042. };
  1043. let Ok(raw) = raw else { return };
  1044. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  1045. // IDXGIAdapter1; `raw` owns that interface.
  1046. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  1047. eprintln!(
  1048. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  1049. desc.VendorId, desc.Flags
  1050. );
  1051. assert_eq!(
  1052. warp_adapter().is_ok(),
  1053. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  1054. );
  1055. }
  1056. }
  1057. /// The batches of clamped records in one scratch buffer
  1058. /// ([`HostList::batch_place`]).
  1059. const BATCHES: u32 = 8;
  1060. /// A host command list and its allocator, always used together.
  1061. pub(crate) struct HostList {
  1062. allocator: ID3D12CommandAllocator,
  1063. pub(crate) list: ID3D12GraphicsCommandList,
  1064. /// Work for submission time, in recorded order.
  1065. deferred: Mutex<Deferred>,
  1066. /// Upload memory for data the list's draws make (expanded vertices),
  1067. /// reused after a reset.
  1068. scratch: Mutex<Scratch>,
  1069. /// Host texture states the list assumes, by host copy: at its start and
  1070. /// at its end. Lists are recorded on many threads and run in submission
  1071. /// order, so the transitions from a texture's real state are made at
  1072. /// submission, in `prelude`. Holding the copies keeps every texture the
  1073. /// list names alive until it is reset, even if the title releases the
  1074. /// resource first.
  1075. states: Mutex<States>,
  1076. /// What the list does with depth textures that have a colour twin, by
  1077. /// twin ([`TwinUse`]).
  1078. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  1079. /// The list that runs those transitions just before this one, made
  1080. /// when the list first has such transitions ([`lazy_prelude`]).
  1081. prelude: OnceLock<Option<Prelude>>,
  1082. /// The pipelines the list binds, for reports of slow submissions.
  1083. pipelines: std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>,
  1084. /// What its indirect executions ran, for the report of a removed device.
  1085. #[cfg(feature = "diagnostics")]
  1086. indirects: indirects::Shared,
  1087. /// The work its indirect executions may still do (`indirect`): a
  1088. /// shader-writable word, zeroed when the list is submitted, and after
  1089. /// it what the clamp notes about mesh records. In memory the CPU maps.
  1090. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  1091. /// The same words in the card's own memory ([`card_budget`]), which the
  1092. /// clamp uses instead when there is one: zeroed in the list before its
  1093. /// first clamp, its notes copied to `budget` when the list closes.
  1094. card_budget: OnceLock<Option<ID3D12Resource>>,
  1095. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  1096. /// grown to the largest indirect execution recorded on the list.
  1097. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  1098. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  1099. /// how many batches of this recording have a place in them.
  1100. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  1101. /// Refreshes of host copies that a thread of ours is still finding, and
  1102. /// where among the list's steps they belong ([`aside`]).
  1103. coming: Mutex<Option<(usize, std::sync::Arc<aside::Coming>)>>,
  1104. /// Another number each time something changes that what a draw reads
  1105. /// depends on ([`HostList::changed_something`]); no two lists have the
  1106. /// same.
  1107. epoch: std::sync::atomic::AtomicU64,
  1108. /// Counts the list in [`ALIVE`] while it lives.
  1109. _alive: Counted,
  1110. /// The texts of the markers `note_op` set, in order (for device-removed
  1111. /// data without marker texts), with the host GPU range a copy reads.
  1112. #[cfg(feature = "diagnostics")]
  1113. notes: std::sync::Arc<Mutex<Vec<Note>>>,
  1114. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  1115. /// and at the end, and where they are read back.
  1116. #[cfg(feature = "diagnostics")]
  1117. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  1118. }
  1119. /// A list's prelude: an allocator and a closed list.
  1120. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  1121. /// Whether a host list's prelude is made when the list first needs one. A
  1122. /// prelude runs the texture transitions and twin copies a list needs before
  1123. /// it; lists that name no texture never have one, and every host list was
  1124. /// made with one all the same: twice the host objects per list, for the
  1125. /// title's 630 lists and for every list made anew.
  1126. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  1127. fn lazy_prelude() -> bool {
  1128. static ON: OnceLock<bool> = OnceLock::new();
  1129. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  1130. }
  1131. /// Timestamps per list (diagnostics); commands past them are not timed.
  1132. #[cfg(feature = "diagnostics")]
  1133. const STAMPS: u32 = 4096;
  1134. /// A marker's text and the host range its command reads (diagnostics).
  1135. #[cfg(feature = "diagnostics")]
  1136. type Note = (String, Option<(u64, u64)>);
  1137. type States = std::collections::HashMap<
  1138. usize,
  1139. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  1140. >;
  1141. /// What a list does with a depth texture that has a colour twin
  1142. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  1143. /// in submission order, so a list cannot know which side an earlier list
  1144. /// leaves behind: it notes which sides it uses as it finds them, and its
  1145. /// prelude copies one side into the other at submission if that side is
  1146. /// behind then. From its first use of a side on, the list knows.
  1147. struct TwinUse {
  1148. /// The depth texture (the title resource's host copy) and its twin.
  1149. depth: std::sync::Arc<crate::resource::HostTexture>,
  1150. twin: std::sync::Arc<crate::resource::Twin>,
  1151. /// The sides (depth texture, twin) the list uses as it finds them.
  1152. needs: [bool; 2],
  1153. /// Whether each side lacks what the other was written last, where the
  1154. /// list is now; `None`: as the list found it.
  1155. behind: [Option<bool>; 2],
  1156. /// The draw or dispatch being prepared writes the twin.
  1157. writing: bool,
  1158. /// The depth plane's twin holds what the plane lacks although the list
  1159. /// copied the twins since: the plane's pass waits for the list's close.
  1160. late: bool,
  1161. }
  1162. /// The pass that draws the twin of a depth plane into the plane: one
  1163. /// triangle over each mip of each slice, its pixel shader writing the
  1164. /// twin's texel as the depth, with the depth test "always" and no stencil
  1165. /// (the stencil plane is copied through a buffer and not touched here).
  1166. ///
  1167. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  1168. /// the step times the float nearest 1/65535 (0x37800080). That is how
  1169. /// The title's tiled lighting computes the depth of the
  1170. /// rectangles it then draws with the test "equal", one class of materials
  1171. /// a draw (all six of its vertex shaders multiply the class number by that
  1172. /// constant), so the pass and the draw give the host the same float, and
  1173. /// the host turns the same float into the same 24 bits. The step divided
  1174. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  1175. /// and lands in another 24-bit step for 127 of them (none under 385).
  1176. const PLANE_CORNERS: &str = r#"
  1177. float4 corner(uint i : SV_VertexID) : SV_Position {
  1178. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  1179. }
  1180. "#;
  1181. const PLANE_STEPS: &str = r#"
  1182. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  1183. Texture2DArray<uint> twin : register(t0);
  1184. [RootSignature(RS)]
  1185. float plane(float4 p : SV_Position) : SV_Depth {
  1186. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  1187. }
  1188. "#;
  1189. const PLANE_FLOATS: &str = r#"
  1190. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  1191. Texture2DArray<float> twin : register(t0);
  1192. [RootSignature(RS)]
  1193. float plane(float4 p : SV_Position) : SV_Depth {
  1194. return twin.Load(int4(int2(p.xy), 0, 0));
  1195. }
  1196. "#;
  1197. /// Views of twins the pass reads, in a heap of ours used as a ring.
  1198. /// shortcut: a view must last until its list has run; with one or two
  1199. /// passes a frame the ring is far from coming round.
  1200. const PLANE_VIEWS: u32 = 256;
  1201. /// What the pass draws with: the heap of its views of twins, and per kind
  1202. /// of twin (16-bit steps or floats) and depth format the root signature
  1203. /// and pipeline, made when first needed (`None`: the host refused).
  1204. struct PlanePass {
  1205. views: ID3D12DescriptorHeap,
  1206. cpu: usize,
  1207. gpu: u64,
  1208. step: u32,
  1209. next: AtomicU32,
  1210. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  1211. }
  1212. /// The pass's root signature and pipeline for one kind of twin and one
  1213. /// depth format.
  1214. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  1215. // SAFETY: D3D12 objects are free-threaded.
  1216. unsafe impl Send for PlanePass {}
  1217. // SAFETY: as above.
  1218. unsafe impl Sync for PlanePass {}
  1219. fn plane_pass() -> Option<&'static PlanePass> {
  1220. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  1221. PASS.get_or_init(|| {
  1222. let host = host()?;
  1223. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1224. // SAFETY: plain heap creation and queries.
  1225. unsafe {
  1226. let views: ID3D12DescriptorHeap = host
  1227. .device
  1228. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  1229. Type: kind,
  1230. NumDescriptors: PLANE_VIEWS,
  1231. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  1232. NodeMask: 0,
  1233. })
  1234. .ok()?;
  1235. Some(PlanePass {
  1236. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  1237. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  1238. step: host.device.GetDescriptorHandleIncrementSize(kind),
  1239. views,
  1240. next: AtomicU32::new(0),
  1241. made: Mutex::default(),
  1242. })
  1243. }
  1244. })
  1245. .as_ref()
  1246. }
  1247. /// Compiles function `entry` of `source` for `target` with the system's
  1248. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  1249. pub(crate) fn compile(
  1250. source: &str,
  1251. entry: windows::core::PCSTR,
  1252. target: windows::core::PCSTR,
  1253. ) -> windows::core::Result<Vec<u8>> {
  1254. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  1255. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  1256. let mut code: Option<ID3DBlob> = None;
  1257. let mut errors: Option<ID3DBlob> = None;
  1258. // SAFETY: the source and names live through the call; out pointers ours.
  1259. let compiled = unsafe {
  1260. D3DCompile(
  1261. source.as_ptr().cast(),
  1262. source.len(),
  1263. windows::core::s!("victory"),
  1264. None,
  1265. None,
  1266. entry,
  1267. target,
  1268. 0,
  1269. 0,
  1270. &mut code,
  1271. Some(&mut errors),
  1272. )
  1273. };
  1274. if let Err(e) = compiled {
  1275. if let Some(errors) = errors {
  1276. // SAFETY: the blob's own bytes.
  1277. let text = unsafe {
  1278. std::slice::from_raw_parts(
  1279. errors.GetBufferPointer().cast::<u8>(),
  1280. errors.GetBufferSize(),
  1281. )
  1282. };
  1283. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  1284. }
  1285. return Err(e);
  1286. }
  1287. let code = code.ok_or_else(windows::core::Error::empty)?;
  1288. // SAFETY: the blob's own bytes.
  1289. let bytes = unsafe {
  1290. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  1291. };
  1292. Ok(bytes.to_vec())
  1293. }
  1294. impl PlanePass {
  1295. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  1296. /// or of floats and the depth format `format`.
  1297. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  1298. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1299. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  1300. return pipeline.clone();
  1301. }
  1302. let pipeline = match Self::make(steps, format) {
  1303. Ok(pipeline) => Some(pipeline),
  1304. Err(e) => {
  1305. tracing::warn!(
  1306. error = %e,
  1307. steps,
  1308. format = format.0,
  1309. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  1310. );
  1311. None
  1312. }
  1313. };
  1314. made.push((steps, format.0, pipeline.clone()));
  1315. pipeline
  1316. }
  1317. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  1318. use windows::core::s;
  1319. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  1320. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  1321. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  1322. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  1323. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  1324. pShaderBytecode: bytes.as_ptr().cast(),
  1325. BytecodeLength: bytes.len(),
  1326. };
  1327. // SAFETY: the root signature is inside the pixel shader; the
  1328. // description points at live data and never releases its pointer.
  1329. unsafe {
  1330. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  1331. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1332. pRootSignature: std::mem::transmute_copy(&root),
  1333. VS: code(&vs[..]),
  1334. PS: code(&ps[..]),
  1335. SampleMask: u32::MAX,
  1336. RasterizerState: D3D12_RASTERIZER_DESC {
  1337. FillMode: D3D12_FILL_MODE_SOLID,
  1338. CullMode: D3D12_CULL_MODE_NONE,
  1339. DepthClipEnable: true.into(),
  1340. ..Default::default()
  1341. },
  1342. // Every texel is written; stencil stays off.
  1343. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1344. DepthEnable: true.into(),
  1345. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  1346. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1347. ..Default::default()
  1348. },
  1349. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1350. DSVFormat: format,
  1351. SampleDesc: DXGI_SAMPLE_DESC {
  1352. Count: 1,
  1353. Quality: 0,
  1354. },
  1355. ..Default::default()
  1356. };
  1357. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1358. Ok((root, pipeline))
  1359. }
  1360. }
  1361. }
  1362. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1363. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1364. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1365. /// heap, graphics root signature, pipeline, depth target, viewport,
  1366. /// scissor and topology and puts none of them back: it is for a list that
  1367. /// records nothing of the title's after it.
  1368. fn record_plane_pass(
  1369. list: &ID3D12GraphicsCommandList,
  1370. depth: &ID3D12Resource,
  1371. plane: &ID3D12Resource,
  1372. ) {
  1373. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1374. return;
  1375. };
  1376. // SAFETY: live resources.
  1377. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1378. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1379. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1380. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1381. let steps = twin.Format.0 == 53;
  1382. let format = DXGI_FORMAT(match of.Format.0 {
  1383. 44 => 45,
  1384. 19 => 20,
  1385. typed => typed,
  1386. });
  1387. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1388. return;
  1389. };
  1390. for slice in 0..u32::from(of.DepthOrArraySize) {
  1391. for mip in 0..u32::from(of.MipLevels) {
  1392. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1393. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1394. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1395. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1396. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1397. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1398. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1399. MostDetailedMip: mip,
  1400. MipLevels: 1,
  1401. FirstArraySlice: slice,
  1402. ArraySize: 1,
  1403. ..Default::default()
  1404. },
  1405. },
  1406. };
  1407. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1408. Format: format,
  1409. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1410. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1411. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1412. MipSlice: mip,
  1413. FirstArraySlice: slice,
  1414. ArraySize: 1,
  1415. },
  1416. },
  1417. ..Default::default()
  1418. };
  1419. let target = host.dsv(depth, Some(&target));
  1420. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1421. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1422. ptr: pass.cpu + (slot * pass.step) as usize,
  1423. };
  1424. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1425. ptr: pass.gpu + u64::from(slot * pass.step),
  1426. };
  1427. // SAFETY: an open list; a slot of our heap; live resources and
  1428. // objects (the pass's own live as long as the process).
  1429. unsafe {
  1430. host.device
  1431. .CreateShaderResourceView(plane, Some(&view), cpu);
  1432. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1433. list.SetGraphicsRootSignature(&root);
  1434. list.SetPipelineState(&pipeline);
  1435. list.SetGraphicsRootDescriptorTable(0, gpu);
  1436. list.OMSetRenderTargets(0, None, false, Some(&target));
  1437. list.RSSetViewports(&[D3D12_VIEWPORT {
  1438. TopLeftX: 0.0,
  1439. TopLeftY: 0.0,
  1440. Width: width as f32,
  1441. Height: height as f32,
  1442. MinDepth: 0.0,
  1443. MaxDepth: 1.0,
  1444. }]);
  1445. list.RSSetScissorRects(&[RECT {
  1446. left: 0,
  1447. top: 0,
  1448. right: width as i32,
  1449. bottom: height as i32,
  1450. }]);
  1451. list.IASetPrimitiveTopology(
  1452. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1453. );
  1454. list.DrawInstanced(3, 1, 0, 0);
  1455. }
  1456. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1457. }
  1458. }
  1459. }
  1460. /// Records into `list` the copy of a depth texture into its colour twin
  1461. /// (`colour`) or of the twin into the depth texture, both already in their
  1462. /// copy states: whole textures of one size in one format family, which the
  1463. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1464. /// alone, through the twin's buffer.
  1465. fn record_twin_copy(
  1466. list: &ID3D12GraphicsCommandList,
  1467. depth: &ID3D12Resource,
  1468. twin: &crate::resource::Twin,
  1469. colour: bool,
  1470. ) {
  1471. let (from, to) = if colour {
  1472. (depth, &twin.colour.texture)
  1473. } else {
  1474. (&twin.colour.texture, depth)
  1475. };
  1476. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1477. // shortcut: the depth plane's twin is not given the plane (that is a
  1478. // pass the other way: the plane read by a shader, the twin as its
  1479. // target). The twin then lacks what draws and clears wrote to the
  1480. // plane since shaders last wrote the twin. In the title
  1481. // nothing writes that plane but the twin's pass (its 192 draws against
  1482. // it only test, run 29), so the twin lacks nothing. Counted.
  1483. if colour && twin.plane.is_some() {
  1484. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1485. }
  1486. let Some(through) = &twin.through else {
  1487. // SAFETY: an open list and two live textures.
  1488. unsafe { list.CopyResource(to, from) };
  1489. return;
  1490. };
  1491. // A stencil plane and its twin: each mip and slice of the plane goes
  1492. // into the buffer, laid out as the host lays the plane out for copies,
  1493. // and from the buffer into the other texture, whole subresources both
  1494. // times. In the depth texture the stencil plane's subresources follow
  1495. // the depth plane's; the twin has the one plane.
  1496. let Some(host) = host() else { return };
  1497. // SAFETY: a live texture.
  1498. let of = unsafe { depth.GetDesc() };
  1499. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1500. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1501. // SAFETY: a plain query writing `planes` footprints.
  1502. unsafe {
  1503. host.device.GetCopyableFootprints(
  1504. &of,
  1505. planes,
  1506. planes,
  1507. 0,
  1508. Some(rows.as_mut_ptr()),
  1509. None,
  1510. None,
  1511. None,
  1512. );
  1513. }
  1514. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1515. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1516. // SAFETY: a borrowed pointer the location never releases.
  1517. pResource: unsafe { std::mem::transmute_copy(texture) },
  1518. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1519. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1520. SubresourceIndex: index,
  1521. },
  1522. };
  1523. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1524. // SAFETY: as above.
  1525. pResource: unsafe { std::mem::transmute_copy(through) },
  1526. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1527. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1528. PlacedFootprint: *row,
  1529. },
  1530. };
  1531. let (common, source, dest) = (
  1532. D3D12_RESOURCE_STATE_COMMON,
  1533. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1534. D3D12_RESOURCE_STATE_COPY_DEST,
  1535. );
  1536. // SAFETY: an open list and live resources; the buffer was made as big
  1537. // as these footprints, and rests in the common state between copies.
  1538. unsafe {
  1539. list.ResourceBarrier(&[transition(through, common, dest)]);
  1540. for (i, row) in rows.iter().enumerate() {
  1541. let index = first_from + i as u32;
  1542. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1543. }
  1544. list.ResourceBarrier(&[transition(through, dest, source)]);
  1545. for (i, row) in rows.iter().enumerate() {
  1546. let index = first_to + i as u32;
  1547. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1548. }
  1549. list.ResourceBarrier(&[transition(through, source, common)]);
  1550. }
  1551. }
  1552. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1553. /// builds).
  1554. pub(crate) fn dred_on() -> bool {
  1555. static ON: OnceLock<bool> = OnceLock::new();
  1556. *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED") && !dred_faults() && !dred_light())
  1557. }
  1558. /// Breadcrumbs and the faulting address, but no markers and no texts
  1559. /// (`VICTORY_D3D12_DRED=light`): which list a removed device stopped in, at
  1560. /// which of its commands, and the pipelines the list binds; formatting a text
  1561. /// for every command is what makes the whole of it slow.
  1562. pub(crate) fn dred_light() -> bool {
  1563. static ON: OnceLock<bool> = OnceLock::new();
  1564. *ON.get_or_init(|| {
  1565. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "light")
  1566. })
  1567. }
  1568. /// Any of the three.
  1569. pub(crate) fn dred_any() -> bool {
  1570. dred_on() || dred_light() || dred_faults()
  1571. }
  1572. /// Whether only the faulting address of a removed device is kept
  1573. /// (`VICTORY_D3D12_DRED=faults`): no breadcrumbs, no markers and no texts, so
  1574. /// it costs next to nothing and can stay on while the title is played.
  1575. pub(crate) fn dred_faults() -> bool {
  1576. static ON: OnceLock<bool> = OnceLock::new();
  1577. *ON.get_or_init(|| {
  1578. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "faults")
  1579. })
  1580. }
  1581. /// The lists alive while device-removed data is on, by the number their name
  1582. /// ends in, with their marker texts and the pipelines they bind: a report made
  1583. /// on another thread than the one that submits has no lists of its own.
  1584. #[cfg(feature = "diagnostics")]
  1585. #[allow(clippy::type_complexity)]
  1586. static LIST_NOTES: Mutex<
  1587. std::collections::BTreeMap<
  1588. u32,
  1589. (
  1590. std::sync::Weak<Mutex<Vec<Note>>>,
  1591. std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>,
  1592. std::sync::Weak<Mutex<indirects::Indirects>>,
  1593. ),
  1594. >,
  1595. > = Mutex::new(std::collections::BTreeMap::new());
  1596. /// The number in the name of a list of ours ("victory host list 7", which the
  1597. /// debug layer ends with a note of its own in brackets).
  1598. #[cfg(feature = "diagnostics")]
  1599. fn list_number(name: &str) -> Option<u32> {
  1600. let rest = name.strip_prefix("victory host list ")?;
  1601. let digits = rest.split(' ').next()?;
  1602. (rest.len() == digits.len() || rest[digits.len()..].starts_with(" (")).then(|| digits.parse().ok()).flatten()
  1603. }
  1604. /// Indirect mesh dispatches since the last frame line: the largest group
  1605. /// count a record asked for, and the groups asked in all (from the lists'
  1606. /// budget buffers, a run late).
  1607. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1608. /// Whether a list's indirect-work budget lives in the card's own memory
  1609. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1610. /// before). The clamp charges it with atomics, at least two in a row for
  1611. /// every clamp; in mapped memory on a card of its own each of them
  1612. /// crosses the bus.
  1613. fn card_budget() -> bool {
  1614. static ON: OnceLock<bool> = OnceLock::new();
  1615. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1616. }
  1617. /// Whether each list of a submission runs and is timed on its own, slow
  1618. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1619. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1620. #[cfg(feature = "diagnostics")]
  1621. fn timing() -> bool {
  1622. static ON: OnceLock<bool> = OnceLock::new();
  1623. *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING"))
  1624. }
  1625. /// Names a host object for the device-removed report, which names the
  1626. /// allocations a page fault hit (only with device-removed data on), or for
  1627. /// the frame recorder (`VICTORY_RECORD`).
  1628. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1629. #[cfg(feature = "diagnostics")]
  1630. if crate::book::on()
  1631. && let Ok(resource) = object.cast::<ID3D12Resource>()
  1632. {
  1633. let text = text();
  1634. crate::book::made(&resource, || text.clone());
  1635. return name_it(object, || text);
  1636. }
  1637. name_it(object, text);
  1638. }
  1639. fn name_it(object: &impl Interface, text: impl FnOnce() -> String) {
  1640. #[cfg(feature = "diagnostics")]
  1641. if crate::replay::record::on() {
  1642. let text = text();
  1643. crate::replay::record::name(object, &text);
  1644. if dred_any()
  1645. && let Ok(object) = object.cast::<ID3D12Object>()
  1646. {
  1647. // SAFETY: a plain call on a live object.
  1648. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1649. }
  1650. return;
  1651. }
  1652. if dred_any()
  1653. && let Ok(object) = object.cast::<ID3D12Object>()
  1654. {
  1655. // SAFETY: a plain call on a live object.
  1656. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1657. }
  1658. }
  1659. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1660. /// [`LISTS`]`[3]` until it is first reset.
  1661. struct Counted {
  1662. /// Not reset since it was made.
  1663. fresh: std::sync::atomic::AtomicBool,
  1664. }
  1665. impl Counted {
  1666. fn new() -> Counted {
  1667. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1668. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1669. Counted {
  1670. fresh: std::sync::atomic::AtomicBool::new(true),
  1671. }
  1672. }
  1673. /// The list is reset: it is in use.
  1674. fn used(&self) {
  1675. if self.fresh.swap(false, Ordering::Relaxed) {
  1676. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1677. }
  1678. }
  1679. }
  1680. impl Drop for Counted {
  1681. fn drop(&mut self) {
  1682. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1683. self.used();
  1684. }
  1685. }
  1686. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1687. /// mapping.
  1688. struct Chunk {
  1689. buffer: ID3D12Resource,
  1690. data: usize,
  1691. }
  1692. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1693. // written only by the list that holds the chunk.
  1694. unsafe impl Send for Chunk {}
  1695. /// Upload chunks handed out front to back: the chunks (each with its
  1696. /// bytes), the one in use and the bytes used in it.
  1697. #[derive(Default)]
  1698. struct Scratch {
  1699. chunks: Vec<(Chunk, u64)>,
  1700. current: usize,
  1701. used: u64,
  1702. }
  1703. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1704. unsafe impl Send for Scratch {}
  1705. impl Drop for Scratch {
  1706. fn drop(&mut self) {
  1707. give_chunks(std::mem::take(&mut self.chunks));
  1708. }
  1709. }
  1710. const SCRATCH_CHUNK: u64 = 4 << 20;
  1711. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1712. /// lists put a few constants or a rectangle's corners there, and every
  1713. /// list that did took 4 MiB of the PC's memory for it.
  1714. const SCRATCH_FIRST: u64 = 256 << 10;
  1715. /// The most bytes of chunks kept while no list holds them.
  1716. const SPARE_MOST: u64 = 128 << 20;
  1717. /// The same with [`keep_freed`].
  1718. const SPARE_KEPT: u64 = 1 << 30;
  1719. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1720. /// first needs one, a small one first, and gives all of them back when it
  1721. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1722. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1723. /// host lists of held submissions, which live for one submission, each
  1724. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1725. /// freed per frame of gameplay (run 60).
  1726. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1727. fn scratch_pool() -> bool {
  1728. static ON: OnceLock<bool> = OnceLock::new();
  1729. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1730. }
  1731. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1732. /// for one of the same size.
  1733. struct Spare<T> {
  1734. kept: Vec<(T, u64)>,
  1735. bytes: u64,
  1736. }
  1737. impl<T> Spare<T> {
  1738. const fn new() -> Self {
  1739. Spare { kept: Vec::new(), bytes: 0 }
  1740. }
  1741. /// A kept thing of `size` bytes, the one given last.
  1742. fn take(&mut self, size: u64) -> Option<T> {
  1743. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1744. self.bytes -= size;
  1745. Some(self.kept.remove(at).0)
  1746. }
  1747. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1748. /// `most`: then it comes back.
  1749. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1750. if self.bytes + size > most {
  1751. return Some(thing);
  1752. }
  1753. self.bytes += size;
  1754. self.kept.push((thing, size));
  1755. None
  1756. }
  1757. }
  1758. /// Scratch chunks no list holds.
  1759. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1760. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1761. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1762. if scratch_pool()
  1763. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1764. {
  1765. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1766. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1767. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1768. return Some(chunk);
  1769. }
  1770. let (buffer, data) = host.upload_buffer(size)?;
  1771. name(&buffer, || "list scratch".into());
  1772. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1773. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1774. Some(Chunk {
  1775. buffer,
  1776. data: data as usize,
  1777. })
  1778. }
  1779. /// A list is done with `chunks` (it was reset after its submissions ran,
  1780. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1781. /// without the pool.
  1782. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1783. if chunks.is_empty() {
  1784. return;
  1785. }
  1786. let mut freed = Vec::new();
  1787. {
  1788. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1789. for (chunk, size) in chunks {
  1790. let back = if scratch_pool() {
  1791. spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST })
  1792. } else {
  1793. Some(chunk)
  1794. };
  1795. match back {
  1796. None => {
  1797. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1798. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1799. }
  1800. Some(chunk) => {
  1801. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1802. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1803. freed.push(chunk);
  1804. }
  1805. }
  1806. }
  1807. }
  1808. // Freed outside the lock.
  1809. drop(freed);
  1810. }
  1811. /// What the host keeps for copies in the card's own memory
  1812. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1813. struct CardWork {
  1814. /// Before a submission's lists: what changed on the copies' CPU side
  1815. /// goes to their card side. Those not in use: a plan takes one and
  1816. /// gives it back when its submission has run (`Host::card_done`), so
  1817. /// that submissions sent ahead ([`late`]) each have their own.
  1818. sync: Vec<Prelude>,
  1819. /// After them, in the same submission: the compare of the declared
  1820. /// ranges with their bytes from before. As `sync`.
  1821. check: Vec<Prelude>,
  1822. /// After it ran: the pieces that differ come down.
  1823. fetch: Prelude,
  1824. root: ID3D12RootSignature,
  1825. pso: ID3D12PipelineState,
  1826. /// One dword per piece compared, odd where the piece differs: PC
  1827. /// memory, mapped (buffer, mapping, bytes).
  1828. differs: (ID3D12Resource, usize, u64),
  1829. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1830. fetched: Option<(ID3D12Resource, usize, u64)>,
  1831. /// The dwords of `differs` taken by plans whose results were not read
  1832. /// yet.
  1833. taken: u32,
  1834. /// Plans made and not done with (`Host::card_done`).
  1835. out: u32,
  1836. }
  1837. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1838. // under the submission lock.
  1839. unsafe impl Send for CardWork {}
  1840. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1841. /// The compare of a declared range of a copy in the card's memory with
  1842. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1843. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1844. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1845. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1846. /// byte just outside the range costs a fetch that finds nothing.
  1847. ///
  1848. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1849. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1850. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1851. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1852. /// those steps.
  1853. pub(crate) const CARD_COMPARE: &str = r#"
  1854. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1855. cbuffer Span : register(b0) {
  1856. uint first; // the first piece
  1857. uint skew; // where the copy starts in its piece 0
  1858. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1859. uint pieces;
  1860. uint out_at; // the first piece's dword in `differs`, in bytes
  1861. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1862. };
  1863. ByteAddressBuffer now : register(t0);
  1864. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1865. // last sent up (or hashed whole, the first time).
  1866. RWByteAddressBuffer hashes : register(u0);
  1867. RWByteAddressBuffer differs : register(u1);
  1868. groupshared uint4 parts[64];
  1869. [RootSignature(RS)]
  1870. [numthreads(64, 1, 1)]
  1871. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1872. uint piece = first + id.x;
  1873. uint lo = piece * 65536u;
  1874. lo = lo > skew ? lo - skew : 0u;
  1875. uint hi = min((piece + 1u) * 65536u - skew, size);
  1876. lo = lo & ~15u;
  1877. hi = (hi + 15u) & ~15u;
  1878. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1879. [loop]
  1880. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1881. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1882. h = h.yzwx ^ (h >> 15);
  1883. }
  1884. parts[thread] = h;
  1885. GroupMemoryBarrierWithGroupSync();
  1886. if (thread != 0u) return;
  1887. h = parts[0];
  1888. [loop]
  1889. for (uint i = 1u; i < 64u; ++i) {
  1890. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1891. h = h.yzwx ^ (h >> 15);
  1892. }
  1893. if (compare != 0u) {
  1894. // The flag, and above it 31 bits of the hash (`torn`).
  1895. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1896. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1897. // With the copy-back on its own thread: the next compare of the
  1898. // piece finds what is written from here on.
  1899. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1900. } else {
  1901. hashes.Store4(piece * 16u, h);
  1902. }
  1903. }
  1904. "#;
  1905. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1906. #[cfg(test)]
  1907. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1908. torn::hash(bytes)
  1909. }
  1910. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1911. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1912. /// parts a dispatch can hold.
  1913. ///
  1914. /// # Safety
  1915. /// The list is open with the compare's root signature, pipeline and buffers
  1916. /// set, and the pieces lie in the buffer.
  1917. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1918. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1919. let mut done = 0;
  1920. while done < span.pieces {
  1921. let n = (span.pieces - done).min(MOST);
  1922. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1923. // SAFETY: the caller's.
  1924. unsafe {
  1925. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1926. list.Dispatch(n, 1, 1);
  1927. }
  1928. done += n;
  1929. }
  1930. }
  1931. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1932. /// the card's memory are hashed in runs of pieces that touch, each piece
  1933. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1934. /// per range sent up.
  1935. ///
  1936. /// These passes are ours, they run on the card before every submission's
  1937. /// lists: a pass takes the time of one piece however few its pieces are.
  1938. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1939. /// a piece hashed when it need not be, or not hashed when it should, costs
  1940. /// a fetch that finds nothing and loses no shader write.
  1941. fn rehash_runs() -> bool {
  1942. static ON: OnceLock<bool> = OnceLock::new();
  1943. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1944. }
  1945. /// Since the last frame-rate line, of our own passes over copies in the
  1946. /// card's memory: hash passes after ranges were sent up, the pieces they
  1947. /// hashed, and compare passes after the lists.
  1948. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1949. /// Whether what shaders wrote to copies in the card's memory is merged
  1950. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1951. /// default). The pieces the card's compare found differing come down in
  1952. /// one fetch and were then merged one after the other on the thread that
  1953. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1954. /// with the copy's CPU side byte by byte and put into title memory through
  1955. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1956. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1957. /// landings do not come here: `crate::land` has threads of its own.)
  1958. fn wide_merge() -> bool {
  1959. static ON: OnceLock<bool> = OnceLock::new();
  1960. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1961. }
  1962. /// One declared range of a copy in the card's memory, in a submission.
  1963. struct CardRange {
  1964. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1965. /// As declared (title addresses), for the statistics.
  1966. declared: (usize, usize),
  1967. span: crate::shadow::CardSpan,
  1968. /// Its first piece's dword in the compare's results.
  1969. at: u32,
  1970. /// Whether the card compares it; else every piece is fetched.
  1971. compared: bool,
  1972. /// Looked at by `crate::picked`, and not declared: what is found changed
  1973. /// there was written through a view nobody declared. Not landed.
  1974. picked: bool,
  1975. }
  1976. impl CardPlan {
  1977. /// `crate::picked` is told where what it looked at changed, by the
  1978. /// compare's results.
  1979. fn picked_found(&self, differs: &[u32]) {
  1980. for r in self.ranges.iter().filter(|r| r.picked) {
  1981. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1982. if let Some(p) = changed {
  1983. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1984. }
  1985. }
  1986. }
  1987. }
  1988. /// What a submission does for copies in the card's memory.
  1989. struct CardPlan {
  1990. ranges: Vec<CardRange>,
  1991. /// The compare, run after the submission's lists.
  1992. check: Option<ID3D12CommandList>,
  1993. /// The copies whose card side was brought up to date, alive until the
  1994. /// submission has run.
  1995. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1996. /// The lists of ours the plan recorded (whether the compare, the
  1997. /// list), given back by `Host::card_done`.
  1998. lists: Vec<(bool, Prelude)>,
  1999. /// With [`relay`]: the number of the send to copies in the card's memory
  2000. /// that the submission ran behind ([`QUEUE_ORDER`]).
  2001. sent_as: u64,
  2002. /// With [`upcheck`]: the look at what it sent up.
  2003. looks: Option<upcheck::Looks>,
  2004. /// With [`send`]: the memory its sends come from.
  2005. sends: Option<send::Memory>,
  2006. }
  2007. /// One piece of submission-time work, in recorded order.
  2008. enum Step {
  2009. /// A copy into title memory (destination, source, bytes): the title's
  2010. /// buffer copies, which later refreshes must see.
  2011. Copy(usize, usize, usize),
  2012. /// A copy of title memory into the list's own upload memory, and how
  2013. /// the card could bring the bytes instead.
  2014. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  2015. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  2016. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  2017. /// intervenes.
  2018. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  2019. /// Work that may write title memory.
  2020. Run(Box<dyn Fn() + Send>),
  2021. /// Work that writes host memory only, and the title memory it reads
  2022. /// (from, to; empty for none).
  2023. Host(Box<dyn Fn() + Send>, (usize, usize)),
  2024. /// Shaders write a range (address, bytes) of a buffer's host copy.
  2025. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  2026. /// Brings a texture's staging buffer up to date: once per submission,
  2027. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  2028. Texture(std::sync::Arc<crate::texture::Staging>),
  2029. /// A title buffer copy that the list does on the card ([`place`]): what
  2030. /// is done on the CPU for it.
  2031. Placed(place::Placed),
  2032. }
  2033. /// What a list does on the CPU when it is submitted: copies between host
  2034. /// memory regions (title buffers, upload buffers and buffer copies), and
  2035. /// the upload buffers its GPU commands read, kept until the list is reset.
  2036. #[derive(Default)]
  2037. struct Deferred {
  2038. /// Destination, source, bytes.
  2039. copies: Vec<Step>,
  2040. uploads: Vec<ID3D12Resource>,
  2041. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  2042. upload_bytes: u64,
  2043. /// Host objects the list's commands name (pipelines, root signatures,
  2044. /// descriptor heaps): the title may release its objects before it
  2045. /// submits the list.
  2046. kept: Vec<windows::core::IUnknown>,
  2047. /// Buffer ranges refreshed since the last title copy (host copy,
  2048. /// address, bytes): refreshing them again would find the same bytes.
  2049. refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>,
  2050. /// Textures whose contents the list brings up to date.
  2051. textures: std::collections::HashSet<usize>,
  2052. /// Bottom-of-pipe writes, done once the list has run: address, what,
  2053. /// bytes.
  2054. writes: Vec<(usize, crate::queue::Written, usize)>,
  2055. /// Textures read back (texture to buffer copies), done once the list
  2056. /// has run: the host buffer the list copies the texels into, the title
  2057. /// memory they go to, the bytes of a row, the rows, the title's row
  2058. /// pitch.
  2059. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  2060. /// Whether the indirect-work budget is zeroed for this recording (a
  2061. /// step on the CPU, or in the list for the card's copy).
  2062. budget_zeroed: bool,
  2063. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  2064. /// interface pointer) that a clamp in this recording left readable as
  2065. /// indirect arguments; 0 if none. It stays readable until the next
  2066. /// clamp into it ([`HostList::indirect_state`]).
  2067. indirect_readable: usize,
  2068. }
  2069. impl Deferred {
  2070. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  2071. /// reset.
  2072. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  2073. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  2074. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  2075. self.upload_bytes += size;
  2076. self.uploads.push(buffer);
  2077. }
  2078. }
  2079. impl Drop for Deferred {
  2080. fn drop(&mut self) {
  2081. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  2082. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  2083. }
  2084. }
  2085. /// Whether a queue's submissions go to the card without a wait for each
  2086. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  2087. /// waits for every list on its own).
  2088. ///
  2089. /// Every submission was prepared, sent, waited for and copied back before
  2090. /// the next one was looked at, so the card stood idle while we prepared
  2091. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  2092. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  2093. /// other, on the one thread that submits.
  2094. ///
  2095. /// With the switch a queue's submission is sent and joins a line of
  2096. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  2097. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  2098. /// for the card, what their shaders wrote copied back once per byte, then
  2099. /// their bottom-of-pipe writes and the fence signals behind them, in
  2100. /// order) at the next point where the title, or our own preparing, can
  2101. /// observe what they do. Those points, exactly:
  2102. ///
  2103. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  2104. /// read-back or map of a texture, a clear or upload run at once;
  2105. /// 2. the next submission reads title memory that a flight's shaders may
  2106. /// write: a title buffer copy, a fill of upload memory, a texture's
  2107. /// memory, any step that runs code of ours on title memory
  2108. /// ([`late_blocked`]);
  2109. /// 3. the next submission refreshes a range of a host copy that a flight's
  2110. /// shaders may write, and the title wrote a page of it since it was last
  2111. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  2112. /// alone until the flight's writes are back, as it always did within a
  2113. /// submission;
  2114. /// 4. a queue stands at a wait for a memory value that no flight's
  2115. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  2116. /// write ([`late_met`]);
  2117. /// 5. the title blocks on a fence without an event;
  2118. /// 6. the card has run every flight (a thread of ours waits for that:
  2119. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  2120. ///
  2121. /// What the title is told (bottom-of-pipe writes, fence values) is told
  2122. /// when the card has really run the work, later than before and never
  2123. /// earlier; a fence signalled on a queue while flights are in the air is
  2124. /// set behind them. A wait for a memory value that a flight's
  2125. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  2126. /// the card behind that flight, which is the order the wait asks for.
  2127. ///
  2128. /// What it assumes beyond today: memory the title rewrites between two of
  2129. /// its submissions, without waiting for the first, may be seen by the
  2130. /// first's shaders (as on the console, where the card reads title memory
  2131. /// when it runs, not when the list is submitted).
  2132. pub(crate) fn late() -> bool {
  2133. late_stage() > 0
  2134. }
  2135. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  2136. fn late_stage() -> u8 {
  2137. static STAGE: OnceLock<u8> = OnceLock::new();
  2138. *STAGE.get_or_init(|| {
  2139. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  2140. return 0;
  2141. }
  2142. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  2143. Ok("1") => 1,
  2144. Ok("2") => 2,
  2145. Ok("3") => 3,
  2146. // The relay alone: on top of stage 3.
  2147. Err(_) if crate::shadow::relay() => 3,
  2148. _ => 0,
  2149. }
  2150. })
  2151. }
  2152. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  2153. /// longer a point. Where the title wrote a page that lies in a range a
  2154. /// flight's shaders may write, the bytes the title changed are found (the
  2155. /// page as it is now against what the copy held when the flight was
  2156. /// prepared) and put into the copy, and only those: what the flight's
  2157. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  2158. /// flights are settled for it only where that cannot be done: memory that
  2159. /// is not write-watched, or a copy in the card's memory with more changed
  2160. /// runs than a submission should send up one by one.
  2161. ///
  2162. /// In run 92 (stage 1) this point settled the flights five times a frame
  2163. /// of twelve, each time with the card's work still to wait for: 172 ms a
  2164. /// frame of waiting were left of 200.
  2165. ///
  2166. /// What differs from settling first: a byte both the title and a flight's
  2167. /// shader wrote is the title's if the shader wrote it first, the shader's
  2168. /// if it wrote it afterwards; settled first it was always the shader's.
  2169. /// The title writing a byte a shader of its own is writing is a race on
  2170. /// the console too.
  2171. fn late_exact() -> bool {
  2172. late_stage() > 1
  2173. }
  2174. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  2175. /// no longer a point where flights are settled). The copy to the back
  2176. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  2177. /// its own for each present in the air) and the swap chain is told to
  2178. /// present behind it; the queue's call returns, and the card finishes the
  2179. /// frame while the title records the next one. What the title is told
  2180. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  2181. /// has run it, by the settling thread.
  2182. ///
  2183. /// What is left out with it: the look whether the presented frame is black
  2184. /// (diagnostics; it reads the frame back at once). A frame that is saved
  2185. /// or listed is presented the old way. Once every second and a half a
  2186. /// submission settles the flights all the same, for the sweep that lets
  2187. /// idle host objects go (it needs nothing in the air).
  2188. pub(crate) fn late_free_present() -> bool {
  2189. late_stage() > 2
  2190. }
  2191. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  2192. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  2193. /// and is off with it, in the timing run and with kept snapshots).
  2194. ///
  2195. /// With [`late`] alone every settle does three things on the thread that
  2196. /// holds the submission lock: it waits for everything in the air, copies
  2197. /// back with the card standing, and only then goes on preparing. The frame
  2198. /// stays a relay: the card works about 242 ms of it and one thread
  2199. /// prepares, waits and copies back for about 220.
  2200. ///
  2201. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  2202. /// soon as the card has run them, in the order they were sent and without
  2203. /// the submission lock: it fetches and merges what their shaders wrote to
  2204. /// copies in the card's memory, compares and merges the other copies,
  2205. /// frees the flights' ranges, and then does their read-backs, their
  2206. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  2207. /// order. The submitting thread meanwhile prepares and sends the next
  2208. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  2209. /// that thread has landed everything in the air, at the same points as
  2210. /// before (the list in [`late`]), so whoever can observe title memory, a
  2211. /// fence or a present still does so only after the flights before it are
  2212. /// merged.
  2213. ///
  2214. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  2215. /// flight; a merge that never stores into memory the card may be writing;
  2216. /// sends to card copies numbered) and here: flights land in the order of
  2217. /// [`LINE`] by one thread, so a later flight's results never reach title
  2218. /// memory before an earlier flight's; the compare on the card stores the
  2219. /// hash it made, so each flight's compare flags exactly what changed since
  2220. /// the compare before it, however late the pieces are fetched; the fetch
  2221. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  2222. /// title bytes the card had received when it ran.
  2223. pub(crate) fn relay() -> bool {
  2224. static ON: OnceLock<bool> = OnceLock::new();
  2225. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  2226. }
  2227. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  2228. /// title memory a flight's shaders may write (a title buffer copy, a fill
  2229. /// of upload memory, a texture) waits only until the flights that declared
  2230. /// that memory have landed, not for everything in the air; and at
  2231. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  2232. /// both wait for everything.
  2233. fn relay_exact() -> bool {
  2234. static ON: OnceLock<bool> = OnceLock::new();
  2235. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  2236. // since the walls of the first room were found drawn in every run with
  2237. // this set and in fewer than half without it).
  2238. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  2239. }
  2240. /// Whether the pieces the relay fetches from the card's memory come over the
  2241. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  2242. /// draws.
  2243. ///
  2244. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  2245. /// and with the relay that is most of a frame: the thread that lands flights
  2246. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  2247. /// a few milliseconds of copying, and everything that waits for a landing
  2248. /// (the title's fences, reads of memory flights may write) waited with it.
  2249. ///
  2250. /// What changes: the fetch runs when its flights are done and beside later
  2251. /// submissions, so of the sends of title bytes it is only known to have run
  2252. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  2253. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  2254. /// the title's, newer than what the flights wrote. A later flight's bytes
  2255. /// may be in what is fetched, as before.
  2256. fn relay_copy() -> bool {
  2257. static ON: OnceLock<bool> = OnceLock::new();
  2258. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  2259. }
  2260. /// Told when something joins [`LINE`], for the thread that lands flights
  2261. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  2262. /// what queues hold.
  2263. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2264. /// Told when flights have landed ([`relay`]): who waits for that looks
  2265. /// again.
  2266. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  2267. /// With [`relay`], the order of what we put on the queue: the number of
  2268. /// sends of changed ranges to copies in the card's memory so far
  2269. /// (`Host::card_before`). Held from the taking of the ranges until their
  2270. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  2271. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  2272. /// later one.
  2273. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  2274. /// Since the last frame-rate line, of the thread that lands flights
  2275. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  2276. /// card with nothing to land, microseconds it waited for fetches of card
  2277. /// copies' pieces, microseconds of landing in all.
  2278. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  2279. /// Of the line's things in order (a flight: the value signalled on the
  2280. /// host's fence behind it; a write or a signal behind a flight: `None`):
  2281. /// how many, from the front, can be landed when the card has reached
  2282. /// `completed`: everything ahead of the first flight it has not run. A
  2283. /// later flight never lands before an earlier one, and what follows a
  2284. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  2285. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  2286. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  2287. }
  2288. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  2289. /// holds, for every piece of every range of the plan, the copy, the
  2290. /// piece's number in the copy and whether the compare flagged it there (or
  2291. /// did not run). The pieces to fetch, under whichever range, in order: all
  2292. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  2293. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  2294. /// the hash, so the second of them may find it stored already and not
  2295. /// flag it.
  2296. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  2297. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  2298. pieces.sort_unstable();
  2299. pieces.dedup();
  2300. pieces
  2301. }
  2302. #[cfg(test)]
  2303. mod relay_tests {
  2304. use super::{flagged_pieces, landable};
  2305. /// Two flights and what follows each: nothing of the second lands
  2306. /// before the card has run it, and nothing behind a flight lands
  2307. /// before the flight.
  2308. #[test]
  2309. fn flights_land_in_the_order_they_were_sent() {
  2310. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  2311. let line = [Some(5), None, None, Some(6), None];
  2312. assert_eq!(landable(&line, 4), 0);
  2313. assert_eq!(landable(&line, 5), 3);
  2314. assert_eq!(landable(&line, 6), 5);
  2315. assert_eq!(landable(&line, u64::MAX), 5);
  2316. // Signals with no flight ahead land at once; behind one they wait.
  2317. assert_eq!(landable(&[None, None], 0), 2);
  2318. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  2319. assert_eq!(landable(&[], 3), 0);
  2320. // After the first three landed, the rest when its turn comes.
  2321. assert_eq!(landable(&line[3..], 5), 0);
  2322. assert_eq!(landable(&line[3..], 6), 2);
  2323. }
  2324. /// A piece flagged under one range of a plan is fetched under every
  2325. /// range that holds a part of it; pieces of other copies are not.
  2326. #[test]
  2327. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  2328. let (a, b) = (0x1000usize, 0x2000usize);
  2329. // Copy a: piece 3 under two ranges, flagged under the first only;
  2330. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  2331. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  2332. let fetch = flagged_pieces(&flags);
  2333. assert!(fetch.contains(&(a, 3)));
  2334. assert!(!fetch.contains(&(a, 4)));
  2335. assert!(!fetch.contains(&(b, 3)));
  2336. assert!(fetch.contains(&(b, 9)));
  2337. assert_eq!(fetch.len(), 2);
  2338. }
  2339. }
  2340. /// The most host lists in the air before the flights are settled
  2341. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  2342. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  2343. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  2344. /// 32 settled the flights three times a
  2345. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  2346. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  2347. /// descriptor slots, upload
  2348. /// memory and scratch chunks are held until then, and a frame's lists held
  2349. /// all at once ran the slots out before (run 45).
  2350. fn late_most() -> usize {
  2351. static MOST: OnceLock<usize> = OnceLock::new();
  2352. *MOST.get_or_init(|| {
  2353. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  2354. })
  2355. }
  2356. /// Whether a submission with bottom-of-pipe writes may fly
  2357. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  2358. /// the title is told at once, as before; for telling a title that polls
  2359. /// such a value from one that does not).
  2360. fn late_writes() -> bool {
  2361. static ON: OnceLock<bool> = OnceLock::new();
  2362. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  2363. }
  2364. /// Per host copy, the ranges a submission's shaders may write, as declared
  2365. /// (address, end).
  2366. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  2367. /// What [`Host::submit`] hands back for a submission it sent and did not
  2368. /// wait for.
  2369. struct Sent {
  2370. /// Its number among the submissions started.
  2371. number: u64,
  2372. card: Option<CardPlan>,
  2373. back: Vec<Declared>,
  2374. /// What was taken off it to be done on the card.
  2375. own: Option<card_steps::Taken>,
  2376. /// Its bottom-of-pipe writes.
  2377. writes: Vec<(usize, crate::queue::Written, usize)>,
  2378. }
  2379. /// A submission on the card that has not been waited for ([`late`]): its
  2380. /// host lists, taken from the title's (which it may reset meanwhile), and
  2381. /// what is to be done once it has run.
  2382. struct Flight {
  2383. number: u64,
  2384. /// The value signalled on the host's fence behind it.
  2385. fence: u64,
  2386. lists: Vec<crate::list::Detached>,
  2387. order: Vec<usize>,
  2388. card: Option<CardPlan>,
  2389. back: Vec<Declared>,
  2390. /// The list of ours that ran ahead of them ([`card_steps`]).
  2391. own: Option<card_steps::Taken>,
  2392. }
  2393. /// One thing in the line of what waits for the card, in order.
  2394. enum Late {
  2395. Run(Flight),
  2396. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  2397. Write(usize, crate::queue::Written, usize),
  2398. /// A fence (its address) signalled behind the flights before it.
  2399. Signal(usize, u64),
  2400. }
  2401. struct Line {
  2402. line: Vec<Late>,
  2403. /// The title memory the flights' shaders may write (address, end), in
  2404. /// order and joined.
  2405. written: Vec<(usize, usize)>,
  2406. /// Host lists in the flights.
  2407. lists: usize,
  2408. /// The value signalled on the host's fence behind the last flight.
  2409. target: u64,
  2410. /// A settle has taken the line and is not done: a signal still goes
  2411. /// behind it.
  2412. settling: bool,
  2413. /// Something was settled away from a queue's own calls: the helper
  2414. /// thread looks at what queues hold.
  2415. poke: bool,
  2416. /// Host lists of settled flights, reset and given back outside the
  2417. /// submission lock ([`land`]: a settle may run under a caller's own
  2418. /// locks).
  2419. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2420. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2421. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2422. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2423. /// With [`card_steps`]: what the flights being landed write.
  2424. landing: Vec<card_steps::Writer>,
  2425. }
  2426. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2427. // into; touched under the lock.
  2428. unsafe impl Send for Line {}
  2429. static LINE: Mutex<Line> = Mutex::new(Line {
  2430. line: Vec::new(),
  2431. written: Vec::new(),
  2432. lists: 0,
  2433. target: 0,
  2434. settling: false,
  2435. poke: false,
  2436. landed: Vec::new(),
  2437. in_hand: Vec::new(),
  2438. landing: Vec::new(),
  2439. });
  2440. /// Told when a flight joins [`LINE`] or it is poked.
  2441. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2442. fn line() -> std::sync::MutexGuard<'static, Line> {
  2443. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2444. }
  2445. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2446. const WHY_SYNC: usize = 2;
  2447. const WHY_CARD_DONE: usize = 3;
  2448. const WHY_VALUE: usize = 4;
  2449. const WHY_STALE: usize = 5;
  2450. const WHY_READ: usize = 6;
  2451. const WHY_RUN: usize = 7;
  2452. const WHY_MOST: usize = 8;
  2453. const WHY_WRITES: usize = 9;
  2454. const WHY_FENCE: usize = 10;
  2455. /// Since the last frame-rate line: submissions sent without a wait;
  2456. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2457. /// microseconds settles waited for the card; value waits met by a flight's
  2458. /// bottom-of-pipe write; fence signals set behind flights.
  2459. /// Then: the settles for title memory read, by what read it (a buffer
  2460. /// copy, a fill of upload memory, a texture).
  2461. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2462. /// Since the last frame-rate line: the microseconds settles waited for the
  2463. /// card, by why they settled (the `WHY_` places).
  2464. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2465. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2466. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2467. if from >= to {
  2468. return false;
  2469. }
  2470. let at = ranges.partition_point(|r| r.1 <= from);
  2471. ranges.get(at).is_some_and(|r| r.0 < to)
  2472. }
  2473. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2474. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2475. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2476. ranges.sort_unstable();
  2477. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2478. for &(from, to) in ranges.iter() {
  2479. match out.last_mut() {
  2480. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2481. _ => out.push((from, to)),
  2482. }
  2483. }
  2484. *ranges = out;
  2485. }
  2486. /// Whether anything is in the air.
  2487. fn flying() -> bool {
  2488. if !late() {
  2489. return false;
  2490. }
  2491. let line = line();
  2492. // (With the relay: also while flights are being landed.)
  2493. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2494. }
  2495. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2496. /// before they are settled, if so. Preparing reads title memory on the
  2497. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2498. /// runs steps of ours that may read or write it anywhere; what the
  2499. /// flights' shaders write is not there yet.
  2500. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2501. let (written, copies) = {
  2502. let line = line();
  2503. if line.written.is_empty() {
  2504. return None;
  2505. }
  2506. (line.written.clone(), card_steps::copies(&line))
  2507. };
  2508. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2509. }
  2510. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2511. /// flights when the title itself wrote the memory since they were given it
  2512. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2513. ///
  2514. /// The title's 174 MB heap is declared written as a whole (a root view has
  2515. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2516. /// bytes a frame, at a new place each time, waited for every flight's
  2517. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2518. /// named). The title writes those bytes just before the draw that reads
  2519. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2520. ///
  2521. /// Or no shader's write went into that page in the last 600 frames
  2522. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2523. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2524. /// before the page was taken.
  2525. ///
  2526. /// What can go wrong: a constant a flight's shader really writes, in a
  2527. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2528. /// for the first time, is read as it was before that flight.
  2529. fn fill_is_titles(src: usize, len: usize) -> bool {
  2530. const SMALL: usize = 64 << 10;
  2531. static ON: OnceLock<bool> = OnceLock::new();
  2532. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2533. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2534. }
  2535. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2536. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2537. /// in (start, bytes).
  2538. #[cfg(feature = "diagnostics")]
  2539. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2540. /// How often and how long, and the address the last one read.
  2541. #[cfg(feature = "diagnostics")]
  2542. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2543. /// What the wait that comes next is for, and why not on the card.
  2544. #[cfg(feature = "diagnostics")]
  2545. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2546. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2547. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2548. /// shaders.
  2549. #[cfg(feature = "diagnostics")]
  2550. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2551. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2552. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2553. /// raw address (1).
  2554. #[cfg(feature = "diagnostics")]
  2555. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2556. if len < 1 << 20 {
  2557. return;
  2558. }
  2559. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2560. let e = all
  2561. .get_or_insert_with(Default::default)
  2562. .entry((address as usize, (address + len) as usize, pipeline))
  2563. .or_insert_with(|| {
  2564. let shaders = match pipeline {
  2565. 0 => "a view in a table".into(),
  2566. 1 => "a raw address".into(),
  2567. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2568. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2569. }),
  2570. };
  2571. (0, shaders)
  2572. });
  2573. e.0 += 1;
  2574. }
  2575. #[cfg(feature = "diagnostics")]
  2576. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2577. let i = written.partition_point(|r| r.1 <= at);
  2578. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2579. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2580. let why = blamed.1;
  2581. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2582. }
  2583. /// Why [`card_steps`] left the submission to the wait that comes next.
  2584. #[cfg(feature = "diagnostics")]
  2585. fn refused(why: &'static str) {
  2586. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2587. }
  2588. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2589. #[cfg(feature = "diagnostics")]
  2590. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2591. if let Some((shadow, from, _)) = stale.first() {
  2592. let (start, len) = shadow.span();
  2593. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2594. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2595. }
  2596. }
  2597. /// The wait for what [`blame`] last named, or a wait of another reason than
  2598. /// title memory read, took `us`.
  2599. #[cfg(feature = "diagnostics")]
  2600. fn blamed(why: usize, us: u64) {
  2601. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2602. let (key, at) = match (why, named) {
  2603. (WHY_READ | WHY_STALE, Some(named)) => named,
  2604. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2605. _ => {
  2606. let kind = match why {
  2607. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2608. WHY_VALUE => "a memory value",
  2609. WHY_STALE => "title memory changed under shader writes",
  2610. WHY_RUN => "a step of ours",
  2611. WHY_MOST => "lists in the air",
  2612. WHY_FENCE => "a blocking fence wait",
  2613. _ => "another reason",
  2614. };
  2615. ((kind, "", 0, 0, 0), 0)
  2616. }
  2617. };
  2618. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2619. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2620. *e = (e.0 + 1, e.1 + us, at);
  2621. }
  2622. /// For the frame-rate line: the five that waited longest.
  2623. #[cfg(feature = "diagnostics")]
  2624. fn log_blame(frames: f64) {
  2625. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2626. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2627. let mut all: Vec<_> = all.into_iter().collect();
  2628. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2629. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2630. // The passes that declare it written, the ones that do so most.
  2631. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2632. for ((a, b, _), (n, shaders)) in &wide {
  2633. if *a < at + len && at < *b {
  2634. *passes.entry(shaders).or_default() += n;
  2635. }
  2636. }
  2637. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2638. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2639. let passes: Vec<String> =
  2640. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2641. tracing::info!(
  2642. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2643. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2644. us as f64 / 1e3 / frames,
  2645. n as f64 / frames,
  2646. passes.join(", "),
  2647. match (why.is_empty(), kind) {
  2648. (true, _) => "",
  2649. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2650. _ => "; not done on the card: ",
  2651. },
  2652. );
  2653. }
  2654. }
  2655. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2656. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2657. touches(written, src, src + len) && !fill_is_titles(src, len)
  2658. }
  2659. /// Whether they stop a title buffer copy, and if so whether by its source.
  2660. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2661. let read = read_blocked(written, src, len);
  2662. (read || touches(written, dst, dst + len)).then_some(read)
  2663. }
  2664. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2665. /// may write (in order, joined); `count` whether the kind of read is
  2666. /// counted for the frame line.
  2667. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2668. if written.is_empty() {
  2669. return None;
  2670. }
  2671. // Destinations of copies at their place, if a step reads them.
  2672. let mut placed: Vec<(usize, usize)> = Vec::new();
  2673. for list in runs {
  2674. for step in &list.deferred().copies {
  2675. match step {
  2676. &Step::Copy(dst, src, len) => {
  2677. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2678. if count {
  2679. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2680. #[cfg(feature = "diagnostics")]
  2681. if _read {
  2682. blame("a buffer copy's source", written, src, len);
  2683. } else {
  2684. blame("a buffer copy's destination", written, dst, len);
  2685. }
  2686. }
  2687. return Some(WHY_READ);
  2688. }
  2689. }
  2690. &Step::Fill(_, src, len, _) => {
  2691. if read_blocked(written, src, len) {
  2692. if count {
  2693. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2694. #[cfg(feature = "diagnostics")]
  2695. blame("a fill of upload memory", written, src, len);
  2696. }
  2697. return Some(WHY_READ);
  2698. }
  2699. }
  2700. Step::Texture(staging) => {
  2701. let (at, len) = staging.memory();
  2702. if touches(written, at, at + len) {
  2703. if count {
  2704. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2705. #[cfg(feature = "diagnostics")]
  2706. blame("a texture", written, at, len);
  2707. }
  2708. return Some(WHY_READ);
  2709. }
  2710. }
  2711. Step::Run(_) => return Some(WHY_RUN),
  2712. Step::Placed(p) => match p.waits(written) {
  2713. place::Waits::No => {}
  2714. place::Waits::ForReaders => placed.push((p.dst, p.dst + p.len)),
  2715. place::Waits::Yes => {
  2716. if count {
  2717. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2718. #[cfg(feature = "diagnostics")]
  2719. blame("a buffer copy at its place", written, p.src, p.len);
  2720. }
  2721. return Some(WHY_READ);
  2722. }
  2723. },
  2724. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2725. }
  2726. }
  2727. }
  2728. (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ)
  2729. }
  2730. /// With flights in the air, after the submission's write-watch asking:
  2731. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2732. /// may write and that the title wrote since it was last copied. The
  2733. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2734. /// the title's bytes there would reach the card a submission late.
  2735. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2736. use std::sync::Arc;
  2737. // Per copy, the span of what is refreshed (a flush brings that much
  2738. // up to date at most).
  2739. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2740. // Where each copy is in it, if shaders may be writing it (none begins to
  2741. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2742. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2743. for list in runs {
  2744. for step in &list.deferred().copies {
  2745. if let Step::Refresh(shadow, address, len) = step {
  2746. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2747. shadow.writes_pending().then(|| {
  2748. spans.push((shadow.clone(), *address, *address + *len));
  2749. spans.len() - 1
  2750. })
  2751. });
  2752. if let Some(i) = *place {
  2753. let s = &mut spans[i];
  2754. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2755. }
  2756. }
  2757. }
  2758. }
  2759. if late_exact() {
  2760. // The title's bytes are put in beside the flights' writes; a
  2761. // settle is still due where that could not be done. At most this
  2762. // many changed runs go up to copies in the card's memory, each a
  2763. // copy of its own there. With [`card_steps`] the pages of the
  2764. // title's ring of constants come here too, which were waited for
  2765. // before: hundreds of short runs each, at about 1.5 us a run.
  2766. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2767. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2768. return spans;
  2769. }
  2770. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2771. spans
  2772. }
  2773. /// How many parts of submissions, and lists, the line's thread gives to the
  2774. /// host as one (`VICTORY_JOIN_PARTS=<n>`; off by default, 1; `VICTORY_JOIN_LISTS`,
  2775. /// 48).
  2776. ///
  2777. /// The idea is fxceless/victory-fork's, commit 39731795 (GPL-3.0-or-later, as
  2778. /// this): the title's lists wait for memory values, which cuts a frame into
  2779. /// some 29 parts, each prepared on its own: the write watch asked, the heaps'
  2780. /// records, the title's bytes under the flights' writes, a list that sends
  2781. /// what changed and one that compares. (Run submit-1, the dorm, 12 of 28 parts
  2782. /// joined, eight at most: the thread works 51.4 ms a frame instead of 54.8, the
  2783. /// frame is 0.6 to 3 ms shorter.) What differs here: the parts are taken
  2784. /// off one queue's entries of the line (`crate::queue`), still go to the queue
  2785. /// in calls of their own, and everything they refresh is brought up to date in
  2786. /// front of the first ([`refresh_front`], without which a later part's title
  2787. /// bytes under an earlier part's declared writes would go missing).
  2788. pub(crate) fn joins() -> (usize, usize) {
  2789. if ahead_of_writes() { joins_asked() } else { (1, 1) }
  2790. }
  2791. fn joins_asked() -> (usize, usize) {
  2792. static MOST: OnceLock<(usize, usize)> = OnceLock::new();
  2793. let of = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<usize>().ok());
  2794. let (parts, lists) = *MOST.get_or_init(|| (of("VICTORY_JOIN_PARTS").unwrap_or(1).max(1), of("VICTORY_JOIN_LISTS").unwrap_or(48).max(1)));
  2795. #[cfg(feature = "diagnostics")]
  2796. if let Some(on) = crate::ab::pick("VICTORY_JOIN_PARTS") {
  2797. return (if on { 8 } else { 1 }, lists);
  2798. }
  2799. (parts, lists)
  2800. }
  2801. /// Whether the part `next` can be prepared together with `ahead`, which goes
  2802. /// before it and has not been sent: nothing done on the CPU for it reads what
  2803. /// those give their shaders, write back or write when they are done, and it
  2804. /// changes no title memory that they read ([`Step::Copy`], [`Step::Run`]).
  2805. pub(crate) fn joinable<'a>(ahead: impl Iterator<Item = &'a HostList>, next: &[&HostList]) -> bool {
  2806. if next.iter().any(|l| l.deferred().copies.iter().any(|s| matches!(s, Step::Copy(..) | Step::Run(_)))) {
  2807. return false;
  2808. }
  2809. let ahead: Vec<&HostList> = ahead.collect();
  2810. let mut written: Vec<(usize, usize)> = declared_writes(&ahead).into_iter().flat_map(|(_, ranges)| ranges).collect();
  2811. for list in &ahead {
  2812. let deferred = list.deferred();
  2813. written.extend(deferred.writes.iter().map(|&(at, _, bytes)| (at, at + bytes)));
  2814. written.extend(deferred.backs.iter().map(|&(_, at, [row, rows, pitch])| (at, at + rows.saturating_sub(1) * pitch + row)));
  2815. }
  2816. let mut joined = Vec::new();
  2817. join_ranges(&mut joined, written);
  2818. blocked_by(&joined, next, false).is_none()
  2819. }
  2820. /// Whether a bottom-of-pipe write of `list` meets `wait`.
  2821. pub(crate) fn will_meet(list: &HostList, wait: &crate::list::ValueWait) -> bool {
  2822. let (address, bytes) = wait.place();
  2823. // The last write there says.
  2824. let deferred = list.deferred();
  2825. let last = deferred.writes.iter().rev().find(|(at, _, n)| *at < address + bytes && address < *at + *n);
  2826. matches!(last, Some((at, crate::queue::Written::Value(v), n)) if *at == address && *n >= bytes && wait.holds_for(*v))
  2827. }
  2828. /// Lists and the order they run in.
  2829. type Run<T> = (Vec<T>, Vec<usize>);
  2830. /// `order`'s first `cut` places and the rest, each with the lists they name;
  2831. /// as it was if a list is named on both sides.
  2832. fn split<T>(lists: Vec<T>, order: Vec<usize>, cut: usize) -> Result<[Run<T>; 2], Run<T>> {
  2833. let (first, second) = order.split_at(cut);
  2834. if first.is_empty() || second.is_empty() || first.iter().any(|i| second.contains(i)) {
  2835. return Err((lists, order));
  2836. }
  2837. let behind: Vec<bool> = (0..lists.len()).map(|i| second.contains(&i)).collect();
  2838. let place = |i: usize| behind[..i].iter().filter(|&&b| b == behind[i]).count();
  2839. let orders = [first, second].map(|half| half.iter().map(|&i| place(i)).collect::<Vec<_>>());
  2840. let mut halves: [Vec<T>; 2] = [Vec::new(), Vec::new()];
  2841. for (list, behind) in lists.into_iter().zip(&behind) {
  2842. halves[usize::from(*behind)].push(list);
  2843. }
  2844. let [a, b] = halves;
  2845. let [x, y] = orders;
  2846. Ok([(a, x), (b, y)])
  2847. }
  2848. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2849. /// air, if there are any, and is set when they are settled. Whether it
  2850. /// did; if not the caller sets the fence now.
  2851. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2852. if !late() {
  2853. return false;
  2854. }
  2855. let mut line = line();
  2856. if line.line.is_empty() && !line.settling {
  2857. return false;
  2858. }
  2859. line.line.push(Late::Signal(fence, value));
  2860. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2861. drop(line);
  2862. // A signal alone (behind a settle under way) has no flight to wake
  2863. // the helper thread for it.
  2864. LINE_MOVED.notify_one();
  2865. RELAY_MOVED.notify_one();
  2866. true
  2867. }
  2868. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2869. /// whether it is met once the flights in the air have run. A flight's
  2870. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2871. /// for the card: the part behind the wait goes to the card behind that
  2872. /// flight, which is the order the wait asks for. If the flights may write
  2873. /// the value in a way not known here (shaders, a timestamp, another
  2874. /// width), they are settled and memory is asked again.
  2875. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2876. if let Some(met) = late_met_known(wait) {
  2877. return met;
  2878. }
  2879. settle_now(WHY_VALUE);
  2880. wait.met()
  2881. }
  2882. /// [`late_met`] without a wait for the card; `None`: it has to be waited for.
  2883. pub(crate) fn late_met_known(wait: &crate::list::ValueWait) -> Option<bool> {
  2884. let (address, bytes) = wait.place();
  2885. {
  2886. let line = line();
  2887. if line.line.is_empty() && line.in_hand.is_empty() {
  2888. return Some(false);
  2889. }
  2890. let mut unsure = touches(&line.written, address, address + bytes);
  2891. // (With the relay: first the writes of flights being landed.)
  2892. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2893. Late::Write(at, what, n) => Some((at, what, n)),
  2894. _ => None,
  2895. }));
  2896. for (at, what, n) in writes {
  2897. if *at >= address + bytes || address >= *at + *n {
  2898. continue;
  2899. }
  2900. match what {
  2901. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2902. if wait.holds_for(*v) {
  2903. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2904. return Some(true);
  2905. }
  2906. }
  2907. _ => unsure = true,
  2908. }
  2909. }
  2910. if !unsure {
  2911. return Some(false);
  2912. }
  2913. }
  2914. None
  2915. }
  2916. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2917. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2918. pub(crate) fn settle_now(why: usize) {
  2919. if !late() {
  2920. return;
  2921. }
  2922. let Some(host) = host() else {
  2923. return;
  2924. };
  2925. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2926. host.settle(&mut submitted, why);
  2927. }
  2928. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2929. pub(crate) fn settle_for_present() {
  2930. settle_now(WHY_SYNC);
  2931. }
  2932. pub(crate) fn settle_for_fence() {
  2933. settle_now(WHY_FENCE);
  2934. }
  2935. /// Resets the host lists of settled flights and keeps them for reuse, as
  2936. /// a queue does for the lists it ran (`crate::list::recycle`).
  2937. fn land() {
  2938. let landed: Vec<_> = {
  2939. let mut line = line();
  2940. let n = line.landed.len().saturating_sub(bury_lag() as usize);
  2941. line.landed.drain(..n).collect()
  2942. };
  2943. for (lists, order) in landed {
  2944. crate::list::recycle(lists, &order);
  2945. }
  2946. }
  2947. /// The thread that settles the flights once the card has run them all
  2948. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2949. /// at the next call that settles, and a title thread that polls such a
  2950. /// value while the submitting thread waits for that thread would never
  2951. /// see it.
  2952. fn late_helper() {
  2953. crate::cores::keep_on_fast_cores("victory-late-wait");
  2954. let Some(host) = host() else {
  2955. return;
  2956. };
  2957. // SAFETY: a plain event of our own.
  2958. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2959. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2960. return;
  2961. };
  2962. loop {
  2963. let target = {
  2964. let mut line = line();
  2965. loop {
  2966. if line.poke {
  2967. line.poke = false;
  2968. break None;
  2969. }
  2970. // (With the relay the flights are another thread's.)
  2971. if !relay() && !line.line.is_empty() && !line.settling {
  2972. break Some(line.target);
  2973. }
  2974. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2975. }
  2976. };
  2977. let Some(target) = target else {
  2978. let mut helping = crate::timeline::span("helper: landed lists reset and given back");
  2979. land();
  2980. helping.next("helper: looking at what queues hold");
  2981. crate::queue::release_held(false);
  2982. continue;
  2983. };
  2984. // The card first, without the submission lock: the submitting
  2985. // thread prepares and sends meanwhile.
  2986. // SAFETY: our fence and event.
  2987. unsafe {
  2988. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2989. #[cfg(feature = "diagnostics")]
  2990. let _card = crate::timeline::card_wait(Some(target));
  2991. WaitForSingleObject(event, INFINITE);
  2992. }
  2993. }
  2994. {
  2995. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2996. // Something newer went up meanwhile: the card is waited for
  2997. // again, the submitting thread is not held up for it.
  2998. if line().target != target {
  2999. continue;
  3000. }
  3001. host.settle(&mut submitted, WHY_CARD_DONE);
  3002. }
  3003. land();
  3004. crate::queue::release_held(false);
  3005. }
  3006. }
  3007. /// Starts the threads of [`late`], once: the one that settles flights when
  3008. /// the card has run them and looks at what queues hold, and with [`relay`]
  3009. /// the one that lands flights.
  3010. fn late_threads() {
  3011. static HELPER: std::sync::Once = std::sync::Once::new();
  3012. HELPER.call_once(|| {
  3013. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  3014. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  3015. }
  3016. tracing::info!(
  3017. most = late_most(),
  3018. writes = late_writes(),
  3019. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  3020. );
  3021. if relay() {
  3022. // Without it nothing would ever land.
  3023. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  3024. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  3025. }
  3026. tracing::info!(
  3027. exact = relay_exact(),
  3028. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  3029. );
  3030. }
  3031. });
  3032. }
  3033. /// With [`relay`]: waits until `done` says so of the line, looked at each
  3034. /// time flights have landed. Counted as a settle for `why`, and its time
  3035. /// as waiting for the card. The caller may hold the submission lock: the
  3036. /// thread that lands flights never takes it.
  3037. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  3038. let mut line = line();
  3039. if done(&line) {
  3040. return;
  3041. }
  3042. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  3043. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  3044. let was_working = working(false);
  3045. let waiting = std::time::Instant::now();
  3046. let _waiting = crate::timeline::span(match why {
  3047. WHY_SYNC => "waiting for landings: everything (a present, the sweep)",
  3048. WHY_VALUE => "waiting for landings: a memory value",
  3049. WHY_STALE => "waiting for landings: title memory changed under shader writes",
  3050. WHY_READ => "waiting for landings: title memory read",
  3051. WHY_MOST => "waiting for landings: lists in the air",
  3052. WHY_FENCE => "waiting for landings: a blocking fence wait",
  3053. _ => "waiting for landings: another reason",
  3054. });
  3055. while !done(&line) {
  3056. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  3057. }
  3058. drop(line);
  3059. stood(waiting);
  3060. working(was_working);
  3061. let us = waiting.elapsed().as_micros() as u64;
  3062. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  3063. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  3064. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  3065. #[cfg(feature = "diagnostics")]
  3066. blamed(why, us);
  3067. }
  3068. /// What the thread that lands flights fetches card copies' pieces with
  3069. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  3070. /// behind the submission lock), and the memory the pieces come down to.
  3071. struct RelayFetch {
  3072. list: Prelude,
  3073. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  3074. queue: Option<ID3D12CommandQueue>,
  3075. fence: ID3D12Fence,
  3076. event: HANDLE,
  3077. /// The last value signalled on `fence`.
  3078. sent: u64,
  3079. /// Buffer, mapping, bytes.
  3080. buffer: Option<(ID3D12Resource, usize, u64)>,
  3081. /// Pieces caught while a later flight was writing them.
  3082. suspects: torn::Suspects,
  3083. /// What earlier fetches brought of flights not landed yet.
  3084. had: crate::land::Had,
  3085. }
  3086. /// The thread that lands flights ([`relay`]): as soon as the card has run
  3087. /// the first flights of the line it takes them, with what follows them,
  3088. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  3089. /// the card, or for a flight. It takes neither the submission lock nor
  3090. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  3091. /// lists and looking at what queues hold are left to [`late_helper`].
  3092. fn relay_worker() {
  3093. crate::cores::keep_on_fast_cores("victory-relay");
  3094. let Some(host) = host() else {
  3095. return;
  3096. };
  3097. // SAFETY: a plain event of our own.
  3098. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  3099. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  3100. };
  3101. let mut fetch: Option<RelayFetch> = None;
  3102. loop {
  3103. let next = {
  3104. let mut line = line();
  3105. loop {
  3106. if line.line.is_empty() {
  3107. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  3108. continue;
  3109. }
  3110. let fences: Vec<Option<u64>> = line
  3111. .line
  3112. .iter()
  3113. .map(|l| match l {
  3114. Late::Run(flight) => Some(flight.fence),
  3115. _ => None,
  3116. })
  3117. .collect();
  3118. // SAFETY: a plain query.
  3119. let completed = unsafe { host.fence.GetCompletedValue() };
  3120. let n = landable(&fences, completed);
  3121. if n == 0 {
  3122. // The first thing is a flight the card has not run.
  3123. break Err(fences[0].unwrap_or(0));
  3124. }
  3125. line.settling = true;
  3126. let items: Vec<Late> = line.line.drain(..n).collect();
  3127. line.in_hand = items
  3128. .iter()
  3129. .filter_map(|l| match l {
  3130. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  3131. _ => None,
  3132. })
  3133. .collect();
  3134. if card_steps::stage() > 0 {
  3135. line.landing = card_steps::writers(&items);
  3136. }
  3137. break Ok(items);
  3138. }
  3139. };
  3140. match next {
  3141. Ok(items) => host.relay_land(items, &mut fetch),
  3142. Err(target) => {
  3143. let waiting = std::time::Instant::now();
  3144. #[cfg(feature = "diagnostics")]
  3145. let _card = crate::timeline::card_wait(Some(target));
  3146. // SAFETY: the host's fence and this thread's event.
  3147. let waited = unsafe {
  3148. host.fence.SetEventOnCompletion(target, event).map(|()| {
  3149. WaitForSingleObject(event, INFINITE);
  3150. })
  3151. };
  3152. if waited.is_err() {
  3153. std::thread::sleep(std::time::Duration::from_millis(1));
  3154. }
  3155. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  3156. }
  3157. }
  3158. }
  3159. }
  3160. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  3161. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  3162. /// once, the pieces that differ found on several threads; but the merge is
  3163. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  3164. /// are not done with here (each flight's are, afterwards). In two steps:
  3165. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  3166. /// which needs nothing that the fetch from the card's memory brings), and
  3167. /// the merge.
  3168. struct RelayBack {
  3169. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  3170. found: Option<Vec<Vec<(usize, usize)>>>,
  3171. }
  3172. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  3173. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3174. for (shadow, declared) in back {
  3175. if shadow.carded() {
  3176. continue;
  3177. }
  3178. let mut spans: Vec<(usize, usize)> = Vec::new();
  3179. join_ranges(&mut spans, declared.iter().copied());
  3180. for &(from, to) in &spans {
  3181. shadow.relay_compared(from, to - from);
  3182. }
  3183. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3184. }
  3185. RelayBack { work, found: None }
  3186. }
  3187. impl RelayBack {
  3188. /// Looks the ranges through, once; its time counts as `stat`.
  3189. fn look(&mut self, stat: usize) {
  3190. if self.work.is_empty() || self.found.is_some() {
  3191. return;
  3192. }
  3193. let scanning = std::time::Instant::now();
  3194. // Looked through without a lock: a piece that changes meanwhile (a
  3195. // later flight writing, the title's bytes going in) is found now or
  3196. // by that flight's landing, and the merge looks again under the
  3197. // lock.
  3198. self.found = Some(crate::shadow::find_all(&self.work));
  3199. crate::land::spent(stat, scanning);
  3200. #[cfg(feature = "diagnostics")]
  3201. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3202. }
  3203. /// What differs goes into title memory.
  3204. fn merge(mut self) {
  3205. use crate::land;
  3206. self.look(land::stat::SCAN);
  3207. let Some(found) = self.found else {
  3208. return;
  3209. };
  3210. let merging = std::time::Instant::now();
  3211. let mut written: Vec<u64> = Vec::new();
  3212. if land::on() {
  3213. // Pieces in the same block of title memory in one job, in order.
  3214. let pieces: Vec<(usize, usize, usize)> =
  3215. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  3216. let start = |i: usize| self.work[i].0.span().0 as usize;
  3217. let mut order: Vec<usize> = (0..pieces.len()).collect();
  3218. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  3219. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  3220. let jobs = land::jobs(&cut);
  3221. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  3222. land::each(jobs.len(), &|j| {
  3223. let working = std::time::Instant::now();
  3224. let mut notes = land::Notes::default();
  3225. for &p in &order[jobs[j].clone()] {
  3226. let (i, at, n) = pieces[p];
  3227. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  3228. }
  3229. notes.flush();
  3230. land::spent(land::stat::BACK_ALL, working);
  3231. });
  3232. land::count(land::stat::JOBS, jobs.len() as u64);
  3233. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  3234. } else {
  3235. let (mut now, mut title) = (Vec::new(), Vec::new());
  3236. for ((shadow, ..), found) in self.work.iter().zip(found) {
  3237. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  3238. written.push(found.into_iter().map(merge).sum());
  3239. }
  3240. }
  3241. land::spent(land::stat::BACK, merging);
  3242. for ((_, from, to), written) in self.work.iter().zip(written) {
  3243. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  3244. #[cfg(feature = "diagnostics")]
  3245. crate::copystat::compared(*from, to - from, written as usize);
  3246. let _ = (from, to);
  3247. }
  3248. }
  3249. }
  3250. /// For the frame-rate line, with [`late`]: what the line of flights did
  3251. /// per frame since the last one.
  3252. fn late_line(frames: f64) {
  3253. if !late() {
  3254. return;
  3255. }
  3256. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3257. tracing::info!(
  3258. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  3259. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  3260. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  3261. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  3262. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  3263. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  3264. s[0],
  3265. s[1],
  3266. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  3267. s[12] / 1000.0,
  3268. s[WHY_SYNC],
  3269. s[WHY_CARD_DONE],
  3270. s[WHY_VALUE],
  3271. s[WHY_STALE],
  3272. s[WHY_READ],
  3273. s[15],
  3274. s[16],
  3275. s[17],
  3276. s[WHY_RUN],
  3277. late_most(),
  3278. s[WHY_MOST],
  3279. s[WHY_WRITES],
  3280. s[WHY_FENCE],
  3281. s[13],
  3282. s[14],
  3283. );
  3284. {
  3285. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  3286. tracing::info!(
  3287. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  3288. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  3289. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  3290. w[WHY_SYNC],
  3291. w[WHY_CARD_DONE],
  3292. w[WHY_VALUE],
  3293. w[WHY_STALE],
  3294. w[WHY_READ],
  3295. w[WHY_RUN],
  3296. w[WHY_MOST],
  3297. w[WHY_WRITES],
  3298. w[WHY_FENCE],
  3299. );
  3300. }
  3301. if relay() {
  3302. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3303. tracing::info!(
  3304. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  3305. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  3306. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  3307. \"settles\" above are waits of other threads for it)",
  3308. r[1],
  3309. r[0],
  3310. r[2] / 1000.0,
  3311. r[3] / 1000.0,
  3312. r[4] / 1000.0,
  3313. );
  3314. if send::own() {
  3315. let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3316. tracing::info!(
  3317. "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
  3318. taking them out of the CPU sides",
  3319. t[0] / (1 << 20) as f64,
  3320. t[1],
  3321. t[2],
  3322. t[3] / 1000.0,
  3323. );
  3324. }
  3325. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3326. if t[0] > 0.0 {
  3327. tracing::info!(
  3328. "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",
  3329. t[0],
  3330. t[1],
  3331. t[2],
  3332. );
  3333. }
  3334. }
  3335. crate::land::log(frames);
  3336. if place::on() {
  3337. let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3338. tracing::info!(
  3339. "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",
  3340. t[0],
  3341. t[1] / 1024.0,
  3342. t[2],
  3343. t[3],
  3344. );
  3345. }
  3346. card_steps::log(frames);
  3347. crate::picked::log(frames);
  3348. #[cfg(feature = "diagnostics")]
  3349. log_blame(frames);
  3350. if late_exact() {
  3351. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  3352. tracing::info!(
  3353. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  3354. {runs:.0} changed runs, {:.2} MB",
  3355. bytes / (1 << 20) as f64
  3356. );
  3357. }
  3358. }
  3359. pub(crate) mod aside;
  3360. pub(crate) mod awake;
  3361. mod card_steps;
  3362. pub(crate) mod indirects;
  3363. #[cfg(feature = "diagnostics")]
  3364. mod panel;
  3365. mod place;
  3366. mod send;
  3367. pub(crate) use send::{goes_as_words, words_under};
  3368. #[cfg(feature = "diagnostics")]
  3369. pub(crate) mod spans;
  3370. mod torn;
  3371. #[cfg(feature = "diagnostics")]
  3372. mod traffic;
  3373. pub(crate) mod upcheck;
  3374. #[cfg(feature = "diagnostics")]
  3375. mod stamps;
  3376. #[cfg(feature = "diagnostics")]
  3377. pub(crate) use stamps::{timeline_ready, timeline_restart, timeline_stamps};
  3378. #[cfg(test)]
  3379. mod late_tests {
  3380. use super::{continues, join_ranges, touches};
  3381. /// Copies join only when both ends continue and the whole does not
  3382. /// overlap itself.
  3383. #[test]
  3384. fn copies_join_only_end_to_end_and_apart() {
  3385. // (destination, source, bytes)
  3386. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  3387. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  3388. // A gap, or only one side continues.
  3389. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  3390. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  3391. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  3392. // Together they would overlap: the second reads what the first wrote.
  3393. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  3394. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  3395. // They touch without overlapping.
  3396. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  3397. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  3398. }
  3399. /// Ranges are found by what they hold, not by where they start, and a
  3400. /// range that only touches another's end does not touch it.
  3401. #[test]
  3402. fn ranges_touch_where_they_overlap() {
  3403. let mut ranges = Vec::new();
  3404. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  3405. assert_eq!(ranges, [(10, 25), (40, 60)]);
  3406. join_ranges(&mut ranges, [(25, 40)]);
  3407. assert_eq!(ranges, [(10, 60)]);
  3408. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  3409. for (from, to, hit) in [
  3410. (0, 10, false),
  3411. (0, 11, true),
  3412. (24, 25, true),
  3413. (25, 40, false),
  3414. (25, 41, true),
  3415. (59, 200, true),
  3416. (60, 100, false),
  3417. (100, 101, true),
  3418. (101, 500, false),
  3419. (30, 30, false),
  3420. (50, 50, false),
  3421. ] {
  3422. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  3423. }
  3424. assert!(!touches(&[], 0, usize::MAX));
  3425. }
  3426. }
  3427. /// Whether a title buffer copy that continues the one recorded before it
  3428. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  3429. /// default).
  3430. ///
  3431. /// Each copy is done at submission through the kernel, which reports a
  3432. /// page that is not there instead of faulting (`copy_mapped`), tells the
  3433. /// write watch and the guards, and ends the refreshes gathered so far: a
  3434. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  3435. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  3436. /// continue the one before is counted either way and said on its own line
  3437. /// with the frame rate; the switch is worth that many kernel calls.
  3438. ///
  3439. /// Joined, the same bytes move: [`continues`] joins only copies whose
  3440. /// ranges, taken together, do not overlap, and nothing is recorded between
  3441. /// two steps that follow each other. What differs: a page that is not
  3442. /// mapped now fails the joined copy as a whole (it then goes page by page,
  3443. /// zeros for what cannot be read, as a single copy does), where before
  3444. /// only the copy that held it did.
  3445. fn join_copies() -> bool {
  3446. static ON: OnceLock<bool> = OnceLock::new();
  3447. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  3448. }
  3449. /// Since the last frame-rate line: title buffer copies recorded, and those
  3450. /// that continue the one before ([`join_copies`]).
  3451. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  3452. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  3453. /// where `last` ended, source and destination both, and the two as one do
  3454. /// not overlap (source over destination): then one copy of both moves the
  3455. /// bytes the two would move in turn.
  3456. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  3457. let ((d, s, n), (dst, src, len)) = (last, next);
  3458. let Some(all) = n.checked_add(len) else {
  3459. return false;
  3460. };
  3461. d.checked_add(n) == Some(dst)
  3462. && s.checked_add(n) == Some(src)
  3463. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  3464. }
  3465. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  3466. /// One list's lock at a time: a submission may name a list twice.
  3467. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  3468. let mut back: Vec<Declared> = Vec::new();
  3469. // Where each copy is in it, and the ranges seen: dispatches declare the
  3470. // same ranges thousands of times a frame.
  3471. let mut places: ByCopy<usize> = ByCopy::default();
  3472. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  3473. for list in runs {
  3474. for step in &list.deferred().copies {
  3475. if let Step::GpuWrite(shadow, address, len) = step {
  3476. let key = std::sync::Arc::as_ptr(shadow) as usize;
  3477. if !seen.insert((key, *address, *len)) {
  3478. continue;
  3479. }
  3480. let i = *places.entry(key).or_insert_with(|| {
  3481. back.push((shadow.clone(), Vec::new()));
  3482. back.len() - 1
  3483. });
  3484. back[i].1.push((*address, *address + *len));
  3485. }
  3486. }
  3487. }
  3488. back
  3489. }
  3490. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  3491. /// lines that say what the title's CPU was given while it decided whether
  3492. /// the camera is in a room. The values of the small read-backs
  3493. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  3494. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  3495. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  3496. /// copies found stale after their refresh (`shadow.rs`; only with
  3497. /// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
  3498. /// runtime, the read requests that fail (with 2: every request).
  3499. pub(crate) fn walls_trace() -> bool {
  3500. static ON: OnceLock<bool> = OnceLock::new();
  3501. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  3502. }
  3503. /// After `list` has run: the texels its read-backs copied into host
  3504. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  3505. ///
  3506. /// A submission that is waited for did this itself. One sent ahead
  3507. /// ([`late`]) did not, at any stage: the flights' lists were settled
  3508. /// without it, so the title read a buffer nobody wrote, as before read-backs
  3509. /// were made (the exposure metering's two small float targets, every frame).
  3510. fn read_backs(list: &HostList) {
  3511. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  3512. let mut data = std::ptr::null_mut();
  3513. // SAFETY: a read-back buffer of ours, written by the list that has
  3514. // run; the title's destination holds every row (checked when the
  3515. // copy was recorded).
  3516. unsafe {
  3517. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  3518. let from = data.cast::<u8>().cast_const();
  3519. for line in 0..*rows {
  3520. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  3521. }
  3522. // The walls trace: what the title is handed (one row of at
  3523. // most 24 values: its 5x1 and 1x1 float targets).
  3524. if walls_trace() && *rows == 1 && *row <= 96 {
  3525. let mut values = [0f32; 24];
  3526. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  3527. tracing::info!(
  3528. frame = crate::frame::current(),
  3529. to = format_args!("{:#x}", *at),
  3530. bytes = *row,
  3531. values = ?&values[..*row / 4],
  3532. "walls trace: a read-back lands in title memory"
  3533. );
  3534. }
  3535. buffer.Unmap(0, None);
  3536. }
  3537. }
  3538. }
  3539. }
  3540. /// After the card ran what declared `back`: what shaders wrote there goes
  3541. /// into title memory, and the ranges are done with.
  3542. fn hand_back(back: &[Declared]) {
  3543. if crate::shadow::wide_back() {
  3544. // Every range first (the pieces that differ, found on several
  3545. // threads), then the merges, in order, as below.
  3546. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3547. for (shadow, declared) in back {
  3548. if shadow.carded() {
  3549. continue;
  3550. }
  3551. let mut sorted = declared.clone();
  3552. sorted.sort_unstable();
  3553. let mut spans: Vec<(usize, usize)> = Vec::new();
  3554. for (from, to) in sorted {
  3555. match spans.last_mut() {
  3556. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3557. _ => spans.push((from, to)),
  3558. }
  3559. }
  3560. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3561. }
  3562. #[cfg(feature = "diagnostics")]
  3563. let scanning = std::time::Instant::now();
  3564. let found = crate::shadow::find_all(&work);
  3565. #[cfg(feature = "diagnostics")]
  3566. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3567. for ((shadow, from, to), found) in work.iter().zip(found) {
  3568. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3569. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3570. #[cfg(feature = "diagnostics")]
  3571. crate::copystat::compared(*from, to - from, written);
  3572. }
  3573. for (shadow, declared) in back {
  3574. shadow.copy_back_done(declared);
  3575. }
  3576. return;
  3577. }
  3578. for (shadow, declared) in back {
  3579. if shadow.carded() {
  3580. // Done before (`Host::card_back`).
  3581. shadow.copy_back_done(declared);
  3582. continue;
  3583. }
  3584. // Each byte compared once: the world declares dozens of views
  3585. // of its 174 MB heap that overlap almost entirely, and comparing
  3586. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3587. // MB shaders wrote. Only ranges that overlap or touch are
  3588. // joined: what lies between two was not given to shaders (the
  3589. // snapshot does not hold it).
  3590. let mut sorted = declared.clone();
  3591. sorted.sort_unstable();
  3592. let mut spans: Vec<(usize, usize)> = Vec::new();
  3593. for (from, to) in sorted {
  3594. match spans.last_mut() {
  3595. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3596. _ => spans.push((from, to)),
  3597. }
  3598. }
  3599. for (from, to) in spans {
  3600. let written = shadow.copy_back(from, to - from);
  3601. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3602. #[cfg(feature = "diagnostics")]
  3603. crate::copystat::compared(from, to - from, written);
  3604. }
  3605. shadow.copy_back_done(declared);
  3606. }
  3607. }
  3608. impl Host {
  3609. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3610. /// mesh shaders need both); logged once.
  3611. pub(crate) fn mesh_shaders(&self) -> bool {
  3612. static MESH: OnceLock<bool> = OnceLock::new();
  3613. *MESH.get_or_init(|| {
  3614. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3615. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3616. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3617. };
  3618. // SAFETY: each query writes its own structure of the given size.
  3619. let ok = unsafe {
  3620. self.device
  3621. .CheckFeatureSupport(
  3622. D3D12_FEATURE_D3D12_OPTIONS7,
  3623. (&raw mut options).cast(),
  3624. size_of_val(&options) as u32,
  3625. )
  3626. .is_ok()
  3627. && self
  3628. .device
  3629. .CheckFeatureSupport(
  3630. D3D12_FEATURE_SHADER_MODEL,
  3631. (&raw mut model).cast(),
  3632. size_of_val(&model) as u32,
  3633. )
  3634. .is_ok()
  3635. };
  3636. let mesh = ok
  3637. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3638. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3639. tracing::info!(mesh, "host mesh shader support");
  3640. mesh
  3641. })
  3642. }
  3643. /// Whether the host GPU supports the depth bounds test; logged once.
  3644. pub(crate) fn depth_bounds(&self) -> bool {
  3645. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3646. *BOUNDS.get_or_init(|| {
  3647. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3648. // SAFETY: writes `options` of the given size.
  3649. let ok = unsafe {
  3650. self.device
  3651. .CheckFeatureSupport(
  3652. D3D12_FEATURE_D3D12_OPTIONS2,
  3653. (&raw mut options).cast(),
  3654. size_of_val(&options) as u32,
  3655. )
  3656. .is_ok()
  3657. };
  3658. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3659. tracing::info!(supported, "host depth bounds support");
  3660. supported
  3661. })
  3662. }
  3663. /// A new list, open for recording.
  3664. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3665. #[cfg(feature = "diagnostics")]
  3666. let started = std::time::Instant::now();
  3667. #[cfg(feature = "diagnostics")]
  3668. let before = private_bytes();
  3669. let list = self.make_list();
  3670. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3671. // (May shrink while a list is made, on another thread's account:
  3672. // added as it is, the sum is what counts.)
  3673. #[cfg(feature = "diagnostics")]
  3674. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3675. #[cfg(feature = "diagnostics")]
  3676. {
  3677. use crate::copystat::{C, add};
  3678. add(C::HostLists, 1);
  3679. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3680. }
  3681. list
  3682. }
  3683. /// An allocator and a closed list for a prelude.
  3684. fn make_prelude(&self) -> Option<Prelude> {
  3685. // SAFETY: plain object creation.
  3686. let made: windows::core::Result<Prelude> = unsafe {
  3687. (|| {
  3688. let allocator: ID3D12CommandAllocator =
  3689. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3690. let list: ID3D12GraphicsCommandList =
  3691. self.device
  3692. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3693. list.Close()?;
  3694. Ok((allocator, list))
  3695. })()
  3696. };
  3697. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3698. match made {
  3699. Ok(prelude) => Some(prelude),
  3700. Err(e) => {
  3701. tracing::warn!(error = %e, "no host list for a prelude");
  3702. None
  3703. }
  3704. }
  3705. }
  3706. fn make_list(&self) -> windows::core::Result<HostList> {
  3707. // SAFETY: plain object creation.
  3708. unsafe {
  3709. let allocator: ID3D12CommandAllocator = self
  3710. .device
  3711. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3712. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3713. 0,
  3714. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3715. &allocator,
  3716. None,
  3717. )?;
  3718. let prelude = OnceLock::new();
  3719. if !lazy_prelude() {
  3720. let _ = prelude.set(self.make_prelude());
  3721. }
  3722. #[cfg(feature = "diagnostics")]
  3723. let notes = std::sync::Arc::<Mutex<Vec<Note>>>::default();
  3724. let pipelines = std::sync::Arc::<Mutex<std::collections::BTreeSet<String>>>::default();
  3725. #[cfg(feature = "diagnostics")]
  3726. let indirects = indirects::Shared::default();
  3727. #[cfg(feature = "diagnostics")]
  3728. if dred_on() || dred_light() {
  3729. static NUMBER: AtomicU32 = AtomicU32::new(0);
  3730. let number = NUMBER.fetch_add(1, Ordering::Relaxed);
  3731. name(&list, || format!("victory host list {number}"));
  3732. let mut all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  3733. if number.is_multiple_of(256) {
  3734. all.retain(|_, l| l.0.strong_count() > 0);
  3735. }
  3736. all.insert(
  3737. number,
  3738. (
  3739. std::sync::Arc::downgrade(&notes),
  3740. std::sync::Arc::downgrade(&pipelines),
  3741. std::sync::Arc::downgrade(&indirects),
  3742. ),
  3743. );
  3744. }
  3745. Ok(HostList {
  3746. allocator,
  3747. list,
  3748. deferred: Mutex::default(),
  3749. scratch: Mutex::default(),
  3750. states: Mutex::default(),
  3751. twins: Mutex::default(),
  3752. prelude,
  3753. pipelines,
  3754. #[cfg(feature = "diagnostics")]
  3755. indirects,
  3756. budget: OnceLock::new(),
  3757. card_budget: OnceLock::new(),
  3758. indirect_args: Mutex::default(),
  3759. batch_args: Mutex::default(),
  3760. coming: Mutex::default(),
  3761. epoch: std::sync::atomic::AtomicU64::new(next_epoch()),
  3762. _alive: Counted::new(),
  3763. #[cfg(feature = "diagnostics")]
  3764. notes,
  3765. #[cfg(feature = "diagnostics")]
  3766. stamps: OnceLock::new(),
  3767. })
  3768. }
  3769. }
  3770. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3771. fn card_clock(&self) -> Option<&'static CardClock> {
  3772. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3773. static WATCH: std::sync::Once = std::sync::Once::new();
  3774. let clock = CLOCK
  3775. .get_or_init(|| {
  3776. // SAFETY: a plain fence on our device.
  3777. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3778. Some(CardClock {
  3779. fence,
  3780. state: Mutex::new((0, None)),
  3781. sent: std::sync::Condvar::new(),
  3782. })
  3783. })
  3784. .as_ref()?;
  3785. WATCH.call_once(|| {
  3786. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3787. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3788. }
  3789. });
  3790. Some(clock)
  3791. }
  3792. /// Lists of ours just went to the queue: the clock's signal goes
  3793. /// behind them, and an idle stretch of the card, if one was under way,
  3794. /// ends here ([`CARD_CLOCK_US`]).
  3795. fn card_sent(&self) {
  3796. let Some(clock) = self.card_clock() else {
  3797. return;
  3798. };
  3799. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3800. state.0 += 1;
  3801. // SAFETY: our queue and the clock's fence.
  3802. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3803. if let Some((since, worked_then)) = state.1.take() {
  3804. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3805. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3806. }
  3807. drop(state);
  3808. clock.sent.notify_one();
  3809. }
  3810. /// Whether the host has what copies in the card's memory need (three
  3811. /// lists and the compare); made at the first ask. A copy goes to the
  3812. /// card's memory only if it has.
  3813. pub(crate) fn card_ready(&self) -> bool {
  3814. static READY: OnceLock<bool> = OnceLock::new();
  3815. *READY.get_or_init(|| match self.make_card_work() {
  3816. Ok(work) => {
  3817. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3818. true
  3819. }
  3820. Err(e) => {
  3821. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3822. false
  3823. }
  3824. })
  3825. }
  3826. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3827. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3828. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3829. let mut code: Option<ID3DBlob> = None;
  3830. // SAFETY: the source and names live through the call; the out
  3831. // pointer is ours.
  3832. unsafe {
  3833. D3DCompile(
  3834. CARD_COMPARE.as_ptr().cast(),
  3835. CARD_COMPARE.len(),
  3836. windows::core::s!("card compare"),
  3837. None,
  3838. None,
  3839. windows::core::s!("main"),
  3840. windows::core::s!("cs_5_1"),
  3841. 0,
  3842. 0,
  3843. &mut code,
  3844. None,
  3845. )?;
  3846. }
  3847. let code = code.ok_or_else(windows::core::Error::empty)?;
  3848. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3849. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3850. // in one submission.
  3851. const RESULTS: u64 = 1 << 20;
  3852. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3853. name(&differs, || "card compare results".into());
  3854. // SAFETY: the blob's own bytes; the root signature is inside the
  3855. // shader.
  3856. unsafe {
  3857. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3858. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3859. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3860. pRootSignature: std::mem::transmute_copy(&root),
  3861. CS: D3D12_SHADER_BYTECODE {
  3862. pShaderBytecode: bytes.as_ptr().cast(),
  3863. BytecodeLength: bytes.len(),
  3864. },
  3865. ..Default::default()
  3866. })?;
  3867. #[cfg(feature = "diagnostics")]
  3868. name(&pso, || crate::replay::play::COMPARE.into());
  3869. Ok(CardWork {
  3870. sync: vec![list()?],
  3871. check: vec![list()?],
  3872. fetch: list()?,
  3873. root,
  3874. pso,
  3875. differs: (differs, data as usize, RESULTS),
  3876. fetched: None,
  3877. taken: 0,
  3878. out: 0,
  3879. })
  3880. }
  3881. }
  3882. /// Before a submission's lists run, for copies in the card's memory
  3883. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3884. /// the last submission goes to their card side (a list of ours, run
  3885. /// now; the submission's lists follow it on the queue), and the ranges
  3886. /// this submission's shaders may write get a compare to run after its
  3887. /// lists. `None` if there is nothing to do.
  3888. ///
  3889. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3890. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3891. /// `relay`).
  3892. /// `picked`: ranges that may be written too, and ranges to look at
  3893. /// (`crate::picked`).
  3894. fn card_before(&self, declared: &[Declared], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3895. use std::sync::Arc;
  3896. if !crate::shadow::cards() {
  3897. return None;
  3898. }
  3899. // The ranges this submission's shaders may write, per copy.
  3900. let declared: Vec<Declared> = declared.iter().filter(|(shadow, _)| shadow.carded()).cloned().collect();
  3901. let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
  3902. // (Of a copy with a declared range here, that says it.)
  3903. let looked: Vec<&crate::picked::Range> =
  3904. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3905. // With the relay: the order of the queue is held from here until
  3906. // what is taken is on the queue, and the taking is numbered.
  3907. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3908. let sent_as = match order.as_mut() {
  3909. Some(order) => {
  3910. **order += 1;
  3911. **order
  3912. }
  3913. None => 0,
  3914. };
  3915. let mut dirty = crate::shadow::card_dirty(sent_as);
  3916. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3917. return None;
  3918. }
  3919. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3920. let work = work.as_mut()?;
  3921. // A copy whose shader writes are declared for the first time gets
  3922. // its bytes from before, whole.
  3923. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3924. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3925. if shadow.card_make_before(|size| {
  3926. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3927. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3928. Some(before)
  3929. }) {
  3930. whole.push(shadow.clone());
  3931. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3932. dirty.push((shadow.clone(), Vec::new()));
  3933. }
  3934. }
  3935. }
  3936. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3937. let mut looks = None;
  3938. // The bytes as they are now, whatever later submissions put there.
  3939. let own = if send::own() { send::take(self, &dirty) } else { None };
  3940. if !dirty.is_empty() {
  3941. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3942. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3943. };
  3944. let (allocator, list) = &sync;
  3945. // SAFETY: the list's last run finished (it ran ahead of a
  3946. // submission that was waited for, and came back after that);
  3947. // live buffers, and the ranges lie in them.
  3948. let recorded = unsafe {
  3949. (|| -> windows::core::Result<()> {
  3950. allocator.Reset()?;
  3951. list.Reset(allocator, None)?;
  3952. if upcheck::on() {
  3953. looks = upcheck::record(self, list, &dirty);
  3954. }
  3955. // Every copy first, then one barrier call, then every
  3956. // pass: a wait between each copy and its pass had the
  3957. // card do them one after the other.
  3958. let mut sent = Vec::new();
  3959. if let Some(own) = &own {
  3960. own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
  3961. }
  3962. for (shadow, ranges) in &dirty {
  3963. let Some((staging, before, _)) = shadow.card_sides() else {
  3964. continue;
  3965. };
  3966. for &(a, b) in ranges {
  3967. if own.is_none() {
  3968. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3969. }
  3970. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3971. }
  3972. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3973. #[cfg(feature = "diagnostics")]
  3974. traffic::moved(traffic::UP, shadow.span(), ranges.iter().copied());
  3975. if own.is_none() && before.is_some() && !ranges.is_empty() {
  3976. sent.push(transition(
  3977. &shadow.buffer,
  3978. D3D12_RESOURCE_STATE_COPY_DEST,
  3979. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3980. ));
  3981. }
  3982. }
  3983. if !sent.is_empty() {
  3984. list.ResourceBarrier(&sent);
  3985. }
  3986. list.SetComputeRootSignature(&work.root);
  3987. list.SetPipelineState(&work.pso);
  3988. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3989. for (shadow, ranges) in &dirty {
  3990. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3991. continue;
  3992. };
  3993. // No twin (it cost the card the copy's size again,
  3994. // 399 MB in run 75): `before` holds a 128-bit hash
  3995. // of each 64 KiB piece. The pieces just sent up are
  3996. // hashed again, all of them the first time; the
  3997. // compare after the lists hashes the declared
  3998. // pieces and flags those whose hash is another.
  3999. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  4000. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  4001. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  4002. vec![shadow.card_run(0, usize::MAX)]
  4003. } else {
  4004. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  4005. };
  4006. // The same pieces in fewer passes (`rehash_runs`).
  4007. let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
  4008. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  4009. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  4010. for run in runs {
  4011. card_pass(list, &run, size as u32, 0, 0);
  4012. }
  4013. }
  4014. list.Close()?;
  4015. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4016. Ok(())
  4017. })()
  4018. };
  4019. if let Err(e) = recorded {
  4020. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  4021. }
  4022. used.push((false, sync));
  4023. }
  4024. drop(order);
  4025. let mut plan = CardPlan {
  4026. ranges: Vec::new(),
  4027. check: None,
  4028. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  4029. lists: used,
  4030. sent_as,
  4031. looks,
  4032. sends: own.map(send::Own::memory),
  4033. };
  4034. // Each byte once, as the copy-back joins the declared ranges. The
  4035. // results go behind those of plans still in the air.
  4036. let mut at = work.taken;
  4037. for (shadow, ranges) in &declared {
  4038. let mut sorted = ranges.clone();
  4039. sorted.sort_unstable();
  4040. let mut spans: Vec<(usize, usize)> = Vec::new();
  4041. for (from, to) in sorted {
  4042. match spans.last_mut() {
  4043. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  4044. _ => spans.push((from, to)),
  4045. }
  4046. }
  4047. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  4048. for (from, to) in spans {
  4049. let Some(span) = shadow.card_span(from, to) else {
  4050. continue;
  4051. };
  4052. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  4053. plan.ranges.push(CardRange {
  4054. shadow: shadow.clone(),
  4055. declared: (from, to),
  4056. span,
  4057. at,
  4058. compared,
  4059. picked: false,
  4060. });
  4061. if compared {
  4062. at += span.pieces;
  4063. }
  4064. }
  4065. }
  4066. for (shadow, from, len) in looked {
  4067. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  4068. if let Some(span) = shadow.card_span(*from, from + len)
  4069. && twin
  4070. && u64::from(at + span.pieces) * 4 <= work.differs.2
  4071. {
  4072. plan.ranges.push(CardRange {
  4073. shadow: shadow.clone(),
  4074. declared: (*from, from + len),
  4075. span,
  4076. at,
  4077. compared: true,
  4078. picked: true,
  4079. });
  4080. at += span.pieces;
  4081. }
  4082. }
  4083. work.taken = at;
  4084. if plan.ranges.iter().any(|r| r.compared) {
  4085. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  4086. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  4087. };
  4088. let (allocator, list) = &check;
  4089. // SAFETY: the list's last run finished (its submission was
  4090. // waited for, and it came back after that); live buffers; the
  4091. // compare's own root signature.
  4092. let recorded = unsafe {
  4093. (|| -> windows::core::Result<ID3D12CommandList> {
  4094. allocator.Reset()?;
  4095. list.Reset(allocator, None)?;
  4096. // What the submission's shaders wrote, first.
  4097. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  4098. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  4099. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  4100. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  4101. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  4102. pResource: std::mem::ManuallyDrop::new(None),
  4103. }),
  4104. },
  4105. }]);
  4106. list.SetComputeRootSignature(&work.root);
  4107. list.SetPipelineState(&work.pso);
  4108. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  4109. for r in plan.ranges.iter().filter(|r| r.compared) {
  4110. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  4111. continue;
  4112. };
  4113. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  4114. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  4115. // (What is only looked at keeps its hashes: what
  4116. // changed there is the next declared range's to land.)
  4117. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  4118. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  4119. }
  4120. list.Close()?;
  4121. list.cast()
  4122. })()
  4123. };
  4124. match recorded {
  4125. Ok(list) => plan.check = Some(list),
  4126. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  4127. }
  4128. plan.lists.push((true, check));
  4129. }
  4130. work.out += 1;
  4131. Some(plan)
  4132. }
  4133. /// With [`relay`]: whether the compare's result area is half taken by
  4134. /// plans in the air. It starts from the beginning only when no plan is
  4135. /// out, so the caller lets the flights land first.
  4136. fn card_results_low(&self) -> bool {
  4137. CARD_WORK
  4138. .lock()
  4139. .unwrap_or_else(|e| e.into_inner())
  4140. .as_ref()
  4141. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  4142. }
  4143. /// The plan's submission has run and its results were read
  4144. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  4145. /// when nothing of ours is on the card, so the compare's results start
  4146. /// from the beginning again.
  4147. fn card_done(&self, plan: CardPlan) {
  4148. if let Some(looks) = plan.looks {
  4149. looks.read();
  4150. }
  4151. if let Some(memory) = plan.sends {
  4152. send::give_back(memory);
  4153. }
  4154. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4155. let Some(work) = work.as_mut() else {
  4156. return;
  4157. };
  4158. for (check, list) in plan.lists {
  4159. if check { work.check.push(list) } else { work.sync.push(list) }
  4160. }
  4161. work.out = work.out.saturating_sub(1);
  4162. // With the relay other plans may be on the card, their results
  4163. // not read yet: the area starts again only when none is out.
  4164. if !relay() || work.out == 0 {
  4165. work.taken = 0;
  4166. }
  4167. }
  4168. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  4169. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  4170. // SAFETY: plain object creation.
  4171. let copying = relay_copy().then(|| unsafe {
  4172. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  4173. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  4174. let list: ID3D12GraphicsCommandList =
  4175. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  4176. list.Close()?;
  4177. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  4178. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  4179. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  4180. ..Default::default()
  4181. })?;
  4182. Ok(((allocator, list), queue))
  4183. })()
  4184. });
  4185. let (list, queue) = match copying {
  4186. Some(Ok((list, queue))) => (list, Some(queue)),
  4187. Some(Err(e)) => {
  4188. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  4189. (self.make_prelude()?, None)
  4190. }
  4191. None => (self.make_prelude()?, None),
  4192. };
  4193. // SAFETY: plain objects of our own.
  4194. unsafe {
  4195. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  4196. let event = CreateEventW(None, false, false, None).ok()?;
  4197. Some(RelayFetch {
  4198. list,
  4199. queue,
  4200. fence,
  4201. event,
  4202. sent: 0,
  4203. buffer: None,
  4204. suspects: torn::Suspects::default(),
  4205. had: crate::land::Had::default(),
  4206. })
  4207. }
  4208. }
  4209. /// [`relay`], on the thread that lands flights: for the plans of the
  4210. /// flights being landed (the card has run them), the pieces their
  4211. /// compares flagged are fetched, once each, with a list and a wait of
  4212. /// this thread's own, and what shaders wrote in them goes into title
  4213. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  4214. /// no submission lock; a piece flagged under one range of a plan is
  4215. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  4216. /// whatever was sent meanwhile, so it may bring a later flight's
  4217. /// bytes, which that flight's landing then finds merged already; and
  4218. /// nothing is sent back up. `plans` come with the value signalled behind
  4219. /// their flight. `meanwhile` is called while the fetch is on its way, if
  4220. /// there is one.
  4221. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  4222. use crate::land;
  4223. let gathering = std::time::Instant::now();
  4224. let differs = {
  4225. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4226. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  4227. };
  4228. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  4229. let mut total = 0u64;
  4230. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  4231. fetch.had.landing(first);
  4232. }
  4233. // SAFETY: the mapping of the results. The compares of these plans
  4234. // have run, and their dwords are given to no other plan before these
  4235. // are done with (`card_done`).
  4236. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  4237. if let Some(differs) = differs {
  4238. // Pieces caught while a later flight was at them (`torn`).
  4239. let suspects = fetch.as_ref().map(|f| &f.suspects);
  4240. let mut seen = std::collections::HashSet::new();
  4241. for &(plan, behind) in plans {
  4242. plan.picked_found(differs);
  4243. let flags: Vec<(usize, u32, bool)> = plan
  4244. .ranges
  4245. .iter()
  4246. .filter(|r| !r.picked)
  4247. .flat_map(|r| {
  4248. (0..r.span.pieces).map(move |p| {
  4249. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  4250. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  4251. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  4252. })
  4253. })
  4254. .collect();
  4255. let fetched = flagged_pieces(&flags);
  4256. for r in plan.ranges.iter().filter(|r| !r.picked) {
  4257. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  4258. if upcheck::on() {
  4259. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  4260. }
  4261. for p in 0..r.span.pieces {
  4262. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  4263. continue;
  4264. }
  4265. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4266. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  4267. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  4268. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  4269. land::count(land::stat::HAD, 1);
  4270. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  4271. if land::skip_on() {
  4272. continue;
  4273. }
  4274. }
  4275. if upcheck::on() {
  4276. upcheck::fetched(r.shadow.id(), lo);
  4277. }
  4278. seen.insert((copy, lo, hi));
  4279. pieces.push((r.shadow.clone(), lo, hi, total));
  4280. total += (hi - lo) as u64;
  4281. }
  4282. }
  4283. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4284. }
  4285. }
  4286. }
  4287. if land::on() {
  4288. // In the order they are landed, each byte of a copy once.
  4289. let keys: Vec<land::Piece> =
  4290. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  4291. total = 0;
  4292. pieces = land::ordered(&keys)
  4293. .into_iter()
  4294. .map(|(i, title, len)| {
  4295. let shadow = &pieces[i].0;
  4296. let lo = title - shadow.span().0 as usize;
  4297. let at = total;
  4298. total += len as u64;
  4299. (shadow.clone(), lo, lo + len, at)
  4300. })
  4301. .collect();
  4302. }
  4303. land::spent(land::stat::GATHER, gathering);
  4304. if fetch.is_none() {
  4305. *fetch = self.make_relay_fetch();
  4306. }
  4307. // On the copy queue a later flight may be at a piece while it is
  4308. // fetched: the pieces come down whole, to be hashed.
  4309. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  4310. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  4311. if let Some(check) = &check {
  4312. total = check.total;
  4313. }
  4314. #[cfg(feature = "diagnostics")]
  4315. for (shadow, lo, hi, _) in &pieces {
  4316. traffic::moved(traffic::FETCHED, shadow.span(), std::iter::once((*lo, *hi)));
  4317. }
  4318. // The sends these flights ran behind, all a fetch on the copy queue
  4319. // is known to have run behind.
  4320. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  4321. if pieces.is_empty() {
  4322. // Nothing to fetch: every send so far is older than the next
  4323. // fetch, if that goes to the queue the sends went to.
  4324. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  4325. true => behind,
  4326. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  4327. };
  4328. crate::shadow::relay_fetched(after);
  4329. return;
  4330. }
  4331. let Some(f) = fetch.as_mut() else {
  4332. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  4333. };
  4334. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  4335. let size = total.next_multiple_of(16 << 20);
  4336. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4337. }
  4338. let Some((buffer, data, _)) = f.buffer.clone() else {
  4339. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  4340. };
  4341. f.sent += 1;
  4342. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  4343. let copy_queue = f.queue.clone();
  4344. let waiting = std::time::Instant::now();
  4345. // The flights the fetch runs behind: those in the line by now have
  4346. // been given to the queue. On the copy queue, those landed here.
  4347. let ahead = match copy_queue {
  4348. Some(_) => 0,
  4349. None => line().target,
  4350. };
  4351. // SAFETY: the list's last run was waited for by this thread; live
  4352. // buffers (the copies are held by the plans); the fence and the
  4353. // event are this thread's.
  4354. let ran = unsafe {
  4355. (|| -> windows::core::Result<u64> {
  4356. allocator.Reset()?;
  4357. list.Reset(&allocator, None)?;
  4358. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  4359. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  4360. }
  4361. list.Close()?;
  4362. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  4363. let _fetching = crate::timeline::span("landing: fetching pieces");
  4364. if let Some(queue) = &copy_queue {
  4365. queue.ExecuteCommandLists(&lists);
  4366. queue.Signal(&fence, sent)?;
  4367. meanwhile();
  4368. fence.SetEventOnCompletion(sent, event)?;
  4369. #[cfg(feature = "diagnostics")]
  4370. let _card = crate::timeline::card_wait(None);
  4371. WaitForSingleObject(event, INFINITE);
  4372. return Ok(behind);
  4373. }
  4374. // In the order of the queue: the sends of title bytes so
  4375. // far are ahead of this fetch, every later one behind it.
  4376. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  4377. self.queue.ExecuteCommandLists(&lists);
  4378. let after = *order;
  4379. drop(order);
  4380. self.card_sent();
  4381. self.queue.Signal(&fence, sent)?;
  4382. meanwhile();
  4383. fence.SetEventOnCompletion(sent, event)?;
  4384. #[cfg(feature = "diagnostics")]
  4385. let _card = crate::timeline::card_wait(None);
  4386. WaitForSingleObject(event, INFINITE);
  4387. Ok(after)
  4388. })()
  4389. };
  4390. let after = match ran {
  4391. Ok(after) => after,
  4392. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  4393. };
  4394. let us = waiting.elapsed().as_micros() as u64;
  4395. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  4396. {
  4397. use crate::shadow::CARD_STATS;
  4398. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4399. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4400. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4401. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  4402. }
  4403. let merging = std::time::Instant::now();
  4404. let _merging = crate::timeline::span("landing: merging fetched pieces");
  4405. let mut written = 0;
  4406. if land::on() {
  4407. let titles: Vec<(usize, usize)> =
  4408. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  4409. let jobs = land::jobs(&titles);
  4410. let put = std::sync::atomic::AtomicU64::new(0);
  4411. land::each(jobs.len(), &|j| {
  4412. let working = std::time::Instant::now();
  4413. if let Some(check) = &check {
  4414. for i in jobs[j].clone() {
  4415. // SAFETY: as below.
  4416. unsafe { check.look(i, data) };
  4417. }
  4418. }
  4419. let mut notes = land::Notes::default();
  4420. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  4421. let addressed: Vec<(usize, usize, usize)> =
  4422. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  4423. // SAFETY: the mapping of the fetched bytes, `total` of
  4424. // them; the copy into it has run, and the next waits
  4425. // for this call.
  4426. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  4427. }
  4428. notes.flush();
  4429. land::spent(land::stat::CARD_ALL, working);
  4430. });
  4431. land::count(land::stat::JOBS, jobs.len() as u64);
  4432. written = put.into_inner();
  4433. } else {
  4434. let mut title = Vec::new();
  4435. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  4436. if let Some(check) = &check {
  4437. // SAFETY: as below.
  4438. unsafe { check.look(i, data) };
  4439. }
  4440. // SAFETY: the mapping of the fetched bytes, `total` of them;
  4441. // the copy into it has run.
  4442. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  4443. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  4444. shadow.walls_merged(gpu.len(), merged);
  4445. written += merged as u64;
  4446. }
  4447. }
  4448. land::spent(land::stat::CARD, merging);
  4449. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  4450. if let Some(f) = fetch.as_mut() {
  4451. if let Some(check) = &check {
  4452. check.done(&mut f.suspects);
  4453. }
  4454. f.had.fetched(
  4455. ahead,
  4456. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  4457. );
  4458. }
  4459. // Sends up to `after` are of no use to any later merge.
  4460. crate::shadow::relay_fetched(after);
  4461. }
  4462. /// [`relay`], on the thread that lands flights: `items` are the first
  4463. /// things of the line, flights the card has run and what follows them.
  4464. /// What their shaders wrote goes into title memory (copies in the
  4465. /// card's memory first, then the others, each byte once whichever
  4466. /// flights declared it); then every flight's ranges are done with;
  4467. /// then, in the line's order, each flight's read-backs, its
  4468. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  4469. /// is complete before the title is told anything.
  4470. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  4471. let landing = std::time::Instant::now();
  4472. let mut stage = crate::timeline::span("landing: what is to be looked through");
  4473. {
  4474. let flights: Vec<&Flight> = items
  4475. .iter()
  4476. .filter_map(|l| match l {
  4477. Late::Run(flight) => Some(flight),
  4478. _ => None,
  4479. })
  4480. .collect();
  4481. if !flights.is_empty() {
  4482. // SAFETY: a plain query.
  4483. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4484. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  4485. fail(format_args!(
  4486. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  4487. flights.len(),
  4488. runs.len(),
  4489. self.removal_data(&runs),
  4490. last_notes(&runs)
  4491. ));
  4492. }
  4493. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  4494. // (Each byte once: the ranges are joined.)
  4495. let mut back: Vec<Declared> = Vec::new();
  4496. for flight in &flights {
  4497. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  4498. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4499. Some((_, all)) => all.extend_from_slice(ranges),
  4500. None => back.push((shadow.clone(), ranges.clone())),
  4501. }
  4502. }
  4503. }
  4504. let mut hand_back = relay_hand_back(&back);
  4505. stage.next("landing: copies in the card's memory");
  4506. self.relay_card_back(&plans, fetch, &mut || {
  4507. if crate::land::on() {
  4508. let _looking = crate::timeline::span("landing: looking through copies, beside the fetch");
  4509. hand_back.look(crate::land::stat::SCAN_BESIDE);
  4510. }
  4511. });
  4512. stage.next("landing: copies in the PC's memory");
  4513. hand_back.merge();
  4514. stage.next("landing: ranges done with");
  4515. let finishing = std::time::Instant::now();
  4516. // Only now, and flight by flight: a range another flight
  4517. // in the air declared too stays closed to refreshes.
  4518. for flight in &flights {
  4519. for (shadow, ranges) in &flight.back {
  4520. shadow.copy_back_done(ranges);
  4521. }
  4522. }
  4523. crate::land::spent(crate::land::stat::DONE, finishing);
  4524. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4525. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  4526. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  4527. }
  4528. }
  4529. // In the order given: what tells the title the card is done.
  4530. stage.next("landing: read-backs, telling the title");
  4531. let mut last = 0;
  4532. let mut landed = Vec::new();
  4533. let mut telling = std::time::Instant::now();
  4534. for item in items {
  4535. telling = match item {
  4536. Late::Run(flight) => {
  4537. last = flight.number;
  4538. for &i in &flight.order {
  4539. read_backs(flight.lists[i].host());
  4540. }
  4541. if let Some(card) = flight.card {
  4542. self.card_done(card);
  4543. }
  4544. if let Some(own) = flight.own {
  4545. own.landed();
  4546. }
  4547. landed.push((flight.lists, flight.order));
  4548. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  4549. }
  4550. Late::Write(at, what, bytes) => {
  4551. what.write(at as *mut u8, bytes);
  4552. crate::land::spent(crate::land::stat::TOLD, telling)
  4553. }
  4554. Late::Signal(fence, value) => {
  4555. crate::fence::set(fence as crate::object::This, value);
  4556. crate::land::spent(crate::land::stat::TOLD, telling)
  4557. }
  4558. };
  4559. }
  4560. if last > 0 {
  4561. FINISHED.store(last, Ordering::Release);
  4562. bury(last);
  4563. }
  4564. stage.next("landing: the rest");
  4565. self.log_messages();
  4566. crate::land::spent(crate::land::stat::REST, telling);
  4567. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4568. {
  4569. let mut line = line();
  4570. let Line {
  4571. line: items,
  4572. written,
  4573. lists,
  4574. settling,
  4575. poke,
  4576. landed: kept,
  4577. in_hand,
  4578. landing,
  4579. ..
  4580. } = &mut *line;
  4581. kept.extend(landed);
  4582. in_hand.clear();
  4583. landing.clear();
  4584. // What is still in the air, from the flights that are.
  4585. written.clear();
  4586. *lists = 0;
  4587. let mut ranges = Vec::new();
  4588. for item in items.iter() {
  4589. if let Late::Run(flight) = item {
  4590. *lists += flight.order.len().max(1);
  4591. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  4592. }
  4593. }
  4594. join_ranges(written, ranges);
  4595. *settling = false;
  4596. // The landed lists are reset, and what queues hold looked at,
  4597. // by the helper thread (they take locks a waiter may hold).
  4598. *poke = true;
  4599. }
  4600. LINE_MOVED.notify_all();
  4601. LINE_LANDED.notify_all();
  4602. }
  4603. /// After a submission ran, for copies in the card's memory: the pieces
  4604. /// of the declared ranges that the compare found differing (all of a
  4605. /// range it did not compare) are fetched, with one more wait for the
  4606. /// card, and what shaders wrote in them goes into title memory.
  4607. /// `submitted` is the last value signalled on the fence. `seen` holds
  4608. /// the pieces fetched already since the card was last waited for
  4609. /// (several submissions settled together name the same ones).
  4610. fn card_back(
  4611. &self,
  4612. plan: &CardPlan,
  4613. submitted: &mut u64,
  4614. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4615. ) {
  4616. if plan.ranges.is_empty() {
  4617. return;
  4618. }
  4619. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4620. let Some(work) = work.as_mut() else {
  4621. return;
  4622. };
  4623. // SAFETY: the mapping of the results, which the compare (it has
  4624. // run) wrote.
  4625. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4626. // The pieces to fetch: the range, the offsets in its copy, and
  4627. // where the bytes come down.
  4628. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4629. let mut total = 0u64;
  4630. plan.picked_found(differs);
  4631. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4632. for p in 0..r.span.pieces {
  4633. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4634. continue;
  4635. }
  4636. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4637. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4638. pieces.push((i, lo, hi, total));
  4639. total += (hi - lo) as u64;
  4640. }
  4641. }
  4642. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4643. }
  4644. let mut written = vec![0usize; plan.ranges.len()];
  4645. if !pieces.is_empty() {
  4646. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4647. let size = total.next_multiple_of(16 << 20);
  4648. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4649. }
  4650. let Some((fetched, data, _)) = &work.fetched else {
  4651. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4652. };
  4653. let waiting = std::time::Instant::now();
  4654. let (allocator, list) = &work.fetch;
  4655. // SAFETY: the list's last run was waited for; live buffers; the
  4656. // fence and event are ours, under the submission lock.
  4657. let ran = unsafe {
  4658. (|| -> windows::core::Result<()> {
  4659. allocator.Reset()?;
  4660. list.Reset(allocator, None)?;
  4661. for &(i, lo, hi, at) in &pieces {
  4662. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4663. }
  4664. list.Close()?;
  4665. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4666. self.card_sent();
  4667. *submitted += 1;
  4668. self.queue.Signal(&self.fence, *submitted)?;
  4669. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4670. let was_working = working(false);
  4671. WaitForSingleObject(self.event, INFINITE);
  4672. stood(waiting);
  4673. working(was_working);
  4674. Ok(())
  4675. })()
  4676. };
  4677. if let Err(e) = ran {
  4678. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4679. }
  4680. {
  4681. use crate::shadow::CARD_STATS;
  4682. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4683. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4684. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4685. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4686. }
  4687. if wide_merge() && pieces.len() >= 8 {
  4688. // The pieces are apart from one another (each its own bytes
  4689. // of its copy and of title memory): several at a time.
  4690. let fetched = *data;
  4691. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4692. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4693. let each = pieces.len().div_ceil(8);
  4694. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4695. .chunks(each)
  4696. .map(|chunk| {
  4697. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4698. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4699. let counts = counts.clone();
  4700. Box::new(move || {
  4701. let mut title = Vec::new();
  4702. for (shadow, i, lo, hi, at) in chunk {
  4703. // SAFETY: the mapping of the fetched bytes;
  4704. // the copy into it has run, and the caller
  4705. // waits for this job.
  4706. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4707. let merged = shadow.card_merge(lo, gpu, &mut title);
  4708. shadow.walls_merged(gpu.len(), merged);
  4709. counts[i].fetch_add(merged, Ordering::Relaxed);
  4710. }
  4711. }) as Box<dyn FnOnce() + Send>
  4712. })
  4713. .collect();
  4714. crate::shadow::wide_run(jobs);
  4715. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4716. *written += count.load(Ordering::Relaxed);
  4717. }
  4718. } else {
  4719. let mut title = Vec::new();
  4720. for &(i, lo, hi, at) in &pieces {
  4721. // SAFETY: the mapping of the fetched bytes, `total` of
  4722. // them; the copy into it has run.
  4723. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4724. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4725. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4726. written[i] += merged;
  4727. }
  4728. }
  4729. }
  4730. for (r, written) in plan.ranges.iter().zip(written) {
  4731. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4732. let (from, to) = r.declared;
  4733. #[cfg(feature = "diagnostics")]
  4734. crate::copystat::compared(from, to - from, written);
  4735. let _ = (from, to);
  4736. }
  4737. }
  4738. /// Runs closed lists and waits for them, and with [`late`] for
  4739. /// everything sent to the card before them, which is settled first.
  4740. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4741. // Behind what the title's queues were given before it.
  4742. crate::queue::before_sync();
  4743. let _ = self.submit(runs, &[], false);
  4744. }
  4745. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4746. /// from the title's, go to the card in `order` and are not waited for.
  4747. /// They join the line of flights and are settled, with the others in
  4748. /// the air, at the next point where what they do can be observed
  4749. /// ([`late`] lists those points); their host lists are reset and kept
  4750. /// for reuse then, as a queue does for the lists it ran.
  4751. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4752. self.execute_parts(lists, order, &[]);
  4753. }
  4754. /// [`Host::execute_late`] of parts of submissions in one: another begins
  4755. /// at each place of `order` in `parts` ([`joins`]).
  4756. pub(crate) fn execute_parts(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>, parts: &[usize]) {
  4757. if order.is_empty() {
  4758. crate::list::recycle(lists, &order);
  4759. return;
  4760. }
  4761. late_threads();
  4762. if let Some(cut) = {
  4763. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4764. card_steps::cut_for(&runs)
  4765. } {
  4766. match split(lists, order, cut) {
  4767. Ok([(lists, order), (more, behind)]) => {
  4768. let first: Vec<usize> = parts.iter().copied().filter(|&p| p < cut).collect();
  4769. let second: Vec<usize> = parts.iter().filter(|&&p| p > cut).map(|p| p - cut).collect();
  4770. self.execute_parts(lists, order, &first);
  4771. self.execute_parts(more, behind, &second);
  4772. }
  4773. Err((lists, order)) => self.send_late(lists, order, parts),
  4774. }
  4775. return;
  4776. }
  4777. self.send_late(lists, order, parts);
  4778. }
  4779. fn send_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>, parts: &[usize]) {
  4780. let sent = {
  4781. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4782. self.submit(&runs, parts, true)
  4783. };
  4784. let Some((mut submitted, sent)) = sent else {
  4785. // (Not reached: a submission sent ahead always comes back.)
  4786. crate::list::recycle(lists, &order);
  4787. return;
  4788. };
  4789. let told = !sent.writes.is_empty();
  4790. let sizes = crate::memory::asked_sizes(order.iter().map(|&i| lists[i].host()));
  4791. let most = {
  4792. let mut line = line();
  4793. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4794. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4795. *flying += order.len();
  4796. *target = *submitted;
  4797. items.push(Late::Run(Flight {
  4798. number: sent.number,
  4799. fence: *target,
  4800. lists,
  4801. order,
  4802. card: sent.card,
  4803. back: sent.back,
  4804. own: sent.own,
  4805. }));
  4806. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4807. *flying >= late_most()
  4808. };
  4809. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4810. RELAY_MOVED.notify_one();
  4811. if told && !late_writes() {
  4812. self.settle(&mut submitted, WHY_WRITES);
  4813. } else if sizes {
  4814. self.settle(&mut submitted, WHY_READ);
  4815. } else if most && relay_exact() {
  4816. // Until there are fewer, not until there are none.
  4817. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4818. } else if most {
  4819. self.settle(&mut submitted, WHY_MOST);
  4820. } else {
  4821. LINE_MOVED.notify_one();
  4822. }
  4823. drop(submitted);
  4824. let _landing = crate::timeline::span("landed lists reset and given back");
  4825. land();
  4826. }
  4827. /// Sends `list`, a closed list of ours (the present's copy), as a
  4828. /// flight ([`late_free_present`]): not waited for, settled with the
  4829. /// others. The caller keeps the list and does not reset it before the
  4830. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4831. /// it ran and was waited for after all.
  4832. fn execute_own(&self, list: &HostList) -> u64 {
  4833. late_threads();
  4834. let Some((submitted, sent)) = self.submit(&[list], &[], true) else {
  4835. return 0;
  4836. };
  4837. let number = sent.number;
  4838. {
  4839. let mut line = line();
  4840. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4841. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4842. *flying += 1;
  4843. *target = *submitted;
  4844. items.push(Late::Run(Flight {
  4845. number,
  4846. fence: *target,
  4847. lists: Vec::new(),
  4848. order: Vec::new(),
  4849. card: sent.card,
  4850. back: sent.back,
  4851. own: sent.own,
  4852. }));
  4853. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4854. }
  4855. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4856. LINE_MOVED.notify_one();
  4857. RELAY_MOVED.notify_one();
  4858. drop(submitted);
  4859. number
  4860. }
  4861. /// Waits for the card to run every flight in the air ([`late`]) and
  4862. /// does what they left to do, as [`Host::execute`] does for one
  4863. /// submission after its wait: the pieces their shaders wrote in copies
  4864. /// in the card's memory are fetched and merged (each once), the ranges
  4865. /// they declared in the other copies are compared and copied back
  4866. /// (each byte once, whichever flights declared it), and then, in the
  4867. /// order they were given: their bottom-of-pipe writes and the fence
  4868. /// signals behind them. `submitted` is the submission lock's value;
  4869. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4870. ///
  4871. /// Everything in the air is settled, never the first flights alone:
  4872. /// the merge writes the copies' CPU side, which a flight still on the
  4873. /// card may be writing too.
  4874. fn settle(&self, submitted: &mut u64, why: usize) {
  4875. if !late() {
  4876. return;
  4877. }
  4878. if relay() {
  4879. // Nothing is settled here: the thread that lands flights does
  4880. // it, in order, and this waits until nothing is in the air and
  4881. // nothing is being landed. Every point that settled before
  4882. // comes here, so each still sees title memory, fences and
  4883. // bottom-of-pipe values as after a settle.
  4884. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4885. return;
  4886. }
  4887. let was_working = working(true);
  4888. let _settling = crate::timeline::span("settling flights");
  4889. let mut counted = false;
  4890. loop {
  4891. let items = {
  4892. let mut line = line();
  4893. if line.line.is_empty() {
  4894. line.settling = false;
  4895. break;
  4896. }
  4897. line.settling = true;
  4898. line.written.clear();
  4899. line.lists = 0;
  4900. std::mem::take(&mut line.line)
  4901. };
  4902. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4903. if !counted {
  4904. counted = true;
  4905. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4906. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4907. }
  4908. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4909. if flights > 0 {
  4910. submitting(2, flights);
  4911. let waiting = std::time::Instant::now();
  4912. // SAFETY: the fence and event are ours, under the
  4913. // submission lock; `submitted` is the last value signalled.
  4914. unsafe {
  4915. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4916. Ok(()) => {
  4917. working(false);
  4918. #[cfg(feature = "diagnostics")]
  4919. let _card = crate::timeline::card_wait(Some(*submitted));
  4920. WaitForSingleObject(self.event, INFINITE);
  4921. stood(waiting);
  4922. working(true);
  4923. }
  4924. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4925. }
  4926. }
  4927. let gpu = waiting.elapsed();
  4928. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4929. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4930. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4931. #[cfg(feature = "diagnostics")]
  4932. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4933. format!("{flights} submissions sent ahead, settled together")
  4934. });
  4935. // SAFETY: a plain query.
  4936. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4937. let runs: Vec<&HostList> = items
  4938. .iter()
  4939. .filter_map(|i| match i {
  4940. Late::Run(f) => Some(f),
  4941. _ => None,
  4942. })
  4943. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4944. .collect();
  4945. fail(format_args!(
  4946. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4947. runs.len(),
  4948. self.removal_data(&runs),
  4949. last_notes(&runs)
  4950. ));
  4951. }
  4952. submitting(3, flights);
  4953. let copying = std::time::Instant::now();
  4954. let mut seen = std::collections::HashSet::new();
  4955. let mut back: Vec<Declared> = Vec::new();
  4956. for item in &items {
  4957. let Late::Run(flight) = item else {
  4958. continue;
  4959. };
  4960. if let Some(card) = &flight.card {
  4961. self.card_back(card, submitted, &mut seen);
  4962. }
  4963. for (shadow, ranges) in &flight.back {
  4964. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4965. Some((_, all)) => {
  4966. for range in ranges {
  4967. if !all.contains(range) {
  4968. all.push(*range);
  4969. }
  4970. }
  4971. }
  4972. None => back.push((shadow.clone(), ranges.clone())),
  4973. }
  4974. }
  4975. }
  4976. hand_back(&back);
  4977. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4978. }
  4979. // In the order given: what tells the title the card is done.
  4980. let mut last = 0;
  4981. let mut landed = Vec::new();
  4982. for item in items {
  4983. match item {
  4984. Late::Run(flight) => {
  4985. last = flight.number;
  4986. for &i in &flight.order {
  4987. read_backs(flight.lists[i].host());
  4988. }
  4989. if let Some(card) = flight.card {
  4990. self.card_done(card);
  4991. }
  4992. landed.push((flight.lists, flight.order));
  4993. }
  4994. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4995. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4996. }
  4997. }
  4998. if last > 0 {
  4999. FINISHED.store(last, Ordering::Release);
  5000. bury(last);
  5001. }
  5002. line().landed.extend(landed);
  5003. }
  5004. if counted {
  5005. self.log_messages();
  5006. submitting(0, 0);
  5007. // What was settled may be what a queue stands at, and the
  5008. // caller may not be one that looks (a read-back, a present).
  5009. if why != WHY_CARD_DONE {
  5010. line().poke = true;
  5011. LINE_MOVED.notify_one();
  5012. }
  5013. }
  5014. working(was_working);
  5015. }
  5016. /// For a submission of `runs` that refreshes the ranges `stale` of host
  5017. /// copies, which flights may be writing and the title wrote too
  5018. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  5019. /// those of the submission's one asking, which is made again.
  5020. ///
  5021. /// With [`card_steps`] only the flights that declared them: a range of
  5022. /// a copy nobody declared any more is refreshed like any other. What
  5023. /// they landed is title memory written, so everything is asked and
  5024. /// looked at again; what is left after three times waits as before.
  5025. fn settle_stale(
  5026. &self,
  5027. submitted: &mut u64,
  5028. runs: &[&HostList],
  5029. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  5030. ranges: &[(usize, usize)],
  5031. ) {
  5032. if relay_exact() && card_steps::stage() > 0 {
  5033. for _ in 0..3 {
  5034. #[cfg(feature = "diagnostics")]
  5035. blame_stale(&stale);
  5036. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  5037. crate::watch::ask_once(ranges);
  5038. stale = stale_under_flights(runs);
  5039. if stale.is_empty() {
  5040. return;
  5041. }
  5042. }
  5043. }
  5044. #[cfg(feature = "diagnostics")]
  5045. blame_stale(&stale);
  5046. self.settle(submitted, WHY_STALE);
  5047. crate::watch::ask_once(ranges);
  5048. }
  5049. /// [`Host::execute`], or with `late` the first half of
  5050. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  5051. /// to be done once they have run comes back with the submission lock
  5052. /// still held.
  5053. ///
  5054. /// `parts`: the lists of `runs` at which another part begins
  5055. /// ([`joins`]): those go to the queue in calls of their own, one after the
  5056. /// other, as they would have.
  5057. fn submit<'a>(&'a self, runs: &[&HostList], parts: &[usize], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  5058. #[cfg(feature = "diagnostics")]
  5059. let called = std::time::Instant::now();
  5060. #[cfg(feature = "diagnostics")]
  5061. crate::copystat::submission_begins();
  5062. // One submission at a time from preparation to copy-back: snapshots
  5063. // and the ranges shaders write are per host copy, not per submission.
  5064. let mut stage = crate::timeline::span("submit: the submission lock");
  5065. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  5066. let was_working = working(true);
  5067. submitting(1, runs.len());
  5068. #[cfg(feature = "diagnostics")]
  5069. let ahead = Split::begin();
  5070. #[cfg(feature = "diagnostics")]
  5071. SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed);
  5072. stage.next("submit: steps given to the card");
  5073. // Flights in the air ([`late`]): a submission that is waited for
  5074. // settles them first, one sent ahead only if preparing it reads
  5075. // what they write.
  5076. // Or the reads are done on the card, behind the flights.
  5077. let own = if late { self.card_steps(runs) } else { None };
  5078. #[cfg(feature = "diagnostics")]
  5079. ahead.part(12);
  5080. stage.next("submit: waiting for flights it reads from");
  5081. if !late {
  5082. self.settle(&mut submitted, WHY_SYNC);
  5083. } else if own.is_none()
  5084. && let Some(why) = late_blocked(runs)
  5085. {
  5086. if relay_exact() && why == WHY_READ {
  5087. // Only until the flights that may write what is read have
  5088. // landed: their copy-back's end, not the card's other work.
  5089. relay_wait(why, |line| {
  5090. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  5091. });
  5092. } else {
  5093. self.settle(&mut submitted, why);
  5094. }
  5095. }
  5096. #[cfg(feature = "diagnostics")]
  5097. ahead.part(13);
  5098. // Descriptors the title copied into placed heaps directly, before
  5099. // command lists that index those slots are submitted.
  5100. let heaps_synced = crate::descriptor::begin_sync_heaps();
  5101. // That list runs first, and is one of the submission's from here on.
  5102. let with: Vec<&HostList>;
  5103. let runs = match &own {
  5104. Some(own) => {
  5105. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  5106. &with[..]
  5107. }
  5108. None => runs,
  5109. };
  5110. let parts: Vec<usize> = parts.iter().map(|&n| n + usize::from(own.is_some())).collect();
  5111. stage.next("submit: the sweep");
  5112. let behind = late && flying();
  5113. // Before this submission counts as started: what the sweep lets go
  5114. // of is named by no list, and nothing runs now (behind flights the
  5115. // sweep waits for a submission that finds none in the air: there is
  5116. // one at every present).
  5117. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  5118. if !behind {
  5119. if upcheck::on() {
  5120. upcheck::at_rest(self);
  5121. }
  5122. sweep();
  5123. SWEPT.store(now_ms(), Ordering::Relaxed);
  5124. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  5125. // With the present sent ahead nothing else brings a moment
  5126. // with nothing in the air: one is made for the sweep.
  5127. self.settle(&mut submitted, WHY_SYNC);
  5128. if upcheck::on() {
  5129. upcheck::at_rest(self);
  5130. }
  5131. sweep();
  5132. SWEPT.store(now_ms(), Ordering::Relaxed);
  5133. }
  5134. let behind = late && flying();
  5135. stage.next("submit: gathering what to ask about");
  5136. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  5137. // The ranges shaders write are counted for it (with the relay).
  5138. crate::shadow::preparing(this_submission);
  5139. let started = std::time::Instant::now();
  5140. #[cfg(feature = "diagnostics")]
  5141. ahead.part(14);
  5142. #[cfg(feature = "diagnostics")]
  5143. let lock = (started - called).as_micros() as u64;
  5144. #[cfg(feature = "diagnostics")]
  5145. crate::copystat::add(crate::copystat::C::Submissions, 1);
  5146. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  5147. // Where each run's lists start in `lists`.
  5148. let mut firsts = Vec::with_capacity(runs.len());
  5149. let mut batch = Batch::default();
  5150. #[cfg(feature = "diagnostics")]
  5151. let split = Split::begin();
  5152. // The time a settle of flights takes inside this preparing: the
  5153. // wait for the card and the copy-back have their own places on the
  5154. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  5155. let mut settled = std::time::Duration::ZERO;
  5156. // One write-watch asking for everything the submission refreshes
  5157. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  5158. if crate::watch::once() {
  5159. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  5160. for list in runs {
  5161. for step in &list.deferred().copies {
  5162. if let Step::Refresh(shadow, address, len) = step
  5163. && shadow.asked_ahead()
  5164. {
  5165. let span = spans
  5166. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  5167. .or_insert((*address, *address + *len));
  5168. *span = (span.0.min(*address), span.1.max(*address + *len));
  5169. }
  5170. }
  5171. }
  5172. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  5173. #[cfg(feature = "diagnostics")]
  5174. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  5175. stage.next("submit: asking the write watch");
  5176. crate::watch::ask_once(&ranges);
  5177. #[cfg(feature = "diagnostics")]
  5178. split.part(0);
  5179. stage.next("submit: title bytes under flights' writes");
  5180. // Behind flights: the title wrote memory that a flight's shaders
  5181. // may write too, and this submission refreshes it. The flights
  5182. // are settled, and the asking made again: the copy-back wrote
  5183. // title memory, which other copies of it must see.
  5184. if upcheck::on() {
  5185. upcheck::order(runs);
  5186. if behind {
  5187. upcheck::reads(runs);
  5188. }
  5189. }
  5190. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  5191. if !stale.is_empty() {
  5192. let settling = std::time::Instant::now();
  5193. self.settle_stale(&mut submitted, runs, stale, &ranges);
  5194. settled += settling.elapsed();
  5195. }
  5196. } else if behind && !stale_under_flights(runs).is_empty() {
  5197. let settling = std::time::Instant::now();
  5198. self.settle(&mut submitted, WHY_STALE);
  5199. settled += settling.elapsed();
  5200. }
  5201. #[cfg(feature = "diagnostics")]
  5202. split.part(1);
  5203. // What flights in the air may write.
  5204. let air = line().written.clone();
  5205. stage.next("submit: refreshes ahead of writes");
  5206. if refresh_front() {
  5207. batch.refresh_front(runs, &parts);
  5208. } else if ahead_of_writes() {
  5209. batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  5210. }
  5211. stage.next("submit: the lists' steps");
  5212. for list in runs {
  5213. list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  5214. firsts.push(lists.len());
  5215. if let Some(prelude) = list.prelude() {
  5216. lists.push(Some(prelude));
  5217. }
  5218. lists.push(list.list.cast().ok());
  5219. }
  5220. batch.fill();
  5221. stage.next("submit: the last refreshes");
  5222. batch.flush();
  5223. crate::watch::ask_once_end();
  5224. #[cfg(feature = "diagnostics")]
  5225. split.part(2);
  5226. stage.next("submit: snapshots");
  5227. // The snapshots of the ranges shaders may write, if they were left
  5228. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  5229. // lists have not gone to the card.
  5230. {
  5231. #[cfg(feature = "diagnostics")]
  5232. let snapshots = std::time::Instant::now();
  5233. crate::shadow::take_snapshots();
  5234. #[cfg(feature = "diagnostics")]
  5235. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  5236. }
  5237. #[cfg(feature = "diagnostics")]
  5238. split.part(3);
  5239. stage.next("submit: copies in the card's memory");
  5240. // Copies in the card's memory: what changed on their CPU side goes
  5241. // up ahead of the lists, and a compare of what the shaders may
  5242. // write follows them in the same submission.
  5243. let flown = late && relay();
  5244. if flown && self.card_results_low() {
  5245. let settling = std::time::Instant::now();
  5246. self.settle(&mut submitted, WHY_MOST);
  5247. settled += settling.elapsed();
  5248. }
  5249. // What shaders may write through views they pick: last, so that no
  5250. // refresh of this submission leaves it alone.
  5251. let picked = crate::picked::declare(runs);
  5252. for (shadow, at, len) in &picked.written {
  5253. shadow.writing(*at, *len);
  5254. }
  5255. let declared = declared_writes(runs);
  5256. let card = self.card_before(&declared, &picked, flown);
  5257. // The sends are taken: from here on the references hold what the
  5258. // copies in the lists put.
  5259. for (shadow, at, bytes) in batch.placed.drain(..) {
  5260. shadow.placed_copy(at, &bytes);
  5261. }
  5262. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  5263. lists.push(Some(check));
  5264. }
  5265. #[cfg(feature = "diagnostics")]
  5266. split.part(4);
  5267. stage.next("submit: waiting for the heaps' records");
  5268. drop(heaps_synced);
  5269. // The slots that waited for a texture's host copy, before the
  5270. // lists that may read them run.
  5271. crate::descriptor::make_waiting();
  5272. #[cfg(feature = "diagnostics")]
  5273. split.part(15);
  5274. let prepared = std::time::Instant::now();
  5275. stage.next("submit: sending");
  5276. // When it runs on the card, for the timeline.
  5277. #[cfg(feature = "diagnostics")]
  5278. let stamp = stamps::take();
  5279. #[cfg(feature = "diagnostics")]
  5280. if let Some((ahead, behind)) = stamp.and_then(stamps::lists) {
  5281. lists.insert(0, Some(ahead));
  5282. lists.push(Some(behind));
  5283. firsts.iter_mut().for_each(|first| *first += 1);
  5284. }
  5285. #[cfg(feature = "diagnostics")]
  5286. let sending = crate::timeline::ticks();
  5287. if late {
  5288. *submitted += 1;
  5289. #[cfg(feature = "diagnostics")]
  5290. if let Some([front, behind]) = self.span_lists() {
  5291. lists.insert(0, Some(front));
  5292. lists.push(Some(behind));
  5293. firsts.iter_mut().for_each(|first| *first += 1);
  5294. }
  5295. let cuts: Vec<usize> = parts.iter().filter_map(|&n| firsts.get(n).copied()).collect();
  5296. // SAFETY: closed lists; the fence is ours.
  5297. let signalled = unsafe {
  5298. let mut from = 0;
  5299. for to in cuts.into_iter().chain([lists.len()]) {
  5300. self.queue.ExecuteCommandLists(&lists[from..to]);
  5301. from = to;
  5302. }
  5303. self.queue.Signal(&self.fence, *submitted)
  5304. };
  5305. awake::sent(&self.device);
  5306. #[cfg(feature = "diagnostics")]
  5307. crate::timeline::sent(sending, *submitted, stamp);
  5308. self.card_sent();
  5309. stage.next("submit: noting what is in the air");
  5310. if let Err(e) = signalled {
  5311. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  5312. }
  5313. #[cfg(feature = "diagnostics")]
  5314. split.part(5);
  5315. let back = crate::picked::with(declared, &picked.written);
  5316. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  5317. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  5318. submitting(0, 0);
  5319. #[cfg(feature = "diagnostics")]
  5320. crate::copystat::submission_ends(lock);
  5321. let sent = Sent {
  5322. number: this_submission,
  5323. card,
  5324. back,
  5325. own,
  5326. writes,
  5327. };
  5328. working(was_working);
  5329. return Some((submitted, sent));
  5330. }
  5331. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  5332. #[cfg(feature = "diagnostics")]
  5333. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  5334. firsts
  5335. .iter()
  5336. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  5337. .map(|(&a, &b)| &lists[a..b])
  5338. .collect()
  5339. } else {
  5340. vec![&lists[..]]
  5341. };
  5342. #[cfg(not(feature = "diagnostics"))]
  5343. let groups = [&lists[..]];
  5344. submitting(2, runs.len());
  5345. for (i, group) in groups.iter().enumerate() {
  5346. *submitted += 1;
  5347. let started = std::time::Instant::now();
  5348. // SAFETY: closed lists; the fence and event are ours.
  5349. unsafe {
  5350. self.queue.ExecuteCommandLists(group);
  5351. self.card_sent();
  5352. let waited = self
  5353. .queue
  5354. .Signal(&self.fence, *submitted)
  5355. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  5356. #[cfg(feature = "diagnostics")]
  5357. crate::timeline::sent(sending, *submitted, stamp);
  5358. match waited {
  5359. Ok(()) => {
  5360. working(false);
  5361. #[cfg(feature = "diagnostics")]
  5362. let _card = crate::timeline::card_wait(Some(*submitted));
  5363. WaitForSingleObject(self.event, INFINITE);
  5364. stood(started);
  5365. working(true);
  5366. }
  5367. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  5368. }
  5369. }
  5370. // With timing on each group is one of `runs` (and the compare
  5371. // of copies in the card's memory, with the last): every
  5372. // command's time on the card goes to the sums by pipeline.
  5373. #[cfg(feature = "diagnostics")]
  5374. if timing() {
  5375. // SAFETY: a plain query.
  5376. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  5377. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  5378. crate::copystat::command_took(&op, ms);
  5379. }
  5380. }
  5381. // A submission of one list was never named here (`groups.len()
  5382. // > 1` was the test): the two 50 ms lists of the gameplay
  5383. // frame, each a submission of its own, printed nothing.
  5384. #[cfg(feature = "diagnostics")]
  5385. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  5386. // SAFETY: a plain query.
  5387. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  5388. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  5389. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  5390. for (ms, op) in runs[i].slowest(frequency, 6) {
  5391. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  5392. }
  5393. }
  5394. let _ = (i, started);
  5395. }
  5396. let _ = &firsts;
  5397. FINISHED.store(this_submission, Ordering::Release);
  5398. bury(this_submission);
  5399. let gpu = prepared.elapsed();
  5400. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  5401. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  5402. #[cfg(feature = "diagnostics")]
  5403. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  5404. let pipelines: std::collections::BTreeSet<String> = runs
  5405. .iter()
  5406. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  5407. .collect();
  5408. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  5409. text.chars().take(1200).collect()
  5410. });
  5411. // The host resets a device whose submission runs for about 2 s.
  5412. if gpu > std::time::Duration::from_millis(250) {
  5413. let pipelines: std::collections::BTreeSet<String> = runs
  5414. .iter()
  5415. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  5416. .collect();
  5417. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  5418. }
  5419. // SAFETY: a plain query.
  5420. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  5421. fail(format_args!(
  5422. "host GPU device removed after a submission of {} lists{}{}",
  5423. runs.len(),
  5424. self.removal_data(runs),
  5425. last_notes(runs)
  5426. ));
  5427. }
  5428. submitting(3, runs.len());
  5429. stage.next("submit: copying back");
  5430. // What shaders wrote goes back before the bottom-of-pipe writes,
  5431. // which tell the title the GPU is done; each range once per
  5432. // submission, however many dispatches declared it (the world's
  5433. // passes declare the same big ranges dozens of times).
  5434. let copying = std::time::Instant::now();
  5435. // For copies in the card's memory the compare has run there: the
  5436. // pieces that differ are fetched and merged.
  5437. if let Some(card) = &card {
  5438. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  5439. }
  5440. let back = crate::picked::with(declared, &picked.written);
  5441. hand_back(&back);
  5442. if let Some(card) = card {
  5443. self.card_done(card);
  5444. }
  5445. #[cfg(feature = "diagnostics")]
  5446. if !back.is_empty() {
  5447. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  5448. }
  5449. // Nothing of this submission goes back to the title: no range of
  5450. // shader writes, no value written when it is done. The wait for
  5451. // such a one is only for order and for what the card still holds.
  5452. #[cfg(feature = "diagnostics")]
  5453. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  5454. use crate::copystat::{C, add};
  5455. add(C::NothingBack, 1);
  5456. add(C::NothingBackUs, gpu.as_micros() as u64);
  5457. }
  5458. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  5459. for list in runs {
  5460. // Read backs first: a value written at the bottom of the pipe
  5461. // may be what tells the title that they are there.
  5462. read_backs(list);
  5463. for &(at, what, bytes) in &list.deferred().writes {
  5464. what.write(at as *mut u8, bytes);
  5465. }
  5466. }
  5467. self.log_messages();
  5468. submitting(0, 0);
  5469. #[cfg(feature = "diagnostics")]
  5470. crate::copystat::submission_ends(lock);
  5471. // With the relay: nothing is in the air now, so no fetch still to
  5472. // be merged is older than the sends to card copies so far, and
  5473. // their notes can go.
  5474. if relay() {
  5475. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  5476. }
  5477. working(was_working);
  5478. None
  5479. }
  5480. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  5481. /// it lies in (by the names we give them) or the title memory copy just
  5482. /// below it; for each list that did not finish, the command it stopped
  5483. /// at and what the draws and dispatches in flight there run (or, in
  5484. /// lists that never started, the pipelines they bind).
  5485. fn removal_data(&self, runs: &[&HostList]) -> String {
  5486. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  5487. return String::new();
  5488. };
  5489. let mut text = String::new();
  5490. let mut fault_va = None;
  5491. // SAFETY: the outputs are the runtime's, valid while the device
  5492. // lives; nodes are walked as linked, histories have their counts.
  5493. unsafe {
  5494. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  5495. && fault.PageFaultVA != 0
  5496. {
  5497. let va = fault.PageFaultVA;
  5498. fault_va = Some(va);
  5499. text.push_str(&format!("; page fault at {va:#x}"));
  5500. for (what, head) in [
  5501. ("inside", fault.pHeadExistingAllocationNode),
  5502. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  5503. ] {
  5504. let mut names = Vec::new();
  5505. let mut node = head;
  5506. while let Some(n) = node.as_ref()
  5507. && names.len() < 8
  5508. {
  5509. let name = if n.ObjectNameW.is_null() {
  5510. "unnamed".to_owned()
  5511. } else {
  5512. n.ObjectNameW.to_string().unwrap_or_default()
  5513. };
  5514. names.push(format!("{name} (type {})", n.AllocationType.0));
  5515. node = n.pNext;
  5516. }
  5517. if !names.is_empty() {
  5518. text.push_str(&format!("; {what} {names:?}"));
  5519. }
  5520. }
  5521. text.push_str(&crate::shadow::near(va));
  5522. text.push_str(&crate::descriptor::host::near_heaps(va));
  5523. #[cfg(feature = "diagnostics")]
  5524. text.push_str(&crate::book::at_loss(va));
  5525. }
  5526. // The plain output: the extended one (with marker texts) came
  5527. // back without stopped lists on this host.
  5528. if dred_faults() {
  5529. return text;
  5530. }
  5531. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  5532. Ok(crumbs) => crumbs,
  5533. Err(e) => {
  5534. text.push_str(&format!("; no breadcrumbs ({e})"));
  5535. return text;
  5536. }
  5537. };
  5538. // Every list's progress (done/count), in the runtime's order.
  5539. let mut progress = Vec::new();
  5540. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  5541. while let Some(p) = node.as_ref() {
  5542. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5543. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  5544. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  5545. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  5546. node = p.pNext;
  5547. }
  5548. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  5549. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  5550. while let Some(p) = plain.as_ref() {
  5551. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5552. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  5553. let history =
  5554. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  5555. text.push_str(&format!(
  5556. "; a list stopped at command {done} of {} (op {})",
  5557. p.BreadcrumbCount, history[done as usize].0
  5558. ));
  5559. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  5560. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  5561. let named = [
  5562. (!p.pCommandListDebugNameW.is_null()).then(|| p.pCommandListDebugNameW.to_string().unwrap_or_default()),
  5563. (!p.pCommandListDebugNameA.is_null()).then(|| {
  5564. std::ffi::CStr::from_ptr(p.pCommandListDebugNameA.cast()).to_string_lossy().into_owned()
  5565. }),
  5566. ]
  5567. .into_iter()
  5568. .flatten()
  5569. .next()
  5570. .unwrap_or_default();
  5571. text.push_str(&format!(" of \"{named}\""));
  5572. // Not one of the caller's: by the name.
  5573. #[cfg(feature = "diagnostics")]
  5574. let by_name = list_number(&named).and_then(|n| {
  5575. let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  5576. all.get(&n).map(|(notes, pipelines, _)| (notes.upgrade(), pipelines.upgrade()))
  5577. });
  5578. #[cfg(feature = "diagnostics")]
  5579. let indirects = run.map(|r| r.indirects.clone()).or_else(|| {
  5580. let n = list_number(&named)?;
  5581. LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()).get(&n)?.2.upgrade()
  5582. });
  5583. #[cfg(not(feature = "diagnostics"))]
  5584. #[allow(clippy::type_complexity)]
  5585. let by_name: Option<(Option<()>, Option<std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>>)> = None;
  5586. #[cfg(feature = "diagnostics")]
  5587. let noted = run.map(|r| r.notes.clone()).or_else(|| by_name.as_ref().and_then(|b| b.0.clone()));
  5588. let bound = run.map(|r| r.pipelines.clone()).or_else(|| by_name.as_ref().and_then(|b| b.1.clone()));
  5589. // The k-th marker command is the k-th note.
  5590. #[cfg(feature = "diagnostics")]
  5591. let markers: Vec<(u32, String)> = noted.map_or_else(Vec::new, |notes| {
  5592. let notes = notes.lock().unwrap_or_else(|e| e.into_inner());
  5593. history
  5594. .iter()
  5595. .enumerate()
  5596. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  5597. .zip(notes.iter())
  5598. .map(|((at, _), (note, range))| {
  5599. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  5600. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  5601. })
  5602. .collect()
  5603. });
  5604. #[cfg(not(feature = "diagnostics"))]
  5605. let markers: Vec<(u32, String)> = Vec::new();
  5606. #[cfg(not(feature = "diagnostics"))]
  5607. let _ = fault_va;
  5608. if done > 0 {
  5609. text.push_str(&in_flight(history, &markers, done as usize));
  5610. }
  5611. #[cfg(feature = "diagnostics")]
  5612. if let Some(indirects) = indirects {
  5613. text.push_str(&indirects_around(history, done as usize, &indirects));
  5614. }
  5615. // (Without markers a list that stopped midway says what
  5616. // it may have been at only by what it binds.)
  5617. if (done == 0 || markers.is_empty())
  5618. && let Some(bound) = bound
  5619. {
  5620. let pipelines = bound.lock().unwrap_or_else(|e| e.into_inner());
  5621. text.push_str(&format!(", its pipelines {pipelines:?}"));
  5622. }
  5623. }
  5624. plain = p.pNext;
  5625. }
  5626. }
  5627. text
  5628. }
  5629. /// Moves the debug layer's messages into our log; returns the first
  5630. /// error among them.
  5631. pub(crate) fn log_messages(&self) -> Option<String> {
  5632. let Some(queue) = &self.messages else {
  5633. return None;
  5634. };
  5635. let mut first_error = None;
  5636. // SAFETY: each message is read into a buffer of the size the queue
  5637. // reports, then the queue is emptied.
  5638. unsafe {
  5639. for i in 0..queue.GetNumStoredMessages() {
  5640. let mut size = 0;
  5641. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  5642. continue;
  5643. }
  5644. let mut buffer = vec![0u64; size.div_ceil(8)];
  5645. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  5646. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  5647. let m = &*message;
  5648. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  5649. let text = String::from_utf8_lossy(text);
  5650. let text = text.trim_end_matches('\0');
  5651. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  5652. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  5653. first_error = Some(text.to_owned());
  5654. }
  5655. }
  5656. }
  5657. queue.ClearStoredMessages();
  5658. }
  5659. first_error
  5660. }
  5661. /// A host render target view of `resource`, valid until it is recorded.
  5662. pub(crate) fn rtv(
  5663. &self,
  5664. resource: Option<&ID3D12Resource>,
  5665. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  5666. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5667. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5668. // SAFETY: a slot of our heap and a live resource, or none with a
  5669. // description (a typed null view).
  5670. unsafe {
  5671. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  5672. handle.ptr += (slot * self.rtv_size) as usize;
  5673. self.device
  5674. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  5675. handle
  5676. }
  5677. }
  5678. /// A host depth view of `resource`, valid until it is recorded.
  5679. pub(crate) fn dsv(
  5680. &self,
  5681. resource: &ID3D12Resource,
  5682. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  5683. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5684. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5685. // SAFETY: a slot of our heap and a live resource.
  5686. unsafe {
  5687. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  5688. handle.ptr += (slot * self.dsv_size) as usize;
  5689. self.device
  5690. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  5691. handle
  5692. }
  5693. }
  5694. }
  5695. impl HostList {
  5696. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  5697. #[cfg(feature = "diagnostics")]
  5698. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  5699. if !timing() {
  5700. return None;
  5701. }
  5702. self.stamps
  5703. .get_or_init(|| {
  5704. let device = &host()?.device;
  5705. let mut heap: Option<ID3D12QueryHeap> = None;
  5706. let mut back: Option<ID3D12Resource> = None;
  5707. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  5708. let desc = D3D12_RESOURCE_DESC {
  5709. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5710. Width: u64::from(STAMPS) * 8,
  5711. Height: 1,
  5712. DepthOrArraySize: 1,
  5713. MipLevels: 1,
  5714. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  5715. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5716. ..Default::default()
  5717. };
  5718. // SAFETY: plain object creation.
  5719. unsafe {
  5720. device
  5721. .CreateQueryHeap(
  5722. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  5723. &mut heap,
  5724. )
  5725. .ok()?;
  5726. device
  5727. .CreateCommittedResource(
  5728. &readback,
  5729. D3D12_HEAP_FLAG_NONE,
  5730. &desc,
  5731. D3D12_RESOURCE_STATE_COPY_DEST,
  5732. None,
  5733. &mut back,
  5734. )
  5735. .ok()?;
  5736. }
  5737. Some((heap?, back?))
  5738. })
  5739. .as_ref()
  5740. }
  5741. /// The noted commands that took longest on the GPU, longest first, as
  5742. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  5743. #[cfg(feature = "diagnostics")]
  5744. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  5745. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  5746. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  5747. return Vec::new();
  5748. };
  5749. let mut data = std::ptr::null_mut();
  5750. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  5751. // SAFETY: a read-back buffer the finished list resolved into.
  5752. let stamps: Vec<u64> = unsafe {
  5753. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  5754. return Vec::new();
  5755. }
  5756. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  5757. back.Unmap(0, None);
  5758. s
  5759. };
  5760. let mut times: Vec<(f64, String)> = (0..count)
  5761. .map(|i| {
  5762. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5763. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5764. })
  5765. .collect();
  5766. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5767. times.truncate(n);
  5768. times
  5769. }
  5770. pub(crate) fn close(&self) {
  5771. let _closing = crate::timeline::span("closing a host list");
  5772. self.twins_to_depth();
  5773. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5774. if let Some((scratch, _)) = scratch {
  5775. self.indirect_common(&scratch);
  5776. }
  5777. self.batches_common();
  5778. self.card_budget_out();
  5779. self.take_coming();
  5780. #[cfg(feature = "diagnostics")]
  5781. if let Some((heap, back)) = self.stamps() {
  5782. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5783. // SAFETY: an open list, our heap and read-back buffer.
  5784. unsafe {
  5785. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5786. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5787. }
  5788. }
  5789. // SAFETY: our list.
  5790. if let Err(e) = unsafe { self.list.Close() } {
  5791. fail(format_args!(
  5792. "a host command list did not close ({e}): a command recorded into it was invalid"
  5793. ));
  5794. }
  5795. }
  5796. /// `work` finds, on a thread of ours, refreshes that belong at this
  5797. /// place among the list's steps; they are there when the list is closed.
  5798. pub(crate) fn refreshes_coming(&self, work: impl FnOnce() -> Vec<aside::Refresh> + Send + 'static) {
  5799. self.take_coming();
  5800. let at = self.deferred().copies.len();
  5801. let coming = aside::begin(work);
  5802. *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = Some((at, coming));
  5803. }
  5804. /// The refreshes that were still to come are put among the steps.
  5805. fn take_coming(&self) {
  5806. let Some((at, coming)) = self.coming.lock().unwrap_or_else(|e| e.into_inner()).take() else {
  5807. return;
  5808. };
  5809. let found = coming.wait();
  5810. let mut deferred = self.deferred();
  5811. let at = at.min(deferred.copies.len());
  5812. deferred
  5813. .copies
  5814. .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize)));
  5815. }
  5816. /// Only after the list's last submission finished (every one is waited
  5817. /// for).
  5818. pub(crate) fn reset(&self) {
  5819. self.changed_something();
  5820. #[cfg(feature = "diagnostics")]
  5821. let started = std::time::Instant::now();
  5822. let _resetting = crate::timeline::span("resetting a host list");
  5823. self._alive.used();
  5824. *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None;
  5825. *self.deferred() = Deferred::default();
  5826. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5827. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5828. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5829. #[cfg(feature = "diagnostics")]
  5830. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5831. #[cfg(feature = "diagnostics")]
  5832. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5833. {
  5834. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5835. (scratch.current, scratch.used) = (0, 0);
  5836. // Every submission of the list has run: nothing reads its
  5837. // scratch memory any more, and the next list to ask takes it.
  5838. if scratch_pool() {
  5839. give_chunks(std::mem::take(&mut scratch.chunks));
  5840. }
  5841. }
  5842. // SAFETY: the list is not executing.
  5843. let reset = unsafe {
  5844. self.allocator
  5845. .Reset()
  5846. .and_then(|()| self.list.Reset(&self.allocator, None))
  5847. };
  5848. if let Err(e) = reset {
  5849. fail(format_args!("a host command list did not reset ({e})"));
  5850. }
  5851. #[cfg(feature = "diagnostics")]
  5852. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5853. }
  5854. /// Something changed in this list that bringing a draw's textures and
  5855. /// buffers up to date depends on: a texture's state, a twin, what was
  5856. /// refreshed.
  5857. pub(crate) fn changed_something(&self) {
  5858. self.epoch.store(next_epoch(), Ordering::Relaxed);
  5859. }
  5860. /// See [`HostList::changed_something`].
  5861. pub(crate) fn epoch(&self) -> u64 {
  5862. self.epoch.load(Ordering::Relaxed)
  5863. }
  5864. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5865. /// list: the host texture and the state it leaves, if that is a change.
  5866. /// The list's first use of a texture records nothing: its prelude brings
  5867. /// the texture there at submission.
  5868. pub(crate) fn transition(
  5869. &self,
  5870. resource: crate::object::This,
  5871. wanted: u32,
  5872. ) -> Option<(&'static ID3D12Resource, u32)> {
  5873. let copy = crate::resource::host_copy(resource)?;
  5874. // SAFETY: as in `crate::resource::host_resource`; the list's states
  5875. // hold the copy from here on.
  5876. let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(&copy.texture) };
  5877. let wanted = legal_for(copy.flags(), wanted);
  5878. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5879. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5880. std::collections::hash_map::Entry::Vacant(v) => {
  5881. v.insert((wanted, wanted, copy));
  5882. self.changed_something();
  5883. None
  5884. }
  5885. std::collections::hash_map::Entry::Occupied(mut o) => {
  5886. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5887. if before != wanted {
  5888. self.changed_something();
  5889. }
  5890. (before != wanted).then_some((texture, before))
  5891. }
  5892. }
  5893. }
  5894. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5895. /// as [`HostList::transition`] does a title resource's host copy, and
  5896. /// records the barrier: for textures that are not a title resource's
  5897. /// host copy (colour twins) and for the copies between the two.
  5898. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5899. let wanted = legal_for(copy.flags(), wanted);
  5900. self.changed_something();
  5901. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5902. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5903. std::collections::hash_map::Entry::Vacant(v) => {
  5904. v.insert((wanted, wanted, copy.clone()));
  5905. None
  5906. }
  5907. std::collections::hash_map::Entry::Occupied(mut o) => {
  5908. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5909. (before != wanted).then_some(before)
  5910. }
  5911. };
  5912. drop(states);
  5913. if let Some(before) = before {
  5914. let barrier = transition(
  5915. &copy.texture,
  5916. D3D12_RESOURCE_STATES(before as i32),
  5917. D3D12_RESOURCE_STATES(wanted as i32),
  5918. );
  5919. // SAFETY: an open list and a live texture.
  5920. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5921. }
  5922. }
  5923. /// A use of title texture `resource` about to be recorded, if it is a
  5924. /// depth texture with a colour twin (false if it is not): of the twin
  5925. /// (`colour`: unordered access) or of the depth texture (depth target,
  5926. /// clear, shader read, copy, resolve), writing it or only reading. The
  5927. /// side used is first brought up to date: by a copy recorded here if
  5928. /// this list wrote the other side since, by the list's prelude if the
  5929. /// list uses the side as it finds it. The twin is left in the
  5930. /// unordered access state; the caller moves the depth texture to the
  5931. /// state its use needs, as for any texture. A twin still ahead when the
  5932. /// list closes is copied then (`twins_to_depth`).
  5933. /// shortcut: every depth target bound for a draw counts as written
  5934. /// (also when the draw only tests), and every unordered access view a
  5935. /// shader names as written; views a shader picks from the heap by a
  5936. /// computed index are not seen here at all.
  5937. pub(crate) fn twin_use(
  5938. &self,
  5939. resource: crate::object::This,
  5940. colour: bool,
  5941. write: bool,
  5942. ) -> bool {
  5943. const UNORDERED_ACCESS: u32 = 0x8;
  5944. // Asked for every texture a draw reads: most have no twin.
  5945. let Some(twin) = crate::resource::twin(resource) else {
  5946. return false;
  5947. };
  5948. let Some(depth) = crate::resource::host_copy(resource) else {
  5949. return false;
  5950. };
  5951. let side = usize::from(colour);
  5952. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5953. let u = twins
  5954. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5955. .or_insert_with(|| TwinUse {
  5956. depth: depth.clone(),
  5957. twin: twin.clone(),
  5958. needs: [false; 2],
  5959. behind: [None; 2],
  5960. writing: false,
  5961. late: false,
  5962. });
  5963. let was = (u.needs, u.behind, u.writing);
  5964. let copy = match u.behind[side] {
  5965. Some(behind) => behind,
  5966. None => {
  5967. u.needs[side] = true;
  5968. false
  5969. }
  5970. };
  5971. u.behind[side] = Some(false);
  5972. match (write, colour) {
  5973. // Shaders write the twin when the draw or dispatch runs: what
  5974. // the same one reads of the depth texture is prepared before
  5975. // (`twins_written`).
  5976. (true, true) => u.writing = true,
  5977. (true, false) => u.behind[1] = Some(true),
  5978. (false, _) => {}
  5979. }
  5980. if was != (u.needs, u.behind, u.writing) || copy || colour {
  5981. self.changed_something();
  5982. }
  5983. // shortcut: the depth plane's twin is not drawn into the plane
  5984. // here: the pass sets a pipeline and a target of ours, which a list
  5985. // still recording the title's commands cannot take. This use sees
  5986. // the plane as it was; the pass runs when the list closes
  5987. // (`twins_to_depth`). Counted.
  5988. if copy && !colour && twin.plane.is_some() {
  5989. u.late = true;
  5990. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5991. }
  5992. drop(twins);
  5993. if copy {
  5994. self.twin_copy(&depth, &twin, colour);
  5995. } else if colour {
  5996. self.settle(&twin.colour, UNORDERED_ACCESS);
  5997. }
  5998. // The depth plane's twin is written through unordered access too.
  5999. if colour && let Some(plane) = &twin.plane {
  6000. self.settle(plane, UNORDERED_ACCESS);
  6001. }
  6002. true
  6003. }
  6004. /// Records the pass that draws the twin of the depth plane of `depth`
  6005. /// into the plane, if `twin` has one, with the moves to the states the
  6006. /// pass needs; the twin is left in the unordered access state. Only
  6007. /// for a list that records nothing of the title's afterwards
  6008. /// (`record_plane_pass`).
  6009. fn pass_plane(
  6010. &self,
  6011. depth: &std::sync::Arc<crate::resource::HostTexture>,
  6012. twin: &crate::resource::Twin,
  6013. ) {
  6014. const UNORDERED_ACCESS: u32 = 0x8;
  6015. const DEPTH_WRITE: u32 = 0x10;
  6016. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  6017. let Some(plane) = &twin.plane else { return };
  6018. self.settle(depth, DEPTH_WRITE);
  6019. self.settle(plane, PIXEL_SHADER_RESOURCE);
  6020. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  6021. self.settle(plane, UNORDERED_ACCESS);
  6022. }
  6023. /// Records the copy of a depth texture into its colour twin (`colour`)
  6024. /// or of the twin into the depth texture, with the moves to the copy
  6025. /// states. The twin is left in the unordered access state.
  6026. fn twin_copy(
  6027. &self,
  6028. depth: &std::sync::Arc<crate::resource::HostTexture>,
  6029. twin: &crate::resource::Twin,
  6030. colour: bool,
  6031. ) {
  6032. const UNORDERED_ACCESS: u32 = 0x8;
  6033. const COPY_DEST: u32 = 0x400;
  6034. const COPY_SOURCE: u32 = 0x800;
  6035. let (from, to) = if colour {
  6036. (depth, &twin.colour)
  6037. } else {
  6038. (&twin.colour, depth)
  6039. };
  6040. self.settle(from, COPY_SOURCE);
  6041. self.settle(to, COPY_DEST);
  6042. record_twin_copy(&self.list, &depth.texture, twin, colour);
  6043. self.settle(&twin.colour, UNORDERED_ACCESS);
  6044. }
  6045. /// Before the list closes: the depth textures whose twins it wrote last
  6046. /// are given what was written, and left readable by shaders. Shaders
  6047. /// that pick a view from the heap by a computed index are not seen by
  6048. /// `twin_use` and read the depth texture in lists that never name it
  6049. /// (in a captured frame of the title no table names a shadow
  6050. /// map for reading but the pass that fills the next one).
  6051. fn twins_to_depth(&self) {
  6052. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  6053. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  6054. let written: Vec<_> = twins
  6055. .values_mut()
  6056. .filter(|u| u.behind[0] == Some(true) || u.late)
  6057. .map(|u| {
  6058. // Not copied again if the list copied since the last write
  6059. // and only the depth plane's pass is left.
  6060. let copy = u.behind[0] == Some(true);
  6061. u.behind[0] = Some(false);
  6062. u.late = false;
  6063. (u.depth.clone(), u.twin.clone(), copy)
  6064. })
  6065. .collect();
  6066. drop(twins);
  6067. for (depth, twin, copy) in &written {
  6068. if *copy {
  6069. self.twin_copy(depth, twin, false);
  6070. }
  6071. // Nothing of the title's is recorded after this: the pass may
  6072. // leave its own pipeline and target set.
  6073. self.pass_plane(depth, twin);
  6074. self.settle(depth, SHADER_RESOURCE);
  6075. }
  6076. }
  6077. /// The draw or dispatch just prepared is recorded: the twins it writes
  6078. /// now hold what their depth textures lack.
  6079. pub(crate) fn twins_written(&self) {
  6080. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  6081. for u in twins.values_mut().filter(|u| u.writing) {
  6082. u.writing = false;
  6083. u.behind[0] = Some(true);
  6084. self.changed_something();
  6085. }
  6086. }
  6087. /// At submission: the list that moves each texture this list uses from
  6088. /// its real state to the one the list starts with; the textures' real
  6089. /// states become those the list ends with. For depth textures with a
  6090. /// colour twin it first copies the side the list uses as it finds it
  6091. /// from the other, if a list submitted earlier left it behind.
  6092. fn prelude(&self) -> Option<ID3D12CommandList> {
  6093. const COPY_DEST: u32 = 0x400;
  6094. const COPY_SOURCE: u32 = 0x800;
  6095. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  6096. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  6097. // The copies (depth texture, twin, whether into the twin); the
  6098. // sides are then as this list leaves them.
  6099. let mut syncs = Vec::new();
  6100. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  6101. for u in twins.values() {
  6102. let real = u.twin.behind.load(Ordering::Relaxed);
  6103. let mut behind = [real & 1 != 0, real & 2 != 0];
  6104. for side in [0, 1] {
  6105. if u.needs[side] && behind[side] {
  6106. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  6107. behind = [false; 2];
  6108. }
  6109. }
  6110. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  6111. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  6112. u.twin.behind.store(left, Ordering::Relaxed);
  6113. }
  6114. drop(twins);
  6115. // A copy runs with its textures in the copy states: each moves
  6116. // there from its real state, and from there to the state the list
  6117. // starts with (back to its real state if the list does not use it).
  6118. let mut to_copy = Vec::new();
  6119. let mut barriers = Vec::new();
  6120. let mut copying = std::collections::HashMap::new();
  6121. for (depth, twin, colour) in &syncs {
  6122. let (from, to) = if *colour {
  6123. (depth, &twin.colour)
  6124. } else {
  6125. (&twin.colour, depth)
  6126. };
  6127. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  6128. let key = std::sync::Arc::as_ptr(texture) as usize;
  6129. let real = texture.state.load(Ordering::Relaxed);
  6130. copying.insert(key, state);
  6131. if real != state {
  6132. to_copy.push(transition(
  6133. &texture.texture,
  6134. host_state(real),
  6135. host_state(state),
  6136. ));
  6137. if !states.contains_key(&key) {
  6138. barriers.push(transition(
  6139. &texture.texture,
  6140. host_state(state),
  6141. host_state(real),
  6142. ));
  6143. }
  6144. }
  6145. }
  6146. }
  6147. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  6148. let real = copy.state.swap(*last, Ordering::Relaxed);
  6149. let real = copying.get(key).copied().unwrap_or(real);
  6150. (real != *first)
  6151. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  6152. }));
  6153. if barriers.is_empty() && syncs.is_empty() {
  6154. return None;
  6155. }
  6156. let Some((allocator, list)) = self
  6157. .prelude
  6158. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  6159. .as_ref()
  6160. else {
  6161. fail(format_args!("no host list for a state prelude"));
  6162. };
  6163. // SAFETY: the prelude is not executing (every submission is waited
  6164. // for); the textures are live.
  6165. let recorded = unsafe {
  6166. allocator.Reset().and_then(|()| {
  6167. list.Reset(allocator, None)?;
  6168. if !to_copy.is_empty() {
  6169. list.ResourceBarrier(&to_copy);
  6170. }
  6171. for (depth, twin, colour) in &syncs {
  6172. record_twin_copy(list, &depth.texture, twin, *colour);
  6173. }
  6174. if !barriers.is_empty() {
  6175. list.ResourceBarrier(&barriers);
  6176. }
  6177. list.Close()
  6178. })
  6179. };
  6180. if let Err(e) = recorded {
  6181. fail(format_args!("a host state prelude did not record ({e})"));
  6182. }
  6183. list.cast().ok()
  6184. }
  6185. /// Notes what the command about to be recorded does, as a marker
  6186. /// command whose text the list keeps (diagnostics, with device-removed
  6187. /// data on): the report pairs the breadcrumbs' marker commands with the
  6188. /// texts in order and names the commands a fault stopped among.
  6189. #[cfg(feature = "diagnostics")]
  6190. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  6191. self.note(what, None);
  6192. }
  6193. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  6194. /// `(address, bytes)`: the report places the faulting address in it.
  6195. #[cfg(feature = "diagnostics")]
  6196. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  6197. self.note(what, Some(range));
  6198. }
  6199. #[cfg(feature = "diagnostics")]
  6200. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  6201. if !dred_on() {
  6202. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  6203. return;
  6204. }
  6205. {
  6206. let started = std::time::Instant::now();
  6207. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  6208. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  6209. // SAFETY: an open list and our query heap.
  6210. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  6211. }
  6212. let what = what();
  6213. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  6214. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  6215. const UNICODE: u32 = 0;
  6216. // SAFETY: an open list; the marker is copied when recorded.
  6217. unsafe {
  6218. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  6219. };
  6220. self.notes
  6221. .lock()
  6222. .unwrap_or_else(|e| e.into_inner())
  6223. .push((what, range));
  6224. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  6225. }
  6226. }
  6227. /// Whether nothing recorded since the list was opened does any work:
  6228. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  6229. /// upload or resolve (they defer a step or move a texture's state), no
  6230. /// bottom-of-pipe write. State set on the list does not count.
  6231. pub(crate) fn untouched(&self) -> bool {
  6232. {
  6233. let deferred = self.deferred();
  6234. if !(deferred.copies.is_empty()
  6235. && deferred.uploads.is_empty()
  6236. && deferred.kept.is_empty()
  6237. && deferred.textures.is_empty()
  6238. && deferred.writes.is_empty()
  6239. && deferred.backs.is_empty())
  6240. {
  6241. return false;
  6242. }
  6243. }
  6244. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  6245. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  6246. }
  6247. /// Notes an indirect execution, while device-removed data is kept
  6248. /// ([`indirects`]).
  6249. #[cfg(feature = "diagnostics")]
  6250. pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) {
  6251. if dred_on() || dred_light() {
  6252. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user);
  6253. }
  6254. }
  6255. /// Notes a pipeline the list binds.
  6256. pub(crate) fn used_pipeline(&self, name: &str) {
  6257. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  6258. if !pipelines.contains(name) {
  6259. pipelines.insert(name.to_owned());
  6260. }
  6261. }
  6262. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  6263. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  6264. }
  6265. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  6266. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  6267. let mut deferred = self.deferred();
  6268. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  6269. // A copy that goes on where the one recorded just before it ended,
  6270. // source and destination both: with `join_copies` the two are one
  6271. // step.
  6272. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  6273. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  6274. {
  6275. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  6276. if join_copies() {
  6277. *n += len;
  6278. return;
  6279. }
  6280. }
  6281. deferred
  6282. .copies
  6283. .push(Step::Copy(dst as usize, src as usize, len));
  6284. deferred.refreshed.clear();
  6285. self.changed_something();
  6286. }
  6287. /// Copies `len` bytes of title memory at `src` into the list's upload
  6288. /// memory at `dst` when the list is submitted.
  6289. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  6290. self.deferred()
  6291. .copies
  6292. .push(Step::Fill(dst as usize, src as usize, len, None));
  6293. }
  6294. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  6295. /// title heap's address, and the slot) shows.
  6296. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  6297. self.deferred()
  6298. .copies
  6299. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  6300. }
  6301. /// As [`HostList::defer_fill`], for the beginning of a buffer
  6302. /// [`HostList::upload`] made.
  6303. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  6304. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  6305. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  6306. }
  6307. /// Brings `[address, address + len)` of a buffer's host copy up to date
  6308. /// when the list is submitted (once per range until a title copy
  6309. /// intervenes), keeping the copy alive until the list is reset.
  6310. pub(crate) fn defer_refresh(
  6311. &self,
  6312. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  6313. address: usize,
  6314. len: usize,
  6315. ) {
  6316. let mut deferred = self.deferred();
  6317. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  6318. if deferred.refreshed.insert(key) {
  6319. deferred
  6320. .copies
  6321. .push(Step::Refresh(shadow.clone(), address, len));
  6322. }
  6323. }
  6324. /// Shaders of the list write `[address, address + len)` of a buffer's
  6325. /// host copy: copied back into title memory once the list has run.
  6326. pub(crate) fn defer_gpu_write(
  6327. &self,
  6328. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  6329. address: usize,
  6330. len: usize,
  6331. ) {
  6332. self.deferred()
  6333. .copies
  6334. .push(Step::GpuWrite(shadow.clone(), address, len));
  6335. }
  6336. /// A read back: once the list has run, `rows` rows of `row` bytes go
  6337. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  6338. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  6339. /// the list is reset.
  6340. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  6341. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  6342. }
  6343. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  6344. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  6345. self.deferred().writes.push((dst as usize, what, bytes));
  6346. }
  6347. /// A mapped upload buffer of `size` bytes, alive until the list is
  6348. /// reset.
  6349. ///
  6350. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  6351. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6352. // With [`card_steps`] the card may be the one that fills it.
  6353. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  6354. name(&buffer, || format!("list upload {size:#x}"));
  6355. self.deferred().hold_upload(buffer.clone(), size);
  6356. Some((buffer, data))
  6357. }
  6358. /// `len` bytes of upload memory (256-byte aligned) until the list is
  6359. /// reset: the host GPU address and the CPU pointer.
  6360. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  6361. let (buffer, at, data) = self.scratch_at(len)?;
  6362. // SAFETY: a live buffer.
  6363. Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data))
  6364. }
  6365. /// [`HostList::scratch`] and the buffer it lies in, for a descriptor
  6366. /// slot to hold: the slot outlives the list's use of it.
  6367. pub(crate) fn scratch_held(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  6368. let (buffer, at, data) = self.scratch_at(len)?;
  6369. // SAFETY: a live buffer.
  6370. let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at;
  6371. Some((buffer, gpu, data))
  6372. }
  6373. /// [`HostList::scratch`]: the buffer, the offset in it and the CPU
  6374. /// pointer.
  6375. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  6376. let host = host()?;
  6377. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  6378. let len = len.max(1).next_multiple_of(256);
  6379. if len > SCRATCH_CHUNK {
  6380. let (buffer, data) = host.upload_buffer(len)?;
  6381. name(&buffer, || format!("list scratch {len:#x}"));
  6382. self.deferred().hold_upload(buffer.clone(), len);
  6383. return Some((buffer, 0, data));
  6384. }
  6385. // The chunk in use while `len` fits in what is left of it, else the
  6386. // next one (a list's first chunk may be a small one).
  6387. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  6388. (s.current, s.used) = (s.current + 1, 0);
  6389. }
  6390. if s.current == s.chunks.len() {
  6391. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  6392. SCRATCH_FIRST
  6393. } else {
  6394. SCRATCH_CHUNK
  6395. };
  6396. let chunk = take_chunk(host, size)?;
  6397. s.chunks.push((chunk, size));
  6398. s.used = 0;
  6399. }
  6400. let (data, buffer) = (s.chunks[s.current].0.data, s.chunks[s.current].0.buffer.clone());
  6401. let at = s.used;
  6402. s.used += len;
  6403. Some((buffer, at, (data + at as usize) as *mut u8))
  6404. }
  6405. /// The bytes of scratch chunks the list holds now (after a reset:
  6406. /// none while lists share their chunks).
  6407. pub(crate) fn scratch_kept(&self) -> u64 {
  6408. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  6409. scratch.chunks.iter().map(|c| c.1).sum()
  6410. }
  6411. /// The host address of the list's indirect-work budget, zeroed at each
  6412. /// submission of the list from the first use after a reset on.
  6413. pub(crate) fn budget(&self) -> Option<u64> {
  6414. let (buffer, data) = self
  6415. .budget
  6416. .get_or_init(|| {
  6417. let (b, d) = host()?.shared_buffer(256)?;
  6418. Some((b, d as usize))
  6419. })
  6420. .as_ref()?;
  6421. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  6422. let mut deferred = self.deferred();
  6423. if !deferred.budget_zeroed {
  6424. deferred.budget_zeroed = true;
  6425. let at = *data;
  6426. // SAFETY: the list's own mapped words, written before it runs.
  6427. // The words after the budget hold what the clamp noted about the
  6428. // list's last run (mesh dispatches: the largest group count
  6429. // asked for, the groups asked in all; with the card's copy, as
  6430. // the list's end copied them here): taken, then zeroed.
  6431. let notes = Box::new(move || unsafe {
  6432. let words = at as *mut u32;
  6433. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  6434. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  6435. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  6436. for k in 0..3 {
  6437. words.add(k).write_volatile(0);
  6438. }
  6439. });
  6440. deferred.copies.push(Step::Host(notes, (0, 0)));
  6441. drop(deferred);
  6442. if let Some(card) = card {
  6443. self.zero_card_budget(card);
  6444. }
  6445. }
  6446. // SAFETY: a live buffer.
  6447. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  6448. }
  6449. /// The budget's words in the card's own memory ([`card_budget`]), if
  6450. /// the list can zero them itself (`WriteBufferImmediate`).
  6451. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  6452. if !card_budget() {
  6453. return None;
  6454. }
  6455. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  6456. let buffer = host()?.uav_buffer(256)?;
  6457. name(&buffer, || "indirect budget".to_owned());
  6458. Some(buffer)
  6459. }
  6460. /// Records, before the list's first clamp, the zeroing of the card's
  6461. /// copy of the budget: common, written as a copy, then left for
  6462. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  6463. fn zero_card_budget(&self, card: &ID3D12Resource) {
  6464. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  6465. return;
  6466. };
  6467. // SAFETY: a live buffer.
  6468. let at = unsafe { card.GetGPUVirtualAddress() };
  6469. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  6470. Dest: at + offset,
  6471. Value: 0,
  6472. });
  6473. // SAFETY: an open list; the buffer is the list's own and in the
  6474. // common state at the start of every recording.
  6475. unsafe {
  6476. self.list.ResourceBarrier(&[transition(
  6477. card,
  6478. D3D12_RESOURCE_STATE_COMMON,
  6479. D3D12_RESOURCE_STATE_COPY_DEST,
  6480. )]);
  6481. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  6482. self.list.ResourceBarrier(&[transition(
  6483. card,
  6484. D3D12_RESOURCE_STATE_COPY_DEST,
  6485. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  6486. )]);
  6487. }
  6488. }
  6489. /// Before the list closes, if this recording charged the card's copy
  6490. /// of the budget: its notes on mesh records go to the mapped words
  6491. /// (read at the next submission), and it goes back to common.
  6492. fn card_budget_out(&self) {
  6493. if !self.deferred().budget_zeroed {
  6494. return;
  6495. }
  6496. let (Some(Some(card)), Some(Some((mapped, _)))) =
  6497. (self.card_budget.get(), self.budget.get())
  6498. else {
  6499. return;
  6500. };
  6501. // SAFETY: an open list; both buffers are the list's own. The
  6502. // mapped one is promoted from common to the copy destination.
  6503. unsafe {
  6504. self.list.ResourceBarrier(&[transition(
  6505. card,
  6506. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  6507. D3D12_RESOURCE_STATE_COPY_SOURCE,
  6508. )]);
  6509. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  6510. self.list.ResourceBarrier(&[transition(
  6511. card,
  6512. D3D12_RESOURCE_STATE_COPY_SOURCE,
  6513. D3D12_RESOURCE_STATE_COMMON,
  6514. )]);
  6515. }
  6516. }
  6517. /// A device-local unordered-access buffer of at least `size` bytes for
  6518. /// clamped indirect arguments, reused across executions and resets of the
  6519. /// list. Smaller buffers replaced mid-list stay alive until
  6520. /// [`HostList::reset`].
  6521. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  6522. let needed = size.max(64 << 10);
  6523. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  6524. if let Some((buffer, cap)) = &*slot
  6525. && *cap >= needed
  6526. {
  6527. return Some(buffer.clone());
  6528. }
  6529. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  6530. let alloc = prev
  6531. .saturating_mul(2)
  6532. .max(needed)
  6533. .next_multiple_of(64 << 10);
  6534. let buffer = host()?.uav_buffer(alloc)?;
  6535. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  6536. let old = slot.replace((buffer.clone(), alloc));
  6537. drop(slot);
  6538. if let Some((old_buf, _)) = old {
  6539. // It ends the list common, as every scratch buffer does.
  6540. self.indirect_common(&old_buf);
  6541. self.keep(&old_buf);
  6542. }
  6543. Some(buffer)
  6544. }
  6545. /// Where the next batch of clamped records goes: a device-local buffer
  6546. /// the list keeps from recording to recording, the batch's place in it
  6547. /// and the state the buffer is in. Every batch of a recording has a place
  6548. /// of its own: the executions before it may still read theirs.
  6549. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  6550. use crate::indirect::batch::{JOBS, SLOT};
  6551. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6552. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  6553. if buffer == args.0.len() {
  6554. let size = u64::from(BATCHES * JOBS * SLOT);
  6555. let made = host()?.uav_buffer(size)?;
  6556. name(&made, || format!("indirect batches {size:#x}"));
  6557. args.0.push(made);
  6558. }
  6559. args.1 += 1;
  6560. // (Its first batch finds it as the recording before left it:
  6561. // `batches_common`.)
  6562. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  6563. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  6564. }
  6565. /// Before the list closes: the scratch buffers of the batched clamps go
  6566. /// back to the common state, where the next recording expects them.
  6567. fn batches_common(&self) {
  6568. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6569. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  6570. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  6571. .iter()
  6572. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  6573. .collect();
  6574. if !barriers.is_empty() {
  6575. // SAFETY: an open list and live buffers this recording left in
  6576. // `INDIRECT_ARGUMENT`.
  6577. unsafe { self.list.ResourceBarrier(&barriers) };
  6578. }
  6579. }
  6580. /// Moves `scratch` back to the common state if a clamp left it readable
  6581. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  6582. /// list's first clamp expects it. Done before the list closes and before
  6583. /// a bigger scratch buffer replaces it: one barrier per list (where
  6584. /// there was one per indirect execution), and the list ends as it
  6585. /// begins however it is submitted.
  6586. fn indirect_common(&self, scratch: &ID3D12Resource) {
  6587. {
  6588. let mut deferred = self.deferred();
  6589. if deferred.indirect_readable != scratch.as_raw() as usize {
  6590. return;
  6591. }
  6592. deferred.indirect_readable = 0;
  6593. }
  6594. let barrier = transition(
  6595. scratch,
  6596. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  6597. D3D12_RESOURCE_STATE_COMMON,
  6598. );
  6599. // SAFETY: an open list and a live buffer this recording left in
  6600. // `INDIRECT_ARGUMENT`.
  6601. unsafe { self.list.ResourceBarrier(&[barrier]) };
  6602. }
  6603. /// The state the list's indirect scratch buffer `scratch` is in at this
  6604. /// point of the recording: indirect arguments if a clamp in this
  6605. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  6606. /// common: the state a buffer is made in, and the one a recording
  6607. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  6608. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  6609. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  6610. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  6611. } else {
  6612. D3D12_RESOURCE_STATE_COMMON
  6613. }
  6614. }
  6615. /// A clamp recorded in this list left `scratch` readable as indirect
  6616. /// arguments. It stays so for every execution that reads it, until the
  6617. /// next clamp moves it back to unordered access.
  6618. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  6619. self.deferred().indirect_readable = scratch.as_raw() as usize;
  6620. }
  6621. /// Keeps `object` alive until the list is reset.
  6622. pub(crate) fn keep(&self, object: &impl Interface) {
  6623. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  6624. self.deferred().kept.push(object);
  6625. }
  6626. }
  6627. /// Whether this is the first time since the reset that the list asks
  6628. /// about `key` (a texture to bring up to date).
  6629. pub(crate) fn first_use(&self, key: usize) -> bool {
  6630. self.deferred().textures.insert(key)
  6631. }
  6632. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  6633. /// reset.
  6634. pub(crate) fn used(&self, key: usize) -> bool {
  6635. self.deferred().textures.contains(&key)
  6636. }
  6637. /// Runs `work` when the list is submitted, in order with its copies.
  6638. /// `work` may write title memory (refreshes after it copy again).
  6639. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  6640. self.deferred().copies.push(Step::Run(Box::new(work)));
  6641. self.deferred().refreshed.clear();
  6642. self.changed_something();
  6643. }
  6644. /// As [`HostList::defer`], for work that writes only host memory.
  6645. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  6646. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  6647. }
  6648. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  6649. /// memory at `from`.
  6650. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  6651. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  6652. }
  6653. /// Brings a texture's staging buffer up to date when the list is
  6654. /// submitted, keeping it alive until the list is reset.
  6655. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  6656. self.deferred().copies.push(Step::Texture(staging));
  6657. }
  6658. /// Runs the list's submission-time steps; refreshes go into `batch`
  6659. /// (the title's big buffers, a 174 MB one among them, are read by most
  6660. /// lists of a submission, through many ranges). Copies and fills that
  6661. /// `taken` names (by their place) are left out: they are done on the
  6662. /// card ([`card_steps`]).
  6663. fn run_deferred(&self, batch: &mut Batch, air: &[(usize, usize)], taken: impl Fn(usize) -> bool) {
  6664. #[cfg(feature = "diagnostics")]
  6665. use crate::copystat::{C, add};
  6666. // The time and the bytes of the copies and fills, some 13,000 a
  6667. // frame between 20,000 refreshes: summed here and added once.
  6668. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  6669. #[cfg(feature = "diagnostics")]
  6670. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  6671. for (i, step) in self.deferred().copies.iter().enumerate() {
  6672. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  6673. continue;
  6674. }
  6675. let (started, copied) = match step {
  6676. &Step::Copy(dst, src, len) => {
  6677. let started = std::time::Instant::now();
  6678. #[cfg(feature = "diagnostics")]
  6679. {
  6680. copies += 1;
  6681. }
  6682. batch.fill();
  6683. batch.title_written();
  6684. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  6685. // With the submission's one asking: the journal learns it.
  6686. crate::watch::wrote(dst, len);
  6687. // What the card holds there may be another value although
  6688. // ours did not change.
  6689. if send::own() {
  6690. crate::shadow::send_copied(dst, len);
  6691. }
  6692. (started, len)
  6693. }
  6694. &Step::Fill(dst, src, len, _) => {
  6695. #[cfg(feature = "diagnostics")]
  6696. {
  6697. copies += 1;
  6698. }
  6699. if wide_fills() {
  6700. batch.fills.push((dst, src, len));
  6701. bytes += len as u64;
  6702. continue;
  6703. }
  6704. let started = std::time::Instant::now();
  6705. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6706. (started, len)
  6707. }
  6708. Step::Placed(p) => {
  6709. let started = std::time::Instant::now();
  6710. let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len);
  6711. batch.fill();
  6712. if free {
  6713. batch.title_written();
  6714. }
  6715. if let Some(bytes) = p.prepare(free) {
  6716. batch.placed.push((p.shadow.clone(), p.dst, bytes));
  6717. }
  6718. (started, p.len)
  6719. }
  6720. Step::Refresh(shadow, address, len) => {
  6721. #[cfg(feature = "diagnostics")]
  6722. {
  6723. refreshes += 1;
  6724. refreshed += *len as u64;
  6725. }
  6726. batch.add(shadow, *address, *len);
  6727. continue;
  6728. }
  6729. Step::Run(work) | Step::Host(work, _) => {
  6730. batch.fill();
  6731. #[cfg(feature = "diagnostics")]
  6732. let started = std::time::Instant::now();
  6733. if matches!(step, Step::Run(_)) {
  6734. batch.title_written();
  6735. }
  6736. let _step = crate::timeline::span("a step of ours");
  6737. work();
  6738. // It wrote title memory, where is not known here: the
  6739. // submission's one asking ends, later refreshes ask anew.
  6740. if matches!(step, Step::Run(_)) {
  6741. crate::watch::ask_once_end();
  6742. }
  6743. #[cfg(feature = "diagnostics")]
  6744. {
  6745. add(C::Runs, 1);
  6746. add(C::RunUs, started.elapsed().as_micros() as u64);
  6747. }
  6748. continue;
  6749. }
  6750. Step::GpuWrite(shadow, address, len) => {
  6751. // The shaders start from the title's data: this copy's
  6752. // pending refresh first. The other copies' wait for
  6753. // the next flush of all (flushing all of them at every
  6754. // range a dispatch writes made thousands of write-watch
  6755. // askings a frame).
  6756. batch.flush_one(shadow);
  6757. #[cfg(feature = "diagnostics")]
  6758. let snapshot = std::time::Instant::now();
  6759. shadow.writing(*address, *len);
  6760. #[cfg(feature = "diagnostics")]
  6761. {
  6762. add(C::GpuWrites, 1);
  6763. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  6764. }
  6765. continue;
  6766. }
  6767. Step::Texture(staging) => {
  6768. if batch.texture_due(staging) {
  6769. batch.due.push(staging.clone());
  6770. if !wide_textures() {
  6771. batch.refresh_textures();
  6772. }
  6773. }
  6774. continue;
  6775. }
  6776. };
  6777. us += started.elapsed();
  6778. bytes += copied as u64;
  6779. }
  6780. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  6781. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  6782. #[cfg(feature = "diagnostics")]
  6783. {
  6784. add(C::Copies, copies);
  6785. add(C::CopyBytes, bytes);
  6786. add(C::Refreshes, refreshes);
  6787. add(C::RefreshBytes, refreshed);
  6788. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  6789. }
  6790. }
  6791. }
  6792. /// The numbers of [`HostList::epoch`].
  6793. fn next_epoch() -> u64 {
  6794. static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
  6795. NEXT.fetch_add(1, Ordering::Relaxed)
  6796. }
  6797. /// A table by a copy's address.
  6798. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  6799. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  6800. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  6801. /// but our own.
  6802. #[derive(Default)]
  6803. pub(crate) struct AddressHash(u64);
  6804. impl std::hash::Hasher for AddressHash {
  6805. fn finish(&self) -> u64 {
  6806. self.0
  6807. }
  6808. fn write(&mut self, bytes: &[u8]) {
  6809. for &b in bytes {
  6810. self.write_usize(usize::from(b));
  6811. }
  6812. }
  6813. fn write_usize(&mut self, n: usize) {
  6814. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  6815. self.0 = h ^ (h >> 32);
  6816. }
  6817. fn write_u64(&mut self, n: u64) {
  6818. self.write_usize(n as usize);
  6819. }
  6820. fn write_u32(&mut self, n: u32) {
  6821. self.write_usize(n as usize);
  6822. }
  6823. }
  6824. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  6825. /// preparing: the write-watch asking for a submission; the title's bytes put
  6826. /// in under flights' writes; the lists' steps, the refreshes among them; the
  6827. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  6828. /// of the steps: the refreshes, and the copies and fills (those with the
  6829. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  6830. /// is of. Of the refreshes, those before ranges are given to shaders, one
  6831. /// copy at a time: nanoseconds, and how many. Ahead of all that: the wait for
  6832. /// the submission lock, the steps done on the card planned ([`card_steps`]),
  6833. /// the flights waited for, the heaps' records and what is swept; and, at the
  6834. /// end, the wait for the heaps' records.
  6835. #[cfg(feature = "diagnostics")]
  6836. static SPLIT: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16];
  6837. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  6838. /// those known to copy nothing, and those done on several threads.
  6839. #[cfg(feature = "diagnostics")]
  6840. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  6841. /// Counts into [`SPLIT`].
  6842. #[cfg(feature = "diagnostics")]
  6843. struct Split(std::cell::Cell<std::time::Instant>);
  6844. #[cfg(feature = "diagnostics")]
  6845. impl Split {
  6846. fn begin() -> Split {
  6847. Split(std::cell::Cell::new(std::time::Instant::now()))
  6848. }
  6849. /// Nanoseconds since the last part.
  6850. fn so_far(&self) -> u64 {
  6851. self.0.get().elapsed().as_nanos() as u64
  6852. }
  6853. /// What came since the last part was part `i`.
  6854. fn part(&self, i: usize) {
  6855. let now = std::time::Instant::now();
  6856. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  6857. }
  6858. }
  6859. /// The split of the preparing, per frame, for the frame-rate line.
  6860. #[cfg(feature = "diagnostics")]
  6861. fn split_line(frames: f64) {
  6862. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6863. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  6864. let e: Vec<f64> = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect();
  6865. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  6866. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6867. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
  6868. tracing::info!(
  6869. "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' \
  6870. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  6871. 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 \
  6872. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the submission lock, {:.1} \
  6873. planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is swept; at the end {:.1} waiting \
  6874. for the heaps' records; asked early by a thread of its own {:.0} pieces of 2 MiB, {:.1} ms (VICTORY_ASK_EARLY)",
  6875. ms[0],
  6876. ms[8],
  6877. ms[1],
  6878. ms[2],
  6879. ms[6],
  6880. f[0],
  6881. f[1],
  6882. f[2],
  6883. f[3],
  6884. ms[9],
  6885. ms[10] * 1e6,
  6886. ms[7],
  6887. ms[3],
  6888. ms[4],
  6889. ms[5],
  6890. if crate::watch::light() { "on" } else { "off" },
  6891. ms[11],
  6892. ms[12],
  6893. ms[13],
  6894. ms[14],
  6895. ms[15],
  6896. e[0],
  6897. e[1] / 1e3,
  6898. );
  6899. tracing::info!(
  6900. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6901. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6902. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6903. waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
  6904. as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
  6905. a[0],
  6906. a[1] / 1024.0,
  6907. a[11] / 1e6,
  6908. a[12],
  6909. a[10],
  6910. a[9],
  6911. a[2],
  6912. a[3],
  6913. a[4],
  6914. a[5],
  6915. a[6],
  6916. a[7] / 1e6,
  6917. a[8] / 1e6,
  6918. s[0] / 1048576.0,
  6919. s[1] / 1048576.0,
  6920. s[2] / 1048576.0,
  6921. s[3],
  6922. );
  6923. tracing::info!(
  6924. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures; the \
  6925. first two beside the recording (VICTORY_HEAP_PASS_ASIDE), {:.1} ms waited for at the lists' close",
  6926. h[0],
  6927. h[1],
  6928. h[2],
  6929. aside::WAITED.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames,
  6930. );
  6931. }
  6932. /// Whether a submission's refreshes of host copies run on several threads,
  6933. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6934. ///
  6935. /// A submission brings some sixty copies up to date, one after the other
  6936. /// on the submitting thread: for each, the pages the title wrote are asked
  6937. /// for and read through the kernel into the copy. That is the frame line's
  6938. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6939. /// another: each refresh writes its own copy and its own notes, and reads
  6940. /// title memory. With the switch the copies of a flush (four or more) are
  6941. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6942. /// The write-watch journal and the guards are behind their own locks, as
  6943. /// they are for the title's threads.
  6944. fn wide_refresh() -> bool {
  6945. static ON: OnceLock<bool> = OnceLock::new();
  6946. *ON.get_or_init(|| {
  6947. wide_refresh_enabled(
  6948. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6949. std::thread::available_parallelism().ok().map(|n| n.get()),
  6950. )
  6951. })
  6952. }
  6953. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6954. match setting {
  6955. Some("1") => true,
  6956. Some("0") => false,
  6957. _ => logical_cpus.is_some_and(|n| n >= 4),
  6958. }
  6959. }
  6960. #[cfg(test)]
  6961. mod wide_refresh_tests {
  6962. use super::wide_refresh_enabled;
  6963. #[test]
  6964. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6965. assert!(wide_refresh_enabled(None, Some(4)));
  6966. assert!(wide_refresh_enabled(None, Some(16)));
  6967. assert!(!wide_refresh_enabled(None, Some(2)));
  6968. assert!(!wide_refresh_enabled(None, None));
  6969. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6970. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6971. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6972. }
  6973. }
  6974. /// A submission's refreshes not done yet, merged per buffer copy into the
  6975. /// range that covers them: done before a step that writes title memory or
  6976. /// gives a range to shaders, and before the lists run.
  6977. ///
  6978. /// Also the textures brought up to date in the submission so far: most
  6979. /// lists of a world submission sample the same textures, and a texture in
  6980. /// physical-page memory is hashed whole each time it is checked. Checked
  6981. /// once, it is checked again only after a step that writes title memory.
  6982. #[derive(Default)]
  6983. struct Batch {
  6984. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6985. /// Where each copy (by address) is in `refreshes`: the list that makes
  6986. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6987. /// for every refresh of a submission was tens of millions of
  6988. /// comparisons a frame.
  6989. index: ByCopy<usize>,
  6990. /// Staging buffers (by address) refreshed since the last title write,
  6991. /// or due to be.
  6992. textures: std::collections::HashSet<usize>,
  6993. /// Those due ([`Batch::refresh_textures`]).
  6994. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6995. /// What copies at their place in the submission's lists put into title
  6996. /// memory ([`place`]): the host copy, the title address, the bytes.
  6997. placed: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, Vec<u8>)>,
  6998. /// Fills not done yet (destination, source, bytes): [`wide_fills`].
  6999. fills: Vec<(usize, usize, usize)>,
  7000. /// Copies (by address) brought up to date ahead of the steps, and the
  7001. /// range (from, to) ([`Batch::refresh_ahead`]).
  7002. ahead: ByCopy<(usize, usize)>,
  7003. /// `ahead` holds everything the submission refreshes
  7004. /// ([`Batch::refresh_front`]).
  7005. front: bool,
  7006. }
  7007. /// Whether the copies that a submission's shaders write are brought up to
  7008. /// date together, on several threads, ahead of its steps
  7009. /// (`VICTORY_REFRESH_AHEAD=0`: each before the step that gives it to them).
  7010. ///
  7011. /// 580 copies a frame, one after the other on the submitting thread, 3.4 to
  7012. /// 6.5 ms (session play-1125-0203).
  7013. fn ahead_of_writes() -> bool {
  7014. static ON: OnceLock<bool> = OnceLock::new();
  7015. *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_AHEAD").is_none_or(|v| v != "0") && wide_refresh() && crate::watch::light())
  7016. }
  7017. /// Whether everything a submission refreshes is brought up to date in one go,
  7018. /// on several threads, ahead of its steps (`VICTORY_REFRESH_FRONT=1`, and with
  7019. /// `VICTORY_JOIN_PARTS`, which needs it; else in groups where the steps ask
  7020. /// for it). Measured on its own at nothing (run submit-1: refreshes 17.1 ms a
  7021. /// frame without, 18.3 with).
  7022. ///
  7023. /// A submission's refreshes were done in up to five groups one after the other
  7024. /// (the copies its shaders write, those between its steps, what is left),
  7025. /// each ending with the threads waiting for the last copy; and the submitting
  7026. /// thread went over all the steps once for each question it has (what to ask
  7027. /// about, what flights may write too, what shaders write). A refresh may come
  7028. /// earlier than its step: the title's bytes are the same until a step writes
  7029. /// title memory, and behind such a step everything is asked for again, as it
  7030. /// was.
  7031. fn refresh_front() -> bool {
  7032. static ON: OnceLock<bool> = OnceLock::new();
  7033. ahead_of_writes() && (joins_asked().0 > 1 || *ON.get_or_init(|| crate::switch::on("VICTORY_REFRESH_FRONT")))
  7034. }
  7035. /// Per copy what is refreshed in front of a submission's steps, as
  7036. /// [`written_spans`]'s but of all copies, up to the copy's first write by
  7037. /// shaders in each part of the submission (`Touch::Part`: another begins).
  7038. /// What a part refreshes of a copy it has given to its shaders stays where it
  7039. /// stands: around what they write. What a later part refreshes is the
  7040. /// title's bytes of before either.
  7041. fn front_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> {
  7042. let mut at: ByCopy<usize> = ByCopy::default();
  7043. // (Copy, from, to), in the order they come, and the part that gave it to
  7044. // shaders last.
  7045. let mut spans: Vec<(usize, usize, usize)> = Vec::new();
  7046. let mut given: Vec<u32> = Vec::new();
  7047. let (mut part, mut last) = (1, usize::MAX);
  7048. for step in steps {
  7049. match step {
  7050. Touch::Refresh(copy, from, to) => {
  7051. // (Most come several times on end.)
  7052. let i = if spans.get(last).is_some_and(|s| s.0 == copy) {
  7053. last
  7054. } else {
  7055. *at.entry(copy).or_insert_with(|| {
  7056. spans.push((copy, usize::MAX, 0));
  7057. given.push(0);
  7058. spans.len() - 1
  7059. })
  7060. };
  7061. last = i;
  7062. if given[i] != part {
  7063. let span = &mut spans[i];
  7064. (span.1, span.2) = (span.1.min(from), span.2.max(to));
  7065. }
  7066. }
  7067. Touch::Write(copy) => {
  7068. let i = *at.entry(copy).or_insert_with(|| {
  7069. spans.push((copy, usize::MAX, 0));
  7070. given.push(0);
  7071. spans.len() - 1
  7072. });
  7073. given[i] = part;
  7074. }
  7075. Touch::Part => part += 1,
  7076. Touch::Title | Touch::Nothing => {}
  7077. }
  7078. }
  7079. spans.retain(|s| s.1 < s.2);
  7080. spans
  7081. }
  7082. /// What a step is to the copies' refreshes, for [`written_spans`].
  7083. enum Touch {
  7084. /// A refresh of a copy (by address), from, to.
  7085. Refresh(usize, usize, usize),
  7086. /// The copy is given to shaders.
  7087. Write(usize),
  7088. /// Title memory is written.
  7089. Title,
  7090. Nothing,
  7091. /// Another part of the submission begins.
  7092. Part,
  7093. }
  7094. /// Of `steps`, up to the first that writes title memory: the copies given to
  7095. /// shaders, each with the range its refreshes before that cover.
  7096. fn written_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> {
  7097. // (From, to, given to shaders.)
  7098. let mut spans: ByCopy<(usize, usize, bool)> = ByCopy::default();
  7099. for step in steps {
  7100. match step {
  7101. Touch::Refresh(copy, from, to) => {
  7102. let span = spans.entry(copy).or_insert((from, to, false));
  7103. if !span.2 {
  7104. (span.0, span.1) = (span.0.min(from), span.1.max(to));
  7105. }
  7106. }
  7107. // (Not refreshed before: nothing of it is due.)
  7108. Touch::Write(copy) => {
  7109. if let Some(span) = spans.get_mut(&copy) {
  7110. span.2 = true;
  7111. }
  7112. }
  7113. Touch::Title => break,
  7114. Touch::Nothing | Touch::Part => {}
  7115. }
  7116. }
  7117. spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect()
  7118. }
  7119. #[cfg(test)]
  7120. mod written_spans_tests {
  7121. use super::{Touch, front_spans, split, written_spans};
  7122. #[test]
  7123. fn everything_is_refreshed_in_front_but_what_a_part_gave_its_shaders() {
  7124. use Touch::{Nothing, Part, Refresh, Title, Write};
  7125. let found = front_spans(
  7126. [
  7127. Refresh(1, 10, 20),
  7128. Refresh(1, 12, 25),
  7129. Refresh(2, 0, 5),
  7130. Nothing,
  7131. Write(1),
  7132. // (Around what the part's own shaders write.)
  7133. Refresh(1, 0, 100),
  7134. Write(3),
  7135. Refresh(3, 1, 2),
  7136. Title,
  7137. Refresh(4, 7, 9),
  7138. Part,
  7139. // The next part's bytes under the first one's writes.
  7140. Refresh(1, 30, 40),
  7141. Write(4),
  7142. Refresh(4, 0, 9),
  7143. ]
  7144. .into_iter(),
  7145. );
  7146. assert_eq!(found, [(1, 10, 40), (2, 0, 5), (4, 7, 9)]);
  7147. }
  7148. #[test]
  7149. fn a_submission_is_cut_between_its_lists() {
  7150. // Lists c and e are in neither half's order: they go with the first.
  7151. let Ok([first, second]) = split(vec!['a', 'b', 'c', 'd', 'e'], vec![1, 3, 0], 1) else {
  7152. panic!("no list is named twice");
  7153. };
  7154. let run = |(lists, order): &(Vec<char>, Vec<usize>)| order.iter().map(|&i| lists[i]).collect::<String>();
  7155. assert_eq!((run(&first), run(&second)), ("b".into(), "da".into()));
  7156. assert_eq!(first.0.len() + second.0.len(), 5);
  7157. assert!(split(vec!['a', 'b'], vec![0, 1, 0], 2).is_err());
  7158. assert!(split(vec!['a', 'b'], vec![0, 1], 0).is_err());
  7159. }
  7160. #[test]
  7161. fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() {
  7162. use Touch::{Nothing, Refresh, Title, Write};
  7163. let mut found = written_spans(
  7164. [
  7165. Refresh(1, 10, 20),
  7166. Refresh(2, 0, 5),
  7167. Nothing,
  7168. Refresh(1, 30, 40),
  7169. Write(1),
  7170. Refresh(1, 0, 100),
  7171. Write(3),
  7172. Refresh(3, 1, 2),
  7173. Refresh(4, 7, 9),
  7174. Write(4),
  7175. Title,
  7176. Write(2),
  7177. ]
  7178. .into_iter(),
  7179. );
  7180. found.sort_unstable();
  7181. assert_eq!(found, [(1, 10, 40), (4, 7, 9)]);
  7182. }
  7183. }
  7184. /// Whether the fills of a submission's upload memory are done together on
  7185. /// several threads (`VICTORY_WIDE_FILLS=0`: one after the other, where the
  7186. /// lists name them).
  7187. ///
  7188. /// They are 7,000 to 12,000 a frame, some 500 bytes each, 5 ms of the
  7189. /// submitting thread. Each reads title memory and writes memory of its own
  7190. /// that the card alone reads, when the lists run; they are done before the
  7191. /// next step that writes title memory or runs code of ours, and before the
  7192. /// submission goes on from its steps.
  7193. fn wide_fills() -> bool {
  7194. static ON: OnceLock<bool> = OnceLock::new();
  7195. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_FILLS").is_none_or(|v| v != "0") && wide_refresh())
  7196. }
  7197. /// Whether a submission's textures are brought up to date on several
  7198. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  7199. /// name them, as before).
  7200. ///
  7201. /// They are read, hashed and, if they changed, detiled into their staging
  7202. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  7203. /// its own buffer, notes and lock, and is refreshed by the title's own
  7204. /// threads as it is. They are done before the next step that writes title
  7205. /// memory, as the copies' refreshes are, and before the lists go to the
  7206. /// card. What is new: the note of a list that its upload takes what the
  7207. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  7208. /// an earlier list of the submission asked for, not behind it. The texture
  7209. /// is then uploaded by a later list too, once more than needed.
  7210. fn wide_textures() -> bool {
  7211. static ON: OnceLock<bool> = OnceLock::new();
  7212. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  7213. }
  7214. impl Batch {
  7215. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  7216. let end = address + len;
  7217. let key = std::sync::Arc::as_ptr(shadow) as usize;
  7218. if self.ahead.get(&key).is_some_and(|&(from, to)| from <= address && end <= to) {
  7219. return;
  7220. }
  7221. match self.index.get(&key) {
  7222. Some(&at) => {
  7223. let r = &mut self.refreshes[at];
  7224. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  7225. }
  7226. None => {
  7227. self.index.insert(key, self.refreshes.len());
  7228. self.refreshes.push((shadow.clone(), address, end));
  7229. }
  7230. }
  7231. }
  7232. /// Before shaders are given a range of `shadow`'s copy: its pending
  7233. /// refresh is done, the others stay pending.
  7234. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  7235. // From here on it is refreshed around what the shaders write. (What
  7236. // is in front of all the steps was, up to here.)
  7237. if !self.front {
  7238. self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize));
  7239. }
  7240. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  7241. return;
  7242. };
  7243. let (shadow, from, to) = self.refreshes.swap_remove(at);
  7244. // The last entry took its place.
  7245. if let Some(moved) = self.refreshes.get(at) {
  7246. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  7247. }
  7248. #[cfg(feature = "diagnostics")]
  7249. let started = std::time::Instant::now();
  7250. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  7251. Self::update(&shadow, from, to);
  7252. }
  7253. #[cfg(feature = "diagnostics")]
  7254. {
  7255. let ns = started.elapsed().as_nanos() as u64;
  7256. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  7257. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  7258. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  7259. }
  7260. }
  7261. /// Brings `[from, to)` of a copy up to date, timed.
  7262. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  7263. let started = std::time::Instant::now();
  7264. let _one = crate::timeline::span("a copy's refresh");
  7265. let copied = shadow.update(from, to - from);
  7266. let us = started.elapsed().as_micros() as u64;
  7267. #[cfg(feature = "diagnostics")]
  7268. crate::copystat::range(from, to - from, us, 0);
  7269. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  7270. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  7271. }
  7272. /// Whether `staging` is still to be refreshed in this submission (and
  7273. /// notes it refreshed).
  7274. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  7275. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  7276. }
  7277. /// Before a step that writes title memory: pending refreshes are done
  7278. /// first, and textures are checked again after it.
  7279. fn title_written(&mut self) {
  7280. self.flush();
  7281. self.ahead.clear();
  7282. self.textures.clear();
  7283. }
  7284. /// Before the steps of `runs` ([`refresh_front`]), a new part of the
  7285. /// submission beginning at each of `parts`.
  7286. fn refresh_front(&mut self, runs: &[&HostList], parts: &[usize]) {
  7287. let mut copies: ByCopy<std::sync::Arc<crate::shadow::Shadow>> = ByCopy::default();
  7288. let mut due = Vec::new();
  7289. let mut touches = Vec::new();
  7290. for (n, list) in runs.iter().enumerate() {
  7291. if parts.contains(&n) {
  7292. touches.push(Touch::Part);
  7293. }
  7294. let mut last = 0;
  7295. for step in &list.deferred().copies {
  7296. match step {
  7297. Step::Refresh(shadow, at, len) => {
  7298. let key = std::sync::Arc::as_ptr(shadow) as usize;
  7299. if key != last {
  7300. copies.entry(key).or_insert_with(|| shadow.clone());
  7301. last = key;
  7302. }
  7303. touches.push(Touch::Refresh(key, *at, *at + *len));
  7304. }
  7305. Step::GpuWrite(shadow, ..) => touches.push(Touch::Write(std::sync::Arc::as_ptr(shadow) as usize)),
  7306. Step::Texture(staging) if wide_textures() => {
  7307. if self.texture_due(staging) {
  7308. due.push(staging.clone());
  7309. }
  7310. }
  7311. _ => {}
  7312. }
  7313. }
  7314. }
  7315. let spans: Vec<_> = front_spans(touches.into_iter())
  7316. .into_iter()
  7317. .filter_map(|(key, from, to)| Some((copies.remove(&key)?, from, to)))
  7318. .collect();
  7319. self.front = true;
  7320. for (shadow, from, to) in &spans {
  7321. self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to));
  7322. }
  7323. #[cfg(feature = "diagnostics")]
  7324. {
  7325. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  7326. FLUSHES[1].fetch_add(spans.len() as u64, Ordering::Relaxed);
  7327. }
  7328. let _flush = crate::timeline::span("refreshes of copies");
  7329. let started = std::time::Instant::now();
  7330. let before = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed));
  7331. // Those known to copy nothing are said so here, unless they are very
  7332. // many: then beside the others.
  7333. const FEW: usize = 256;
  7334. let mut spans = spans;
  7335. let many = spans.len() > FEW;
  7336. if !many {
  7337. #[cfg(feature = "diagnostics")]
  7338. let all = spans.len();
  7339. spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  7340. #[cfg(feature = "diagnostics")]
  7341. FLUSHES[2].fetch_add((all - spans.len()) as u64, Ordering::Relaxed);
  7342. }
  7343. let ahead = spans.len() > 1;
  7344. if ahead {
  7345. let ranges: Vec<(usize, usize)> = spans.iter().filter(|r| r.0.asked_ahead()).map(|r| (r.1, r.2)).collect();
  7346. crate::watch::ask_ahead(&ranges);
  7347. }
  7348. #[cfg(feature = "diagnostics")]
  7349. FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed);
  7350. crate::shadow::wide_each(spans.len() + due.len(), move |i| {
  7351. // The textures first: they are the longer pieces.
  7352. let Some(i) = i.checked_sub(due.len()) else {
  7353. due[i].refresh();
  7354. return;
  7355. };
  7356. let (shadow, from, to) = &spans[i];
  7357. if many && shadow.nothing_new(*from, *to - *from) {
  7358. #[cfg(feature = "diagnostics")]
  7359. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  7360. return;
  7361. }
  7362. Self::update(shadow, *from, *to);
  7363. });
  7364. if ahead {
  7365. crate::watch::ask_ahead_done();
  7366. }
  7367. // The time counted is the time it took, not the threads' sum.
  7368. let took = started.elapsed().as_micros() as u64;
  7369. let summed = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed)).iter().zip(before).map(|(now, was)| now.saturating_sub(was)).collect::<Vec<_>>();
  7370. PREPARING[2].fetch_sub(summed[1], Ordering::Relaxed);
  7371. PREPARING[0].fetch_sub(summed[0], Ordering::Relaxed);
  7372. PREPARING[0].fetch_add(took, Ordering::Relaxed);
  7373. #[cfg(feature = "diagnostics")]
  7374. SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
  7375. }
  7376. /// Before the steps of `runs` ([`ahead_of_writes`]); copies and fills
  7377. /// that `taken` names are not done on the CPU.
  7378. fn refresh_ahead(&mut self, runs: &[&HostList], taken: impl Fn(&HostList, usize) -> bool) {
  7379. let mut copies: ByCopy<std::sync::Arc<crate::shadow::Shadow>> = ByCopy::default();
  7380. let mut touches = Vec::new();
  7381. 'steps: for list in runs {
  7382. for (i, step) in list.deferred().copies.iter().enumerate() {
  7383. touches.push(match step {
  7384. Step::Refresh(shadow, at, len) => {
  7385. let key = std::sync::Arc::as_ptr(shadow) as usize;
  7386. copies.entry(key).or_insert_with(|| shadow.clone());
  7387. Touch::Refresh(key, *at, *at + *len)
  7388. }
  7389. Step::GpuWrite(shadow, ..) => Touch::Write(std::sync::Arc::as_ptr(shadow) as usize),
  7390. Step::Copy(..) if taken(list, i) => Touch::Nothing,
  7391. Step::Copy(..) | Step::Run(_) | Step::Placed(_) => break 'steps,
  7392. _ => Touch::Nothing,
  7393. });
  7394. }
  7395. }
  7396. let due: Vec<_> = written_spans(touches.into_iter())
  7397. .into_iter()
  7398. .filter_map(|(key, from, to)| Some((copies.get(&key)?.clone(), from, to)))
  7399. .collect();
  7400. for (shadow, from, to) in &due {
  7401. self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to));
  7402. }
  7403. #[cfg(feature = "diagnostics")]
  7404. let began = std::time::Instant::now();
  7405. let started = std::time::Instant::now();
  7406. let before = PREPARING[0].load(Ordering::Relaxed);
  7407. crate::shadow::wide_each(due.len(), move |i| {
  7408. let (shadow, from, to) = &due[i];
  7409. if !shadow.nothing_new(*from, *to - *from) {
  7410. Self::update(shadow, *from, *to);
  7411. }
  7412. });
  7413. // The time counted is the time it took, not the threads' sum.
  7414. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  7415. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  7416. #[cfg(feature = "diagnostics")]
  7417. {
  7418. let ns = began.elapsed().as_nanos() as u64;
  7419. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  7420. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  7421. }
  7422. }
  7423. /// The fills noted are done.
  7424. fn fill(&mut self) {
  7425. // Below this many the threads cost more than they save.
  7426. const FEW: usize = 96;
  7427. const PART: usize = 64;
  7428. if self.fills.is_empty() {
  7429. return;
  7430. }
  7431. let started = std::time::Instant::now();
  7432. if self.fills.len() < FEW {
  7433. for (dst, src, len) in self.fills.drain(..) {
  7434. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  7435. }
  7436. } else {
  7437. let fills = std::mem::take(&mut self.fills);
  7438. crate::shadow::wide_each(fills.len().div_ceil(PART), move |i| {
  7439. for &(dst, src, len) in fills.iter().skip(i * PART).take(PART) {
  7440. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  7441. }
  7442. });
  7443. }
  7444. let took = started.elapsed();
  7445. PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed);
  7446. #[cfg(feature = "diagnostics")]
  7447. SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed);
  7448. }
  7449. /// The textures due are brought up to date.
  7450. fn refresh_textures(&mut self) {
  7451. if self.due.len() < 2 || !wide_textures() {
  7452. self.due.drain(..).for_each(|staging| staging.refresh());
  7453. return;
  7454. }
  7455. let _textures = crate::timeline::span("textures brought up to date");
  7456. // The time counted is the time it took, not the threads' sum.
  7457. let started = std::time::Instant::now();
  7458. let before = PREPARING[2].load(Ordering::Relaxed);
  7459. let due = std::mem::take(&mut self.due);
  7460. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  7461. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  7462. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  7463. }
  7464. fn flush(&mut self) {
  7465. self.refresh_textures();
  7466. self.index.clear();
  7467. if self.refreshes.is_empty() {
  7468. return;
  7469. }
  7470. #[cfg(feature = "diagnostics")]
  7471. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  7472. let _flush = crate::timeline::span("refreshes of copies");
  7473. self.flush_all();
  7474. #[cfg(feature = "diagnostics")]
  7475. {
  7476. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  7477. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  7478. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  7479. }
  7480. }
  7481. fn flush_all(&mut self) {
  7482. // Most of a flush's copies are as they were: they are told so here,
  7483. // from what the submission's asking found, before anything is asked
  7484. // and any thread woken. (Thousands of them, the heap's buffer views
  7485. // once a frame: on the threads, below.)
  7486. const FEW: usize = 256;
  7487. let light = crate::watch::light();
  7488. if light && self.refreshes.len() <= FEW {
  7489. let started = std::time::Instant::now();
  7490. #[cfg(feature = "diagnostics")]
  7491. let all = self.refreshes.len();
  7492. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  7493. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  7494. #[cfg(feature = "diagnostics")]
  7495. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  7496. }
  7497. // One write-watch asking for the copies that lie close together,
  7498. // not one per copy.
  7499. let ahead = self.refreshes.len() > 1;
  7500. if ahead {
  7501. let started = std::time::Instant::now();
  7502. let ranges: Vec<(usize, usize)> = self
  7503. .refreshes
  7504. .iter()
  7505. .filter(|r| r.0.asked_ahead())
  7506. .map(|r| (r.1, r.2))
  7507. .collect();
  7508. crate::watch::ask_ahead(&ranges);
  7509. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  7510. }
  7511. if wide_refresh() && self.refreshes.len() >= 4 {
  7512. // Each copy on its own, several at a time: a copy's refresh
  7513. // writes that copy and reads title memory, nothing of another's.
  7514. // The time counted is the time it took, not the threads' sum.
  7515. let started = std::time::Instant::now();
  7516. let before = PREPARING[0].load(Ordering::Relaxed);
  7517. #[cfg(feature = "diagnostics")]
  7518. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  7519. if light {
  7520. // A number to a free thread, not a job to each copy.
  7521. let refreshes = std::mem::take(&mut self.refreshes);
  7522. crate::shadow::wide_each(refreshes.len(), move |i| {
  7523. let (shadow, from, to) = &refreshes[i];
  7524. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  7525. #[cfg(feature = "diagnostics")]
  7526. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  7527. return;
  7528. }
  7529. Self::update(shadow, *from, *to);
  7530. });
  7531. } else {
  7532. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  7533. .refreshes
  7534. .drain(..)
  7535. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  7536. .collect();
  7537. crate::shadow::wide_run(jobs);
  7538. }
  7539. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  7540. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  7541. } else {
  7542. for (shadow, from, to) in self.refreshes.drain(..) {
  7543. Self::update(&shadow, from, to);
  7544. }
  7545. }
  7546. if ahead {
  7547. crate::watch::ask_ahead_done();
  7548. }
  7549. }
  7550. }
  7551. /// Copies title memory at submission. The ranges were checked against their
  7552. /// resources when recorded, but the title may since have unmapped pages of
  7553. /// them (tiled memory, page mappings), which read as zeros here; a title
  7554. /// destination (`title_dst`) that is not all mapped is left alone.
  7555. ///
  7556. /// The source is read through the kernel (`ReadProcessMemory`), which
  7557. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  7558. /// cost about 2 ms per copy in the title's big pools (it walks the page
  7559. /// tables to the region's end), which made copies run at 100-200 MB/s.
  7560. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  7561. #[cfg(feature = "diagnostics")]
  7562. match crate::copystat::mode() {
  7563. 1 => {
  7564. // SAFETY: timing only: the caller vouches for the source.
  7565. unsafe { std::ptr::copy(src, dst, len) };
  7566. return;
  7567. }
  7568. 2 => return,
  7569. _ => {}
  7570. }
  7571. if len == 0 {
  7572. return;
  7573. }
  7574. // A title destination that is not all mapped is left alone. Asking
  7575. // Windows first (`VirtualQuery`) walks the page tables to the end of
  7576. // the destination's region: in the title's big blocks that is
  7577. // milliseconds a copy, and it was a seventh of the submitting thread's
  7578. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  7579. // says the same when it fails, so the question is only asked then.
  7580. // `VICTORY_COPY_ASK=1` asks first, as before.
  7581. static ASK: OnceLock<bool> = OnceLock::new();
  7582. let ask_first = title_dst
  7583. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  7584. if ask_first && !crate::texture::committed(dst, len) {
  7585. return;
  7586. }
  7587. if title_dst {
  7588. // The kernel writes the destination: it must not be guarded.
  7589. crate::watch::writing(dst as usize, len);
  7590. }
  7591. #[cfg(feature = "diagnostics")]
  7592. let moved = std::time::Instant::now();
  7593. let since = crate::watch::changes();
  7594. // (A title destination that is away only while the runtime changes a
  7595. // mapping beside it is written when that is done.)
  7596. let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
  7597. #[cfg(feature = "diagnostics")]
  7598. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  7599. if whole {
  7600. return;
  7601. }
  7602. // The copy failed: a source page is not there, or the destination is
  7603. // not all mapped. Then the destination stays as it is (the kernel may
  7604. // have written its first pages).
  7605. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  7606. crate::watch::lost("a copy of the title's", dst as usize, len);
  7607. return;
  7608. }
  7609. #[cfg(feature = "diagnostics")]
  7610. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  7611. #[cfg(feature = "diagnostics")]
  7612. let sparse = std::time::Instant::now();
  7613. if !title_dst && len >= 64 << 10 {
  7614. read_sparse(src, dst, len);
  7615. } else {
  7616. read_pieces(src, dst, len);
  7617. }
  7618. #[cfg(feature = "diagnostics")]
  7619. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  7620. }
  7621. /// After a failed bulk read into host memory, skip contiguous holes. Never
  7622. /// cache the query across copies: the title may remap the same address.
  7623. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  7624. use windows_sys::Win32::System::Memory::{
  7625. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  7626. };
  7627. let mut offset = 0;
  7628. while offset < len {
  7629. let at = src.wrapping_add(offset);
  7630. let to = dst.wrapping_add(offset);
  7631. let remaining = len - offset;
  7632. // SAFETY: the query inspects an address and fills a local structure.
  7633. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  7634. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  7635. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  7636. .saturating_sub(at as usize).min(remaining);
  7637. if size != size_of_val(&info) || n == 0 {
  7638. read_pieces(at, to, remaining);
  7639. break;
  7640. }
  7641. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  7642. #[cfg(feature = "diagnostics")]
  7643. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  7644. // SAFETY: this path is only used with a writable host destination.
  7645. unsafe { to.write_bytes(0, n) };
  7646. } else if !read(at, to, n) {
  7647. // A mapping may change between query and read.
  7648. read_pieces(at, to, n);
  7649. }
  7650. offset += n;
  7651. }
  7652. }
  7653. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  7654. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  7655. // that fails), zeros for what cannot be read.
  7656. for_pieces(src as usize, len, 64 << 10, |at, n| {
  7657. let to = dst.wrapping_add(at - src as usize);
  7658. if !read(at as *const u8, to, n) {
  7659. for_pieces(at, n, 4 << 10, |at, n| {
  7660. let to = dst.wrapping_add(at - src as usize);
  7661. if !read(at as *const u8, to, n) {
  7662. #[cfg(feature = "diagnostics")]
  7663. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  7664. zero(to, n);
  7665. }
  7666. });
  7667. }
  7668. });
  7669. }
  7670. /// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
  7671. /// destination of a title's copy), which can go between the question whether
  7672. /// it is there and this.
  7673. fn zero(to: *mut u8, n: usize) {
  7674. static ZEROS: [u8; 4096] = [0; 4096];
  7675. if n <= ZEROS.len() && crate::safecopy::on() {
  7676. // SAFETY: a destination that is not there fails the copy.
  7677. if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
  7678. crate::watch::lost("zeros", to as usize, n);
  7679. }
  7680. return;
  7681. }
  7682. // SAFETY: inside the destination, which is mapped.
  7683. unsafe { to.write_bytes(0, n) };
  7684. }
  7685. /// Reads title memory at `src` into `dst`; false if a page of it is not
  7686. /// readable.
  7687. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  7688. read(src, dst.as_mut_ptr(), dst.len())
  7689. }
  7690. /// Reads what is there of the `dst.len()` bytes of title memory at `src`,
  7691. /// zeros for the rest; returns how many bytes were there. Safe while the
  7692. /// runtime remaps title memory (the kernel, or a copy that takes the fault,
  7693. /// reads). What the runtime's record says is mapped is read in one go each,
  7694. /// and by pieces where that fails; memory it has no record of by pieces.
  7695. pub(crate) fn read_there(src: *const u8, dst: &mut [u8]) -> usize {
  7696. dst.fill(0);
  7697. let (start, len) = (src as usize, dst.len());
  7698. let mut got = 0;
  7699. let mut runs = crate::inplace::shown_runs(start, len);
  7700. if runs.is_empty() {
  7701. runs.push((start, len));
  7702. }
  7703. for (at, n) in runs {
  7704. let piece = &mut dst[at - start..at - start + n];
  7705. if read_into(at as *const u8, piece) {
  7706. got += n;
  7707. continue;
  7708. }
  7709. // (What failed may have written its first pages.)
  7710. piece.fill(0);
  7711. for_pieces(at, n, 64 << 10, |from, n| {
  7712. let piece = &mut dst[from - start..from - start + n];
  7713. if read_into(from as *const u8, piece) {
  7714. got += n;
  7715. return;
  7716. }
  7717. piece.fill(0);
  7718. for_pieces(from, n, 4 << 10, |from, n| {
  7719. let piece = &mut dst[from - start..from - start + n];
  7720. if read_into(from as *const u8, piece) {
  7721. got += n;
  7722. } else {
  7723. piece.fill(0);
  7724. }
  7725. });
  7726. });
  7727. }
  7728. got
  7729. }
  7730. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  7731. /// readable.
  7732. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  7733. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  7734. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7735. if crate::safecopy::on() {
  7736. // SAFETY: the destination is mapped writable memory of `len` bytes;
  7737. // a source page that is not there fails the copy.
  7738. return unsafe { crate::safecopy::copy(dst, src, len) };
  7739. }
  7740. let mut done = 0;
  7741. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  7742. // kernel checks the source.
  7743. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  7744. }
  7745. #[link(name = "ntdll", kind = "raw-dylib")]
  7746. unsafe extern "system" {
  7747. /// The kernel's write into a process's memory, `(process, address,
  7748. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  7749. /// the range is not there or not writable. It changes no protection.
  7750. fn NtWriteVirtualMemory(
  7751. process: *mut std::ffi::c_void,
  7752. base: *mut std::ffi::c_void,
  7753. buffer: *const std::ffi::c_void,
  7754. size: usize,
  7755. written: *mut usize,
  7756. ) -> i32;
  7757. }
  7758. /// Whether title memory is written with the kernel's own call
  7759. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  7760. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  7761. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  7762. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  7763. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  7764. fn direct_writes() -> bool {
  7765. static ON: OnceLock<bool> = OnceLock::new();
  7766. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  7767. }
  7768. /// Copies host memory into title memory after a submission (what shaders
  7769. /// wrote), leaving pages that are not mapped alone.
  7770. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  7771. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  7772. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7773. let direct = direct_writes();
  7774. let since = crate::watch::changes();
  7775. let write = |at: usize, n: usize| {
  7776. let from = src.wrapping_add(at - dst as usize);
  7777. if crate::safecopy::on() {
  7778. // SAFETY: the source is ours; a destination page that is not
  7779. // there, or not writable, fails the copy.
  7780. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  7781. }
  7782. let mut done = 0;
  7783. if direct {
  7784. // SAFETY: as below; the kernel checks the destination and
  7785. // writes nothing it cannot (the caller opened its guards:
  7786. // `crate::watch::writing`).
  7787. return unsafe {
  7788. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  7789. };
  7790. }
  7791. // SAFETY: the source is our mapped host copy; the kernel checks the
  7792. // destination.
  7793. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  7794. };
  7795. if len == 0 || write(dst as usize, len) {
  7796. return;
  7797. }
  7798. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  7799. if !write(at, n) {
  7800. for_pieces(at, n, 4 << 10, |at, n| {
  7801. if write(at, n) {
  7802. return;
  7803. }
  7804. // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
  7805. // refresh guarded the block again since the caller opened
  7806. // it; and any where the runtime was changing a mapping.
  7807. crate::watch::writing(at, n);
  7808. if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
  7809. crate::watch::lost("a host copy's bytes", at, n);
  7810. }
  7811. });
  7812. }
  7813. });
  7814. }
  7815. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  7816. /// `step`.
  7817. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  7818. let end = start + len;
  7819. let mut at = start;
  7820. while at < end {
  7821. let next = ((at / step + 1) * step).min(end);
  7822. f(at, next - at);
  7823. at = next;
  7824. }
  7825. }
  7826. impl Host {
  7827. /// The queue everything of ours runs on, for a call that must go to it
  7828. /// in order with the lists (`crate::tiles`: a texture's levels are
  7829. /// given memory ahead of the list that uploads them).
  7830. pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
  7831. &self.queue
  7832. }
  7833. /// A buffer in the upload heap, mapped for writing.
  7834. /// A buffer of `size` bytes the card writes and we read (a read back),
  7835. /// in the state copies into it need.
  7836. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7837. let heap = D3D12_HEAP_PROPERTIES {
  7838. Type: D3D12_HEAP_TYPE_READBACK,
  7839. ..Default::default()
  7840. };
  7841. let desc = D3D12_RESOURCE_DESC {
  7842. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7843. Width: size.max(1),
  7844. Height: 1,
  7845. DepthOrArraySize: 1,
  7846. MipLevels: 1,
  7847. SampleDesc: DXGI_SAMPLE_DESC {
  7848. Count: 1,
  7849. Quality: 0,
  7850. },
  7851. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7852. ..Default::default()
  7853. };
  7854. let mut buffer: Option<ID3D12Resource> = None;
  7855. // SAFETY: plain creation of a read-back buffer.
  7856. let made = unsafe {
  7857. self.device.CreateCommittedResource(
  7858. &heap,
  7859. D3D12_HEAP_FLAG_NONE,
  7860. &desc,
  7861. D3D12_RESOURCE_STATE_COPY_DEST,
  7862. None,
  7863. &mut buffer,
  7864. )
  7865. };
  7866. match made {
  7867. Ok(()) => buffer,
  7868. Err(e) => {
  7869. tracing::warn!(error = %e, size, "no read-back buffer");
  7870. None
  7871. }
  7872. }
  7873. }
  7874. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7875. MADE[0].fetch_add(1, Ordering::Relaxed);
  7876. MADE[1].fetch_add(size, Ordering::Relaxed);
  7877. let heap = D3D12_HEAP_PROPERTIES {
  7878. Type: D3D12_HEAP_TYPE_UPLOAD,
  7879. ..Default::default()
  7880. };
  7881. let desc = D3D12_RESOURCE_DESC {
  7882. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7883. Width: size.max(1),
  7884. Height: 1,
  7885. DepthOrArraySize: 1,
  7886. MipLevels: 1,
  7887. SampleDesc: DXGI_SAMPLE_DESC {
  7888. Count: 1,
  7889. Quality: 0,
  7890. },
  7891. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7892. ..Default::default()
  7893. };
  7894. let mut buffer: Option<ID3D12Resource> = None;
  7895. let mut data = std::ptr::null_mut();
  7896. // SAFETY: plain creation and mapping of an upload buffer.
  7897. let made = unsafe {
  7898. self.device
  7899. .CreateCommittedResource(
  7900. &heap,
  7901. not_resident(),
  7902. &desc,
  7903. D3D12_RESOURCE_STATE_GENERIC_READ,
  7904. None,
  7905. &mut buffer,
  7906. )
  7907. .and_then(|()| {
  7908. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7909. resident(&self.device, b)?;
  7910. b.Map(0, None, Some(&mut data))
  7911. })
  7912. };
  7913. #[cfg(feature = "diagnostics")]
  7914. if made.is_ok()
  7915. && let Some(b) = &buffer
  7916. {
  7917. crate::book::made(b, || "an upload buffer".into());
  7918. }
  7919. match made {
  7920. Ok(()) => Some((buffer?, data.cast())),
  7921. Err(e) => {
  7922. tracing::warn!(error = %e, size, "no upload buffer");
  7923. None
  7924. }
  7925. }
  7926. }
  7927. }
  7928. /// The swap chain formats a presented texture can be copied into: its own
  7929. /// family's.
  7930. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  7931. Some(match format.0 {
  7932. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  7933. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  7934. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  7935. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  7936. _ => return None,
  7937. })
  7938. }
  7939. const BUFFERS: u32 = 2;
  7940. struct Presenter {
  7941. swap_chain: IDXGISwapChain3,
  7942. width: u32,
  7943. height: u32,
  7944. format: DXGI_FORMAT,
  7945. copy: HostList,
  7946. /// With presents sent ahead ([`late_free_present`]): a list for each
  7947. /// present in the air, and the submission it last flew as (it is used
  7948. /// again once that one has finished).
  7949. ahead: Vec<(HostList, u64)>,
  7950. hwnd: HWND,
  7951. meter: Meter,
  7952. #[cfg(feature = "diagnostics")]
  7953. panel: panel::Panel,
  7954. }
  7955. /// The frame rate, shown in the window's caption every second and logged
  7956. /// every few seconds.
  7957. struct Meter {
  7958. since: std::time::Instant,
  7959. frames: u32,
  7960. #[cfg(feature = "diagnostics")]
  7961. copy_stats_frames: u64,
  7962. drawn: u64,
  7963. logged: std::time::Instant,
  7964. /// The caption the window had, once read.
  7965. caption: Option<Vec<u16>>,
  7966. }
  7967. impl Meter {
  7968. fn new() -> Self {
  7969. let now = std::time::Instant::now();
  7970. Meter {
  7971. since: now,
  7972. frames: 0,
  7973. #[cfg(feature = "diagnostics")]
  7974. copy_stats_frames: 0,
  7975. drawn: crate::draw::drawn(),
  7976. logged: now,
  7977. caption: None,
  7978. }
  7979. }
  7980. /// Whether the next frame counted makes the frame-rate line.
  7981. #[cfg(feature = "diagnostics")]
  7982. fn line_due(&self) -> bool {
  7983. self.since.elapsed() >= std::time::Duration::from_secs(1)
  7984. }
  7985. /// Counts a presented frame.
  7986. fn frame(&mut self, hwnd: HWND) {
  7987. #[cfg(feature = "diagnostics")]
  7988. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  7989. #[cfg(feature = "diagnostics")]
  7990. crate::copystat::presented();
  7991. self.frames += 1;
  7992. #[cfg(feature = "diagnostics")]
  7993. {
  7994. self.copy_stats_frames += 1;
  7995. }
  7996. let elapsed = self.since.elapsed();
  7997. if elapsed < std::time::Duration::from_secs(1) {
  7998. return;
  7999. }
  8000. let drawn = crate::draw::drawn();
  8001. let frames = f64::from(self.frames);
  8002. let fps = frames / elapsed.as_secs_f64();
  8003. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  8004. let draws = (drawn - self.drawn) as f64 / frames;
  8005. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  8006. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  8007. let [cpu, gpu] = [0, 1].map(|i| {
  8008. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  8009. });
  8010. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  8011. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  8012. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  8013. });
  8014. let [back_ms, back_mb] = [0, 1].map(|i| {
  8015. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  8016. });
  8017. let dropped = crate::draw::take_dropped() as f64 / frames;
  8018. let indirect = crate::list::take_indirect() as f64 / frames;
  8019. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  8020. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  8021. tracing::info!(
  8022. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  8023. );
  8024. crate::shadow::exact_line(frames);
  8025. crate::descriptor::sync_line(frames);
  8026. late_line(frames);
  8027. crate::queue::behind_line(frames);
  8028. card_clock_line(frames, ms);
  8029. #[cfg(feature = "diagnostics")]
  8030. spans::line(frames);
  8031. crate::shadow::back_line(frames);
  8032. #[cfg(feature = "diagnostics")]
  8033. split_line(frames);
  8034. {
  8035. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  8036. if passes + compares > 0.0 {
  8037. tracing::info!(
  8038. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  8039. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  8040. if rehash_runs() { "on" } else { "off" }
  8041. );
  8042. }
  8043. }
  8044. {
  8045. let [own, asking, still, all] =
  8046. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  8047. if all >= 1.0 {
  8048. tracing::info!(
  8049. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  8050. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  8051. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  8052. );
  8053. }
  8054. let [through, left, filled, short] =
  8055. [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  8056. if through + left + filled > 0.0 {
  8057. tracing::info!(
  8058. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  8059. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \
  8060. {filled:.1} first fillings from the pages there (VICTORY_TEXTURE_FILL=0: left empty), {short:.1} of them \
  8061. with less than was mapped (looked at again)"
  8062. );
  8063. }
  8064. }
  8065. {
  8066. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  8067. if copies > 0.0 {
  8068. tracing::info!(
  8069. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  8070. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  8071. if join_copies() { "on" } else { "off" }
  8072. );
  8073. }
  8074. }
  8075. // Passes over the heap's buffer views for shaders that pick them by index.
  8076. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  8077. let picked_ms =
  8078. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  8079. // Copies between depth textures and their colour twins, each way.
  8080. let [twin_to_depth, twin_to_colour] =
  8081. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  8082. // Depth planes drawn from their twins.
  8083. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  8084. // Copies in the card's memory (`crate::shadow::cards`).
  8085. let card = crate::shadow::card_stats();
  8086. #[cfg(feature = "diagnostics")]
  8087. let slow = crate::watch::slow_asks();
  8088. // Over the same frames as the counts above.
  8089. #[cfg(feature = "diagnostics")]
  8090. let drops = crate::pipeline::take_drops();
  8091. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  8092. self.logged = std::time::Instant::now();
  8093. tracing::info!(
  8094. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  8095. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  8096. );
  8097. crate::tiles::status();
  8098. {
  8099. let [queued, due, away, partly, oldest] =
  8100. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  8101. let [same, parts, tails] =
  8102. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  8103. tracing::info!(
  8104. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  8105. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  8106. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  8107. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  8108. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  8109. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  8110. {} made slots found unmapped and made null",
  8111. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  8112. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  8113. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  8114. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  8115. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  8116. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  8117. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  8118. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  8119. );
  8120. }
  8121. if crate::resource::held_only() {
  8122. let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed));
  8123. let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed));
  8124. tracing::info!(
  8125. "textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \
  8126. levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \
  8127. {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \
  8128. out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free; \
  8129. {} looks for textures to let go, {:.2} ms each, the longest {:.1}",
  8130. bytes >> 20,
  8131. whole >> 20,
  8132. crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed),
  8133. crate::pool::texture_room() >> 20,
  8134. crate::resource::SWEPT_US[0].load(Ordering::Relaxed),
  8135. crate::resource::SWEPT_US[1].load(Ordering::Relaxed) as f64
  8136. / 1e3
  8137. / crate::resource::SWEPT_US[0].load(Ordering::Relaxed).max(1) as f64,
  8138. crate::resource::SWEPT_US[2].load(Ordering::Relaxed) as f64 / 1e3
  8139. );
  8140. }
  8141. {
  8142. let mode = crate::watch::page_writes();
  8143. let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
  8144. let [kept, dropped, slots, uploaded] =
  8145. [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
  8146. tracing::info!(
  8147. "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)",
  8148. bytes >> 20,
  8149. if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
  8150. if mode & 4 != 0 { "told as well" } else { "counted only" },
  8151. if mode & 2 != 0 { "made due again" } else { "left as they were" }
  8152. );
  8153. }
  8154. #[cfg(feature = "diagnostics")]
  8155. tracing::info!(
  8156. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  8157. slow[0] as f64 / frames,
  8158. slow[1] as f64 / 1e3 / frames,
  8159. slow[2] as f64 / 1e3
  8160. );
  8161. if crate::shadow::cards() {
  8162. let per_frame = |i: usize| card[i] as f64 / frames;
  8163. tracing::info!(
  8164. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  8165. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  8166. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  8167. card[7],
  8168. card[8] >> 20,
  8169. card[9] >> 20,
  8170. per_frame(0) / 1e6,
  8171. per_frame(1),
  8172. per_frame(2),
  8173. per_frame(3),
  8174. per_frame(4) / 1e6,
  8175. per_frame(5),
  8176. per_frame(6) / 1e3
  8177. );
  8178. }
  8179. tracing::info!(
  8180. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  8181. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  8182. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  8183. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  8184. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  8185. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  8186. {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}",
  8187. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  8188. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  8189. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  8190. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  8191. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  8192. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  8193. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  8194. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  8195. refused = format!(
  8196. "{} ({} 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",
  8197. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  8198. crate::shadow::OWN_MADE.load(Ordering::Relaxed),
  8199. crate::resource::TWINS[0].load(Ordering::Relaxed),
  8200. crate::resource::TWINS[1].load(Ordering::Relaxed),
  8201. crate::resource::PLANES[1].load(Ordering::Relaxed),
  8202. crate::resource::PLANES[2].load(Ordering::Relaxed)
  8203. ),
  8204. making = crate::pipeline::making(),
  8205. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  8206. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  8207. );
  8208. #[cfg(feature = "diagnostics")]
  8209. {
  8210. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  8211. tracing::info!(
  8212. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  8213. put[0],
  8214. put[1],
  8215. put[2] / 1e6,
  8216. put[3]
  8217. );
  8218. traffic::line(self.copy_stats_frames as f64);
  8219. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  8220. for (why, n) in drops.iter().take(40) {
  8221. tracing::info!(
  8222. "dropped {:.1}/frame without a host pipeline: {why}",
  8223. *n as f64 / frames
  8224. );
  8225. }
  8226. }
  8227. }
  8228. if self.caption.is_none() {
  8229. // The window's own text, read without a message.
  8230. let mut buffer = vec![0u16; 512];
  8231. // SAFETY: a window handle and a buffer of that length.
  8232. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  8233. buffer.truncate(n.max(0) as usize);
  8234. self.caption = Some(buffer);
  8235. }
  8236. let Some(caption) = &self.caption else { return };
  8237. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  8238. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  8239. text.push(0);
  8240. // Setting the text waits for the window's thread (a title thread,
  8241. // which may not pump for a while), so a thread of ours does it and
  8242. // presenting never waits; it takes the newest text when free.
  8243. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  8244. static SETTER: std::sync::Once = std::sync::Once::new();
  8245. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  8246. SETTER.call_once(|| {
  8247. let _ = std::thread::Builder::new()
  8248. .name("victory-caption".into())
  8249. .spawn(|| {
  8250. loop {
  8251. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  8252. match next {
  8253. // SAFETY: a window handle and a NUL-terminated text.
  8254. Some((hwnd, text)) => unsafe {
  8255. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  8256. },
  8257. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  8258. }
  8259. }
  8260. });
  8261. });
  8262. }
  8263. }
  8264. impl Host {
  8265. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  8266. /// as frame `frame` (saved if captures are on). `None` if nothing was
  8267. /// shown; else, in diagnostics builds, whether the frame was black.
  8268. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  8269. // SAFETY: a live resource.
  8270. let desc = unsafe { texture.GetDesc() };
  8271. let Some(format) = swap_format(desc.Format) else {
  8272. tracing::warn!(format = desc.Format.0, "cannot present this format");
  8273. return None;
  8274. };
  8275. let (width, height) = (desc.Width as u32, desc.Height);
  8276. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  8277. if presenter.is_none() {
  8278. *presenter = match self.presenter(width, height, format) {
  8279. Ok(p) => Some(p),
  8280. Err(e) => {
  8281. tracing::warn!(error = %e, "no swap chain");
  8282. return None;
  8283. }
  8284. };
  8285. }
  8286. let p = presenter.as_mut()?;
  8287. if (p.width, p.height, p.format) != (width, height, format) {
  8288. // Presents sent ahead hold back buffers until they have run.
  8289. settle_now(WHY_SYNC);
  8290. // SAFETY: no back buffer is held; every submission was waited for.
  8291. let resized = unsafe {
  8292. p.swap_chain
  8293. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  8294. };
  8295. match resized {
  8296. Ok(()) => {
  8297. (p.width, p.height, p.format) = (width, height, format);
  8298. tracing::info!(
  8299. width,
  8300. height,
  8301. format = format.0,
  8302. frame,
  8303. "the swap chain's buffers were made again for another size or format"
  8304. );
  8305. self.log_video_memory("right after the swap chain's buffers were made again");
  8306. }
  8307. Err(e) => {
  8308. tracing::warn!(error = %e, width, height, "swap chain not resized");
  8309. return None;
  8310. }
  8311. }
  8312. }
  8313. let state = D3D12_RESOURCE_STATES(state as i32);
  8314. // SAFETY: our swap chain, list and a live source texture.
  8315. unsafe {
  8316. let index = p.swap_chain.GetCurrentBackBufferIndex();
  8317. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  8318. return None;
  8319. };
  8320. // Sent ahead ([`late_free_present`]) unless the frame is to be
  8321. // read back at once (a saved or listed frame): then a list of
  8322. // its own, one whose last flight has finished or a new one.
  8323. #[cfg(feature = "diagnostics")]
  8324. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  8325. #[cfg(not(feature = "diagnostics"))]
  8326. let read_now = false;
  8327. let slot = if late_free_present() && !read_now {
  8328. let finished = FINISHED.load(Ordering::Acquire);
  8329. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  8330. let list = self.new_list().ok()?;
  8331. list.close();
  8332. p.ahead.push((list, 0));
  8333. Some(p.ahead.len() - 1)
  8334. })
  8335. } else {
  8336. None
  8337. };
  8338. let copy = match slot {
  8339. Some(i) => &p.ahead[i].0,
  8340. None => &p.copy,
  8341. };
  8342. copy.reset();
  8343. let list = &copy.list;
  8344. list.ResourceBarrier(&[
  8345. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  8346. transition(
  8347. &back,
  8348. D3D12_RESOURCE_STATE_PRESENT,
  8349. D3D12_RESOURCE_STATE_COPY_DEST,
  8350. ),
  8351. ]);
  8352. list.CopyResource(&back, texture);
  8353. #[cfg(feature = "diagnostics")]
  8354. let capture = crate::capture::wanted(frame)
  8355. .then(|| crate::capture::read_back(&self.device, list, texture))
  8356. .flatten();
  8357. #[cfg(feature = "diagnostics")]
  8358. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  8359. #[cfg(feature = "diagnostics")]
  8360. let watched = crate::popwatch::take(&self.device, list, texture);
  8361. #[cfg(feature = "diagnostics")]
  8362. p.panel.draw(self, copy, &back, (width, height), format);
  8363. #[cfg(not(feature = "diagnostics"))]
  8364. let _ = frame;
  8365. list.ResourceBarrier(&[
  8366. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  8367. transition(
  8368. &back,
  8369. D3D12_RESOURCE_STATE_COPY_DEST,
  8370. D3D12_RESOURCE_STATE_PRESENT,
  8371. ),
  8372. ]);
  8373. copy.close();
  8374. let flown = match slot {
  8375. Some(i) => {
  8376. let flown = self.execute_own(copy);
  8377. p.ahead[i].1 = flown;
  8378. flown
  8379. }
  8380. None => {
  8381. self.execute(&[copy]);
  8382. 0
  8383. }
  8384. };
  8385. #[cfg(feature = "diagnostics")]
  8386. if let Some(taken) = watched {
  8387. crate::popwatch::sent(taken, flown, frame);
  8388. }
  8389. #[cfg(not(feature = "diagnostics"))]
  8390. let _ = flown;
  8391. #[cfg(feature = "diagnostics")]
  8392. if let Some((buffer, footprint)) = capture {
  8393. crate::capture::save_read_back(frame, &buffer, &footprint);
  8394. }
  8395. #[cfg(feature = "diagnostics")]
  8396. crate::replay::record::present(texture, state);
  8397. let mut showing = crate::timeline::span("the host's Present");
  8398. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  8399. showing.next("the frame meter");
  8400. #[cfg(feature = "diagnostics")]
  8401. p.panel.frame(p.meter.line_due());
  8402. p.meter.frame(p.hwnd);
  8403. showing.end();
  8404. #[cfg(feature = "diagnostics")]
  8405. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  8406. #[cfg(not(feature = "diagnostics"))]
  8407. Some(false)
  8408. }
  8409. }
  8410. fn presenter(
  8411. &self,
  8412. width: u32,
  8413. height: u32,
  8414. format: DXGI_FORMAT,
  8415. ) -> windows::core::Result<Presenter> {
  8416. let hwnd = match title_window() {
  8417. Some(hwnd) => hwnd,
  8418. None => window(width, height)?,
  8419. };
  8420. self.log_video_memory("right before the swap chain is made");
  8421. // SAFETY: plain object creation for our window.
  8422. unsafe {
  8423. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  8424. let desc = DXGI_SWAP_CHAIN_DESC1 {
  8425. Width: width,
  8426. Height: height,
  8427. Format: format,
  8428. SampleDesc: DXGI_SAMPLE_DESC {
  8429. Count: 1,
  8430. Quality: 0,
  8431. },
  8432. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  8433. BufferCount: BUFFERS,
  8434. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  8435. ..Default::default()
  8436. };
  8437. let swap_chain = factory
  8438. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  8439. .cast::<IDXGISwapChain3>()?;
  8440. let copy = self.new_list()?;
  8441. copy.close();
  8442. tracing::info!(width, height, format = format.0, "presenting to a window");
  8443. self.log_video_memory("right after the swap chain is made");
  8444. Ok(Presenter {
  8445. swap_chain,
  8446. width,
  8447. height,
  8448. format,
  8449. copy,
  8450. ahead: Vec::new(),
  8451. hwnd,
  8452. meter: Meter::new(),
  8453. #[cfg(feature = "diagnostics")]
  8454. panel: panel::Panel::new(),
  8455. })
  8456. }
  8457. }
  8458. }
  8459. /// A visible top-level window of this process: the one the title made, if
  8460. /// it made one.
  8461. fn title_window() -> Option<HWND> {
  8462. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  8463. let mut process = 0;
  8464. // SAFETY: a window handle from the enumeration; `found` is ours.
  8465. unsafe {
  8466. GetWindowThreadProcessId(hwnd, Some(&mut process));
  8467. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  8468. && IsWindowVisible(hwnd).as_bool()
  8469. {
  8470. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  8471. return false.into();
  8472. }
  8473. }
  8474. true.into()
  8475. }
  8476. let mut found: Option<HWND> = None;
  8477. // SAFETY: the callback only writes `found`, which outlives the call.
  8478. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  8479. found
  8480. }
  8481. /// `state` without the bits the host texture's flags forbid: the console
  8482. /// lets the title name states its own resources allow (unordered access on
  8483. /// a depth target, whose host copy cannot have both).
  8484. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  8485. // SAFETY: a plain query.
  8486. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  8487. }
  8488. /// [`legal_state`] for a texture with resource flags `flags`.
  8489. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  8490. // (flag, set or clear forbids, state bits): render target, unordered
  8491. // access, depth, denied shader resource.
  8492. const FORBIDDEN: [(u32, bool, u32); 4] = [
  8493. (0x1, false, 0x4),
  8494. (0x4, false, 0x8),
  8495. (0x2, false, 0x10 | 0x20),
  8496. (0x8, true, 0x40 | 0x80),
  8497. ];
  8498. FORBIDDEN
  8499. .iter()
  8500. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  8501. .fold(state, |s, &(_, _, bits)| s & !bits)
  8502. }
  8503. impl Host {
  8504. /// The card's memory as the system accounts it to this process, in
  8505. /// bytes: the budget and the use of the card's own memory, then of the
  8506. /// PC's memory shared with the card (where the system moves what does
  8507. /// not fit on the card).
  8508. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  8509. let adapter = self.adapter.as_ref()?;
  8510. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  8511. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  8512. // SAFETY: plain queries that fill our structures.
  8513. unsafe {
  8514. adapter
  8515. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  8516. .ok()?;
  8517. adapter
  8518. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  8519. .ok()?;
  8520. }
  8521. // The card's budget moved by 256 MB or more since the last look:
  8522. // said at once, with what was in use at the last look, so the log
  8523. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  8524. // the first world frame in runs 179 to 185, and the memory line,
  8525. // seconds later, was the first to show it. We reserve nothing
  8526. // and make the swap chain once, at the start.)
  8527. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  8528. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  8529. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  8530. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  8531. tracing::info!(
  8532. "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",
  8533. last[0] >> 20,
  8534. own.Budget >> 20,
  8535. crate::frame::current(),
  8536. last[1] >> 20,
  8537. last[2] >> 20
  8538. );
  8539. self.log_video_memory("right after that change");
  8540. }
  8541. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  8542. }
  8543. /// Both of the system's memory groups for this process, in bytes: for
  8544. /// the card's own memory and then for the PC's memory shared with the
  8545. /// card, the budget, the use, what could still be reserved and what
  8546. /// is reserved (the layer reserves none).
  8547. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  8548. let adapter = self.adapter.as_ref()?;
  8549. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  8550. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  8551. // SAFETY: plain queries that fill our structures.
  8552. unsafe {
  8553. adapter
  8554. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  8555. .ok()?;
  8556. adapter
  8557. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  8558. .ok()?;
  8559. }
  8560. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  8561. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  8562. };
  8563. Some([all(&own), all(&shared)])
  8564. }
  8565. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  8566. pub(crate) fn log_video_memory(&self, when: &str) {
  8567. let Some([own, shared]) = self.video_memory_groups() else {
  8568. return;
  8569. };
  8570. tracing::info!(
  8571. "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)",
  8572. when,
  8573. own[0] >> 20,
  8574. own[1] >> 20,
  8575. own[2] >> 20,
  8576. own[3] >> 20,
  8577. shared[0] >> 20,
  8578. shared[1] >> 20,
  8579. shared[2] >> 20,
  8580. shared[3] >> 20
  8581. );
  8582. }
  8583. /// A buffer in system memory that the CPU maps (write-back, so reading
  8584. /// it is fast too) and shaders read and write: for host copies of title
  8585. /// memory that shaders write, which upload memory cannot be. Starts in
  8586. /// the common state (buffers move out of it implicitly).
  8587. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  8588. MADE[2].fetch_add(1, Ordering::Relaxed);
  8589. MADE[3].fetch_add(size, Ordering::Relaxed);
  8590. let heap = D3D12_HEAP_PROPERTIES {
  8591. Type: D3D12_HEAP_TYPE_CUSTOM,
  8592. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  8593. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  8594. ..Default::default()
  8595. };
  8596. let desc = D3D12_RESOURCE_DESC {
  8597. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  8598. Width: size.max(1),
  8599. Height: 1,
  8600. DepthOrArraySize: 1,
  8601. MipLevels: 1,
  8602. SampleDesc: DXGI_SAMPLE_DESC {
  8603. Count: 1,
  8604. Quality: 0,
  8605. },
  8606. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  8607. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  8608. ..Default::default()
  8609. };
  8610. let mut buffer: Option<ID3D12Resource> = None;
  8611. let mut data = std::ptr::null_mut();
  8612. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  8613. let made = unsafe {
  8614. self.device
  8615. .CreateCommittedResource(
  8616. &heap,
  8617. not_resident(),
  8618. &desc,
  8619. D3D12_RESOURCE_STATE_COMMON,
  8620. None,
  8621. &mut buffer,
  8622. )
  8623. .and_then(|()| {
  8624. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  8625. resident(&self.device, b)?;
  8626. mapped(&self.device)?;
  8627. b.Map(0, None, Some(&mut data))
  8628. })
  8629. };
  8630. #[cfg(feature = "diagnostics")]
  8631. if made.is_ok()
  8632. && let Some(b) = &buffer
  8633. {
  8634. crate::book::made(b, || "a shared buffer".into());
  8635. }
  8636. match made {
  8637. Ok(()) => Some((buffer?, data.cast())),
  8638. Err(e) => {
  8639. tracing::warn!(error = %e, size, "no shared buffer");
  8640. None
  8641. }
  8642. }
  8643. }
  8644. /// Whether buffers can lie in the card's memory and be mapped by the CPU
  8645. /// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver
  8646. /// that offer it); logged once.
  8647. pub(crate) fn mapped_card_memory(&self) -> bool {
  8648. static THERE: OnceLock<bool> = OnceLock::new();
  8649. *THERE.get_or_init(|| {
  8650. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default();
  8651. // SAFETY: writes `options` of the given size.
  8652. let ok = unsafe {
  8653. self.device
  8654. .CheckFeatureSupport(
  8655. D3D12_FEATURE_D3D12_OPTIONS16,
  8656. (&raw mut options).cast(),
  8657. size_of_val(&options) as u32,
  8658. )
  8659. .is_ok()
  8660. };
  8661. let supported = ok && options.GPUUploadHeapSupported.as_bool();
  8662. tracing::info!(supported, "card memory the CPU maps");
  8663. supported
  8664. })
  8665. }
  8666. /// A buffer in the card's own memory that the CPU maps, shaders read and
  8667. /// (with `written`) may write. The CPU should only write it: a read of the
  8668. /// mapping crosses the bus a few bytes at a time.
  8669. pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> {
  8670. if !self.mapped_card_memory() {
  8671. return None;
  8672. }
  8673. MADE[4].fetch_add(1, Ordering::Relaxed);
  8674. MADE[5].fetch_add(size, Ordering::Relaxed);
  8675. let heap = D3D12_HEAP_PROPERTIES {
  8676. Type: D3D12_HEAP_TYPE_GPU_UPLOAD,
  8677. ..Default::default()
  8678. };
  8679. let desc = D3D12_RESOURCE_DESC {
  8680. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  8681. Width: size.max(1),
  8682. Height: 1,
  8683. DepthOrArraySize: 1,
  8684. MipLevels: 1,
  8685. SampleDesc: DXGI_SAMPLE_DESC {
  8686. Count: 1,
  8687. Quality: 0,
  8688. },
  8689. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  8690. Flags: if written {
  8691. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
  8692. } else {
  8693. D3D12_RESOURCE_FLAG_NONE
  8694. },
  8695. ..Default::default()
  8696. };
  8697. let mut buffer: Option<ID3D12Resource> = None;
  8698. let mut data = std::ptr::null_mut();
  8699. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  8700. let made = unsafe {
  8701. self.device
  8702. .CreateCommittedResource(
  8703. &heap,
  8704. not_resident(),
  8705. &desc,
  8706. D3D12_RESOURCE_STATE_COMMON,
  8707. None,
  8708. &mut buffer,
  8709. )
  8710. .and_then(|()| {
  8711. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  8712. resident(&self.device, b)?;
  8713. mapped(&self.device)?;
  8714. b.Map(0, None, Some(&mut data))
  8715. })
  8716. };
  8717. match made {
  8718. Ok(()) => Some((buffer?, data.cast())),
  8719. Err(e) => {
  8720. tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps");
  8721. None
  8722. }
  8723. }
  8724. }
  8725. /// A device-local buffer shaders may write (unordered access) and indirect
  8726. /// execution may read, starting in the common state.
  8727. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  8728. MADE[4].fetch_add(1, Ordering::Relaxed);
  8729. MADE[5].fetch_add(size, Ordering::Relaxed);
  8730. let heap = D3D12_HEAP_PROPERTIES {
  8731. Type: D3D12_HEAP_TYPE_DEFAULT,
  8732. ..Default::default()
  8733. };
  8734. let desc = D3D12_RESOURCE_DESC {
  8735. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  8736. Width: size.max(1),
  8737. Height: 1,
  8738. DepthOrArraySize: 1,
  8739. MipLevels: 1,
  8740. SampleDesc: DXGI_SAMPLE_DESC {
  8741. Count: 1,
  8742. Quality: 0,
  8743. },
  8744. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  8745. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  8746. ..Default::default()
  8747. };
  8748. let mut buffer: Option<ID3D12Resource> = None;
  8749. // SAFETY: plain creation of a device-local buffer.
  8750. let made = unsafe {
  8751. self.device.CreateCommittedResource(
  8752. &heap,
  8753. not_resident(),
  8754. &desc,
  8755. D3D12_RESOURCE_STATE_COMMON,
  8756. None,
  8757. &mut buffer,
  8758. )
  8759. };
  8760. #[cfg(feature = "diagnostics")]
  8761. if let Some(b) = &buffer {
  8762. crate::book::made(b, || "an unordered access buffer".into());
  8763. }
  8764. let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))).and_then(|()| mapped(&self.device));
  8765. match made {
  8766. Ok(()) => buffer,
  8767. Err(e) => {
  8768. tracing::warn!(error = %e, size, "no unordered-access buffer");
  8769. None
  8770. }
  8771. }
  8772. }
  8773. }
  8774. /// For adapters without device-removed data (the software one): the last
  8775. /// commands each list of the failed submission noted (diagnostics, with
  8776. /// `VICTORY_D3D12_DRED`).
  8777. fn last_notes(runs: &[&HostList]) -> String {
  8778. #[cfg(feature = "diagnostics")]
  8779. {
  8780. let mut text = String::new();
  8781. for (i, r) in runs.iter().enumerate() {
  8782. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  8783. for (n, _) in notes.iter().rev().take(6).rev() {
  8784. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  8785. }
  8786. }
  8787. text
  8788. }
  8789. #[cfg(not(feature = "diagnostics"))]
  8790. {
  8791. let _ = runs;
  8792. String::new()
  8793. }
  8794. }
  8795. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  8796. /// command reads (diagnostics).
  8797. #[cfg(feature = "diagnostics")]
  8798. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  8799. let end = start + bytes;
  8800. if va < start {
  8801. format!(" (fault {:#x} below its source)", start - va)
  8802. } else if va < end {
  8803. format!(" (fault at source +{:#x})", va - start)
  8804. } else {
  8805. format!(" (fault {:#x} past its source's end)", va - end)
  8806. }
  8807. }
  8808. /// The commands that may have been running where a list stopped at
  8809. /// command `done`: those between the barriers around it (work between
  8810. /// barriers overlaps on the GPU), by kind, and what the markers just
  8811. /// before them say (`HostList::note_op`: diagnostics builds with
  8812. /// device-removed data on).
  8813. /// For a list that stopped at command `done`: what the indirect executions
  8814. /// there ran, from the one before it to the next barrier (four at most), and
  8815. /// what the heap slots their user data names hold now.
  8816. #[cfg(feature = "diagnostics")]
  8817. fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &indirects::Shared) -> String {
  8818. let indirect = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT;
  8819. let all = all.lock().unwrap_or_else(|e| e.into_inner());
  8820. let mut text = String::new();
  8821. let mut shown = 0;
  8822. let mesh = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_DISPATCHMESH;
  8823. for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) {
  8824. if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) {
  8825. break;
  8826. }
  8827. if !indirect(op) && !mesh(op) {
  8828. continue;
  8829. }
  8830. shown += 1;
  8831. let direct = mesh(op);
  8832. let nth = if direct { indirects::before(history, at, mesh) } else { indirects::before(history, at, indirect) };
  8833. let Some((what, words)) = all.nth(nth, direct) else {
  8834. continue;
  8835. };
  8836. text.push_str(&format!("; command {at} ran {what}"));
  8837. for (word, slot, what) in crate::descriptor::host::describe_slots(words) {
  8838. text.push_str(&format!(", word {word} slot {slot}: {what}"));
  8839. }
  8840. }
  8841. text
  8842. }
  8843. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  8844. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  8845. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  8846. let to = history[done..]
  8847. .iter()
  8848. .position(barrier)
  8849. .map_or(history.len(), |b| (done + b).max(done + 1));
  8850. let mut text = format!(", commands {from}..{to} between its barriers:");
  8851. let mut shown = 0;
  8852. // From just before the command the GPU had not finished: the first
  8853. // twelve after the barrier named draws long done when a list of 79
  8854. // mesh draws stopped at its 45th (run 41).
  8855. for i in from.max(done.saturating_sub(4))..to {
  8856. let op = history[i];
  8857. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  8858. continue;
  8859. }
  8860. shown += 1;
  8861. let marker = i
  8862. .checked_sub(1)
  8863. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  8864. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  8865. .map_or("no marker", |(_, s)| s.as_str());
  8866. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  8867. }
  8868. text
  8869. }
  8870. pub(crate) fn transition(
  8871. resource: &ID3D12Resource,
  8872. before: D3D12_RESOURCE_STATES,
  8873. after: D3D12_RESOURCE_STATES,
  8874. ) -> D3D12_RESOURCE_BARRIER {
  8875. D3D12_RESOURCE_BARRIER {
  8876. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  8877. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  8878. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  8879. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  8880. // SAFETY: a borrowed pointer; the barrier never releases it.
  8881. pResource: unsafe { std::mem::transmute_copy(resource) },
  8882. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  8883. StateBefore: before,
  8884. StateAfter: after,
  8885. }),
  8886. },
  8887. }
  8888. }
  8889. /// A window of the given client size, owned by its own message thread.
  8890. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  8891. let (sender, receiver) = std::sync::mpsc::channel();
  8892. std::thread::Builder::new()
  8893. .name("victory-window".into())
  8894. .spawn(move || {
  8895. let made = make_window(width, height);
  8896. let ok = made.is_ok();
  8897. let _ = sender.send(made.map(|h| h.0 as usize));
  8898. if ok {
  8899. pump();
  8900. }
  8901. })
  8902. .map_err(|_| windows::core::Error::empty())?;
  8903. let hwnd = receiver
  8904. .recv()
  8905. .map_err(|_| windows::core::Error::empty())??;
  8906. Ok(HWND(hwnd as *mut _))
  8907. }
  8908. extern "system" fn window_proc(
  8909. hwnd: HWND,
  8910. message: u32,
  8911. wparam: WPARAM,
  8912. lparam: LPARAM,
  8913. ) -> LRESULT {
  8914. // SAFETY: the default handling for our window.
  8915. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  8916. }
  8917. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  8918. const CLASS: PCWSTR = w!("VIctory");
  8919. // SAFETY: registers our class once and creates a window of it.
  8920. unsafe {
  8921. let instance = GetModuleHandleW(None)?;
  8922. let class = WNDCLASSEXW {
  8923. cbSize: size_of::<WNDCLASSEXW>() as u32,
  8924. lpfnWndProc: Some(window_proc),
  8925. hInstance: instance.into(),
  8926. lpszClassName: CLASS,
  8927. hCursor: LoadCursorW(None, IDC_ARROW)?,
  8928. ..Default::default()
  8929. };
  8930. RegisterClassExW(&class);
  8931. let mut rect = RECT {
  8932. left: 0,
  8933. top: 0,
  8934. right: width as i32,
  8935. bottom: height as i32,
  8936. };
  8937. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  8938. CreateWindowExW(
  8939. WINDOW_EX_STYLE(0),
  8940. CLASS,
  8941. w!("VIctory"),
  8942. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  8943. CW_USEDEFAULT,
  8944. CW_USEDEFAULT,
  8945. rect.right - rect.left,
  8946. rect.bottom - rect.top,
  8947. None,
  8948. None,
  8949. Some(instance.into()),
  8950. None,
  8951. )
  8952. }
  8953. }
  8954. fn pump() {
  8955. let mut message = MSG::default();
  8956. // SAFETY: the standard message loop of this thread's window.
  8957. unsafe {
  8958. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  8959. let _ = TranslateMessage(&message);
  8960. DispatchMessageW(&message);
  8961. }
  8962. }
  8963. }
  8964. #[cfg(test)]
  8965. mod trail {
  8966. /// The trail keeps the newest things, and the report made when the
  8967. /// host device is removed says them and the pipeline library's state
  8968. /// (no card is asked for any of it).
  8969. #[test]
  8970. fn the_removal_report_says_the_newest_things_done() {
  8971. for n in 0..super::TRAIL_MOST + 5 {
  8972. super::trail(|| format!("thing {n} done"));
  8973. }
  8974. let text = super::removal_context();
  8975. assert!(text.contains("the submitting thread was"));
  8976. assert!(text.contains("pipeline library: no call running"));
  8977. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  8978. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  8979. }
  8980. }
  8981. #[cfg(test)]
  8982. mod spare {
  8983. use super::Spare;
  8984. /// Kept things come back by size, the last given first, and nothing is
  8985. /// kept past the limit.
  8986. #[test]
  8987. fn kept_things_come_back_by_size_within_the_limit() {
  8988. let mut spare: Spare<u32> = Spare::new();
  8989. assert_eq!(spare.take(4), None);
  8990. assert_eq!(spare.give(1, 4, 10), None);
  8991. assert_eq!(spare.give(2, 1, 10), None);
  8992. assert_eq!(spare.give(3, 4, 10), None);
  8993. assert_eq!(spare.bytes, 9);
  8994. // Past the limit: handed back, nothing changes.
  8995. assert_eq!(spare.give(4, 4, 10), Some(4));
  8996. assert_eq!(spare.bytes, 9);
  8997. assert_eq!(spare.take(2), None, "no thing of that size");
  8998. assert_eq!(spare.take(4), Some(3));
  8999. assert_eq!(spare.take(4), Some(1));
  9000. assert_eq!(spare.take(4), None);
  9001. assert_eq!(spare.take(1), Some(2));
  9002. assert_eq!(spare.bytes, 0);
  9003. assert!(spare.kept.is_empty());
  9004. }
  9005. }
  9006. #[cfg(test)]
  9007. mod refresh_tests {
  9008. use super::Batch;
  9009. use crate::shadow::Shadow;
  9010. use std::sync::Arc;
  9011. use windows_sys::Win32::System::Memory::{
  9012. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  9013. VirtualAlloc,
  9014. };
  9015. const PAGE: usize = 64 << 10;
  9016. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  9017. /// Title memory for the tests (never given back: copies of it stay in
  9018. /// the guards): write-watched, or a view of a section.
  9019. fn title(len: usize, view: bool) -> usize {
  9020. // SAFETY: plain allocations.
  9021. let at = unsafe {
  9022. if view {
  9023. let section =
  9024. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  9025. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  9026. // As the runtime tells of it.
  9027. crate::title_memory_section(section as usize, len as u64, true);
  9028. crate::title_memory_remapped(at, len);
  9029. crate::title_memory_view(at, len, section as usize, 0);
  9030. at
  9031. } else {
  9032. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  9033. }
  9034. };
  9035. assert_ne!(at, 0);
  9036. at
  9037. }
  9038. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  9039. /// and every fourth page not there: as a title that streams has it.
  9040. fn with_holes(blocks: usize) -> usize {
  9041. use windows_sys::Win32::System::Memory::{
  9042. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  9043. VirtualAlloc2, VirtualFree,
  9044. };
  9045. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  9046. // SAFETY: a placeholder and a section of our own.
  9047. unsafe {
  9048. let at = VirtualAlloc2(
  9049. GetCurrentProcess(),
  9050. std::ptr::null(),
  9051. blocks * PAGE,
  9052. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  9053. PAGE_NOACCESS,
  9054. std::ptr::null_mut(),
  9055. 0,
  9056. ) as usize;
  9057. assert_ne!(at, 0);
  9058. let len = blocks * PAGE;
  9059. let section =
  9060. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  9061. for block in (0..blocks).filter(|b| b % 4 != 3) {
  9062. let to = at + block * PAGE;
  9063. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  9064. let view = MapViewOfFile3(
  9065. section,
  9066. GetCurrentProcess(),
  9067. to as *const _,
  9068. (block * PAGE) as u64,
  9069. PAGE,
  9070. MEM_REPLACE_PLACEHOLDER,
  9071. PAGE_READWRITE,
  9072. std::ptr::null_mut(),
  9073. 0,
  9074. );
  9075. assert_eq!(view.Value as usize, to);
  9076. crate::title_memory_remapped(to, PAGE);
  9077. }
  9078. at
  9079. }
  9080. }
  9081. fn memory(len: usize) -> *mut u8 {
  9082. // SAFETY: a plain allocation.
  9083. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  9084. }
  9085. struct Random(u64);
  9086. impl Random {
  9087. fn below(&mut self, n: usize) -> usize {
  9088. self.0 ^= self.0 << 13;
  9089. self.0 ^= self.0 >> 7;
  9090. self.0 ^= self.0 << 17;
  9091. (self.0 >> 11) as usize % n
  9092. }
  9093. }
  9094. /// Prepares as a submission does: one asking for all the ranges, the
  9095. /// refreshes in several flushes, the asking's end.
  9096. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  9097. // One at a time, as submissions are.
  9098. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  9099. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  9100. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  9101. crate::watch::ask_once(&asked);
  9102. let mut batch = Batch::default();
  9103. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  9104. for (shadow, at, len) in part {
  9105. batch.add(shadow, *at, *len);
  9106. }
  9107. batch.flush();
  9108. }
  9109. crate::watch::ask_once_end();
  9110. }
  9111. /// Whatever is written where, by the title or by us, and whichever
  9112. /// copies (of both kinds of memory, over one another, none on a page
  9113. /// line) are refreshed in which ranges: a refreshed range holds what
  9114. /// title memory holds.
  9115. #[test]
  9116. fn refreshed_ranges_hold_title_memory() {
  9117. // SAFETY (all blocks): title memory and copies of the test's own,
  9118. // written by this thread and, in `Batch::flush`, by the threads that
  9119. // refresh, which are done when it returns.
  9120. let mut random = Random(0x1234_5678_9ABC_DEF1);
  9121. const LEN: usize = 24 * PAGE;
  9122. let regions = [title(LEN, false), title(LEN, true)];
  9123. let mut copies = Vec::new();
  9124. for &region in &regions {
  9125. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  9126. let data = memory(to - from);
  9127. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  9128. }
  9129. }
  9130. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  9131. for round in 0..600 {
  9132. for _ in 0..random.below(4) {
  9133. let at = regions[random.below(2)] + random.below(LEN - 64);
  9134. let n = 1 + random.below(60);
  9135. if random.below(3) == 0 {
  9136. // What shaders wrote.
  9137. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  9138. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  9139. Shadow::put(at, &was, &now);
  9140. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  9141. continue;
  9142. }
  9143. for i in 0..n {
  9144. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  9145. }
  9146. }
  9147. let mut ranges = Vec::new();
  9148. for (shadow, _) in &copies {
  9149. if random.below(3) == 0 {
  9150. continue;
  9151. }
  9152. let (start, len) = shadow.span();
  9153. let (start, len) = (start as usize, len as usize);
  9154. // Often the range of the time before, as a list's is.
  9155. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  9156. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  9157. ranges.push((shadow.clone(), start + from, n));
  9158. }
  9159. if ranges.is_empty() {
  9160. continue;
  9161. }
  9162. let flushes = 1 + random.below(3);
  9163. submission(&ranges, flushes);
  9164. for (shadow, at, n) in &ranges {
  9165. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  9166. let start = shadow.span().0 as usize;
  9167. let same = unsafe {
  9168. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  9169. };
  9170. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  9171. }
  9172. }
  9173. }
  9174. /// A copy in the card's memory, with the card's side and the sends to it
  9175. /// played by the test.
  9176. struct Carded {
  9177. shadow: Arc<Shadow>,
  9178. data: usize,
  9179. start: usize,
  9180. len: usize,
  9181. /// The last send, the last send every fetch to come is behind, and
  9182. /// the card's bytes: the queue's order is the order it is locked in.
  9183. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  9184. /// Whether a flight that writes it has not landed.
  9185. flying: std::sync::atomic::AtomicBool,
  9186. /// The dword of each eight its shaders write.
  9187. class: usize,
  9188. }
  9189. impl Carded {
  9190. fn new(start: usize, len: usize, class: usize) -> Carded {
  9191. let data = memory(len);
  9192. Carded {
  9193. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  9194. data: data as usize,
  9195. start,
  9196. len,
  9197. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  9198. flying: std::sync::atomic::AtomicBool::new(false),
  9199. class,
  9200. }
  9201. }
  9202. /// What changed on the CPU's side goes up.
  9203. fn send(&self) {
  9204. let mut card = self.card.lock().unwrap();
  9205. card.0 += 1;
  9206. let (number, merged) = (card.0, card.1);
  9207. for (a, b) in self.shadow.send_up(number, merged) {
  9208. // SAFETY: the copy's bytes; nothing writes those that are to
  9209. // go up.
  9210. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  9211. }
  9212. }
  9213. }
  9214. /// Everything at once: the title writes its memory on two threads, the
  9215. /// submitting thread puts its bytes in under shader writes
  9216. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  9217. /// the card's memory, one not), sends up what changed and declares what
  9218. /// the next flight's shaders write, and what flights wrote is landed
  9219. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  9220. /// still and the copies are refreshed once more, each of them, and the
  9221. /// card's side of those that have one, hold what title memory holds, and
  9222. /// title memory what was written last.
  9223. ///
  9224. /// Into the first copy shaders write besides through a view nobody
  9225. /// declared, words the title does not write: nothing that goes up ever
  9226. /// puts an older value over those.
  9227. ///
  9228. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  9229. /// only takes the block out of the guards' clean ones and leaves its bit,
  9230. /// or if a fault leaves the bit; in some thousand rounds,
  9231. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  9232. #[test]
  9233. fn landings_title_writes_and_light_refreshes_at_once() {
  9234. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  9235. assert!(crate::safecopy::on());
  9236. const LEN: usize = 24 * PAGE;
  9237. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  9238. let region = title(LEN, true);
  9239. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  9240. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  9241. let plain = {
  9242. let (start, len) = (region + 700, LEN - 9000);
  9243. let data = memory(len);
  9244. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  9245. };
  9246. // What was last written so, by offset.
  9247. let mut undeclared = std::collections::HashMap::new();
  9248. let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0");
  9249. let stop = AtomicBool::new(false);
  9250. // Also when an assertion fails on one of the threads.
  9251. struct Stop<'a>(&'a AtomicBool);
  9252. impl Drop for Stop<'_> {
  9253. fn drop(&mut self) {
  9254. self.0.store(true, Ordering::Relaxed);
  9255. }
  9256. }
  9257. // Held shared by who writes title memory, alone while it is looked at.
  9258. let still = std::sync::RwLock::new(());
  9259. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  9260. std::thread::scope(|s| {
  9261. for t in 0..2usize {
  9262. let (stop, still) = (&stop, &still);
  9263. s.spawn(move || {
  9264. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  9265. let mut value = 0u32;
  9266. while !stop.load(Ordering::Relaxed) {
  9267. {
  9268. let _moving = still.read().unwrap();
  9269. for _ in 0..3 {
  9270. value += 1;
  9271. // Of each eight dwords, one a thread.
  9272. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  9273. dword(at).store(value, Ordering::Relaxed);
  9274. }
  9275. }
  9276. std::thread::sleep(std::time::Duration::from_micros(20));
  9277. }
  9278. });
  9279. }
  9280. // Lands flights.
  9281. {
  9282. let (carded, stop) = (&carded, &stop);
  9283. s.spawn(move || {
  9284. let _stop = Stop(stop);
  9285. while let Ok((which, ranges, value)) = flights.recv() {
  9286. let c = &carded[which];
  9287. // Fetched: the card's bytes, behind every send so far.
  9288. let (after, now) = {
  9289. let card = c.card.lock().unwrap();
  9290. (card.0, card.2.clone())
  9291. };
  9292. // By piece: 64 KiB of title memory.
  9293. let mut pieces = Vec::new();
  9294. for &(from, to) in &ranges {
  9295. let mut at = from;
  9296. while at < to {
  9297. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  9298. pieces.push((at, next, now.as_ptr() as usize + at));
  9299. at = next;
  9300. }
  9301. }
  9302. let parts: Vec<_> = pieces.chunks(3).collect();
  9303. crate::land::each(parts.len(), &|i| {
  9304. let mut notes = crate::land::Notes::default();
  9305. // SAFETY: the bytes of `now`; each piece once.
  9306. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  9307. notes.flush();
  9308. });
  9309. for &(from, to) in &ranges {
  9310. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  9311. // (The next fetch may have brought more.)
  9312. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  9313. }
  9314. }
  9315. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  9316. c.shadow.copy_back_done(&done);
  9317. c.card.lock().unwrap().1 = after;
  9318. c.flying.store(false, Ordering::Release);
  9319. }
  9320. });
  9321. }
  9322. let _stop = Stop(&stop);
  9323. let mut random = Random(0xABCD_EF01_2345_6789);
  9324. let check = |round: usize, random: &mut Random, quiet: bool| {
  9325. for c in &carded {
  9326. if c.shadow.writes_pending() {
  9327. let mut runs = usize::MAX;
  9328. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  9329. }
  9330. }
  9331. let mut ranges = Vec::new();
  9332. for (shadow, start, len) in
  9333. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  9334. {
  9335. // All of it, or a part; often the same part.
  9336. let (from, n) = match random.below(3) {
  9337. _ if quiet => (0, len),
  9338. 0 => (0, len),
  9339. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  9340. _ => {
  9341. let from = random.below(len / 4) * 4;
  9342. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  9343. }
  9344. };
  9345. ranges.push((shadow.clone(), start + from, n));
  9346. }
  9347. submission(&ranges, 1 + random.below(3));
  9348. carded.iter().for_each(Carded::send);
  9349. };
  9350. let mut value = 1u32;
  9351. for round in 0..rounds {
  9352. check(round, &mut random, false);
  9353. if exact {
  9354. let c = &carded[0];
  9355. let mut card = c.card.lock().unwrap();
  9356. for _ in 0..40 {
  9357. value += 1;
  9358. let at = random.below(LEN / 32) * 32 + 4 * 6;
  9359. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  9360. undeclared.insert(at, value);
  9361. }
  9362. }
  9363. // The flight of this submission: its shaders' writes.
  9364. for (which, c) in carded.iter().enumerate() {
  9365. if c.flying.swap(true, Ordering::Acquire) {
  9366. continue;
  9367. }
  9368. value += 1;
  9369. let mut ranges: Vec<(usize, usize)> = Vec::new();
  9370. let first = random.below(6) * PAGE / 2;
  9371. for k in 0..2 {
  9372. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  9373. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  9374. if from < to {
  9375. ranges.push((from, to));
  9376. }
  9377. }
  9378. for &(from, to) in &ranges {
  9379. c.shadow.writing(c.start + from, to - from);
  9380. }
  9381. {
  9382. let mut card = c.card.lock().unwrap();
  9383. for &(from, to) in &ranges {
  9384. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  9385. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  9386. }
  9387. }
  9388. }
  9389. fly.send((which, ranges, value)).unwrap();
  9390. }
  9391. if round % 20 != 19 {
  9392. continue;
  9393. }
  9394. // Still: no flight in the air, no title write.
  9395. let _still = still.write().unwrap();
  9396. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  9397. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  9398. std::thread::yield_now();
  9399. }
  9400. check(round, &mut random, true);
  9401. // SAFETY: the test's own memory, written by nobody now.
  9402. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  9403. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  9404. for c in &carded {
  9405. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  9406. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  9407. let card = c.card.lock().unwrap();
  9408. let mut side = card.2.clone();
  9409. if c.class == carded[0].class {
  9410. // (They may have been landed meanwhile, by a flight
  9411. // that declared their range, and may not.)
  9412. for (&at, &value) in &undeclared {
  9413. let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
  9414. assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
  9415. side[at..at + 4].copy_from_slice(&there[at..at + 4]);
  9416. }
  9417. }
  9418. assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
  9419. }
  9420. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  9421. }
  9422. drop(fly);
  9423. });
  9424. }
  9425. /// The title's bytes put in under shader writes, for a copy of 174 MB
  9426. /// whose shader writes were declared as 40 ranges that overlap, with 12
  9427. /// pages written since. Run with `--ignored --nocapture`, and with
  9428. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  9429. #[test]
  9430. #[ignore]
  9431. fn bytes_under_overlapping_ranges() {
  9432. const BIG: usize = 174 << 20;
  9433. let big = title(BIG, true);
  9434. // SAFETY (both): the test's own memory.
  9435. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  9436. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  9437. copy.update(big, BIG);
  9438. copy.take_dirty();
  9439. for i in 0..40 {
  9440. copy.writing(big + i * 5920, BIG - i * 5920);
  9441. }
  9442. let mut best = f64::MAX;
  9443. for round in 0..30 {
  9444. for i in 0..12 {
  9445. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  9446. }
  9447. let started = std::time::Instant::now();
  9448. let mut runs = usize::MAX;
  9449. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  9450. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  9451. copy.take_dirty();
  9452. }
  9453. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  9454. }
  9455. /// A range nothing wrote is known to be as it was, at its ends too, and
  9456. /// is so no more once something wrote it.
  9457. #[test]
  9458. fn unchanged_ranges_are_known() {
  9459. for view in [false, true] {
  9460. let region = title(8 * PAGE, view);
  9461. // (A page read for the first time counts as written.)
  9462. // SAFETY: the test's own memory.
  9463. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  9464. let data = memory(8 * PAGE);
  9465. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  9466. // Ends in the middle of pages.
  9467. let (at, len) = (region + 500, 5 * PAGE);
  9468. let look = |expected: bool, what: &str| {
  9469. // The submission's one asking, which takes two ranges. (Again
  9470. // if a submission of another test ended it.)
  9471. let mut known = false;
  9472. for _ in 0..100 {
  9473. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  9474. known = copy.nothing_new(at, len);
  9475. if known || !expected {
  9476. break;
  9477. }
  9478. }
  9479. assert_eq!(known, expected, "view {view}: {what}");
  9480. let copied = copy.update(at, len);
  9481. crate::watch::ask_once_end();
  9482. copied
  9483. };
  9484. assert_eq!(look(false, "never taken"), len);
  9485. assert_eq!(look(true, "taken"), 0);
  9486. assert_eq!(look(true, "taken"), 0);
  9487. // SAFETY: the test's own memory.
  9488. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  9489. // (The kernel names the 4 KiB, the guards only the block.)
  9490. assert_eq!(look(false, "written at its end"), if view { PAGE } else { 4096 } - 500);
  9491. assert_eq!(look(true, "taken again"), 0);
  9492. // Outside the range, on its last page.
  9493. // SAFETY: as above.
  9494. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  9495. assert_eq!(look(false, "written on its last page"), 500);
  9496. // A longer range was never taken whole.
  9497. assert!(!copy.nothing_new(region, 6 * PAGE));
  9498. }
  9499. }
  9500. /// Of a copy in the card's memory only the dwords title memory changed go
  9501. /// up, and none beside them, not even between two in 64 bytes; a page
  9502. /// never taken goes up whole.
  9503. #[test]
  9504. fn only_what_differs_goes_up() {
  9505. let region = title(4 * PAGE, true);
  9506. let data = memory(4 * PAGE);
  9507. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  9508. copy.update(region, 4 * PAGE);
  9509. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  9510. // What the relay does: shader writes into title memory, and into the
  9511. // CPU's side.
  9512. crate::watch::landing(region + PAGE + 640, 64);
  9513. // SAFETY: the test's own memory.
  9514. unsafe {
  9515. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  9516. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  9517. }
  9518. copy.update(region, 4 * PAGE);
  9519. let again = copy.take_dirty();
  9520. // SAFETY: as above.
  9521. unsafe {
  9522. ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
  9523. ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
  9524. ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
  9525. // The value that was there.
  9526. ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
  9527. }
  9528. copy.update(region, 4 * PAGE);
  9529. let written = copy.take_dirty();
  9530. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") {
  9531. assert_eq!(again, []);
  9532. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
  9533. } else {
  9534. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  9535. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  9536. }
  9537. // SAFETY: as above.
  9538. assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
  9539. }
  9540. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  9541. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  9542. /// big copy that 55 landed pieces and 9 title writes opened, while a
  9543. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  9544. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  9545. #[test]
  9546. #[ignore]
  9547. fn frame_of_refreshes() {
  9548. let mut random = Random(0x9876_5432_1234_5671);
  9549. const EACH: usize = 224 << 10;
  9550. const BIG: usize = 174 << 20;
  9551. let watched = title(3000 * EACH, false);
  9552. // `VICTORY_BENCH_HOLES=0`: views without holes.
  9553. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  9554. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  9555. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  9556. let big = title(BIG, true);
  9557. // SAFETY: the test's own memory.
  9558. unsafe {
  9559. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  9560. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  9561. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  9562. }
  9563. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  9564. }
  9565. let mut small = Vec::new();
  9566. for i in 0..4400 {
  9567. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  9568. let data = memory(EACH);
  9569. // The range views read, not all of the copy.
  9570. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  9571. }
  9572. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  9573. // The same memory, as another copy: what is landed is landed through
  9574. // it, and the refreshes are of the first.
  9575. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  9576. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  9577. let (mut sum, mut landing) = (0.0, 0.0);
  9578. const FRAMES: usize = 12;
  9579. for frame in 0..FRAMES {
  9580. let mut took = [0f64; 2];
  9581. for i in 0..30 {
  9582. // The title's writes, and the relay's beside the submission.
  9583. for _ in 0..9 {
  9584. let at = views + random.below(1400 * EACH / 8) * 8;
  9585. if there(at) {
  9586. // SAFETY: the test's own memory.
  9587. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  9588. }
  9589. }
  9590. for _ in 0..60 {
  9591. let at = watched + random.below(3000 * EACH / 8) * 8;
  9592. // SAFETY: the test's own memory.
  9593. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  9594. }
  9595. let first = random.below(BIG / PAGE - 60);
  9596. let lands = lands.clone();
  9597. let land = std::thread::spawn(move || {
  9598. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  9599. let started = std::time::Instant::now();
  9600. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  9601. let pieces: Vec<_> =
  9602. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  9603. let mut notes = crate::land::Notes::default();
  9604. // SAFETY: the bytes of `now`; nothing else lands here.
  9605. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  9606. notes.flush();
  9607. }
  9608. started.elapsed().as_secs_f64() * 1e3
  9609. });
  9610. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  9611. small.iter().cloned().chain([heap.clone()]).collect()
  9612. } else {
  9613. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  9614. };
  9615. let started = std::time::Instant::now();
  9616. submission(&ranges, 3);
  9617. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  9618. let put = land.join().unwrap();
  9619. if frame >= 2 {
  9620. landing += put;
  9621. }
  9622. heap.0.take_dirty();
  9623. }
  9624. if frame >= 2 {
  9625. sum += took[0] + took[1];
  9626. for k in 0..2 {
  9627. best[k] = best[k].min(took[k]);
  9628. asking[k] += took[k];
  9629. }
  9630. }
  9631. }
  9632. println!(
  9633. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  9634. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  9635. crate::watch::light(),
  9636. sum / (FRAMES - 2) as f64,
  9637. asking[0] / (FRAMES - 2) as f64,
  9638. best[0],
  9639. asking[1] / (FRAMES - 2) as f64,
  9640. best[1],
  9641. landing / (FRAMES - 2) as f64,
  9642. );
  9643. #[cfg(feature = "diagnostics")]
  9644. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  9645. }
  9646. }
  9647. #[cfg(test)]
  9648. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  9649. use super::Batch;
  9650. use std::sync::Arc;
  9651. #[test]
  9652. fn a_texture_is_checked_once_per_submission() {
  9653. let mut batch = Batch::default();
  9654. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  9655. // The first list sampling each texture checks it ...
  9656. assert!(batch.texture_due(&a));
  9657. assert!(batch.texture_due(&b));
  9658. // ... later lists of the same submission do not.
  9659. assert!(!batch.texture_due(&a));
  9660. assert!(!batch.texture_due(&a.clone()));
  9661. assert!(!batch.texture_due(&b));
  9662. }
  9663. #[test]
  9664. fn title_writes_make_textures_due_again() {
  9665. let mut batch = Batch::default();
  9666. let a = Arc::new(1u32);
  9667. assert!(batch.texture_due(&a));
  9668. assert!(!batch.texture_due(&a));
  9669. // A copy into title memory or work that may write it may have
  9670. // changed the texture's memory.
  9671. batch.title_written();
  9672. assert!(batch.texture_due(&a));
  9673. assert!(!batch.texture_due(&a));
  9674. // A fresh submission starts over.
  9675. let mut next = Batch::default();
  9676. assert!(next.texture_due(&a));
  9677. }
  9678. /// The hashing a submission does for textures in physical-page memory,
  9679. /// with every list checking the textures it samples (before) and with
  9680. /// each checked once (after). Run with
  9681. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  9682. #[test]
  9683. #[ignore = "benchmark"]
  9684. fn texture_checks_per_submission() {
  9685. const TEXTURES: usize = 48;
  9686. const SIZE: usize = 4 << 20;
  9687. const LISTS: usize = 12;
  9688. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  9689. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  9690. .collect();
  9691. let submit = |dedupe: bool| {
  9692. let mut batch = Batch::default();
  9693. let mut hashed = 0usize;
  9694. let started = std::time::Instant::now();
  9695. for _ in 0..LISTS {
  9696. for t in &textures {
  9697. if !dedupe || batch.texture_due(t) {
  9698. std::hint::black_box(blake3::hash(t));
  9699. hashed += 1;
  9700. }
  9701. }
  9702. }
  9703. (started.elapsed(), hashed)
  9704. };
  9705. submit(false); // warm up
  9706. let (before, n_before) = submit(false);
  9707. let (after, n_after) = submit(true);
  9708. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  9709. println!(
  9710. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  9711. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  9712. SIZE >> 20,
  9713. before.as_secs_f64() / after.as_secs_f64()
  9714. );
  9715. }
  9716. #[test]
  9717. fn vram_idle_ms_scales_with_pressure() {
  9718. let vram_idle_ms = |memory| super::vram_idle_for(memory, false);
  9719. let keeps = |memory| super::vram_idle_for(memory, true);
  9720. let gib = 1024 * 1024 * 1024;
  9721. assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000);
  9722. assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000);
  9723. assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500);
  9724. assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000);
  9725. assert_eq!(keeps(None), 5_000);
  9726. // Normal (< 75%)
  9727. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  9728. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  9729. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  9730. // Moderate (75%..85%)
  9731. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  9732. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  9733. // High (>= 85%, including over-budget)
  9734. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  9735. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  9736. // Missing or zero budget falls back to normal
  9737. assert_eq!(vram_idle_ms(None), 5_000);
  9738. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  9739. }
  9740. #[test]
  9741. fn textures_are_kept_while_the_card_has_room() {
  9742. use super::vram_keep;
  9743. let gib = 1 << 30;
  9744. assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000);
  9745. // Past it: the longest idle ones, enough to come down to 85 %.
  9746. let (ms, bytes) = vram_keep(100 * gib, 90 * gib);
  9747. assert_eq!((ms, bytes), (5_000, 5 * gib));
  9748. assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib));
  9749. assert_eq!(vram_keep(0, 7).0, 5_000);
  9750. }
  9751. #[test]
  9752. fn ram_idle_ms_scales_with_pressure() {
  9753. let ram_idle_ms = |avail| super::ram_idle_for(avail, false);
  9754. assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000);
  9755. assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000);
  9756. assert_eq!(super::ram_idle_for(None, true), 10_000);
  9757. let gib = 1024 * 1024 * 1024;
  9758. // Normal (>= 4 GiB)
  9759. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  9760. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  9761. // Moderate (2 GiB..4 GiB)
  9762. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  9763. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  9764. // High (< 2 GiB)
  9765. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  9766. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  9767. // Missing falls back to normal
  9768. assert_eq!(ram_idle_ms(None), 10_000);
  9769. }
  9770. }