host.rs 417 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505
  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. struct Retired(#[allow(dead_code)] Box<dyn std::any::Any>);
  72. // SAFETY: what is retired is D3D12 objects (free-threaded) and the
  73. // reference-counted wrappers holding them, dropped once.
  74. unsafe impl Send for Retired {}
  75. /// Milliseconds since the first call.
  76. pub(crate) fn now_ms() -> u64 {
  77. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  78. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  79. }
  80. /// This moment, for telling later how long ago it was ([`long_ago`]): the
  81. /// frames begun so far (high half, `crate::frame::current`) and tenths of a
  82. /// second since the start. Host copies of title memory, staging buffers and
  83. /// host textures note when they were last used with it.
  84. pub(crate) fn moment() -> u64 {
  85. (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff)
  86. }
  87. /// Whether `moment` lies at least `ms` milliseconds and `frames` frames
  88. /// back. Both: at seconds per frame, what every frame uses is not touched
  89. /// for seconds, and at many frames per second not for many frames. (A title
  90. /// that never waits for frames has no frame count: nothing is then idle.)
  91. pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
  92. let now = self::moment();
  93. let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
  94. (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
  95. }
  96. /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
  97. pub(crate) fn available_physical_ram() -> Option<u64> {
  98. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  99. // SAFETY: plain data the call fills in.
  100. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  101. m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
  102. // SAFETY: a sized structure.
  103. let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
  104. ok.then_some(m.ullAvailPhys)
  105. }
  106. /// How long host copies of textures the title fills must have been idle to
  107. /// be let go, in milliseconds, and how many bytes of them go at most (the
  108. /// longest idle first): none but those of ten minutes while what is in use
  109. /// of the card (`used`: without what our own blocks have free, with what is
  110. /// kept free for others) is under 88 % of its budget, else enough to come
  111. /// down to 85 %. `VICTORY_TEXTURE_KEEP=0`: [`vram_idle_ms`]' older rule,
  112. /// all that are idle; `=1`: that rule with its two longer times.
  113. ///
  114. /// (By those times everything idle for 2.5 s went from 75 % of the budget
  115. /// on: 61,000 of them in the first 300 s of session play-1125-0203, at 78 to
  116. /// 80 %, of which 13,000 were made and uploaded again.)
  117. pub(crate) fn vram_keep(budget: u64, used: u64) -> (u64, u64) {
  118. const KEPT_MS: u64 = 600_000;
  119. const IDLE_MS: u64 = 5_000;
  120. const SHORT_MS: u64 = 1_500;
  121. if budget == 0 {
  122. return (IDLE_MS, u64::MAX);
  123. }
  124. let share = |percent: u64| budget / 100 * percent;
  125. if used < share(88) {
  126. (KEPT_MS, u64::MAX)
  127. } else if used < share(95) {
  128. (IDLE_MS, used - share(85))
  129. } else {
  130. (SHORT_MS, used - share(85))
  131. }
  132. }
  133. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  134. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  135. /// handles not yet recorded into a list or slot remain protected.
  136. ///
  137. /// With room on the card nothing has to go: in session play-1125-0127 88,000
  138. /// of them (31 GB) went after 5 s with 7 GB of the card free, and 24,700
  139. /// (12 GB) had to be made and uploaded again.
  140. /// `VICTORY_TEXTURE_KEEP=0`: 5 s there too, as before.
  141. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  142. static KEEP: OnceLock<bool> = OnceLock::new();
  143. let keep = *KEEP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_KEEP").is_none_or(|v| v != "0"));
  144. vram_idle_for(video_memory, keep)
  145. }
  146. fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 {
  147. const KEPT_MS: u64 = 600_000;
  148. const LONG_MS: u64 = 30_000;
  149. const NORMAL_MS: u64 = 5_000;
  150. const MODERATE_MS: u64 = 2_500;
  151. const HIGH_MS: u64 = 1_000;
  152. let Some([budget, used, ..]) = video_memory else {
  153. return NORMAL_MS;
  154. };
  155. if budget == 0 {
  156. return NORMAL_MS;
  157. }
  158. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  159. if used_pct >= 85 {
  160. HIGH_MS
  161. } else if used_pct >= 75 {
  162. MODERATE_MS
  163. } else if !keep {
  164. NORMAL_MS
  165. } else if used_pct >= 68 {
  166. LONG_MS
  167. } else {
  168. KEPT_MS
  169. }
  170. }
  171. /// Whether memory the card was given stays with it while there is room (on
  172. /// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader
  173. /// that reads past a view (a raw load through a typed, structured or
  174. /// constant buffer view has no end on AMD: `indirect::tests::raw_loads_past_views`)
  175. /// or through a slot that shows wrong data reads whatever lies there, and
  176. /// nothing happens; where memory was given back it is a page fault, and the
  177. /// device is lost. Both losses of 2026-11-25 were reads in memory given back
  178. /// seconds before (a block of textures; a list's scratch and a window of
  179. /// title memory). Kept are: empty blocks of textures ([`crate::pool`]) below
  180. /// 85 % of the card's budget, windows of title memory and staging buffers
  181. /// for five minutes with 12 GiB of the PC's memory free, and 1 GiB of
  182. /// scratch chunks.
  183. pub(crate) fn keep_freed() -> bool {
  184. static ON: OnceLock<bool> = OnceLock::new();
  185. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_FREED").is_none_or(|v| v != "0"))
  186. }
  187. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  188. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  189. /// when free physical RAM is low. Never returns less than 2,000 ms.
  190. /// With plenty of it five minutes ([`keep_freed`]).
  191. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  192. ram_idle_for(avail_phys, keep_freed())
  193. }
  194. fn ram_idle_for(avail_phys: Option<u64>, keep: bool) -> u64 {
  195. const GIB: u64 = 1024 * 1024 * 1024;
  196. const KEPT_MS: u64 = 300_000;
  197. if keep && avail_phys.is_some_and(|avail| avail >= 12 * GIB) {
  198. return KEPT_MS;
  199. }
  200. const NORMAL_MS: u64 = 10_000;
  201. const MODERATE_MS: u64 = 5_000;
  202. const HIGH_MS: u64 = 2_000;
  203. let Some(avail) = avail_phys else {
  204. return NORMAL_MS;
  205. };
  206. if avail < 2 * GIB {
  207. HIGH_MS
  208. } else if avail < 4 * GIB {
  209. MODERATE_MS
  210. } else {
  211. NORMAL_MS
  212. }
  213. }
  214. /// How many references are held on a host object (its COM count): ours
  215. /// all, since the host's views and commands hold none. A buffer or texture
  216. /// with one is held by its owner alone: no descriptor slot keeps it
  217. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  218. pub(crate) fn references(object: &impl Interface) -> u32 {
  219. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  220. let raw = object.as_raw();
  221. // SAFETY: a live COM object, whose first three methods are those of
  222. // `IUnknown` (query, add a reference, release one); the pair leaves the
  223. // count as it was, and the release returns it. The first is not called.
  224. unsafe {
  225. let methods = *raw.cast::<*const [Method; 3]>();
  226. ((*methods)[1])(raw);
  227. ((*methods)[2])(raw)
  228. }
  229. }
  230. /// Once a second, before a submission starts: lets go of what nothing
  231. /// names any more (copies of windows of title memory, staging buffers,
  232. /// host copies of textures the title fills).
  233. /// `VICTORY_SWEEP=0` keeps everything, as before.
  234. fn sweep() {
  235. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  236. crate::inplace::tick();
  237. static ON: OnceLock<bool> = OnceLock::new();
  238. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  239. return;
  240. }
  241. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  242. let now = now_ms();
  243. let last = LAST.load(Ordering::Relaxed);
  244. if now < last + 1000
  245. || LAST
  246. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  247. .is_err()
  248. {
  249. return;
  250. }
  251. #[cfg(feature = "diagnostics")]
  252. crate::book::check();
  253. crate::pool::room(host().and_then(|h| h.video_memory()));
  254. crate::pipeline::trim_library();
  255. crate::shadow::let_go_idle();
  256. crate::texture::let_go_idle();
  257. crate::resource::let_go_idle();
  258. }
  259. /// The number of the newest submission begun, and of the newest of which all
  260. /// before it have finished too.
  261. pub(crate) fn submissions() -> (u64, u64) {
  262. (STARTED.load(Ordering::Acquire), FINISHED.load(Ordering::Acquire))
  263. }
  264. /// Drops `object` once every submission running now has finished: at once
  265. /// if none is.
  266. pub(crate) fn retire<T: 'static>(object: T) {
  267. // (Those the title made and the host has not begun get the next numbers.)
  268. let queued = crate::queue::queued();
  269. let started = STARTED.load(Ordering::Acquire) + queued;
  270. if bury_lag() == 0 && started <= FINISHED.load(Ordering::Acquire) {
  271. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  272. drop(object);
  273. return;
  274. }
  275. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  276. RETIRED
  277. .lock()
  278. .unwrap_or_else(|e| e.into_inner())
  279. .push_back((started, Retired(Box::new(object))));
  280. }
  281. /// How many submissions later than it could (the last one that may use it
  282. /// has finished) an object let go is dropped, and a host list that has run
  283. /// is reset, about two frames: the device losses of the night of 2026-11-25
  284. /// were page faults in memory nothing of ours named any more, at no command
  285. /// in particular. Objects let go while nothing runs wait as well: lists
  286. /// recorded and not yet sent may name them. `VICTORY_BURY_LAG=0`: not.
  287. fn bury_lag() -> u64 {
  288. static LAG: OnceLock<u64> = OnceLock::new();
  289. *LAG.get_or_init(|| std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(64))
  290. }
  291. /// Drops what waited for submissions up to `finished` ([`bury_lag`]). The
  292. /// numbers come in order, but for threads that overtake each other: one of
  293. /// those is dropped a little later than it could be.
  294. fn bury(finished: u64) {
  295. let finished = finished.saturating_sub(bury_lag());
  296. let done: Vec<(u64, Retired)> = {
  297. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  298. let n = retired.iter().take_while(|(at, _)| *at <= finished).count();
  299. if n == 0 {
  300. return;
  301. }
  302. retired.drain(..n).collect()
  303. };
  304. drop(done);
  305. }
  306. /// Objects [`retire`] dropped at once (no submission was running) and
  307. /// kept until a running submission finished, since the start.
  308. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  309. /// What the layer did to the host's objects lately, newest last (sweeps
  310. /// that let host copies go, pipeline library calls, saves and trims): said
  311. /// once when the host device is removed ([`log_removal_context`]), with
  312. /// what the submitting thread and the pipeline workers were doing at that
  313. /// moment. A device the driver removes "internally" names no command, and
  314. /// the pass that happens to notice first names only the view it was at:
  315. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  316. /// pipeline library call that no line of the log tied to them.
  317. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  318. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  319. /// The entries kept.
  320. const TRAIL_MOST: usize = 96;
  321. fn trail_on() -> bool {
  322. static ON: OnceLock<bool> = OnceLock::new();
  323. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  324. }
  325. /// Microseconds since the first call.
  326. pub(crate) fn now_us() -> u64 {
  327. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  328. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  329. }
  330. /// The calling thread, as the log's other lines name threads.
  331. pub(crate) fn thread_id() -> u32 {
  332. // SAFETY: a plain query.
  333. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  334. }
  335. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  336. /// run when the trail is kept.
  337. pub(crate) fn trail(what: impl FnOnce() -> String) {
  338. if !trail_on() {
  339. return;
  340. }
  341. let entry = (now_us(), thread_id(), what());
  342. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  343. if trail.len() >= TRAIL_MOST {
  344. trail.pop_front();
  345. }
  346. trail.push_back(entry);
  347. }
  348. /// What the submitting thread is doing (0 nothing: between submissions,
  349. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  350. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  351. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  352. fn submitting(phase: u64, lists: usize) {
  353. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  354. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  355. SUBMITTING[0].store(phase, Ordering::Relaxed);
  356. }
  357. /// What was going on when the host device went: whether a submission was
  358. /// on the card, the pipeline library's state and the calls running in it,
  359. /// and the trail.
  360. pub(crate) fn removal_context() -> String {
  361. use std::fmt::Write;
  362. let now = now_us();
  363. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  364. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  365. 0 => "between submissions (nothing of ours was running on the card)",
  366. 1 => "preparing a submission (nothing of ours was running on the card)",
  367. 2 => "waiting for the card to run a submission",
  368. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  369. };
  370. let mut text = format!(
  371. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  372. SUBMITTING[1].load(Ordering::Relaxed),
  373. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  374. crate::pipeline::library_removal_note(),
  375. RETIREMENTS[0].load(Ordering::Relaxed),
  376. RETIREMENTS[1].load(Ordering::Relaxed),
  377. STARTED.load(Ordering::Relaxed),
  378. FINISHED.load(Ordering::Relaxed),
  379. );
  380. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  381. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  382. for (at, thread, what) in trail.iter() {
  383. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  384. }
  385. text
  386. }
  387. /// Says [`removal_context`] in the log, once: called by whoever finds the
  388. /// host device removed.
  389. pub(crate) fn log_removal_context() {
  390. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  391. if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) {
  392. return;
  393. }
  394. tracing::error!("when the host device went: {}", removal_context());
  395. if dred_any() {
  396. let data = host().map(|h| h.removal_data(&[])).unwrap_or_default();
  397. tracing::error!("device-removed data{}", if data.is_empty() { "; none" } else { &data });
  398. }
  399. }
  400. /// Time spent in submissions since the last frame-rate line, in
  401. /// microseconds: preparing them on the CPU (title memory copies, texture
  402. /// detiling), then waiting for the GPU.
  403. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  404. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  405. /// After submissions: shader-written ranges compared and copied back into
  406. /// title memory (microseconds, bytes that differed), since the last
  407. /// frame-rate line.
  408. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  409. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  410. /// The card's clock, for the frame line of every run, in microseconds since
  411. /// the last one: how long the card had nothing of ours queued; how much of
  412. /// that while the thread that holds the submission lock was working (the
  413. /// card idle behind us: preparing and copying back are done with the card
  414. /// standing); and how long that thread stood waiting for the card.
  415. ///
  416. /// Every send of lists to the queue is followed by a signal on a fence of
  417. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  418. /// the newest signal and notes the moment the card reached it with nothing
  419. /// newer sent; the next send ends that idle stretch.
  420. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  421. /// Of the thread that holds the submission lock: the microseconds it has
  422. /// worked so far (preparing, copying back; not its waits for the card), and
  423. /// since when it works now ([`now_us`] plus one; 0: it does not).
  424. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  425. /// The thread that holds the submission lock starts (`on`) or stops
  426. /// working; whether it worked until now.
  427. fn working(on: bool) -> bool {
  428. let now = now_us() + 1;
  429. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  430. if since != 0 {
  431. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  432. }
  433. since != 0
  434. }
  435. /// [`WORKING`] as of now: microseconds worked so far.
  436. fn worked() -> u64 {
  437. let since = WORKING[1].load(Ordering::Relaxed);
  438. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  439. WORKING[0].load(Ordering::Relaxed) + now
  440. }
  441. /// The thread that holds the submission lock stood waiting for the card
  442. /// from `since` until now ([`CARD_CLOCK_US`]).
  443. fn stood(since: std::time::Instant) {
  444. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  445. }
  446. /// What [`CARD_CLOCK_US`] is measured with.
  447. struct CardClock {
  448. fence: ID3D12Fence,
  449. /// Signals sent so far; and, while the card has reached the last of
  450. /// them, since when and what [`worked`] said then.
  451. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  452. sent: std::sync::Condvar,
  453. }
  454. // SAFETY: a fence (free-threaded) behind a lock.
  455. unsafe impl Send for CardClock {}
  456. // SAFETY: as above.
  457. unsafe impl Sync for CardClock {}
  458. /// The clock's thread: waits for the newest signal sent and notes when the
  459. /// card got there with nothing newer behind it.
  460. fn card_clock_watch(clock: &'static CardClock) {
  461. // SAFETY: a plain event of our own.
  462. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  463. return;
  464. };
  465. let mut seen = 0;
  466. loop {
  467. let target = {
  468. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  469. while state.0 == seen {
  470. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  471. }
  472. state.0
  473. };
  474. // SAFETY: the clock's fence and this thread's event.
  475. unsafe {
  476. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  477. WaitForSingleObject(event, INFINITE);
  478. }
  479. }
  480. seen = target;
  481. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  482. if state.0 == target && state.1.is_none() {
  483. state.1 = Some((std::time::Instant::now(), worked()));
  484. }
  485. }
  486. }
  487. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  488. /// frame's time.
  489. fn card_clock_line(frames: f64, ms: f64) {
  490. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  491. tracing::info!(
  492. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  493. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  494. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  495. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  496. );
  497. }
  498. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  499. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  500. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  501. std::sync::atomic::AtomicU64::new(0),
  502. std::sync::atomic::AtomicU64::new(0),
  503. std::sync::atomic::AtomicU64::new(0),
  504. std::sync::atomic::AtomicU64::new(0),
  505. ];
  506. /// Host buffers made since the start, as (count, bytes): in the upload heap
  507. /// (staging, list scratch), shared with the processor (host copies of title
  508. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  509. /// For the memory line: against what is alive, they show what was let go.
  510. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  511. /// What of that is alive now, for the memory line (`MADE` counts what was
  512. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  513. /// and nothing said how many were alive): host lists; the lists' scratch
  514. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  515. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  516. /// instead of made, since the start; and the lists' other upload buffers
  517. /// (texture data copied from buffers, scratch too big for a chunk) and
  518. /// their bytes.
  519. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  520. /// About host lists, for the memory line: lists made by the host since the
  521. /// start; preludes made (a list's second allocator and list, made when it
  522. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  523. /// bytes the process's private memory grew by while lists were being made
  524. /// (what a list costs: host objects with the driver's command memory; 631
  525. /// lists were alive in run 65, each with a prelude it may never use).
  526. /// Then the lists alive that were never reset since they were made: the
  527. /// host sides of title lists the title made and has not used (a host list
  528. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  529. /// makes at its start).
  530. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  531. /// The process's private bytes (diagnostics: around the making of lists).
  532. #[cfg(feature = "diagnostics")]
  533. fn private_bytes() -> u64 {
  534. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  535. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  536. let mut c = PROCESS_MEMORY_COUNTERS {
  537. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  538. ..Default::default()
  539. };
  540. // SAFETY: our own process and a sized structure.
  541. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  542. c.PagefileUsage as u64
  543. }
  544. /// What the runtime does when the host GPU fails for good: report it like a
  545. /// crash and end the run. The console has no such state, and carrying on
  546. /// draws nothing at seconds per frame.
  547. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  548. /// Sets what a host GPU failure does (the runtime's crash report).
  549. pub fn on_failure(report: fn(&str) -> !) {
  550. let _ = ON_FAILURE.set(report);
  551. }
  552. /// Ends the run on a host GPU failure: what failed, the removal reason and
  553. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  554. /// diagnostics build names the command).
  555. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  556. let mut text = what.to_string();
  557. if let Some(host) = host() {
  558. // SAFETY: a plain query.
  559. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  560. text.push_str(&format!("; device removed: {e}"));
  561. log_removal_context();
  562. }
  563. match host.log_messages() {
  564. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  565. None if host.messages.is_none() => text.push_str(
  566. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  567. ),
  568. None => {}
  569. }
  570. }
  571. tracing::error!("{text}");
  572. // Tests have no log: the reason goes to their output.
  573. #[cfg(test)]
  574. eprintln!("host GPU failure: {text}");
  575. match ON_FAILURE.get() {
  576. Some(report) => report(&text),
  577. None => std::process::abort(),
  578. }
  579. }
  580. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  581. /// The host GPU if it is made already.
  582. #[cfg(feature = "diagnostics")]
  583. pub(crate) fn made_host() -> Option<&'static Host> {
  584. HOST.get()?.as_ref()
  585. }
  586. /// The host GPU, created on first use; `None` without one (a run then
  587. /// behaves as before: nothing executes).
  588. pub(crate) fn host() -> Option<&'static Host> {
  589. HOST.get_or_init(|| match create() {
  590. Ok(host) => Some(host),
  591. Err(e) => {
  592. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  593. None
  594. }
  595. })
  596. .as_ref()
  597. }
  598. fn create() -> windows::core::Result<Host> {
  599. // SAFETY: plain D3D12 object creation with valid descriptions.
  600. unsafe {
  601. // The debug layer only in builds with diagnostics.
  602. let debug = cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DEBUG");
  603. if debug {
  604. let mut layer: Option<ID3D12Debug> = None;
  605. match D3D12GetDebugInterface(&mut layer) {
  606. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  607. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  608. }
  609. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  610. // descriptor heap indices and the like become messages naming
  611. // the command instead of page faults. Without state tracking
  612. // (directly indexed textures are not transitioned).
  613. if crate::switch::on("VICTORY_D3D12_GBV")
  614. && let Some(l) = &layer
  615. {
  616. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  617. d1.SetEnableGPUBasedValidation(true);
  618. }
  619. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  620. d2.SetGPUBasedValidationFlags(
  621. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  622. );
  623. }
  624. tracing::info!("GPU-based validation on");
  625. }
  626. }
  627. // Diagnostics: device-removed data (the command that faulted, the
  628. // faulting address), read when the device is removed.
  629. if dred_any() {
  630. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  631. if D3D12GetDebugInterface(&mut dred).is_ok()
  632. && let Some(dred) = dred
  633. {
  634. if dred_on() || dred_light() {
  635. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  636. }
  637. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  638. tracing::info!(
  639. breadcrumbs = dred_on() || dred_light(),
  640. markers = dred_on(),
  641. "crash tracing on (device-removed data)"
  642. );
  643. } else {
  644. tracing::warn!("crash tracing asked for and not there: no device-removed data settings");
  645. }
  646. }
  647. let mut device: Option<ID3D12Device> = None;
  648. // Diagnostics: the software adapter, on which a shader's wild access
  649. // is an access violation in this process (a crash report with the
  650. // address and instruction) instead of a GPU fault and driver reset.
  651. if cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_WARP") {
  652. let adapter = warp_adapter()?;
  653. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  654. tracing::info!("host device on the software adapter (WARP)");
  655. } else {
  656. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  657. // Whether a GPU hang ends the run or freezes the PC (#1054).
  658. crate::tdr::log();
  659. }
  660. let device = device.ok_or_else(windows::core::Error::empty)?;
  661. // Before anything is made with it (`VICTORY_RECORD`).
  662. #[cfg(feature = "diagnostics")]
  663. crate::replay::record::from_env(&device);
  664. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  665. // driver compiling shaders again on the "D3D Background Thread"s,
  666. // for minutes after pipelines were made or loaded) is switched off.
  667. // An experiment: while those threads ran, the same shot took
  668. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  669. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  670. // whether the card is slower with the shaders it then keeps is not
  671. // known.
  672. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  673. && let Ok(device6) = device.cast::<ID3D12Device6>()
  674. {
  675. let set = device6.SetBackgroundProcessingMode(
  676. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  677. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  678. None,
  679. None,
  680. );
  681. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  682. }
  683. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  684. // cross-lane code stays in 32-lane halves translated for waves of 32
  685. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  686. if device
  687. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  688. .is_ok()
  689. {
  690. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  691. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  692. }
  693. let messages = debug
  694. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  695. .flatten();
  696. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  697. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  698. ..Default::default()
  699. })?;
  700. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  701. let event = CreateEventW(None, false, false, None)?;
  702. let rtvs: ID3D12DescriptorHeap =
  703. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  704. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  705. NumDescriptors: RTV_RING,
  706. ..Default::default()
  707. })?;
  708. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  709. let dsvs: ID3D12DescriptorHeap =
  710. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  711. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  712. NumDescriptors: RTV_RING,
  713. ..Default::default()
  714. })?;
  715. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  716. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  717. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  718. .ok();
  719. tracing::info!("host D3D12 device ready");
  720. Ok(Host {
  721. device,
  722. queue,
  723. fence,
  724. submitted: Mutex::new(0),
  725. event,
  726. rtvs,
  727. rtv_size,
  728. dsvs,
  729. dsv_size,
  730. next_dsv: AtomicU32::new(0),
  731. messages,
  732. next_rtv: AtomicU32::new(0),
  733. presenter: Mutex::new(None),
  734. adapter,
  735. })
  736. }
  737. }
  738. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  739. /// Reject it before creating a device in diagnostics' software-only mode.
  740. pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  741. // SAFETY: plain DXGI adapter queries.
  742. unsafe {
  743. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  744. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  745. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  746. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  747. tracing::warn!(
  748. vendor = format_args!("{:#x}", desc.VendorId),
  749. flags = format_args!("{:#x}", desc.Flags),
  750. "DXGI did not identify the WARP adapter as software; refusing device"
  751. );
  752. return Err(windows::core::Error::from_hresult(
  753. windows::Win32::Foundation::E_FAIL,
  754. ));
  755. }
  756. Ok(adapter)
  757. }
  758. }
  759. #[cfg(test)]
  760. mod tests {
  761. /// A list of ours is found by its name, with the debug layer's note or not.
  762. #[cfg(feature = "diagnostics")]
  763. #[test]
  764. fn a_list_is_found_by_the_number_in_its_name() {
  765. assert_eq!(super::list_number("victory host list 7"), Some(7));
  766. assert_eq!(super::list_number("victory host list 158 (debug layer indirect)"), Some(158));
  767. assert_eq!(super::list_number("victory host list 7x"), None);
  768. assert_eq!(super::list_number("victory host list 7 x"), None);
  769. assert_eq!(super::list_number("another list 7"), None);
  770. assert_eq!(super::list_number(""), None);
  771. }
  772. /// What is there of a range some of whose pages are not: those bytes,
  773. /// counted, and zeros for the rest, whatever the buffer held.
  774. #[test]
  775. fn what_is_there_is_read_and_the_rest_is_zeros() {
  776. use windows_sys::Win32::System::Memory::*;
  777. const SIZE: usize = 0x8_0000;
  778. // SAFETY: a reservation of ours; only committed pages are written.
  779. unsafe {
  780. let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  781. assert!(!at.is_null());
  782. // 0-0x1_1000 and 0x3_0000-0x4_0000 are there.
  783. for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] {
  784. assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null());
  785. at.add(from).write_bytes(0x5a, len);
  786. }
  787. // From an address inside a page, as textures are packed.
  788. let mut out = vec![0x77u8; SIZE - 0x300];
  789. assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000);
  790. for (i, &b) in out.iter().enumerate() {
  791. let from = i + 0x300;
  792. let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from);
  793. assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}");
  794. }
  795. // All there: one read.
  796. let mut out = vec![0x77u8; 0x1_0000];
  797. assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000);
  798. assert!(out.iter().all(|&b| b == 0x5a));
  799. // Nothing there.
  800. let mut out = vec![0x77u8; 0x1_0000];
  801. assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0);
  802. assert!(out.iter().all(|&b| b == 0));
  803. assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0);
  804. }
  805. }
  806. /// Zeros for a title destination that went meanwhile are no fault.
  807. #[test]
  808. fn zeros_where_nothing_is_are_lost() {
  809. use windows_sys::Win32::System::Memory::*;
  810. // SAFETY: a reservation of ours, its first page committed.
  811. unsafe {
  812. let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  813. assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
  814. at.write_bytes(7, 4096);
  815. super::zero(at, 4096);
  816. assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
  817. super::zero(at.add(4096), 4096);
  818. VirtualFree(at.cast(), 0, MEM_RELEASE);
  819. }
  820. }
  821. #[test]
  822. fn sparse_copies_preserve_islands_and_observe_remaps() {
  823. use windows_sys::Win32::System::Memory::*;
  824. const N: usize = 5 << 16;
  825. // SAFETY: we reserve a private region, commit selected pages inside it,
  826. // and only directly access the pages while they are writable.
  827. unsafe {
  828. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  829. assert!(!base.is_null());
  830. let mut expected = vec![0; N];
  831. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  832. let at = base.add(offset);
  833. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  834. at.write_bytes(value, 4096);
  835. expected[offset..offset + 4096].fill(value);
  836. }
  837. for remap in [false, true] {
  838. if remap {
  839. let mut old = 0;
  840. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  841. expected[..4096].fill(0);
  842. let at = base.add(1 << 16);
  843. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  844. at.write_bytes(0xc7, 4096);
  845. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  846. }
  847. let mut out = vec![0xee; N];
  848. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  849. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  850. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  851. }
  852. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  853. }
  854. }
  855. use super::*;
  856. #[test]
  857. fn warp_adapter_accepts_only_software() {
  858. // This probes DXGI without creating a D3D12 device or running a title.
  859. // SAFETY: plain DXGI adapter queries.
  860. let raw = unsafe {
  861. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  862. else {
  863. return;
  864. };
  865. factory.EnumWarpAdapter::<IDXGIAdapter>()
  866. };
  867. let Ok(raw) = raw else { return };
  868. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  869. // IDXGIAdapter1; `raw` owns that interface.
  870. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  871. eprintln!(
  872. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  873. desc.VendorId, desc.Flags
  874. );
  875. assert_eq!(
  876. warp_adapter().is_ok(),
  877. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  878. );
  879. }
  880. }
  881. /// The batches of clamped records in one scratch buffer
  882. /// ([`HostList::batch_place`]).
  883. const BATCHES: u32 = 8;
  884. /// A host command list and its allocator, always used together.
  885. pub(crate) struct HostList {
  886. allocator: ID3D12CommandAllocator,
  887. pub(crate) list: ID3D12GraphicsCommandList,
  888. /// Work for submission time, in recorded order.
  889. deferred: Mutex<Deferred>,
  890. /// Upload memory for data the list's draws make (expanded vertices),
  891. /// reused after a reset.
  892. scratch: Mutex<Scratch>,
  893. /// Host texture states the list assumes, by host copy: at its start and
  894. /// at its end. Lists are recorded on many threads and run in submission
  895. /// order, so the transitions from a texture's real state are made at
  896. /// submission, in `prelude`. Holding the copies keeps every texture the
  897. /// list names alive until it is reset, even if the title releases the
  898. /// resource first.
  899. states: Mutex<States>,
  900. /// What the list does with depth textures that have a colour twin, by
  901. /// twin ([`TwinUse`]).
  902. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  903. /// The list that runs those transitions just before this one, made
  904. /// when the list first has such transitions ([`lazy_prelude`]).
  905. prelude: OnceLock<Option<Prelude>>,
  906. /// The pipelines the list binds, for reports of slow submissions.
  907. pipelines: std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>,
  908. /// What its indirect executions ran, for the report of a removed device.
  909. #[cfg(feature = "diagnostics")]
  910. indirects: indirects::Shared,
  911. /// The work its indirect executions may still do (`indirect`): a
  912. /// shader-writable word, zeroed when the list is submitted, and after
  913. /// it what the clamp notes about mesh records. In memory the CPU maps.
  914. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  915. /// The same words in the card's own memory ([`card_budget`]), which the
  916. /// clamp uses instead when there is one: zeroed in the list before its
  917. /// first clamp, its notes copied to `budget` when the list closes.
  918. card_budget: OnceLock<Option<ID3D12Resource>>,
  919. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  920. /// grown to the largest indirect execution recorded on the list.
  921. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  922. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  923. /// how many batches of this recording have a place in them.
  924. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  925. /// Refreshes of host copies that a thread of ours is still finding, and
  926. /// where among the list's steps they belong ([`aside`]).
  927. coming: Mutex<Option<(usize, std::sync::Arc<aside::Coming>)>>,
  928. /// Counts the list in [`ALIVE`] while it lives.
  929. _alive: Counted,
  930. /// The texts of the markers `note_op` set, in order (for device-removed
  931. /// data without marker texts), with the host GPU range a copy reads.
  932. #[cfg(feature = "diagnostics")]
  933. notes: std::sync::Arc<Mutex<Vec<Note>>>,
  934. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  935. /// and at the end, and where they are read back.
  936. #[cfg(feature = "diagnostics")]
  937. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  938. }
  939. /// A list's prelude: an allocator and a closed list.
  940. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  941. /// Whether a host list's prelude is made when the list first needs one. A
  942. /// prelude runs the texture transitions and twin copies a list needs before
  943. /// it; lists that name no texture never have one, and every host list was
  944. /// made with one all the same: twice the host objects per list, for the
  945. /// title's 630 lists and for every list made anew.
  946. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  947. fn lazy_prelude() -> bool {
  948. static ON: OnceLock<bool> = OnceLock::new();
  949. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  950. }
  951. /// Timestamps per list (diagnostics); commands past them are not timed.
  952. #[cfg(feature = "diagnostics")]
  953. const STAMPS: u32 = 4096;
  954. /// A marker's text and the host range its command reads (diagnostics).
  955. #[cfg(feature = "diagnostics")]
  956. type Note = (String, Option<(u64, u64)>);
  957. type States = std::collections::HashMap<
  958. usize,
  959. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  960. >;
  961. /// What a list does with a depth texture that has a colour twin
  962. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  963. /// in submission order, so a list cannot know which side an earlier list
  964. /// leaves behind: it notes which sides it uses as it finds them, and its
  965. /// prelude copies one side into the other at submission if that side is
  966. /// behind then. From its first use of a side on, the list knows.
  967. struct TwinUse {
  968. /// The depth texture (the title resource's host copy) and its twin.
  969. depth: std::sync::Arc<crate::resource::HostTexture>,
  970. twin: std::sync::Arc<crate::resource::Twin>,
  971. /// The sides (depth texture, twin) the list uses as it finds them.
  972. needs: [bool; 2],
  973. /// Whether each side lacks what the other was written last, where the
  974. /// list is now; `None`: as the list found it.
  975. behind: [Option<bool>; 2],
  976. /// The draw or dispatch being prepared writes the twin.
  977. writing: bool,
  978. /// The depth plane's twin holds what the plane lacks although the list
  979. /// copied the twins since: the plane's pass waits for the list's close.
  980. late: bool,
  981. }
  982. /// The pass that draws the twin of a depth plane into the plane: one
  983. /// triangle over each mip of each slice, its pixel shader writing the
  984. /// twin's texel as the depth, with the depth test "always" and no stencil
  985. /// (the stencil plane is copied through a buffer and not touched here).
  986. ///
  987. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  988. /// the step times the float nearest 1/65535 (0x37800080). That is how
  989. /// The title's tiled lighting computes the depth of the
  990. /// rectangles it then draws with the test "equal", one class of materials
  991. /// a draw (all six of its vertex shaders multiply the class number by that
  992. /// constant), so the pass and the draw give the host the same float, and
  993. /// the host turns the same float into the same 24 bits. The step divided
  994. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  995. /// and lands in another 24-bit step for 127 of them (none under 385).
  996. const PLANE_CORNERS: &str = r#"
  997. float4 corner(uint i : SV_VertexID) : SV_Position {
  998. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  999. }
  1000. "#;
  1001. const PLANE_STEPS: &str = r#"
  1002. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  1003. Texture2DArray<uint> twin : register(t0);
  1004. [RootSignature(RS)]
  1005. float plane(float4 p : SV_Position) : SV_Depth {
  1006. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  1007. }
  1008. "#;
  1009. const PLANE_FLOATS: &str = r#"
  1010. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  1011. Texture2DArray<float> twin : register(t0);
  1012. [RootSignature(RS)]
  1013. float plane(float4 p : SV_Position) : SV_Depth {
  1014. return twin.Load(int4(int2(p.xy), 0, 0));
  1015. }
  1016. "#;
  1017. /// Views of twins the pass reads, in a heap of ours used as a ring.
  1018. /// shortcut: a view must last until its list has run; with one or two
  1019. /// passes a frame the ring is far from coming round.
  1020. const PLANE_VIEWS: u32 = 256;
  1021. /// What the pass draws with: the heap of its views of twins, and per kind
  1022. /// of twin (16-bit steps or floats) and depth format the root signature
  1023. /// and pipeline, made when first needed (`None`: the host refused).
  1024. struct PlanePass {
  1025. views: ID3D12DescriptorHeap,
  1026. cpu: usize,
  1027. gpu: u64,
  1028. step: u32,
  1029. next: AtomicU32,
  1030. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  1031. }
  1032. /// The pass's root signature and pipeline for one kind of twin and one
  1033. /// depth format.
  1034. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  1035. // SAFETY: D3D12 objects are free-threaded.
  1036. unsafe impl Send for PlanePass {}
  1037. // SAFETY: as above.
  1038. unsafe impl Sync for PlanePass {}
  1039. fn plane_pass() -> Option<&'static PlanePass> {
  1040. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  1041. PASS.get_or_init(|| {
  1042. let host = host()?;
  1043. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1044. // SAFETY: plain heap creation and queries.
  1045. unsafe {
  1046. let views: ID3D12DescriptorHeap = host
  1047. .device
  1048. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  1049. Type: kind,
  1050. NumDescriptors: PLANE_VIEWS,
  1051. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  1052. NodeMask: 0,
  1053. })
  1054. .ok()?;
  1055. Some(PlanePass {
  1056. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  1057. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  1058. step: host.device.GetDescriptorHandleIncrementSize(kind),
  1059. views,
  1060. next: AtomicU32::new(0),
  1061. made: Mutex::default(),
  1062. })
  1063. }
  1064. })
  1065. .as_ref()
  1066. }
  1067. /// Compiles function `entry` of `source` for `target` with the system's
  1068. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  1069. pub(crate) fn compile(
  1070. source: &str,
  1071. entry: windows::core::PCSTR,
  1072. target: windows::core::PCSTR,
  1073. ) -> windows::core::Result<Vec<u8>> {
  1074. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  1075. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  1076. let mut code: Option<ID3DBlob> = None;
  1077. let mut errors: Option<ID3DBlob> = None;
  1078. // SAFETY: the source and names live through the call; out pointers ours.
  1079. let compiled = unsafe {
  1080. D3DCompile(
  1081. source.as_ptr().cast(),
  1082. source.len(),
  1083. windows::core::s!("victory"),
  1084. None,
  1085. None,
  1086. entry,
  1087. target,
  1088. 0,
  1089. 0,
  1090. &mut code,
  1091. Some(&mut errors),
  1092. )
  1093. };
  1094. if let Err(e) = compiled {
  1095. if let Some(errors) = errors {
  1096. // SAFETY: the blob's own bytes.
  1097. let text = unsafe {
  1098. std::slice::from_raw_parts(
  1099. errors.GetBufferPointer().cast::<u8>(),
  1100. errors.GetBufferSize(),
  1101. )
  1102. };
  1103. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  1104. }
  1105. return Err(e);
  1106. }
  1107. let code = code.ok_or_else(windows::core::Error::empty)?;
  1108. // SAFETY: the blob's own bytes.
  1109. let bytes = unsafe {
  1110. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  1111. };
  1112. Ok(bytes.to_vec())
  1113. }
  1114. impl PlanePass {
  1115. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  1116. /// or of floats and the depth format `format`.
  1117. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  1118. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1119. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  1120. return pipeline.clone();
  1121. }
  1122. let pipeline = match Self::make(steps, format) {
  1123. Ok(pipeline) => Some(pipeline),
  1124. Err(e) => {
  1125. tracing::warn!(
  1126. error = %e,
  1127. steps,
  1128. format = format.0,
  1129. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  1130. );
  1131. None
  1132. }
  1133. };
  1134. made.push((steps, format.0, pipeline.clone()));
  1135. pipeline
  1136. }
  1137. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  1138. use windows::core::s;
  1139. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  1140. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  1141. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  1142. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  1143. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  1144. pShaderBytecode: bytes.as_ptr().cast(),
  1145. BytecodeLength: bytes.len(),
  1146. };
  1147. // SAFETY: the root signature is inside the pixel shader; the
  1148. // description points at live data and never releases its pointer.
  1149. unsafe {
  1150. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  1151. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1152. pRootSignature: std::mem::transmute_copy(&root),
  1153. VS: code(&vs[..]),
  1154. PS: code(&ps[..]),
  1155. SampleMask: u32::MAX,
  1156. RasterizerState: D3D12_RASTERIZER_DESC {
  1157. FillMode: D3D12_FILL_MODE_SOLID,
  1158. CullMode: D3D12_CULL_MODE_NONE,
  1159. DepthClipEnable: true.into(),
  1160. ..Default::default()
  1161. },
  1162. // Every texel is written; stencil stays off.
  1163. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1164. DepthEnable: true.into(),
  1165. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  1166. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1167. ..Default::default()
  1168. },
  1169. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1170. DSVFormat: format,
  1171. SampleDesc: DXGI_SAMPLE_DESC {
  1172. Count: 1,
  1173. Quality: 0,
  1174. },
  1175. ..Default::default()
  1176. };
  1177. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1178. Ok((root, pipeline))
  1179. }
  1180. }
  1181. }
  1182. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1183. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1184. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1185. /// heap, graphics root signature, pipeline, depth target, viewport,
  1186. /// scissor and topology and puts none of them back: it is for a list that
  1187. /// records nothing of the title's after it.
  1188. fn record_plane_pass(
  1189. list: &ID3D12GraphicsCommandList,
  1190. depth: &ID3D12Resource,
  1191. plane: &ID3D12Resource,
  1192. ) {
  1193. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1194. return;
  1195. };
  1196. // SAFETY: live resources.
  1197. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1198. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1199. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1200. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1201. let steps = twin.Format.0 == 53;
  1202. let format = DXGI_FORMAT(match of.Format.0 {
  1203. 44 => 45,
  1204. 19 => 20,
  1205. typed => typed,
  1206. });
  1207. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1208. return;
  1209. };
  1210. for slice in 0..u32::from(of.DepthOrArraySize) {
  1211. for mip in 0..u32::from(of.MipLevels) {
  1212. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1213. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1214. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1215. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1216. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1217. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1218. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1219. MostDetailedMip: mip,
  1220. MipLevels: 1,
  1221. FirstArraySlice: slice,
  1222. ArraySize: 1,
  1223. ..Default::default()
  1224. },
  1225. },
  1226. };
  1227. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1228. Format: format,
  1229. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1230. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1231. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1232. MipSlice: mip,
  1233. FirstArraySlice: slice,
  1234. ArraySize: 1,
  1235. },
  1236. },
  1237. ..Default::default()
  1238. };
  1239. let target = host.dsv(depth, Some(&target));
  1240. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1241. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1242. ptr: pass.cpu + (slot * pass.step) as usize,
  1243. };
  1244. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1245. ptr: pass.gpu + u64::from(slot * pass.step),
  1246. };
  1247. // SAFETY: an open list; a slot of our heap; live resources and
  1248. // objects (the pass's own live as long as the process).
  1249. unsafe {
  1250. host.device
  1251. .CreateShaderResourceView(plane, Some(&view), cpu);
  1252. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1253. list.SetGraphicsRootSignature(&root);
  1254. list.SetPipelineState(&pipeline);
  1255. list.SetGraphicsRootDescriptorTable(0, gpu);
  1256. list.OMSetRenderTargets(0, None, false, Some(&target));
  1257. list.RSSetViewports(&[D3D12_VIEWPORT {
  1258. TopLeftX: 0.0,
  1259. TopLeftY: 0.0,
  1260. Width: width as f32,
  1261. Height: height as f32,
  1262. MinDepth: 0.0,
  1263. MaxDepth: 1.0,
  1264. }]);
  1265. list.RSSetScissorRects(&[RECT {
  1266. left: 0,
  1267. top: 0,
  1268. right: width as i32,
  1269. bottom: height as i32,
  1270. }]);
  1271. list.IASetPrimitiveTopology(
  1272. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1273. );
  1274. list.DrawInstanced(3, 1, 0, 0);
  1275. }
  1276. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1277. }
  1278. }
  1279. }
  1280. /// Records into `list` the copy of a depth texture into its colour twin
  1281. /// (`colour`) or of the twin into the depth texture, both already in their
  1282. /// copy states: whole textures of one size in one format family, which the
  1283. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1284. /// alone, through the twin's buffer.
  1285. fn record_twin_copy(
  1286. list: &ID3D12GraphicsCommandList,
  1287. depth: &ID3D12Resource,
  1288. twin: &crate::resource::Twin,
  1289. colour: bool,
  1290. ) {
  1291. let (from, to) = if colour {
  1292. (depth, &twin.colour.texture)
  1293. } else {
  1294. (&twin.colour.texture, depth)
  1295. };
  1296. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1297. // shortcut: the depth plane's twin is not given the plane (that is a
  1298. // pass the other way: the plane read by a shader, the twin as its
  1299. // target). The twin then lacks what draws and clears wrote to the
  1300. // plane since shaders last wrote the twin. In the title
  1301. // nothing writes that plane but the twin's pass (its 192 draws against
  1302. // it only test, run 29), so the twin lacks nothing. Counted.
  1303. if colour && twin.plane.is_some() {
  1304. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1305. }
  1306. let Some(through) = &twin.through else {
  1307. // SAFETY: an open list and two live textures.
  1308. unsafe { list.CopyResource(to, from) };
  1309. return;
  1310. };
  1311. // A stencil plane and its twin: each mip and slice of the plane goes
  1312. // into the buffer, laid out as the host lays the plane out for copies,
  1313. // and from the buffer into the other texture, whole subresources both
  1314. // times. In the depth texture the stencil plane's subresources follow
  1315. // the depth plane's; the twin has the one plane.
  1316. let Some(host) = host() else { return };
  1317. // SAFETY: a live texture.
  1318. let of = unsafe { depth.GetDesc() };
  1319. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1320. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1321. // SAFETY: a plain query writing `planes` footprints.
  1322. unsafe {
  1323. host.device.GetCopyableFootprints(
  1324. &of,
  1325. planes,
  1326. planes,
  1327. 0,
  1328. Some(rows.as_mut_ptr()),
  1329. None,
  1330. None,
  1331. None,
  1332. );
  1333. }
  1334. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1335. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1336. // SAFETY: a borrowed pointer the location never releases.
  1337. pResource: unsafe { std::mem::transmute_copy(texture) },
  1338. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1339. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1340. SubresourceIndex: index,
  1341. },
  1342. };
  1343. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1344. // SAFETY: as above.
  1345. pResource: unsafe { std::mem::transmute_copy(through) },
  1346. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1347. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1348. PlacedFootprint: *row,
  1349. },
  1350. };
  1351. let (common, source, dest) = (
  1352. D3D12_RESOURCE_STATE_COMMON,
  1353. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1354. D3D12_RESOURCE_STATE_COPY_DEST,
  1355. );
  1356. // SAFETY: an open list and live resources; the buffer was made as big
  1357. // as these footprints, and rests in the common state between copies.
  1358. unsafe {
  1359. list.ResourceBarrier(&[transition(through, common, dest)]);
  1360. for (i, row) in rows.iter().enumerate() {
  1361. let index = first_from + i as u32;
  1362. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1363. }
  1364. list.ResourceBarrier(&[transition(through, dest, source)]);
  1365. for (i, row) in rows.iter().enumerate() {
  1366. let index = first_to + i as u32;
  1367. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1368. }
  1369. list.ResourceBarrier(&[transition(through, source, common)]);
  1370. }
  1371. }
  1372. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1373. /// builds).
  1374. pub(crate) fn dred_on() -> bool {
  1375. static ON: OnceLock<bool> = OnceLock::new();
  1376. *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED") && !dred_faults() && !dred_light())
  1377. }
  1378. /// Breadcrumbs and the faulting address, but no markers and no texts
  1379. /// (`VICTORY_D3D12_DRED=light`): which list a removed device stopped in, at
  1380. /// which of its commands, and the pipelines the list binds; formatting a text
  1381. /// for every command is what makes the whole of it slow.
  1382. pub(crate) fn dred_light() -> bool {
  1383. static ON: OnceLock<bool> = OnceLock::new();
  1384. *ON.get_or_init(|| {
  1385. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "light")
  1386. })
  1387. }
  1388. /// Any of the three.
  1389. pub(crate) fn dred_any() -> bool {
  1390. dred_on() || dred_light() || dred_faults()
  1391. }
  1392. /// Whether only the faulting address of a removed device is kept
  1393. /// (`VICTORY_D3D12_DRED=faults`): no breadcrumbs, no markers and no texts, so
  1394. /// it costs next to nothing and can stay on while the title is played.
  1395. pub(crate) fn dred_faults() -> bool {
  1396. static ON: OnceLock<bool> = OnceLock::new();
  1397. *ON.get_or_init(|| {
  1398. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "faults")
  1399. })
  1400. }
  1401. /// The lists alive while device-removed data is on, by the number their name
  1402. /// ends in, with their marker texts and the pipelines they bind: a report made
  1403. /// on another thread than the one that submits has no lists of its own.
  1404. #[cfg(feature = "diagnostics")]
  1405. #[allow(clippy::type_complexity)]
  1406. static LIST_NOTES: Mutex<
  1407. std::collections::BTreeMap<
  1408. u32,
  1409. (
  1410. std::sync::Weak<Mutex<Vec<Note>>>,
  1411. std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>,
  1412. std::sync::Weak<Mutex<indirects::Indirects>>,
  1413. ),
  1414. >,
  1415. > = Mutex::new(std::collections::BTreeMap::new());
  1416. /// The number in the name of a list of ours ("victory host list 7", which the
  1417. /// debug layer ends with a note of its own in brackets).
  1418. #[cfg(feature = "diagnostics")]
  1419. fn list_number(name: &str) -> Option<u32> {
  1420. let rest = name.strip_prefix("victory host list ")?;
  1421. let digits = rest.split(' ').next()?;
  1422. (rest.len() == digits.len() || rest[digits.len()..].starts_with(" (")).then(|| digits.parse().ok()).flatten()
  1423. }
  1424. /// Indirect mesh dispatches since the last frame line: the largest group
  1425. /// count a record asked for, and the groups asked in all (from the lists'
  1426. /// budget buffers, a run late).
  1427. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1428. /// Whether a list's indirect-work budget lives in the card's own memory
  1429. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1430. /// before). The clamp charges it with atomics, at least two in a row for
  1431. /// every clamp; in mapped memory on a card of its own each of them
  1432. /// crosses the bus.
  1433. fn card_budget() -> bool {
  1434. static ON: OnceLock<bool> = OnceLock::new();
  1435. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1436. }
  1437. /// Whether each list of a submission runs and is timed on its own, slow
  1438. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1439. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1440. #[cfg(feature = "diagnostics")]
  1441. fn timing() -> bool {
  1442. static ON: OnceLock<bool> = OnceLock::new();
  1443. *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING"))
  1444. }
  1445. /// Names a host object for the device-removed report, which names the
  1446. /// allocations a page fault hit (only with device-removed data on), or for
  1447. /// the frame recorder (`VICTORY_RECORD`).
  1448. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1449. #[cfg(feature = "diagnostics")]
  1450. if crate::book::on()
  1451. && let Ok(resource) = object.cast::<ID3D12Resource>()
  1452. {
  1453. let text = text();
  1454. crate::book::made(&resource, || text.clone());
  1455. return name_it(object, || text);
  1456. }
  1457. name_it(object, text);
  1458. }
  1459. fn name_it(object: &impl Interface, text: impl FnOnce() -> String) {
  1460. #[cfg(feature = "diagnostics")]
  1461. if crate::replay::record::on() {
  1462. let text = text();
  1463. crate::replay::record::name(object, &text);
  1464. if dred_any()
  1465. && let Ok(object) = object.cast::<ID3D12Object>()
  1466. {
  1467. // SAFETY: a plain call on a live object.
  1468. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1469. }
  1470. return;
  1471. }
  1472. if dred_any()
  1473. && let Ok(object) = object.cast::<ID3D12Object>()
  1474. {
  1475. // SAFETY: a plain call on a live object.
  1476. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1477. }
  1478. }
  1479. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1480. /// [`LISTS`]`[3]` until it is first reset.
  1481. struct Counted {
  1482. /// Not reset since it was made.
  1483. fresh: std::sync::atomic::AtomicBool,
  1484. }
  1485. impl Counted {
  1486. fn new() -> Counted {
  1487. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1488. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1489. Counted {
  1490. fresh: std::sync::atomic::AtomicBool::new(true),
  1491. }
  1492. }
  1493. /// The list is reset: it is in use.
  1494. fn used(&self) {
  1495. if self.fresh.swap(false, Ordering::Relaxed) {
  1496. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1497. }
  1498. }
  1499. }
  1500. impl Drop for Counted {
  1501. fn drop(&mut self) {
  1502. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1503. self.used();
  1504. }
  1505. }
  1506. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1507. /// mapping.
  1508. struct Chunk {
  1509. buffer: ID3D12Resource,
  1510. data: usize,
  1511. }
  1512. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1513. // written only by the list that holds the chunk.
  1514. unsafe impl Send for Chunk {}
  1515. /// Upload chunks handed out front to back: the chunks (each with its
  1516. /// bytes), the one in use and the bytes used in it.
  1517. #[derive(Default)]
  1518. struct Scratch {
  1519. chunks: Vec<(Chunk, u64)>,
  1520. current: usize,
  1521. used: u64,
  1522. }
  1523. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1524. unsafe impl Send for Scratch {}
  1525. impl Drop for Scratch {
  1526. fn drop(&mut self) {
  1527. give_chunks(std::mem::take(&mut self.chunks));
  1528. }
  1529. }
  1530. const SCRATCH_CHUNK: u64 = 4 << 20;
  1531. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1532. /// lists put a few constants or a rectangle's corners there, and every
  1533. /// list that did took 4 MiB of the PC's memory for it.
  1534. const SCRATCH_FIRST: u64 = 256 << 10;
  1535. /// The most bytes of chunks kept while no list holds them.
  1536. const SPARE_MOST: u64 = 128 << 20;
  1537. /// The same with [`keep_freed`].
  1538. const SPARE_KEPT: u64 = 1 << 30;
  1539. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1540. /// first needs one, a small one first, and gives all of them back when it
  1541. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1542. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1543. /// host lists of held submissions, which live for one submission, each
  1544. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1545. /// freed per frame of gameplay (run 60).
  1546. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1547. fn scratch_pool() -> bool {
  1548. static ON: OnceLock<bool> = OnceLock::new();
  1549. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1550. }
  1551. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1552. /// for one of the same size.
  1553. struct Spare<T> {
  1554. kept: Vec<(T, u64)>,
  1555. bytes: u64,
  1556. }
  1557. impl<T> Spare<T> {
  1558. const fn new() -> Self {
  1559. Spare { kept: Vec::new(), bytes: 0 }
  1560. }
  1561. /// A kept thing of `size` bytes, the one given last.
  1562. fn take(&mut self, size: u64) -> Option<T> {
  1563. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1564. self.bytes -= size;
  1565. Some(self.kept.remove(at).0)
  1566. }
  1567. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1568. /// `most`: then it comes back.
  1569. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1570. if self.bytes + size > most {
  1571. return Some(thing);
  1572. }
  1573. self.bytes += size;
  1574. self.kept.push((thing, size));
  1575. None
  1576. }
  1577. }
  1578. /// Scratch chunks no list holds.
  1579. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1580. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1581. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1582. if scratch_pool()
  1583. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1584. {
  1585. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1586. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1587. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1588. return Some(chunk);
  1589. }
  1590. let (buffer, data) = host.upload_buffer(size)?;
  1591. name(&buffer, || "list scratch".into());
  1592. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1593. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1594. Some(Chunk {
  1595. buffer,
  1596. data: data as usize,
  1597. })
  1598. }
  1599. /// A list is done with `chunks` (it was reset after its submissions ran,
  1600. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1601. /// without the pool.
  1602. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1603. if chunks.is_empty() {
  1604. return;
  1605. }
  1606. let mut freed = Vec::new();
  1607. {
  1608. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1609. for (chunk, size) in chunks {
  1610. let back = if scratch_pool() {
  1611. spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST })
  1612. } else {
  1613. Some(chunk)
  1614. };
  1615. match back {
  1616. None => {
  1617. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1618. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1619. }
  1620. Some(chunk) => {
  1621. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1622. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1623. freed.push(chunk);
  1624. }
  1625. }
  1626. }
  1627. }
  1628. // Freed outside the lock.
  1629. drop(freed);
  1630. }
  1631. /// What the host keeps for copies in the card's own memory
  1632. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1633. struct CardWork {
  1634. /// Before a submission's lists: what changed on the copies' CPU side
  1635. /// goes to their card side. Those not in use: a plan takes one and
  1636. /// gives it back when its submission has run (`Host::card_done`), so
  1637. /// that submissions sent ahead ([`late`]) each have their own.
  1638. sync: Vec<Prelude>,
  1639. /// After them, in the same submission: the compare of the declared
  1640. /// ranges with their bytes from before. As `sync`.
  1641. check: Vec<Prelude>,
  1642. /// After it ran: the pieces that differ come down.
  1643. fetch: Prelude,
  1644. root: ID3D12RootSignature,
  1645. pso: ID3D12PipelineState,
  1646. /// One dword per piece compared, odd where the piece differs: PC
  1647. /// memory, mapped (buffer, mapping, bytes).
  1648. differs: (ID3D12Resource, usize, u64),
  1649. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1650. fetched: Option<(ID3D12Resource, usize, u64)>,
  1651. /// The dwords of `differs` taken by plans whose results were not read
  1652. /// yet.
  1653. taken: u32,
  1654. /// Plans made and not done with (`Host::card_done`).
  1655. out: u32,
  1656. }
  1657. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1658. // under the submission lock.
  1659. unsafe impl Send for CardWork {}
  1660. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1661. /// The compare of a declared range of a copy in the card's memory with
  1662. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1663. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1664. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1665. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1666. /// byte just outside the range costs a fetch that finds nothing.
  1667. ///
  1668. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1669. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1670. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1671. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1672. /// those steps.
  1673. pub(crate) const CARD_COMPARE: &str = r#"
  1674. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1675. cbuffer Span : register(b0) {
  1676. uint first; // the first piece
  1677. uint skew; // where the copy starts in its piece 0
  1678. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1679. uint pieces;
  1680. uint out_at; // the first piece's dword in `differs`, in bytes
  1681. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1682. };
  1683. ByteAddressBuffer now : register(t0);
  1684. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1685. // last sent up (or hashed whole, the first time).
  1686. RWByteAddressBuffer hashes : register(u0);
  1687. RWByteAddressBuffer differs : register(u1);
  1688. groupshared uint4 parts[64];
  1689. [RootSignature(RS)]
  1690. [numthreads(64, 1, 1)]
  1691. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1692. uint piece = first + id.x;
  1693. uint lo = piece * 65536u;
  1694. lo = lo > skew ? lo - skew : 0u;
  1695. uint hi = min((piece + 1u) * 65536u - skew, size);
  1696. lo = lo & ~15u;
  1697. hi = (hi + 15u) & ~15u;
  1698. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1699. [loop]
  1700. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1701. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1702. h = h.yzwx ^ (h >> 15);
  1703. }
  1704. parts[thread] = h;
  1705. GroupMemoryBarrierWithGroupSync();
  1706. if (thread != 0u) return;
  1707. h = parts[0];
  1708. [loop]
  1709. for (uint i = 1u; i < 64u; ++i) {
  1710. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1711. h = h.yzwx ^ (h >> 15);
  1712. }
  1713. if (compare != 0u) {
  1714. // The flag, and above it 31 bits of the hash (`torn`).
  1715. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1716. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1717. // With the copy-back on its own thread: the next compare of the
  1718. // piece finds what is written from here on.
  1719. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1720. } else {
  1721. hashes.Store4(piece * 16u, h);
  1722. }
  1723. }
  1724. "#;
  1725. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1726. #[cfg(test)]
  1727. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1728. torn::hash(bytes)
  1729. }
  1730. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1731. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1732. /// parts a dispatch can hold.
  1733. ///
  1734. /// # Safety
  1735. /// The list is open with the compare's root signature, pipeline and buffers
  1736. /// set, and the pieces lie in the buffer.
  1737. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1738. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1739. let mut done = 0;
  1740. while done < span.pieces {
  1741. let n = (span.pieces - done).min(MOST);
  1742. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1743. // SAFETY: the caller's.
  1744. unsafe {
  1745. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1746. list.Dispatch(n, 1, 1);
  1747. }
  1748. done += n;
  1749. }
  1750. }
  1751. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1752. /// the card's memory are hashed in runs of pieces that touch, each piece
  1753. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1754. /// per range sent up.
  1755. ///
  1756. /// These passes are ours, they run on the card before every submission's
  1757. /// lists: a pass takes the time of one piece however few its pieces are.
  1758. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1759. /// a piece hashed when it need not be, or not hashed when it should, costs
  1760. /// a fetch that finds nothing and loses no shader write.
  1761. fn rehash_runs() -> bool {
  1762. static ON: OnceLock<bool> = OnceLock::new();
  1763. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1764. }
  1765. /// Since the last frame-rate line, of our own passes over copies in the
  1766. /// card's memory: hash passes after ranges were sent up, the pieces they
  1767. /// hashed, and compare passes after the lists.
  1768. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1769. /// Whether what shaders wrote to copies in the card's memory is merged
  1770. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1771. /// default). The pieces the card's compare found differing come down in
  1772. /// one fetch and were then merged one after the other on the thread that
  1773. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1774. /// with the copy's CPU side byte by byte and put into title memory through
  1775. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1776. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1777. /// landings do not come here: `crate::land` has threads of its own.)
  1778. fn wide_merge() -> bool {
  1779. static ON: OnceLock<bool> = OnceLock::new();
  1780. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1781. }
  1782. /// One declared range of a copy in the card's memory, in a submission.
  1783. struct CardRange {
  1784. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1785. /// As declared (title addresses), for the statistics.
  1786. declared: (usize, usize),
  1787. span: crate::shadow::CardSpan,
  1788. /// Its first piece's dword in the compare's results.
  1789. at: u32,
  1790. /// Whether the card compares it; else every piece is fetched.
  1791. compared: bool,
  1792. /// Looked at by `crate::picked`, and not declared: what is found changed
  1793. /// there was written through a view nobody declared. Not landed.
  1794. picked: bool,
  1795. }
  1796. impl CardPlan {
  1797. /// `crate::picked` is told where what it looked at changed, by the
  1798. /// compare's results.
  1799. fn picked_found(&self, differs: &[u32]) {
  1800. for r in self.ranges.iter().filter(|r| r.picked) {
  1801. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1802. if let Some(p) = changed {
  1803. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1804. }
  1805. }
  1806. }
  1807. }
  1808. /// What a submission does for copies in the card's memory.
  1809. struct CardPlan {
  1810. ranges: Vec<CardRange>,
  1811. /// The compare, run after the submission's lists.
  1812. check: Option<ID3D12CommandList>,
  1813. /// The copies whose card side was brought up to date, alive until the
  1814. /// submission has run.
  1815. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1816. /// The lists of ours the plan recorded (whether the compare, the
  1817. /// list), given back by `Host::card_done`.
  1818. lists: Vec<(bool, Prelude)>,
  1819. /// With [`relay`]: the number of the send to copies in the card's memory
  1820. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1821. sent_as: u64,
  1822. /// With [`upcheck`]: the look at what it sent up.
  1823. looks: Option<upcheck::Looks>,
  1824. /// With [`send`]: the memory its sends come from.
  1825. sends: Option<send::Memory>,
  1826. }
  1827. /// One piece of submission-time work, in recorded order.
  1828. enum Step {
  1829. /// A copy into title memory (destination, source, bytes): the title's
  1830. /// buffer copies, which later refreshes must see.
  1831. Copy(usize, usize, usize),
  1832. /// A copy of title memory into the list's own upload memory, and how
  1833. /// the card could bring the bytes instead.
  1834. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  1835. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1836. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1837. /// intervenes.
  1838. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1839. /// Work that may write title memory.
  1840. Run(Box<dyn Fn() + Send>),
  1841. /// Work that writes host memory only, and the title memory it reads
  1842. /// (from, to; empty for none).
  1843. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1844. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1845. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1846. /// Brings a texture's staging buffer up to date: once per submission,
  1847. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1848. Texture(std::sync::Arc<crate::texture::Staging>),
  1849. /// A title buffer copy that the list does on the card ([`place`]): what
  1850. /// is done on the CPU for it.
  1851. Placed(place::Placed),
  1852. }
  1853. /// What a list does on the CPU when it is submitted: copies between host
  1854. /// memory regions (title buffers, upload buffers and buffer copies), and
  1855. /// the upload buffers its GPU commands read, kept until the list is reset.
  1856. #[derive(Default)]
  1857. struct Deferred {
  1858. /// Destination, source, bytes.
  1859. copies: Vec<Step>,
  1860. uploads: Vec<ID3D12Resource>,
  1861. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1862. upload_bytes: u64,
  1863. /// Host objects the list's commands name (pipelines, root signatures,
  1864. /// descriptor heaps): the title may release its objects before it
  1865. /// submits the list.
  1866. kept: Vec<windows::core::IUnknown>,
  1867. /// Buffer ranges refreshed since the last title copy (host copy,
  1868. /// address, bytes): refreshing them again would find the same bytes.
  1869. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1870. /// Textures whose contents the list brings up to date.
  1871. textures: std::collections::HashSet<usize>,
  1872. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1873. /// bytes.
  1874. writes: Vec<(usize, crate::queue::Written, usize)>,
  1875. /// Textures read back (texture to buffer copies), done once the list
  1876. /// has run: the host buffer the list copies the texels into, the title
  1877. /// memory they go to, the bytes of a row, the rows, the title's row
  1878. /// pitch.
  1879. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1880. /// Whether the indirect-work budget is zeroed for this recording (a
  1881. /// step on the CPU, or in the list for the card's copy).
  1882. budget_zeroed: bool,
  1883. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1884. /// interface pointer) that a clamp in this recording left readable as
  1885. /// indirect arguments; 0 if none. It stays readable until the next
  1886. /// clamp into it ([`HostList::indirect_state`]).
  1887. indirect_readable: usize,
  1888. }
  1889. impl Deferred {
  1890. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1891. /// reset.
  1892. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1893. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1894. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1895. self.upload_bytes += size;
  1896. self.uploads.push(buffer);
  1897. }
  1898. }
  1899. impl Drop for Deferred {
  1900. fn drop(&mut self) {
  1901. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1902. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1903. }
  1904. }
  1905. /// Whether a queue's submissions go to the card without a wait for each
  1906. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1907. /// waits for every list on its own).
  1908. ///
  1909. /// Every submission was prepared, sent, waited for and copied back before
  1910. /// the next one was looked at, so the card stood idle while we prepared
  1911. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1912. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1913. /// other, on the one thread that submits.
  1914. ///
  1915. /// With the switch a queue's submission is sent and joins a line of
  1916. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1917. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1918. /// for the card, what their shaders wrote copied back once per byte, then
  1919. /// their bottom-of-pipe writes and the fence signals behind them, in
  1920. /// order) at the next point where the title, or our own preparing, can
  1921. /// observe what they do. Those points, exactly:
  1922. ///
  1923. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1924. /// read-back or map of a texture, a clear or upload run at once;
  1925. /// 2. the next submission reads title memory that a flight's shaders may
  1926. /// write: a title buffer copy, a fill of upload memory, a texture's
  1927. /// memory, any step that runs code of ours on title memory
  1928. /// ([`late_blocked`]);
  1929. /// 3. the next submission refreshes a range of a host copy that a flight's
  1930. /// shaders may write, and the title wrote a page of it since it was last
  1931. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1932. /// alone until the flight's writes are back, as it always did within a
  1933. /// submission;
  1934. /// 4. a queue stands at a wait for a memory value that no flight's
  1935. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1936. /// write ([`late_met`]);
  1937. /// 5. the title blocks on a fence without an event;
  1938. /// 6. the card has run every flight (a thread of ours waits for that:
  1939. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1940. ///
  1941. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1942. /// when the card has really run the work, later than before and never
  1943. /// earlier; a fence signalled on a queue while flights are in the air is
  1944. /// set behind them. A wait for a memory value that a flight's
  1945. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1946. /// the card behind that flight, which is the order the wait asks for.
  1947. ///
  1948. /// What it assumes beyond today: memory the title rewrites between two of
  1949. /// its submissions, without waiting for the first, may be seen by the
  1950. /// first's shaders (as on the console, where the card reads title memory
  1951. /// when it runs, not when the list is submitted).
  1952. pub(crate) fn late() -> bool {
  1953. late_stage() > 0
  1954. }
  1955. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1956. fn late_stage() -> u8 {
  1957. static STAGE: OnceLock<u8> = OnceLock::new();
  1958. *STAGE.get_or_init(|| {
  1959. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1960. return 0;
  1961. }
  1962. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1963. Ok("1") => 1,
  1964. Ok("2") => 2,
  1965. Ok("3") => 3,
  1966. // The relay alone: on top of stage 3.
  1967. Err(_) if crate::shadow::relay() => 3,
  1968. _ => 0,
  1969. }
  1970. })
  1971. }
  1972. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1973. /// longer a point. Where the title wrote a page that lies in a range a
  1974. /// flight's shaders may write, the bytes the title changed are found (the
  1975. /// page as it is now against what the copy held when the flight was
  1976. /// prepared) and put into the copy, and only those: what the flight's
  1977. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1978. /// flights are settled for it only where that cannot be done: memory that
  1979. /// is not write-watched, or a copy in the card's memory with more changed
  1980. /// runs than a submission should send up one by one.
  1981. ///
  1982. /// In run 92 (stage 1) this point settled the flights five times a frame
  1983. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1984. /// frame of waiting were left of 200.
  1985. ///
  1986. /// What differs from settling first: a byte both the title and a flight's
  1987. /// shader wrote is the title's if the shader wrote it first, the shader's
  1988. /// if it wrote it afterwards; settled first it was always the shader's.
  1989. /// The title writing a byte a shader of its own is writing is a race on
  1990. /// the console too.
  1991. fn late_exact() -> bool {
  1992. late_stage() > 1
  1993. }
  1994. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1995. /// no longer a point where flights are settled). The copy to the back
  1996. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1997. /// its own for each present in the air) and the swap chain is told to
  1998. /// present behind it; the queue's call returns, and the card finishes the
  1999. /// frame while the title records the next one. What the title is told
  2000. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  2001. /// has run it, by the settling thread.
  2002. ///
  2003. /// What is left out with it: the look whether the presented frame is black
  2004. /// (diagnostics; it reads the frame back at once). A frame that is saved
  2005. /// or listed is presented the old way. Once every second and a half a
  2006. /// submission settles the flights all the same, for the sweep that lets
  2007. /// idle host objects go (it needs nothing in the air).
  2008. pub(crate) fn late_free_present() -> bool {
  2009. late_stage() > 2
  2010. }
  2011. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  2012. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  2013. /// and is off with it, in the timing run and with kept snapshots).
  2014. ///
  2015. /// With [`late`] alone every settle does three things on the thread that
  2016. /// holds the submission lock: it waits for everything in the air, copies
  2017. /// back with the card standing, and only then goes on preparing. The frame
  2018. /// stays a relay: the card works about 242 ms of it and one thread
  2019. /// prepares, waits and copies back for about 220.
  2020. ///
  2021. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  2022. /// soon as the card has run them, in the order they were sent and without
  2023. /// the submission lock: it fetches and merges what their shaders wrote to
  2024. /// copies in the card's memory, compares and merges the other copies,
  2025. /// frees the flights' ranges, and then does their read-backs, their
  2026. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  2027. /// order. The submitting thread meanwhile prepares and sends the next
  2028. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  2029. /// that thread has landed everything in the air, at the same points as
  2030. /// before (the list in [`late`]), so whoever can observe title memory, a
  2031. /// fence or a present still does so only after the flights before it are
  2032. /// merged.
  2033. ///
  2034. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  2035. /// flight; a merge that never stores into memory the card may be writing;
  2036. /// sends to card copies numbered) and here: flights land in the order of
  2037. /// [`LINE`] by one thread, so a later flight's results never reach title
  2038. /// memory before an earlier flight's; the compare on the card stores the
  2039. /// hash it made, so each flight's compare flags exactly what changed since
  2040. /// the compare before it, however late the pieces are fetched; the fetch
  2041. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  2042. /// title bytes the card had received when it ran.
  2043. pub(crate) fn relay() -> bool {
  2044. static ON: OnceLock<bool> = OnceLock::new();
  2045. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  2046. }
  2047. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  2048. /// title memory a flight's shaders may write (a title buffer copy, a fill
  2049. /// of upload memory, a texture) waits only until the flights that declared
  2050. /// that memory have landed, not for everything in the air; and at
  2051. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  2052. /// both wait for everything.
  2053. fn relay_exact() -> bool {
  2054. static ON: OnceLock<bool> = OnceLock::new();
  2055. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  2056. // since the walls of the first room were found drawn in every run with
  2057. // this set and in fewer than half without it).
  2058. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  2059. }
  2060. /// Whether the pieces the relay fetches from the card's memory come over the
  2061. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  2062. /// draws.
  2063. ///
  2064. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  2065. /// and with the relay that is most of a frame: the thread that lands flights
  2066. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  2067. /// a few milliseconds of copying, and everything that waits for a landing
  2068. /// (the title's fences, reads of memory flights may write) waited with it.
  2069. ///
  2070. /// What changes: the fetch runs when its flights are done and beside later
  2071. /// submissions, so of the sends of title bytes it is only known to have run
  2072. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  2073. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  2074. /// the title's, newer than what the flights wrote. A later flight's bytes
  2075. /// may be in what is fetched, as before.
  2076. fn relay_copy() -> bool {
  2077. static ON: OnceLock<bool> = OnceLock::new();
  2078. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  2079. }
  2080. /// Told when something joins [`LINE`], for the thread that lands flights
  2081. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  2082. /// what queues hold.
  2083. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2084. /// Told when flights have landed ([`relay`]): who waits for that looks
  2085. /// again.
  2086. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  2087. /// With [`relay`], the order of what we put on the queue: the number of
  2088. /// sends of changed ranges to copies in the card's memory so far
  2089. /// (`Host::card_before`). Held from the taking of the ranges until their
  2090. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  2091. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  2092. /// later one.
  2093. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  2094. /// Since the last frame-rate line, of the thread that lands flights
  2095. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  2096. /// card with nothing to land, microseconds it waited for fetches of card
  2097. /// copies' pieces, microseconds of landing in all.
  2098. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  2099. /// Of the line's things in order (a flight: the value signalled on the
  2100. /// host's fence behind it; a write or a signal behind a flight: `None`):
  2101. /// how many, from the front, can be landed when the card has reached
  2102. /// `completed`: everything ahead of the first flight it has not run. A
  2103. /// later flight never lands before an earlier one, and what follows a
  2104. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  2105. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  2106. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  2107. }
  2108. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  2109. /// holds, for every piece of every range of the plan, the copy, the
  2110. /// piece's number in the copy and whether the compare flagged it there (or
  2111. /// did not run). The pieces to fetch, under whichever range, in order: all
  2112. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  2113. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  2114. /// the hash, so the second of them may find it stored already and not
  2115. /// flag it.
  2116. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  2117. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  2118. pieces.sort_unstable();
  2119. pieces.dedup();
  2120. pieces
  2121. }
  2122. #[cfg(test)]
  2123. mod relay_tests {
  2124. use super::{flagged_pieces, landable};
  2125. /// Two flights and what follows each: nothing of the second lands
  2126. /// before the card has run it, and nothing behind a flight lands
  2127. /// before the flight.
  2128. #[test]
  2129. fn flights_land_in_the_order_they_were_sent() {
  2130. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  2131. let line = [Some(5), None, None, Some(6), None];
  2132. assert_eq!(landable(&line, 4), 0);
  2133. assert_eq!(landable(&line, 5), 3);
  2134. assert_eq!(landable(&line, 6), 5);
  2135. assert_eq!(landable(&line, u64::MAX), 5);
  2136. // Signals with no flight ahead land at once; behind one they wait.
  2137. assert_eq!(landable(&[None, None], 0), 2);
  2138. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  2139. assert_eq!(landable(&[], 3), 0);
  2140. // After the first three landed, the rest when its turn comes.
  2141. assert_eq!(landable(&line[3..], 5), 0);
  2142. assert_eq!(landable(&line[3..], 6), 2);
  2143. }
  2144. /// A piece flagged under one range of a plan is fetched under every
  2145. /// range that holds a part of it; pieces of other copies are not.
  2146. #[test]
  2147. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  2148. let (a, b) = (0x1000usize, 0x2000usize);
  2149. // Copy a: piece 3 under two ranges, flagged under the first only;
  2150. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  2151. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  2152. let fetch = flagged_pieces(&flags);
  2153. assert!(fetch.contains(&(a, 3)));
  2154. assert!(!fetch.contains(&(a, 4)));
  2155. assert!(!fetch.contains(&(b, 3)));
  2156. assert!(fetch.contains(&(b, 9)));
  2157. assert_eq!(fetch.len(), 2);
  2158. }
  2159. }
  2160. /// The most host lists in the air before the flights are settled
  2161. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  2162. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  2163. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  2164. /// 32 settled the flights three times a
  2165. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  2166. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  2167. /// descriptor slots, upload
  2168. /// memory and scratch chunks are held until then, and a frame's lists held
  2169. /// all at once ran the slots out before (run 45).
  2170. fn late_most() -> usize {
  2171. static MOST: OnceLock<usize> = OnceLock::new();
  2172. *MOST.get_or_init(|| {
  2173. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  2174. })
  2175. }
  2176. /// Whether a submission with bottom-of-pipe writes may fly
  2177. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  2178. /// the title is told at once, as before; for telling a title that polls
  2179. /// such a value from one that does not).
  2180. fn late_writes() -> bool {
  2181. static ON: OnceLock<bool> = OnceLock::new();
  2182. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  2183. }
  2184. /// Per host copy, the ranges a submission's shaders may write, as declared
  2185. /// (address, end).
  2186. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  2187. /// What [`Host::submit`] hands back for a submission it sent and did not
  2188. /// wait for.
  2189. struct Sent {
  2190. /// Its number among the submissions started.
  2191. number: u64,
  2192. card: Option<CardPlan>,
  2193. back: Vec<Declared>,
  2194. /// What was taken off it to be done on the card.
  2195. own: Option<card_steps::Taken>,
  2196. /// Its bottom-of-pipe writes.
  2197. writes: Vec<(usize, crate::queue::Written, usize)>,
  2198. }
  2199. /// A submission on the card that has not been waited for ([`late`]): its
  2200. /// host lists, taken from the title's (which it may reset meanwhile), and
  2201. /// what is to be done once it has run.
  2202. struct Flight {
  2203. number: u64,
  2204. /// The value signalled on the host's fence behind it.
  2205. fence: u64,
  2206. lists: Vec<crate::list::Detached>,
  2207. order: Vec<usize>,
  2208. card: Option<CardPlan>,
  2209. back: Vec<Declared>,
  2210. /// The list of ours that ran ahead of them ([`card_steps`]).
  2211. own: Option<card_steps::Taken>,
  2212. }
  2213. /// One thing in the line of what waits for the card, in order.
  2214. enum Late {
  2215. Run(Flight),
  2216. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  2217. Write(usize, crate::queue::Written, usize),
  2218. /// A fence (its address) signalled behind the flights before it.
  2219. Signal(usize, u64),
  2220. }
  2221. struct Line {
  2222. line: Vec<Late>,
  2223. /// The title memory the flights' shaders may write (address, end), in
  2224. /// order and joined.
  2225. written: Vec<(usize, usize)>,
  2226. /// Host lists in the flights.
  2227. lists: usize,
  2228. /// The value signalled on the host's fence behind the last flight.
  2229. target: u64,
  2230. /// A settle has taken the line and is not done: a signal still goes
  2231. /// behind it.
  2232. settling: bool,
  2233. /// Something was settled away from a queue's own calls: the helper
  2234. /// thread looks at what queues hold.
  2235. poke: bool,
  2236. /// Host lists of settled flights, reset and given back outside the
  2237. /// submission lock ([`land`]: a settle may run under a caller's own
  2238. /// locks).
  2239. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2240. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2241. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2242. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2243. /// With [`card_steps`]: what the flights being landed write.
  2244. landing: Vec<card_steps::Writer>,
  2245. }
  2246. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2247. // into; touched under the lock.
  2248. unsafe impl Send for Line {}
  2249. static LINE: Mutex<Line> = Mutex::new(Line {
  2250. line: Vec::new(),
  2251. written: Vec::new(),
  2252. lists: 0,
  2253. target: 0,
  2254. settling: false,
  2255. poke: false,
  2256. landed: Vec::new(),
  2257. in_hand: Vec::new(),
  2258. landing: Vec::new(),
  2259. });
  2260. /// Told when a flight joins [`LINE`] or it is poked.
  2261. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2262. fn line() -> std::sync::MutexGuard<'static, Line> {
  2263. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2264. }
  2265. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2266. const WHY_SYNC: usize = 2;
  2267. const WHY_CARD_DONE: usize = 3;
  2268. const WHY_VALUE: usize = 4;
  2269. const WHY_STALE: usize = 5;
  2270. const WHY_READ: usize = 6;
  2271. const WHY_RUN: usize = 7;
  2272. const WHY_MOST: usize = 8;
  2273. const WHY_WRITES: usize = 9;
  2274. const WHY_FENCE: usize = 10;
  2275. /// Since the last frame-rate line: submissions sent without a wait;
  2276. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2277. /// microseconds settles waited for the card; value waits met by a flight's
  2278. /// bottom-of-pipe write; fence signals set behind flights.
  2279. /// Then: the settles for title memory read, by what read it (a buffer
  2280. /// copy, a fill of upload memory, a texture).
  2281. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2282. /// Since the last frame-rate line: the microseconds settles waited for the
  2283. /// card, by why they settled (the `WHY_` places).
  2284. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2285. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2286. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2287. if from >= to {
  2288. return false;
  2289. }
  2290. let at = ranges.partition_point(|r| r.1 <= from);
  2291. ranges.get(at).is_some_and(|r| r.0 < to)
  2292. }
  2293. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2294. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2295. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2296. ranges.sort_unstable();
  2297. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2298. for &(from, to) in ranges.iter() {
  2299. match out.last_mut() {
  2300. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2301. _ => out.push((from, to)),
  2302. }
  2303. }
  2304. *ranges = out;
  2305. }
  2306. /// Whether anything is in the air.
  2307. fn flying() -> bool {
  2308. if !late() {
  2309. return false;
  2310. }
  2311. let line = line();
  2312. // (With the relay: also while flights are being landed.)
  2313. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2314. }
  2315. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2316. /// before they are settled, if so. Preparing reads title memory on the
  2317. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2318. /// runs steps of ours that may read or write it anywhere; what the
  2319. /// flights' shaders write is not there yet.
  2320. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2321. let (written, copies) = {
  2322. let line = line();
  2323. if line.written.is_empty() {
  2324. return None;
  2325. }
  2326. (line.written.clone(), card_steps::copies(&line))
  2327. };
  2328. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2329. }
  2330. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2331. /// flights when the title itself wrote the memory since they were given it
  2332. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2333. ///
  2334. /// The title's 174 MB heap is declared written as a whole (a root view has
  2335. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2336. /// bytes a frame, at a new place each time, waited for every flight's
  2337. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2338. /// named). The title writes those bytes just before the draw that reads
  2339. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2340. ///
  2341. /// Or no shader's write went into that page in the last 600 frames
  2342. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2343. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2344. /// before the page was taken.
  2345. ///
  2346. /// What can go wrong: a constant a flight's shader really writes, in a
  2347. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2348. /// for the first time, is read as it was before that flight.
  2349. fn fill_is_titles(src: usize, len: usize) -> bool {
  2350. const SMALL: usize = 64 << 10;
  2351. static ON: OnceLock<bool> = OnceLock::new();
  2352. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2353. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2354. }
  2355. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2356. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2357. /// in (start, bytes).
  2358. #[cfg(feature = "diagnostics")]
  2359. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2360. /// How often and how long, and the address the last one read.
  2361. #[cfg(feature = "diagnostics")]
  2362. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2363. /// What the wait that comes next is for, and why not on the card.
  2364. #[cfg(feature = "diagnostics")]
  2365. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2366. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2367. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2368. /// shaders.
  2369. #[cfg(feature = "diagnostics")]
  2370. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2371. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2372. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2373. /// raw address (1).
  2374. #[cfg(feature = "diagnostics")]
  2375. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2376. if len < 1 << 20 {
  2377. return;
  2378. }
  2379. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2380. let e = all
  2381. .get_or_insert_with(Default::default)
  2382. .entry((address as usize, (address + len) as usize, pipeline))
  2383. .or_insert_with(|| {
  2384. let shaders = match pipeline {
  2385. 0 => "a view in a table".into(),
  2386. 1 => "a raw address".into(),
  2387. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2388. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2389. }),
  2390. };
  2391. (0, shaders)
  2392. });
  2393. e.0 += 1;
  2394. }
  2395. #[cfg(feature = "diagnostics")]
  2396. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2397. let i = written.partition_point(|r| r.1 <= at);
  2398. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2399. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2400. let why = blamed.1;
  2401. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2402. }
  2403. /// Why [`card_steps`] left the submission to the wait that comes next.
  2404. #[cfg(feature = "diagnostics")]
  2405. fn refused(why: &'static str) {
  2406. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2407. }
  2408. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2409. #[cfg(feature = "diagnostics")]
  2410. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2411. if let Some((shadow, from, _)) = stale.first() {
  2412. let (start, len) = shadow.span();
  2413. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2414. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2415. }
  2416. }
  2417. /// The wait for what [`blame`] last named, or a wait of another reason than
  2418. /// title memory read, took `us`.
  2419. #[cfg(feature = "diagnostics")]
  2420. fn blamed(why: usize, us: u64) {
  2421. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2422. let (key, at) = match (why, named) {
  2423. (WHY_READ | WHY_STALE, Some(named)) => named,
  2424. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2425. _ => {
  2426. let kind = match why {
  2427. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2428. WHY_VALUE => "a memory value",
  2429. WHY_STALE => "title memory changed under shader writes",
  2430. WHY_RUN => "a step of ours",
  2431. WHY_MOST => "lists in the air",
  2432. WHY_FENCE => "a blocking fence wait",
  2433. _ => "another reason",
  2434. };
  2435. ((kind, "", 0, 0, 0), 0)
  2436. }
  2437. };
  2438. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2439. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2440. *e = (e.0 + 1, e.1 + us, at);
  2441. }
  2442. /// For the frame-rate line: the five that waited longest.
  2443. #[cfg(feature = "diagnostics")]
  2444. fn log_blame(frames: f64) {
  2445. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2446. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2447. let mut all: Vec<_> = all.into_iter().collect();
  2448. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2449. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2450. // The passes that declare it written, the ones that do so most.
  2451. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2452. for ((a, b, _), (n, shaders)) in &wide {
  2453. if *a < at + len && at < *b {
  2454. *passes.entry(shaders).or_default() += n;
  2455. }
  2456. }
  2457. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2458. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2459. let passes: Vec<String> =
  2460. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2461. tracing::info!(
  2462. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2463. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2464. us as f64 / 1e3 / frames,
  2465. n as f64 / frames,
  2466. passes.join(", "),
  2467. match (why.is_empty(), kind) {
  2468. (true, _) => "",
  2469. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2470. _ => "; not done on the card: ",
  2471. },
  2472. );
  2473. }
  2474. }
  2475. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2476. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2477. touches(written, src, src + len) && !fill_is_titles(src, len)
  2478. }
  2479. /// Whether they stop a title buffer copy, and if so whether by its source.
  2480. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2481. let read = read_blocked(written, src, len);
  2482. (read || touches(written, dst, dst + len)).then_some(read)
  2483. }
  2484. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2485. /// may write (in order, joined); `count` whether the kind of read is
  2486. /// counted for the frame line.
  2487. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2488. if written.is_empty() {
  2489. return None;
  2490. }
  2491. // Destinations of copies at their place, if a step reads them.
  2492. let mut placed: Vec<(usize, usize)> = Vec::new();
  2493. for list in runs {
  2494. for step in &list.deferred().copies {
  2495. match step {
  2496. &Step::Copy(dst, src, len) => {
  2497. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2498. if count {
  2499. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2500. #[cfg(feature = "diagnostics")]
  2501. if _read {
  2502. blame("a buffer copy's source", written, src, len);
  2503. } else {
  2504. blame("a buffer copy's destination", written, dst, len);
  2505. }
  2506. }
  2507. return Some(WHY_READ);
  2508. }
  2509. }
  2510. &Step::Fill(_, src, len, _) => {
  2511. if read_blocked(written, src, len) {
  2512. if count {
  2513. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2514. #[cfg(feature = "diagnostics")]
  2515. blame("a fill of upload memory", written, src, len);
  2516. }
  2517. return Some(WHY_READ);
  2518. }
  2519. }
  2520. Step::Texture(staging) => {
  2521. let (at, len) = staging.memory();
  2522. if touches(written, at, at + len) {
  2523. if count {
  2524. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2525. #[cfg(feature = "diagnostics")]
  2526. blame("a texture", written, at, len);
  2527. }
  2528. return Some(WHY_READ);
  2529. }
  2530. }
  2531. Step::Run(_) => return Some(WHY_RUN),
  2532. Step::Placed(p) => match p.waits(written) {
  2533. place::Waits::No => {}
  2534. place::Waits::ForReaders => placed.push((p.dst, p.dst + p.len)),
  2535. place::Waits::Yes => {
  2536. if count {
  2537. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2538. #[cfg(feature = "diagnostics")]
  2539. blame("a buffer copy at its place", written, p.src, p.len);
  2540. }
  2541. return Some(WHY_READ);
  2542. }
  2543. },
  2544. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2545. }
  2546. }
  2547. }
  2548. (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ)
  2549. }
  2550. /// With flights in the air, after the submission's write-watch asking:
  2551. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2552. /// may write and that the title wrote since it was last copied. The
  2553. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2554. /// the title's bytes there would reach the card a submission late.
  2555. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2556. use std::sync::Arc;
  2557. // Per copy, the span of what is refreshed (a flush brings that much
  2558. // up to date at most).
  2559. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2560. // Where each copy is in it, if shaders may be writing it (none begins to
  2561. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2562. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2563. for list in runs {
  2564. for step in &list.deferred().copies {
  2565. if let Step::Refresh(shadow, address, len) = step {
  2566. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2567. shadow.writes_pending().then(|| {
  2568. spans.push((shadow.clone(), *address, *address + *len));
  2569. spans.len() - 1
  2570. })
  2571. });
  2572. if let Some(i) = *place {
  2573. let s = &mut spans[i];
  2574. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2575. }
  2576. }
  2577. }
  2578. }
  2579. if late_exact() {
  2580. // The title's bytes are put in beside the flights' writes; a
  2581. // settle is still due where that could not be done. At most this
  2582. // many changed runs go up to copies in the card's memory, each a
  2583. // copy of its own there. With [`card_steps`] the pages of the
  2584. // title's ring of constants come here too, which were waited for
  2585. // before: hundreds of short runs each, at about 1.5 us a run.
  2586. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2587. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2588. return spans;
  2589. }
  2590. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2591. spans
  2592. }
  2593. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2594. /// air, if there are any, and is set when they are settled. Whether it
  2595. /// did; if not the caller sets the fence now.
  2596. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2597. if !late() {
  2598. return false;
  2599. }
  2600. let mut line = line();
  2601. if line.line.is_empty() && !line.settling {
  2602. return false;
  2603. }
  2604. line.line.push(Late::Signal(fence, value));
  2605. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2606. drop(line);
  2607. // A signal alone (behind a settle under way) has no flight to wake
  2608. // the helper thread for it.
  2609. LINE_MOVED.notify_one();
  2610. RELAY_MOVED.notify_one();
  2611. true
  2612. }
  2613. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2614. /// whether it is met once the flights in the air have run. A flight's
  2615. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2616. /// for the card: the part behind the wait goes to the card behind that
  2617. /// flight, which is the order the wait asks for. If the flights may write
  2618. /// the value in a way not known here (shaders, a timestamp, another
  2619. /// width), they are settled and memory is asked again.
  2620. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2621. let (address, bytes) = wait.place();
  2622. {
  2623. let line = line();
  2624. if line.line.is_empty() && line.in_hand.is_empty() {
  2625. return false;
  2626. }
  2627. let mut unsure = touches(&line.written, address, address + bytes);
  2628. // (With the relay: first the writes of flights being landed.)
  2629. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2630. Late::Write(at, what, n) => Some((at, what, n)),
  2631. _ => None,
  2632. }));
  2633. for (at, what, n) in writes {
  2634. if *at >= address + bytes || address >= *at + *n {
  2635. continue;
  2636. }
  2637. match what {
  2638. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2639. if wait.holds_for(*v) {
  2640. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2641. return true;
  2642. }
  2643. }
  2644. _ => unsure = true,
  2645. }
  2646. }
  2647. if !unsure {
  2648. return false;
  2649. }
  2650. }
  2651. settle_now(WHY_VALUE);
  2652. wait.met()
  2653. }
  2654. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2655. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2656. pub(crate) fn settle_now(why: usize) {
  2657. if !late() {
  2658. return;
  2659. }
  2660. let Some(host) = host() else {
  2661. return;
  2662. };
  2663. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2664. host.settle(&mut submitted, why);
  2665. }
  2666. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2667. pub(crate) fn settle_for_present() {
  2668. settle_now(WHY_SYNC);
  2669. }
  2670. pub(crate) fn settle_for_fence() {
  2671. settle_now(WHY_FENCE);
  2672. }
  2673. /// Resets the host lists of settled flights and keeps them for reuse, as
  2674. /// a queue does for the lists it ran (`crate::list::recycle`).
  2675. fn land() {
  2676. let landed: Vec<_> = {
  2677. let mut line = line();
  2678. let n = line.landed.len().saturating_sub(bury_lag() as usize);
  2679. line.landed.drain(..n).collect()
  2680. };
  2681. for (lists, order) in landed {
  2682. crate::list::recycle(lists, &order);
  2683. }
  2684. }
  2685. /// The thread that settles the flights once the card has run them all
  2686. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2687. /// at the next call that settles, and a title thread that polls such a
  2688. /// value while the submitting thread waits for that thread would never
  2689. /// see it.
  2690. fn late_helper() {
  2691. let Some(host) = host() else {
  2692. return;
  2693. };
  2694. // SAFETY: a plain event of our own.
  2695. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2696. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2697. return;
  2698. };
  2699. loop {
  2700. let target = {
  2701. let mut line = line();
  2702. loop {
  2703. if line.poke {
  2704. line.poke = false;
  2705. break None;
  2706. }
  2707. // (With the relay the flights are another thread's.)
  2708. if !relay() && !line.line.is_empty() && !line.settling {
  2709. break Some(line.target);
  2710. }
  2711. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2712. }
  2713. };
  2714. let Some(target) = target else {
  2715. land();
  2716. crate::queue::release_held(false);
  2717. continue;
  2718. };
  2719. // The card first, without the submission lock: the submitting
  2720. // thread prepares and sends meanwhile.
  2721. // SAFETY: our fence and event.
  2722. unsafe {
  2723. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2724. WaitForSingleObject(event, INFINITE);
  2725. }
  2726. }
  2727. {
  2728. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2729. // Something newer went up meanwhile: the card is waited for
  2730. // again, the submitting thread is not held up for it.
  2731. if line().target != target {
  2732. continue;
  2733. }
  2734. host.settle(&mut submitted, WHY_CARD_DONE);
  2735. }
  2736. land();
  2737. crate::queue::release_held(false);
  2738. }
  2739. }
  2740. /// Starts the threads of [`late`], once: the one that settles flights when
  2741. /// the card has run them and looks at what queues hold, and with [`relay`]
  2742. /// the one that lands flights.
  2743. fn late_threads() {
  2744. static HELPER: std::sync::Once = std::sync::Once::new();
  2745. HELPER.call_once(|| {
  2746. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2747. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2748. }
  2749. tracing::info!(
  2750. most = late_most(),
  2751. writes = late_writes(),
  2752. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2753. );
  2754. if relay() {
  2755. // Without it nothing would ever land.
  2756. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2757. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2758. }
  2759. tracing::info!(
  2760. exact = relay_exact(),
  2761. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2762. );
  2763. }
  2764. });
  2765. }
  2766. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2767. /// time flights have landed. Counted as a settle for `why`, and its time
  2768. /// as waiting for the card. The caller may hold the submission lock: the
  2769. /// thread that lands flights never takes it.
  2770. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2771. let mut line = line();
  2772. if done(&line) {
  2773. return;
  2774. }
  2775. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2776. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2777. let was_working = working(false);
  2778. let waiting = std::time::Instant::now();
  2779. while !done(&line) {
  2780. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2781. }
  2782. drop(line);
  2783. stood(waiting);
  2784. working(was_working);
  2785. let us = waiting.elapsed().as_micros() as u64;
  2786. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2787. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2788. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2789. #[cfg(feature = "diagnostics")]
  2790. blamed(why, us);
  2791. }
  2792. /// What the thread that lands flights fetches card copies' pieces with
  2793. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2794. /// behind the submission lock), and the memory the pieces come down to.
  2795. struct RelayFetch {
  2796. list: Prelude,
  2797. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2798. queue: Option<ID3D12CommandQueue>,
  2799. fence: ID3D12Fence,
  2800. event: HANDLE,
  2801. /// The last value signalled on `fence`.
  2802. sent: u64,
  2803. /// Buffer, mapping, bytes.
  2804. buffer: Option<(ID3D12Resource, usize, u64)>,
  2805. /// Pieces caught while a later flight was writing them.
  2806. suspects: torn::Suspects,
  2807. /// What earlier fetches brought of flights not landed yet.
  2808. had: crate::land::Had,
  2809. }
  2810. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2811. /// the first flights of the line it takes them, with what follows them,
  2812. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2813. /// the card, or for a flight. It takes neither the submission lock nor
  2814. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2815. /// lists and looking at what queues hold are left to [`late_helper`].
  2816. fn relay_worker() {
  2817. let Some(host) = host() else {
  2818. return;
  2819. };
  2820. // SAFETY: a plain event of our own.
  2821. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2822. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2823. };
  2824. let mut fetch: Option<RelayFetch> = None;
  2825. loop {
  2826. let next = {
  2827. let mut line = line();
  2828. loop {
  2829. if line.line.is_empty() {
  2830. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2831. continue;
  2832. }
  2833. let fences: Vec<Option<u64>> = line
  2834. .line
  2835. .iter()
  2836. .map(|l| match l {
  2837. Late::Run(flight) => Some(flight.fence),
  2838. _ => None,
  2839. })
  2840. .collect();
  2841. // SAFETY: a plain query.
  2842. let completed = unsafe { host.fence.GetCompletedValue() };
  2843. let n = landable(&fences, completed);
  2844. if n == 0 {
  2845. // The first thing is a flight the card has not run.
  2846. break Err(fences[0].unwrap_or(0));
  2847. }
  2848. line.settling = true;
  2849. let items: Vec<Late> = line.line.drain(..n).collect();
  2850. line.in_hand = items
  2851. .iter()
  2852. .filter_map(|l| match l {
  2853. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2854. _ => None,
  2855. })
  2856. .collect();
  2857. if card_steps::stage() > 0 {
  2858. line.landing = card_steps::writers(&items);
  2859. }
  2860. break Ok(items);
  2861. }
  2862. };
  2863. match next {
  2864. Ok(items) => host.relay_land(items, &mut fetch),
  2865. Err(target) => {
  2866. let waiting = std::time::Instant::now();
  2867. // SAFETY: the host's fence and this thread's event.
  2868. let waited = unsafe {
  2869. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2870. WaitForSingleObject(event, INFINITE);
  2871. })
  2872. };
  2873. if waited.is_err() {
  2874. std::thread::sleep(std::time::Duration::from_millis(1));
  2875. }
  2876. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2877. }
  2878. }
  2879. }
  2880. }
  2881. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2882. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2883. /// once, the pieces that differ found on several threads; but the merge is
  2884. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2885. /// are not done with here (each flight's are, afterwards). In two steps:
  2886. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  2887. /// which needs nothing that the fetch from the card's memory brings), and
  2888. /// the merge.
  2889. struct RelayBack {
  2890. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  2891. found: Option<Vec<Vec<(usize, usize)>>>,
  2892. }
  2893. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  2894. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2895. for (shadow, declared) in back {
  2896. if shadow.carded() {
  2897. continue;
  2898. }
  2899. let mut spans: Vec<(usize, usize)> = Vec::new();
  2900. join_ranges(&mut spans, declared.iter().copied());
  2901. for &(from, to) in &spans {
  2902. shadow.relay_compared(from, to - from);
  2903. }
  2904. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2905. }
  2906. RelayBack { work, found: None }
  2907. }
  2908. impl RelayBack {
  2909. /// Looks the ranges through, once; its time counts as `stat`.
  2910. fn look(&mut self, stat: usize) {
  2911. if self.work.is_empty() || self.found.is_some() {
  2912. return;
  2913. }
  2914. let scanning = std::time::Instant::now();
  2915. // Looked through without a lock: a piece that changes meanwhile (a
  2916. // later flight writing, the title's bytes going in) is found now or
  2917. // by that flight's landing, and the merge looks again under the
  2918. // lock.
  2919. self.found = Some(crate::shadow::find_all(&self.work));
  2920. crate::land::spent(stat, scanning);
  2921. #[cfg(feature = "diagnostics")]
  2922. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2923. }
  2924. /// What differs goes into title memory.
  2925. fn merge(mut self) {
  2926. use crate::land;
  2927. self.look(land::stat::SCAN);
  2928. let Some(found) = self.found else {
  2929. return;
  2930. };
  2931. let merging = std::time::Instant::now();
  2932. let mut written: Vec<u64> = Vec::new();
  2933. if land::on() {
  2934. // Pieces in the same block of title memory in one job, in order.
  2935. let pieces: Vec<(usize, usize, usize)> =
  2936. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  2937. let start = |i: usize| self.work[i].0.span().0 as usize;
  2938. let mut order: Vec<usize> = (0..pieces.len()).collect();
  2939. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  2940. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  2941. let jobs = land::jobs(&cut);
  2942. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  2943. land::each(jobs.len(), &|j| {
  2944. let working = std::time::Instant::now();
  2945. let mut notes = land::Notes::default();
  2946. for &p in &order[jobs[j].clone()] {
  2947. let (i, at, n) = pieces[p];
  2948. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  2949. }
  2950. notes.flush();
  2951. land::spent(land::stat::BACK_ALL, working);
  2952. });
  2953. land::count(land::stat::JOBS, jobs.len() as u64);
  2954. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  2955. } else {
  2956. let (mut now, mut title) = (Vec::new(), Vec::new());
  2957. for ((shadow, ..), found) in self.work.iter().zip(found) {
  2958. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  2959. written.push(found.into_iter().map(merge).sum());
  2960. }
  2961. }
  2962. land::spent(land::stat::BACK, merging);
  2963. for ((_, from, to), written) in self.work.iter().zip(written) {
  2964. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  2965. #[cfg(feature = "diagnostics")]
  2966. crate::copystat::compared(*from, to - from, written as usize);
  2967. let _ = (from, to);
  2968. }
  2969. }
  2970. }
  2971. /// For the frame-rate line, with [`late`]: what the line of flights did
  2972. /// per frame since the last one.
  2973. fn late_line(frames: f64) {
  2974. if !late() {
  2975. return;
  2976. }
  2977. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2978. tracing::info!(
  2979. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2980. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2981. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2982. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2983. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2984. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2985. s[0],
  2986. s[1],
  2987. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2988. s[12] / 1000.0,
  2989. s[WHY_SYNC],
  2990. s[WHY_CARD_DONE],
  2991. s[WHY_VALUE],
  2992. s[WHY_STALE],
  2993. s[WHY_READ],
  2994. s[15],
  2995. s[16],
  2996. s[17],
  2997. s[WHY_RUN],
  2998. late_most(),
  2999. s[WHY_MOST],
  3000. s[WHY_WRITES],
  3001. s[WHY_FENCE],
  3002. s[13],
  3003. s[14],
  3004. );
  3005. {
  3006. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  3007. tracing::info!(
  3008. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  3009. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  3010. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  3011. w[WHY_SYNC],
  3012. w[WHY_CARD_DONE],
  3013. w[WHY_VALUE],
  3014. w[WHY_STALE],
  3015. w[WHY_READ],
  3016. w[WHY_RUN],
  3017. w[WHY_MOST],
  3018. w[WHY_WRITES],
  3019. w[WHY_FENCE],
  3020. );
  3021. }
  3022. if relay() {
  3023. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3024. tracing::info!(
  3025. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  3026. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  3027. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  3028. \"settles\" above are waits of other threads for it)",
  3029. r[1],
  3030. r[0],
  3031. r[2] / 1000.0,
  3032. r[3] / 1000.0,
  3033. r[4] / 1000.0,
  3034. );
  3035. if send::own() {
  3036. let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3037. tracing::info!(
  3038. "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
  3039. taking them out of the CPU sides",
  3040. t[0] / (1 << 20) as f64,
  3041. t[1],
  3042. t[2],
  3043. t[3] / 1000.0,
  3044. );
  3045. }
  3046. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3047. if t[0] > 0.0 {
  3048. tracing::info!(
  3049. "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",
  3050. t[0],
  3051. t[1],
  3052. t[2],
  3053. );
  3054. }
  3055. }
  3056. crate::land::log(frames);
  3057. if place::on() {
  3058. let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  3059. tracing::info!(
  3060. "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",
  3061. t[0],
  3062. t[1] / 1024.0,
  3063. t[2],
  3064. t[3],
  3065. );
  3066. }
  3067. card_steps::log(frames);
  3068. crate::picked::log(frames);
  3069. #[cfg(feature = "diagnostics")]
  3070. log_blame(frames);
  3071. if late_exact() {
  3072. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  3073. tracing::info!(
  3074. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  3075. {runs:.0} changed runs, {:.2} MB",
  3076. bytes / (1 << 20) as f64
  3077. );
  3078. }
  3079. }
  3080. pub(crate) mod aside;
  3081. pub(crate) mod awake;
  3082. mod card_steps;
  3083. pub(crate) mod indirects;
  3084. mod place;
  3085. mod send;
  3086. pub(crate) use send::{goes_as_words, words_under};
  3087. #[cfg(feature = "diagnostics")]
  3088. pub(crate) mod spans;
  3089. mod torn;
  3090. pub(crate) mod upcheck;
  3091. #[cfg(test)]
  3092. mod late_tests {
  3093. use super::{continues, join_ranges, touches};
  3094. /// Copies join only when both ends continue and the whole does not
  3095. /// overlap itself.
  3096. #[test]
  3097. fn copies_join_only_end_to_end_and_apart() {
  3098. // (destination, source, bytes)
  3099. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  3100. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  3101. // A gap, or only one side continues.
  3102. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  3103. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  3104. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  3105. // Together they would overlap: the second reads what the first wrote.
  3106. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  3107. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  3108. // They touch without overlapping.
  3109. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  3110. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  3111. }
  3112. /// Ranges are found by what they hold, not by where they start, and a
  3113. /// range that only touches another's end does not touch it.
  3114. #[test]
  3115. fn ranges_touch_where_they_overlap() {
  3116. let mut ranges = Vec::new();
  3117. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  3118. assert_eq!(ranges, [(10, 25), (40, 60)]);
  3119. join_ranges(&mut ranges, [(25, 40)]);
  3120. assert_eq!(ranges, [(10, 60)]);
  3121. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  3122. for (from, to, hit) in [
  3123. (0, 10, false),
  3124. (0, 11, true),
  3125. (24, 25, true),
  3126. (25, 40, false),
  3127. (25, 41, true),
  3128. (59, 200, true),
  3129. (60, 100, false),
  3130. (100, 101, true),
  3131. (101, 500, false),
  3132. (30, 30, false),
  3133. (50, 50, false),
  3134. ] {
  3135. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  3136. }
  3137. assert!(!touches(&[], 0, usize::MAX));
  3138. }
  3139. }
  3140. /// Whether a title buffer copy that continues the one recorded before it
  3141. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  3142. /// default).
  3143. ///
  3144. /// Each copy is done at submission through the kernel, which reports a
  3145. /// page that is not there instead of faulting (`copy_mapped`), tells the
  3146. /// write watch and the guards, and ends the refreshes gathered so far: a
  3147. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  3148. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  3149. /// continue the one before is counted either way and said on its own line
  3150. /// with the frame rate; the switch is worth that many kernel calls.
  3151. ///
  3152. /// Joined, the same bytes move: [`continues`] joins only copies whose
  3153. /// ranges, taken together, do not overlap, and nothing is recorded between
  3154. /// two steps that follow each other. What differs: a page that is not
  3155. /// mapped now fails the joined copy as a whole (it then goes page by page,
  3156. /// zeros for what cannot be read, as a single copy does), where before
  3157. /// only the copy that held it did.
  3158. fn join_copies() -> bool {
  3159. static ON: OnceLock<bool> = OnceLock::new();
  3160. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  3161. }
  3162. /// Since the last frame-rate line: title buffer copies recorded, and those
  3163. /// that continue the one before ([`join_copies`]).
  3164. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  3165. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  3166. /// where `last` ended, source and destination both, and the two as one do
  3167. /// not overlap (source over destination): then one copy of both moves the
  3168. /// bytes the two would move in turn.
  3169. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  3170. let ((d, s, n), (dst, src, len)) = (last, next);
  3171. let Some(all) = n.checked_add(len) else {
  3172. return false;
  3173. };
  3174. d.checked_add(n) == Some(dst)
  3175. && s.checked_add(n) == Some(src)
  3176. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  3177. }
  3178. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  3179. /// One list's lock at a time: a submission may name a list twice.
  3180. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  3181. let mut back: Vec<Declared> = Vec::new();
  3182. // Where each copy is in it, and the ranges seen: dispatches declare the
  3183. // same ranges thousands of times a frame.
  3184. let mut places: ByCopy<usize> = ByCopy::default();
  3185. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  3186. for list in runs {
  3187. for step in &list.deferred().copies {
  3188. if let Step::GpuWrite(shadow, address, len) = step {
  3189. let key = std::sync::Arc::as_ptr(shadow) as usize;
  3190. if !seen.insert((key, *address, *len)) {
  3191. continue;
  3192. }
  3193. let i = *places.entry(key).or_insert_with(|| {
  3194. back.push((shadow.clone(), Vec::new()));
  3195. back.len() - 1
  3196. });
  3197. back[i].1.push((*address, *address + *len));
  3198. }
  3199. }
  3200. }
  3201. back
  3202. }
  3203. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  3204. /// lines that say what the title's CPU was given while it decided whether
  3205. /// the camera is in a room. The values of the small read-backs
  3206. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  3207. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  3208. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  3209. /// copies found stale after their refresh (`shadow.rs`; only with
  3210. /// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
  3211. /// runtime, the read requests that fail (with 2: every request).
  3212. pub(crate) fn walls_trace() -> bool {
  3213. static ON: OnceLock<bool> = OnceLock::new();
  3214. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  3215. }
  3216. /// After `list` has run: the texels its read-backs copied into host
  3217. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  3218. ///
  3219. /// A submission that is waited for did this itself. One sent ahead
  3220. /// ([`late`]) did not, at any stage: the flights' lists were settled
  3221. /// without it, so the title read a buffer nobody wrote, as before read-backs
  3222. /// were made (the exposure metering's two small float targets, every frame).
  3223. fn read_backs(list: &HostList) {
  3224. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  3225. let mut data = std::ptr::null_mut();
  3226. // SAFETY: a read-back buffer of ours, written by the list that has
  3227. // run; the title's destination holds every row (checked when the
  3228. // copy was recorded).
  3229. unsafe {
  3230. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  3231. let from = data.cast::<u8>().cast_const();
  3232. for line in 0..*rows {
  3233. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  3234. }
  3235. // The walls trace: what the title is handed (one row of at
  3236. // most 24 values: its 5x1 and 1x1 float targets).
  3237. if walls_trace() && *rows == 1 && *row <= 96 {
  3238. let mut values = [0f32; 24];
  3239. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  3240. tracing::info!(
  3241. frame = crate::frame::current(),
  3242. to = format_args!("{:#x}", *at),
  3243. bytes = *row,
  3244. values = ?&values[..*row / 4],
  3245. "walls trace: a read-back lands in title memory"
  3246. );
  3247. }
  3248. buffer.Unmap(0, None);
  3249. }
  3250. }
  3251. }
  3252. }
  3253. /// After the card ran what declared `back`: what shaders wrote there goes
  3254. /// into title memory, and the ranges are done with.
  3255. fn hand_back(back: &[Declared]) {
  3256. if crate::shadow::wide_back() {
  3257. // Every range first (the pieces that differ, found on several
  3258. // threads), then the merges, in order, as below.
  3259. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3260. for (shadow, declared) in back {
  3261. if shadow.carded() {
  3262. continue;
  3263. }
  3264. let mut sorted = declared.clone();
  3265. sorted.sort_unstable();
  3266. let mut spans: Vec<(usize, usize)> = Vec::new();
  3267. for (from, to) in sorted {
  3268. match spans.last_mut() {
  3269. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3270. _ => spans.push((from, to)),
  3271. }
  3272. }
  3273. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3274. }
  3275. #[cfg(feature = "diagnostics")]
  3276. let scanning = std::time::Instant::now();
  3277. let found = crate::shadow::find_all(&work);
  3278. #[cfg(feature = "diagnostics")]
  3279. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3280. for ((shadow, from, to), found) in work.iter().zip(found) {
  3281. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3282. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3283. #[cfg(feature = "diagnostics")]
  3284. crate::copystat::compared(*from, to - from, written);
  3285. }
  3286. for (shadow, declared) in back {
  3287. shadow.copy_back_done(declared);
  3288. }
  3289. return;
  3290. }
  3291. for (shadow, declared) in back {
  3292. if shadow.carded() {
  3293. // Done before (`Host::card_back`).
  3294. shadow.copy_back_done(declared);
  3295. continue;
  3296. }
  3297. // Each byte compared once: the world declares dozens of views
  3298. // of its 174 MB heap that overlap almost entirely, and comparing
  3299. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3300. // MB shaders wrote. Only ranges that overlap or touch are
  3301. // joined: what lies between two was not given to shaders (the
  3302. // snapshot does not hold it).
  3303. let mut sorted = declared.clone();
  3304. sorted.sort_unstable();
  3305. let mut spans: Vec<(usize, usize)> = Vec::new();
  3306. for (from, to) in sorted {
  3307. match spans.last_mut() {
  3308. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3309. _ => spans.push((from, to)),
  3310. }
  3311. }
  3312. for (from, to) in spans {
  3313. let written = shadow.copy_back(from, to - from);
  3314. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3315. #[cfg(feature = "diagnostics")]
  3316. crate::copystat::compared(from, to - from, written);
  3317. }
  3318. shadow.copy_back_done(declared);
  3319. }
  3320. }
  3321. impl Host {
  3322. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3323. /// mesh shaders need both); logged once.
  3324. pub(crate) fn mesh_shaders(&self) -> bool {
  3325. static MESH: OnceLock<bool> = OnceLock::new();
  3326. *MESH.get_or_init(|| {
  3327. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3328. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3329. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3330. };
  3331. // SAFETY: each query writes its own structure of the given size.
  3332. let ok = unsafe {
  3333. self.device
  3334. .CheckFeatureSupport(
  3335. D3D12_FEATURE_D3D12_OPTIONS7,
  3336. (&raw mut options).cast(),
  3337. size_of_val(&options) as u32,
  3338. )
  3339. .is_ok()
  3340. && self
  3341. .device
  3342. .CheckFeatureSupport(
  3343. D3D12_FEATURE_SHADER_MODEL,
  3344. (&raw mut model).cast(),
  3345. size_of_val(&model) as u32,
  3346. )
  3347. .is_ok()
  3348. };
  3349. let mesh = ok
  3350. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3351. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3352. tracing::info!(mesh, "host mesh shader support");
  3353. mesh
  3354. })
  3355. }
  3356. /// Whether the host GPU supports the depth bounds test; logged once.
  3357. pub(crate) fn depth_bounds(&self) -> bool {
  3358. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3359. *BOUNDS.get_or_init(|| {
  3360. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3361. // SAFETY: writes `options` of the given size.
  3362. let ok = unsafe {
  3363. self.device
  3364. .CheckFeatureSupport(
  3365. D3D12_FEATURE_D3D12_OPTIONS2,
  3366. (&raw mut options).cast(),
  3367. size_of_val(&options) as u32,
  3368. )
  3369. .is_ok()
  3370. };
  3371. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3372. tracing::info!(supported, "host depth bounds support");
  3373. supported
  3374. })
  3375. }
  3376. /// A new list, open for recording.
  3377. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3378. #[cfg(feature = "diagnostics")]
  3379. let started = std::time::Instant::now();
  3380. #[cfg(feature = "diagnostics")]
  3381. let before = private_bytes();
  3382. let list = self.make_list();
  3383. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3384. // (May shrink while a list is made, on another thread's account:
  3385. // added as it is, the sum is what counts.)
  3386. #[cfg(feature = "diagnostics")]
  3387. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3388. #[cfg(feature = "diagnostics")]
  3389. {
  3390. use crate::copystat::{C, add};
  3391. add(C::HostLists, 1);
  3392. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3393. }
  3394. list
  3395. }
  3396. /// An allocator and a closed list for a prelude.
  3397. fn make_prelude(&self) -> Option<Prelude> {
  3398. // SAFETY: plain object creation.
  3399. let made: windows::core::Result<Prelude> = unsafe {
  3400. (|| {
  3401. let allocator: ID3D12CommandAllocator =
  3402. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3403. let list: ID3D12GraphicsCommandList =
  3404. self.device
  3405. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3406. list.Close()?;
  3407. Ok((allocator, list))
  3408. })()
  3409. };
  3410. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3411. match made {
  3412. Ok(prelude) => Some(prelude),
  3413. Err(e) => {
  3414. tracing::warn!(error = %e, "no host list for a prelude");
  3415. None
  3416. }
  3417. }
  3418. }
  3419. fn make_list(&self) -> windows::core::Result<HostList> {
  3420. // SAFETY: plain object creation.
  3421. unsafe {
  3422. let allocator: ID3D12CommandAllocator = self
  3423. .device
  3424. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3425. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3426. 0,
  3427. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3428. &allocator,
  3429. None,
  3430. )?;
  3431. let prelude = OnceLock::new();
  3432. if !lazy_prelude() {
  3433. let _ = prelude.set(self.make_prelude());
  3434. }
  3435. #[cfg(feature = "diagnostics")]
  3436. let notes = std::sync::Arc::<Mutex<Vec<Note>>>::default();
  3437. let pipelines = std::sync::Arc::<Mutex<std::collections::BTreeSet<String>>>::default();
  3438. #[cfg(feature = "diagnostics")]
  3439. let indirects = indirects::Shared::default();
  3440. #[cfg(feature = "diagnostics")]
  3441. if dred_on() || dred_light() {
  3442. static NUMBER: AtomicU32 = AtomicU32::new(0);
  3443. let number = NUMBER.fetch_add(1, Ordering::Relaxed);
  3444. name(&list, || format!("victory host list {number}"));
  3445. let mut all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  3446. if number.is_multiple_of(256) {
  3447. all.retain(|_, l| l.0.strong_count() > 0);
  3448. }
  3449. all.insert(
  3450. number,
  3451. (
  3452. std::sync::Arc::downgrade(&notes),
  3453. std::sync::Arc::downgrade(&pipelines),
  3454. std::sync::Arc::downgrade(&indirects),
  3455. ),
  3456. );
  3457. }
  3458. Ok(HostList {
  3459. allocator,
  3460. list,
  3461. deferred: Mutex::default(),
  3462. scratch: Mutex::default(),
  3463. states: Mutex::default(),
  3464. twins: Mutex::default(),
  3465. prelude,
  3466. pipelines,
  3467. #[cfg(feature = "diagnostics")]
  3468. indirects,
  3469. budget: OnceLock::new(),
  3470. card_budget: OnceLock::new(),
  3471. indirect_args: Mutex::default(),
  3472. batch_args: Mutex::default(),
  3473. coming: Mutex::default(),
  3474. _alive: Counted::new(),
  3475. #[cfg(feature = "diagnostics")]
  3476. notes,
  3477. #[cfg(feature = "diagnostics")]
  3478. stamps: OnceLock::new(),
  3479. })
  3480. }
  3481. }
  3482. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3483. fn card_clock(&self) -> Option<&'static CardClock> {
  3484. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3485. static WATCH: std::sync::Once = std::sync::Once::new();
  3486. let clock = CLOCK
  3487. .get_or_init(|| {
  3488. // SAFETY: a plain fence on our device.
  3489. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3490. Some(CardClock {
  3491. fence,
  3492. state: Mutex::new((0, None)),
  3493. sent: std::sync::Condvar::new(),
  3494. })
  3495. })
  3496. .as_ref()?;
  3497. WATCH.call_once(|| {
  3498. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3499. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3500. }
  3501. });
  3502. Some(clock)
  3503. }
  3504. /// Lists of ours just went to the queue: the clock's signal goes
  3505. /// behind them, and an idle stretch of the card, if one was under way,
  3506. /// ends here ([`CARD_CLOCK_US`]).
  3507. fn card_sent(&self) {
  3508. let Some(clock) = self.card_clock() else {
  3509. return;
  3510. };
  3511. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3512. state.0 += 1;
  3513. // SAFETY: our queue and the clock's fence.
  3514. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3515. if let Some((since, worked_then)) = state.1.take() {
  3516. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3517. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3518. }
  3519. drop(state);
  3520. clock.sent.notify_one();
  3521. }
  3522. /// Whether the host has what copies in the card's memory need (three
  3523. /// lists and the compare); made at the first ask. A copy goes to the
  3524. /// card's memory only if it has.
  3525. pub(crate) fn card_ready(&self) -> bool {
  3526. static READY: OnceLock<bool> = OnceLock::new();
  3527. *READY.get_or_init(|| match self.make_card_work() {
  3528. Ok(work) => {
  3529. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3530. true
  3531. }
  3532. Err(e) => {
  3533. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3534. false
  3535. }
  3536. })
  3537. }
  3538. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3539. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3540. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3541. let mut code: Option<ID3DBlob> = None;
  3542. // SAFETY: the source and names live through the call; the out
  3543. // pointer is ours.
  3544. unsafe {
  3545. D3DCompile(
  3546. CARD_COMPARE.as_ptr().cast(),
  3547. CARD_COMPARE.len(),
  3548. windows::core::s!("card compare"),
  3549. None,
  3550. None,
  3551. windows::core::s!("main"),
  3552. windows::core::s!("cs_5_1"),
  3553. 0,
  3554. 0,
  3555. &mut code,
  3556. None,
  3557. )?;
  3558. }
  3559. let code = code.ok_or_else(windows::core::Error::empty)?;
  3560. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3561. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3562. // in one submission.
  3563. const RESULTS: u64 = 1 << 20;
  3564. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3565. name(&differs, || "card compare results".into());
  3566. // SAFETY: the blob's own bytes; the root signature is inside the
  3567. // shader.
  3568. unsafe {
  3569. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3570. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3571. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3572. pRootSignature: std::mem::transmute_copy(&root),
  3573. CS: D3D12_SHADER_BYTECODE {
  3574. pShaderBytecode: bytes.as_ptr().cast(),
  3575. BytecodeLength: bytes.len(),
  3576. },
  3577. ..Default::default()
  3578. })?;
  3579. #[cfg(feature = "diagnostics")]
  3580. name(&pso, || crate::replay::play::COMPARE.into());
  3581. Ok(CardWork {
  3582. sync: vec![list()?],
  3583. check: vec![list()?],
  3584. fetch: list()?,
  3585. root,
  3586. pso,
  3587. differs: (differs, data as usize, RESULTS),
  3588. fetched: None,
  3589. taken: 0,
  3590. out: 0,
  3591. })
  3592. }
  3593. }
  3594. /// Before a submission's lists run, for copies in the card's memory
  3595. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3596. /// the last submission goes to their card side (a list of ours, run
  3597. /// now; the submission's lists follow it on the queue), and the ranges
  3598. /// this submission's shaders may write get a compare to run after its
  3599. /// lists. `None` if there is nothing to do.
  3600. ///
  3601. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3602. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3603. /// `relay`).
  3604. /// `picked`: ranges that may be written too, and ranges to look at
  3605. /// (`crate::picked`).
  3606. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3607. use std::sync::Arc;
  3608. if !crate::shadow::cards() {
  3609. return None;
  3610. }
  3611. // The ranges this submission's shaders may write, per copy.
  3612. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3613. for list in runs {
  3614. for step in &list.deferred().copies {
  3615. if let Step::GpuWrite(shadow, address, len) = step
  3616. && shadow.carded()
  3617. {
  3618. let range = (*address, *address + *len);
  3619. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3620. Some((_, ranges)) => {
  3621. if !ranges.contains(&range) {
  3622. ranges.push(range);
  3623. }
  3624. }
  3625. None => declared.push((shadow.clone(), vec![range])),
  3626. }
  3627. }
  3628. }
  3629. }
  3630. let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
  3631. // (Of a copy with a declared range here, that says it.)
  3632. let looked: Vec<&crate::picked::Range> =
  3633. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3634. // With the relay: the order of the queue is held from here until
  3635. // what is taken is on the queue, and the taking is numbered.
  3636. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3637. let sent_as = match order.as_mut() {
  3638. Some(order) => {
  3639. **order += 1;
  3640. **order
  3641. }
  3642. None => 0,
  3643. };
  3644. let mut dirty = crate::shadow::card_dirty(sent_as);
  3645. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3646. return None;
  3647. }
  3648. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3649. let work = work.as_mut()?;
  3650. // A copy whose shader writes are declared for the first time gets
  3651. // its bytes from before, whole.
  3652. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3653. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3654. if shadow.card_make_before(|size| {
  3655. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3656. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3657. Some(before)
  3658. }) {
  3659. whole.push(shadow.clone());
  3660. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3661. dirty.push((shadow.clone(), Vec::new()));
  3662. }
  3663. }
  3664. }
  3665. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3666. let mut looks = None;
  3667. // The bytes as they are now, whatever later submissions put there.
  3668. let own = if send::own() { send::take(self, &dirty) } else { None };
  3669. if !dirty.is_empty() {
  3670. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3671. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3672. };
  3673. let (allocator, list) = &sync;
  3674. // SAFETY: the list's last run finished (it ran ahead of a
  3675. // submission that was waited for, and came back after that);
  3676. // live buffers, and the ranges lie in them.
  3677. let recorded = unsafe {
  3678. (|| -> windows::core::Result<()> {
  3679. allocator.Reset()?;
  3680. list.Reset(allocator, None)?;
  3681. if upcheck::on() {
  3682. looks = upcheck::record(self, list, &dirty);
  3683. }
  3684. // Every copy first, then one barrier call, then every
  3685. // pass: a wait between each copy and its pass had the
  3686. // card do them one after the other.
  3687. let mut sent = Vec::new();
  3688. if let Some(own) = &own {
  3689. own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
  3690. }
  3691. for (shadow, ranges) in &dirty {
  3692. let Some((staging, before, _)) = shadow.card_sides() else {
  3693. continue;
  3694. };
  3695. for &(a, b) in ranges {
  3696. if own.is_none() {
  3697. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3698. }
  3699. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3700. }
  3701. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3702. if own.is_none() && before.is_some() && !ranges.is_empty() {
  3703. sent.push(transition(
  3704. &shadow.buffer,
  3705. D3D12_RESOURCE_STATE_COPY_DEST,
  3706. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3707. ));
  3708. }
  3709. }
  3710. if !sent.is_empty() {
  3711. list.ResourceBarrier(&sent);
  3712. }
  3713. list.SetComputeRootSignature(&work.root);
  3714. list.SetPipelineState(&work.pso);
  3715. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3716. for (shadow, ranges) in &dirty {
  3717. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3718. continue;
  3719. };
  3720. // No twin (it cost the card the copy's size again,
  3721. // 399 MB in run 75): `before` holds a 128-bit hash
  3722. // of each 64 KiB piece. The pieces just sent up are
  3723. // hashed again, all of them the first time; the
  3724. // compare after the lists hashes the declared
  3725. // pieces and flags those whose hash is another.
  3726. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3727. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3728. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3729. vec![shadow.card_run(0, usize::MAX)]
  3730. } else {
  3731. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3732. };
  3733. // The same pieces in fewer passes (`rehash_runs`).
  3734. let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3735. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3736. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3737. for run in runs {
  3738. card_pass(list, &run, size as u32, 0, 0);
  3739. }
  3740. }
  3741. list.Close()?;
  3742. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3743. Ok(())
  3744. })()
  3745. };
  3746. if let Err(e) = recorded {
  3747. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3748. }
  3749. used.push((false, sync));
  3750. }
  3751. drop(order);
  3752. let mut plan = CardPlan {
  3753. ranges: Vec::new(),
  3754. check: None,
  3755. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3756. lists: used,
  3757. sent_as,
  3758. looks,
  3759. sends: own.map(send::Own::memory),
  3760. };
  3761. // Each byte once, as the copy-back joins the declared ranges. The
  3762. // results go behind those of plans still in the air.
  3763. let mut at = work.taken;
  3764. for (shadow, ranges) in &declared {
  3765. let mut sorted = ranges.clone();
  3766. sorted.sort_unstable();
  3767. let mut spans: Vec<(usize, usize)> = Vec::new();
  3768. for (from, to) in sorted {
  3769. match spans.last_mut() {
  3770. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3771. _ => spans.push((from, to)),
  3772. }
  3773. }
  3774. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3775. for (from, to) in spans {
  3776. let Some(span) = shadow.card_span(from, to) else {
  3777. continue;
  3778. };
  3779. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3780. plan.ranges.push(CardRange {
  3781. shadow: shadow.clone(),
  3782. declared: (from, to),
  3783. span,
  3784. at,
  3785. compared,
  3786. picked: false,
  3787. });
  3788. if compared {
  3789. at += span.pieces;
  3790. }
  3791. }
  3792. }
  3793. for (shadow, from, len) in looked {
  3794. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3795. if let Some(span) = shadow.card_span(*from, from + len)
  3796. && twin
  3797. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3798. {
  3799. plan.ranges.push(CardRange {
  3800. shadow: shadow.clone(),
  3801. declared: (*from, from + len),
  3802. span,
  3803. at,
  3804. compared: true,
  3805. picked: true,
  3806. });
  3807. at += span.pieces;
  3808. }
  3809. }
  3810. work.taken = at;
  3811. if plan.ranges.iter().any(|r| r.compared) {
  3812. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3813. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3814. };
  3815. let (allocator, list) = &check;
  3816. // SAFETY: the list's last run finished (its submission was
  3817. // waited for, and it came back after that); live buffers; the
  3818. // compare's own root signature.
  3819. let recorded = unsafe {
  3820. (|| -> windows::core::Result<ID3D12CommandList> {
  3821. allocator.Reset()?;
  3822. list.Reset(allocator, None)?;
  3823. // What the submission's shaders wrote, first.
  3824. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3825. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3826. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3827. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3828. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3829. pResource: std::mem::ManuallyDrop::new(None),
  3830. }),
  3831. },
  3832. }]);
  3833. list.SetComputeRootSignature(&work.root);
  3834. list.SetPipelineState(&work.pso);
  3835. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3836. for r in plan.ranges.iter().filter(|r| r.compared) {
  3837. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3838. continue;
  3839. };
  3840. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3841. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3842. // (What is only looked at keeps its hashes: what
  3843. // changed there is the next declared range's to land.)
  3844. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  3845. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3846. }
  3847. list.Close()?;
  3848. list.cast()
  3849. })()
  3850. };
  3851. match recorded {
  3852. Ok(list) => plan.check = Some(list),
  3853. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3854. }
  3855. plan.lists.push((true, check));
  3856. }
  3857. work.out += 1;
  3858. Some(plan)
  3859. }
  3860. /// With [`relay`]: whether the compare's result area is half taken by
  3861. /// plans in the air. It starts from the beginning only when no plan is
  3862. /// out, so the caller lets the flights land first.
  3863. fn card_results_low(&self) -> bool {
  3864. CARD_WORK
  3865. .lock()
  3866. .unwrap_or_else(|e| e.into_inner())
  3867. .as_ref()
  3868. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3869. }
  3870. /// The plan's submission has run and its results were read
  3871. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3872. /// when nothing of ours is on the card, so the compare's results start
  3873. /// from the beginning again.
  3874. fn card_done(&self, plan: CardPlan) {
  3875. if let Some(looks) = plan.looks {
  3876. looks.read();
  3877. }
  3878. if let Some(memory) = plan.sends {
  3879. send::give_back(memory);
  3880. }
  3881. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3882. let Some(work) = work.as_mut() else {
  3883. return;
  3884. };
  3885. for (check, list) in plan.lists {
  3886. if check { work.check.push(list) } else { work.sync.push(list) }
  3887. }
  3888. work.out = work.out.saturating_sub(1);
  3889. // With the relay other plans may be on the card, their results
  3890. // not read yet: the area starts again only when none is out.
  3891. if !relay() || work.out == 0 {
  3892. work.taken = 0;
  3893. }
  3894. }
  3895. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3896. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3897. // SAFETY: plain object creation.
  3898. let copying = relay_copy().then(|| unsafe {
  3899. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3900. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3901. let list: ID3D12GraphicsCommandList =
  3902. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3903. list.Close()?;
  3904. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3905. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3906. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3907. ..Default::default()
  3908. })?;
  3909. Ok(((allocator, list), queue))
  3910. })()
  3911. });
  3912. let (list, queue) = match copying {
  3913. Some(Ok((list, queue))) => (list, Some(queue)),
  3914. Some(Err(e)) => {
  3915. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3916. (self.make_prelude()?, None)
  3917. }
  3918. None => (self.make_prelude()?, None),
  3919. };
  3920. // SAFETY: plain objects of our own.
  3921. unsafe {
  3922. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3923. let event = CreateEventW(None, false, false, None).ok()?;
  3924. Some(RelayFetch {
  3925. list,
  3926. queue,
  3927. fence,
  3928. event,
  3929. sent: 0,
  3930. buffer: None,
  3931. suspects: torn::Suspects::default(),
  3932. had: crate::land::Had::default(),
  3933. })
  3934. }
  3935. }
  3936. /// [`relay`], on the thread that lands flights: for the plans of the
  3937. /// flights being landed (the card has run them), the pieces their
  3938. /// compares flagged are fetched, once each, with a list and a wait of
  3939. /// this thread's own, and what shaders wrote in them goes into title
  3940. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3941. /// no submission lock; a piece flagged under one range of a plan is
  3942. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3943. /// whatever was sent meanwhile, so it may bring a later flight's
  3944. /// bytes, which that flight's landing then finds merged already; and
  3945. /// nothing is sent back up. `plans` come with the value signalled behind
  3946. /// their flight. `meanwhile` is called while the fetch is on its way, if
  3947. /// there is one.
  3948. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  3949. use crate::land;
  3950. let gathering = std::time::Instant::now();
  3951. let differs = {
  3952. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3953. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3954. };
  3955. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3956. let mut total = 0u64;
  3957. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  3958. fetch.had.landing(first);
  3959. }
  3960. // SAFETY: the mapping of the results. The compares of these plans
  3961. // have run, and their dwords are given to no other plan before these
  3962. // are done with (`card_done`).
  3963. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  3964. if let Some(differs) = differs {
  3965. // Pieces caught while a later flight was at them (`torn`).
  3966. let suspects = fetch.as_ref().map(|f| &f.suspects);
  3967. let mut seen = std::collections::HashSet::new();
  3968. for &(plan, behind) in plans {
  3969. plan.picked_found(differs);
  3970. let flags: Vec<(usize, u32, bool)> = plan
  3971. .ranges
  3972. .iter()
  3973. .filter(|r| !r.picked)
  3974. .flat_map(|r| {
  3975. (0..r.span.pieces).map(move |p| {
  3976. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  3977. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  3978. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  3979. })
  3980. })
  3981. .collect();
  3982. let fetched = flagged_pieces(&flags);
  3983. for r in plan.ranges.iter().filter(|r| !r.picked) {
  3984. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3985. if upcheck::on() {
  3986. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  3987. }
  3988. for p in 0..r.span.pieces {
  3989. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  3990. continue;
  3991. }
  3992. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3993. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  3994. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  3995. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  3996. land::count(land::stat::HAD, 1);
  3997. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  3998. if land::skip_on() {
  3999. continue;
  4000. }
  4001. }
  4002. if upcheck::on() {
  4003. upcheck::fetched(r.shadow.id(), lo);
  4004. }
  4005. seen.insert((copy, lo, hi));
  4006. pieces.push((r.shadow.clone(), lo, hi, total));
  4007. total += (hi - lo) as u64;
  4008. }
  4009. }
  4010. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4011. }
  4012. }
  4013. }
  4014. if land::on() {
  4015. // In the order they are landed, each byte of a copy once.
  4016. let keys: Vec<land::Piece> =
  4017. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  4018. total = 0;
  4019. pieces = land::ordered(&keys)
  4020. .into_iter()
  4021. .map(|(i, title, len)| {
  4022. let shadow = &pieces[i].0;
  4023. let lo = title - shadow.span().0 as usize;
  4024. let at = total;
  4025. total += len as u64;
  4026. (shadow.clone(), lo, lo + len, at)
  4027. })
  4028. .collect();
  4029. }
  4030. land::spent(land::stat::GATHER, gathering);
  4031. if fetch.is_none() {
  4032. *fetch = self.make_relay_fetch();
  4033. }
  4034. // On the copy queue a later flight may be at a piece while it is
  4035. // fetched: the pieces come down whole, to be hashed.
  4036. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  4037. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  4038. if let Some(check) = &check {
  4039. total = check.total;
  4040. }
  4041. // The sends these flights ran behind, all a fetch on the copy queue
  4042. // is known to have run behind.
  4043. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  4044. if pieces.is_empty() {
  4045. // Nothing to fetch: every send so far is older than the next
  4046. // fetch, if that goes to the queue the sends went to.
  4047. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  4048. true => behind,
  4049. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  4050. };
  4051. crate::shadow::relay_fetched(after);
  4052. return;
  4053. }
  4054. let Some(f) = fetch.as_mut() else {
  4055. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  4056. };
  4057. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  4058. let size = total.next_multiple_of(16 << 20);
  4059. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4060. }
  4061. let Some((buffer, data, _)) = f.buffer.clone() else {
  4062. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  4063. };
  4064. f.sent += 1;
  4065. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  4066. let copy_queue = f.queue.clone();
  4067. let waiting = std::time::Instant::now();
  4068. // The flights the fetch runs behind: those in the line by now have
  4069. // been given to the queue. On the copy queue, those landed here.
  4070. let ahead = match copy_queue {
  4071. Some(_) => 0,
  4072. None => line().target,
  4073. };
  4074. // SAFETY: the list's last run was waited for by this thread; live
  4075. // buffers (the copies are held by the plans); the fence and the
  4076. // event are this thread's.
  4077. let ran = unsafe {
  4078. (|| -> windows::core::Result<u64> {
  4079. allocator.Reset()?;
  4080. list.Reset(&allocator, None)?;
  4081. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  4082. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  4083. }
  4084. list.Close()?;
  4085. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  4086. if let Some(queue) = &copy_queue {
  4087. queue.ExecuteCommandLists(&lists);
  4088. queue.Signal(&fence, sent)?;
  4089. meanwhile();
  4090. fence.SetEventOnCompletion(sent, event)?;
  4091. WaitForSingleObject(event, INFINITE);
  4092. return Ok(behind);
  4093. }
  4094. // In the order of the queue: the sends of title bytes so
  4095. // far are ahead of this fetch, every later one behind it.
  4096. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  4097. self.queue.ExecuteCommandLists(&lists);
  4098. let after = *order;
  4099. drop(order);
  4100. self.card_sent();
  4101. self.queue.Signal(&fence, sent)?;
  4102. meanwhile();
  4103. fence.SetEventOnCompletion(sent, event)?;
  4104. WaitForSingleObject(event, INFINITE);
  4105. Ok(after)
  4106. })()
  4107. };
  4108. let after = match ran {
  4109. Ok(after) => after,
  4110. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  4111. };
  4112. let us = waiting.elapsed().as_micros() as u64;
  4113. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  4114. {
  4115. use crate::shadow::CARD_STATS;
  4116. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4117. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4118. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4119. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  4120. }
  4121. let merging = std::time::Instant::now();
  4122. let mut written = 0;
  4123. if land::on() {
  4124. let titles: Vec<(usize, usize)> =
  4125. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  4126. let jobs = land::jobs(&titles);
  4127. let put = std::sync::atomic::AtomicU64::new(0);
  4128. land::each(jobs.len(), &|j| {
  4129. let working = std::time::Instant::now();
  4130. if let Some(check) = &check {
  4131. for i in jobs[j].clone() {
  4132. // SAFETY: as below.
  4133. unsafe { check.look(i, data) };
  4134. }
  4135. }
  4136. let mut notes = land::Notes::default();
  4137. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  4138. let addressed: Vec<(usize, usize, usize)> =
  4139. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  4140. // SAFETY: the mapping of the fetched bytes, `total` of
  4141. // them; the copy into it has run, and the next waits
  4142. // for this call.
  4143. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  4144. }
  4145. notes.flush();
  4146. land::spent(land::stat::CARD_ALL, working);
  4147. });
  4148. land::count(land::stat::JOBS, jobs.len() as u64);
  4149. written = put.into_inner();
  4150. } else {
  4151. let mut title = Vec::new();
  4152. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  4153. if let Some(check) = &check {
  4154. // SAFETY: as below.
  4155. unsafe { check.look(i, data) };
  4156. }
  4157. // SAFETY: the mapping of the fetched bytes, `total` of them;
  4158. // the copy into it has run.
  4159. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  4160. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  4161. shadow.walls_merged(gpu.len(), merged);
  4162. written += merged as u64;
  4163. }
  4164. }
  4165. land::spent(land::stat::CARD, merging);
  4166. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  4167. if let Some(f) = fetch.as_mut() {
  4168. if let Some(check) = &check {
  4169. check.done(&mut f.suspects);
  4170. }
  4171. f.had.fetched(
  4172. ahead,
  4173. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  4174. );
  4175. }
  4176. // Sends up to `after` are of no use to any later merge.
  4177. crate::shadow::relay_fetched(after);
  4178. }
  4179. /// [`relay`], on the thread that lands flights: `items` are the first
  4180. /// things of the line, flights the card has run and what follows them.
  4181. /// What their shaders wrote goes into title memory (copies in the
  4182. /// card's memory first, then the others, each byte once whichever
  4183. /// flights declared it); then every flight's ranges are done with;
  4184. /// then, in the line's order, each flight's read-backs, its
  4185. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  4186. /// is complete before the title is told anything.
  4187. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  4188. let landing = std::time::Instant::now();
  4189. {
  4190. let flights: Vec<&Flight> = items
  4191. .iter()
  4192. .filter_map(|l| match l {
  4193. Late::Run(flight) => Some(flight),
  4194. _ => None,
  4195. })
  4196. .collect();
  4197. if !flights.is_empty() {
  4198. // SAFETY: a plain query.
  4199. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4200. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  4201. fail(format_args!(
  4202. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  4203. flights.len(),
  4204. runs.len(),
  4205. self.removal_data(&runs),
  4206. last_notes(&runs)
  4207. ));
  4208. }
  4209. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  4210. // (Each byte once: the ranges are joined.)
  4211. let mut back: Vec<Declared> = Vec::new();
  4212. for flight in &flights {
  4213. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  4214. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4215. Some((_, all)) => all.extend_from_slice(ranges),
  4216. None => back.push((shadow.clone(), ranges.clone())),
  4217. }
  4218. }
  4219. }
  4220. let mut hand_back = relay_hand_back(&back);
  4221. self.relay_card_back(&plans, fetch, &mut || {
  4222. if crate::land::on() {
  4223. hand_back.look(crate::land::stat::SCAN_BESIDE);
  4224. }
  4225. });
  4226. hand_back.merge();
  4227. let finishing = std::time::Instant::now();
  4228. // Only now, and flight by flight: a range another flight
  4229. // in the air declared too stays closed to refreshes.
  4230. for flight in &flights {
  4231. for (shadow, ranges) in &flight.back {
  4232. shadow.copy_back_done(ranges);
  4233. }
  4234. }
  4235. crate::land::spent(crate::land::stat::DONE, finishing);
  4236. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4237. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  4238. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  4239. }
  4240. }
  4241. // In the order given: what tells the title the card is done.
  4242. let mut last = 0;
  4243. let mut landed = Vec::new();
  4244. let mut telling = std::time::Instant::now();
  4245. for item in items {
  4246. telling = match item {
  4247. Late::Run(flight) => {
  4248. last = flight.number;
  4249. for &i in &flight.order {
  4250. read_backs(flight.lists[i].host());
  4251. }
  4252. if let Some(card) = flight.card {
  4253. self.card_done(card);
  4254. }
  4255. if let Some(own) = flight.own {
  4256. own.landed();
  4257. }
  4258. landed.push((flight.lists, flight.order));
  4259. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  4260. }
  4261. Late::Write(at, what, bytes) => {
  4262. what.write(at as *mut u8, bytes);
  4263. crate::land::spent(crate::land::stat::TOLD, telling)
  4264. }
  4265. Late::Signal(fence, value) => {
  4266. crate::fence::set(fence as crate::object::This, value);
  4267. crate::land::spent(crate::land::stat::TOLD, telling)
  4268. }
  4269. };
  4270. }
  4271. if last > 0 {
  4272. FINISHED.store(last, Ordering::Release);
  4273. bury(last);
  4274. }
  4275. self.log_messages();
  4276. crate::land::spent(crate::land::stat::REST, telling);
  4277. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4278. {
  4279. let mut line = line();
  4280. let Line {
  4281. line: items,
  4282. written,
  4283. lists,
  4284. settling,
  4285. poke,
  4286. landed: kept,
  4287. in_hand,
  4288. landing,
  4289. ..
  4290. } = &mut *line;
  4291. kept.extend(landed);
  4292. in_hand.clear();
  4293. landing.clear();
  4294. // What is still in the air, from the flights that are.
  4295. written.clear();
  4296. *lists = 0;
  4297. let mut ranges = Vec::new();
  4298. for item in items.iter() {
  4299. if let Late::Run(flight) = item {
  4300. *lists += flight.order.len().max(1);
  4301. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  4302. }
  4303. }
  4304. join_ranges(written, ranges);
  4305. *settling = false;
  4306. // The landed lists are reset, and what queues hold looked at,
  4307. // by the helper thread (they take locks a waiter may hold).
  4308. *poke = true;
  4309. }
  4310. LINE_MOVED.notify_all();
  4311. LINE_LANDED.notify_all();
  4312. }
  4313. /// After a submission ran, for copies in the card's memory: the pieces
  4314. /// of the declared ranges that the compare found differing (all of a
  4315. /// range it did not compare) are fetched, with one more wait for the
  4316. /// card, and what shaders wrote in them goes into title memory.
  4317. /// `submitted` is the last value signalled on the fence. `seen` holds
  4318. /// the pieces fetched already since the card was last waited for
  4319. /// (several submissions settled together name the same ones).
  4320. fn card_back(
  4321. &self,
  4322. plan: &CardPlan,
  4323. submitted: &mut u64,
  4324. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4325. ) {
  4326. if plan.ranges.is_empty() {
  4327. return;
  4328. }
  4329. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4330. let Some(work) = work.as_mut() else {
  4331. return;
  4332. };
  4333. // SAFETY: the mapping of the results, which the compare (it has
  4334. // run) wrote.
  4335. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4336. // The pieces to fetch: the range, the offsets in its copy, and
  4337. // where the bytes come down.
  4338. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4339. let mut total = 0u64;
  4340. plan.picked_found(differs);
  4341. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4342. for p in 0..r.span.pieces {
  4343. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4344. continue;
  4345. }
  4346. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4347. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4348. pieces.push((i, lo, hi, total));
  4349. total += (hi - lo) as u64;
  4350. }
  4351. }
  4352. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4353. }
  4354. let mut written = vec![0usize; plan.ranges.len()];
  4355. if !pieces.is_empty() {
  4356. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4357. let size = total.next_multiple_of(16 << 20);
  4358. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4359. }
  4360. let Some((fetched, data, _)) = &work.fetched else {
  4361. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4362. };
  4363. let waiting = std::time::Instant::now();
  4364. let (allocator, list) = &work.fetch;
  4365. // SAFETY: the list's last run was waited for; live buffers; the
  4366. // fence and event are ours, under the submission lock.
  4367. let ran = unsafe {
  4368. (|| -> windows::core::Result<()> {
  4369. allocator.Reset()?;
  4370. list.Reset(allocator, None)?;
  4371. for &(i, lo, hi, at) in &pieces {
  4372. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4373. }
  4374. list.Close()?;
  4375. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4376. self.card_sent();
  4377. *submitted += 1;
  4378. self.queue.Signal(&self.fence, *submitted)?;
  4379. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4380. let was_working = working(false);
  4381. WaitForSingleObject(self.event, INFINITE);
  4382. stood(waiting);
  4383. working(was_working);
  4384. Ok(())
  4385. })()
  4386. };
  4387. if let Err(e) = ran {
  4388. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4389. }
  4390. {
  4391. use crate::shadow::CARD_STATS;
  4392. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4393. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4394. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4395. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4396. }
  4397. if wide_merge() && pieces.len() >= 8 {
  4398. // The pieces are apart from one another (each its own bytes
  4399. // of its copy and of title memory): several at a time.
  4400. let fetched = *data;
  4401. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4402. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4403. let each = pieces.len().div_ceil(8);
  4404. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4405. .chunks(each)
  4406. .map(|chunk| {
  4407. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4408. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4409. let counts = counts.clone();
  4410. Box::new(move || {
  4411. let mut title = Vec::new();
  4412. for (shadow, i, lo, hi, at) in chunk {
  4413. // SAFETY: the mapping of the fetched bytes;
  4414. // the copy into it has run, and the caller
  4415. // waits for this job.
  4416. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4417. let merged = shadow.card_merge(lo, gpu, &mut title);
  4418. shadow.walls_merged(gpu.len(), merged);
  4419. counts[i].fetch_add(merged, Ordering::Relaxed);
  4420. }
  4421. }) as Box<dyn FnOnce() + Send>
  4422. })
  4423. .collect();
  4424. crate::shadow::wide_run(jobs);
  4425. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4426. *written += count.load(Ordering::Relaxed);
  4427. }
  4428. } else {
  4429. let mut title = Vec::new();
  4430. for &(i, lo, hi, at) in &pieces {
  4431. // SAFETY: the mapping of the fetched bytes, `total` of
  4432. // them; the copy into it has run.
  4433. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4434. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4435. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4436. written[i] += merged;
  4437. }
  4438. }
  4439. }
  4440. for (r, written) in plan.ranges.iter().zip(written) {
  4441. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4442. let (from, to) = r.declared;
  4443. #[cfg(feature = "diagnostics")]
  4444. crate::copystat::compared(from, to - from, written);
  4445. let _ = (from, to);
  4446. }
  4447. }
  4448. /// Runs closed lists and waits for them, and with [`late`] for
  4449. /// everything sent to the card before them, which is settled first.
  4450. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4451. // Behind what the title's queues were given before it.
  4452. crate::queue::before_sync();
  4453. let _ = self.submit(runs, false);
  4454. }
  4455. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4456. /// from the title's, go to the card in `order` and are not waited for.
  4457. /// They join the line of flights and are settled, with the others in
  4458. /// the air, at the next point where what they do can be observed
  4459. /// ([`late`] lists those points); their host lists are reset and kept
  4460. /// for reuse then, as a queue does for the lists it ran.
  4461. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4462. if order.is_empty() {
  4463. crate::list::recycle(lists, &order);
  4464. return;
  4465. }
  4466. late_threads();
  4467. let sent = {
  4468. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4469. self.submit(&runs, true)
  4470. };
  4471. let Some((mut submitted, sent)) = sent else {
  4472. // (Not reached: a submission sent ahead always comes back.)
  4473. crate::list::recycle(lists, &order);
  4474. return;
  4475. };
  4476. let told = !sent.writes.is_empty();
  4477. let most = {
  4478. let mut line = line();
  4479. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4480. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4481. *flying += order.len();
  4482. *target = *submitted;
  4483. items.push(Late::Run(Flight {
  4484. number: sent.number,
  4485. fence: *target,
  4486. lists,
  4487. order,
  4488. card: sent.card,
  4489. back: sent.back,
  4490. own: sent.own,
  4491. }));
  4492. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4493. *flying >= late_most()
  4494. };
  4495. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4496. RELAY_MOVED.notify_one();
  4497. if told && !late_writes() {
  4498. self.settle(&mut submitted, WHY_WRITES);
  4499. } else if most && relay_exact() {
  4500. // Until there are fewer, not until there are none.
  4501. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4502. } else if most {
  4503. self.settle(&mut submitted, WHY_MOST);
  4504. } else {
  4505. LINE_MOVED.notify_one();
  4506. }
  4507. drop(submitted);
  4508. land();
  4509. }
  4510. /// Sends `list`, a closed list of ours (the present's copy), as a
  4511. /// flight ([`late_free_present`]): not waited for, settled with the
  4512. /// others. The caller keeps the list and does not reset it before the
  4513. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4514. /// it ran and was waited for after all.
  4515. fn execute_own(&self, list: &HostList) -> u64 {
  4516. late_threads();
  4517. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4518. return 0;
  4519. };
  4520. let number = sent.number;
  4521. {
  4522. let mut line = line();
  4523. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4524. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4525. *flying += 1;
  4526. *target = *submitted;
  4527. items.push(Late::Run(Flight {
  4528. number,
  4529. fence: *target,
  4530. lists: Vec::new(),
  4531. order: Vec::new(),
  4532. card: sent.card,
  4533. back: sent.back,
  4534. own: sent.own,
  4535. }));
  4536. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4537. }
  4538. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4539. LINE_MOVED.notify_one();
  4540. RELAY_MOVED.notify_one();
  4541. drop(submitted);
  4542. number
  4543. }
  4544. /// Waits for the card to run every flight in the air ([`late`]) and
  4545. /// does what they left to do, as [`Host::execute`] does for one
  4546. /// submission after its wait: the pieces their shaders wrote in copies
  4547. /// in the card's memory are fetched and merged (each once), the ranges
  4548. /// they declared in the other copies are compared and copied back
  4549. /// (each byte once, whichever flights declared it), and then, in the
  4550. /// order they were given: their bottom-of-pipe writes and the fence
  4551. /// signals behind them. `submitted` is the submission lock's value;
  4552. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4553. ///
  4554. /// Everything in the air is settled, never the first flights alone:
  4555. /// the merge writes the copies' CPU side, which a flight still on the
  4556. /// card may be writing too.
  4557. fn settle(&self, submitted: &mut u64, why: usize) {
  4558. if !late() {
  4559. return;
  4560. }
  4561. if relay() {
  4562. // Nothing is settled here: the thread that lands flights does
  4563. // it, in order, and this waits until nothing is in the air and
  4564. // nothing is being landed. Every point that settled before
  4565. // comes here, so each still sees title memory, fences and
  4566. // bottom-of-pipe values as after a settle.
  4567. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4568. return;
  4569. }
  4570. let was_working = working(true);
  4571. let mut counted = false;
  4572. loop {
  4573. let items = {
  4574. let mut line = line();
  4575. if line.line.is_empty() {
  4576. line.settling = false;
  4577. break;
  4578. }
  4579. line.settling = true;
  4580. line.written.clear();
  4581. line.lists = 0;
  4582. std::mem::take(&mut line.line)
  4583. };
  4584. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4585. if !counted {
  4586. counted = true;
  4587. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4588. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4589. }
  4590. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4591. if flights > 0 {
  4592. submitting(2, flights);
  4593. let waiting = std::time::Instant::now();
  4594. // SAFETY: the fence and event are ours, under the
  4595. // submission lock; `submitted` is the last value signalled.
  4596. unsafe {
  4597. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4598. Ok(()) => {
  4599. working(false);
  4600. WaitForSingleObject(self.event, INFINITE);
  4601. stood(waiting);
  4602. working(true);
  4603. }
  4604. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4605. }
  4606. }
  4607. let gpu = waiting.elapsed();
  4608. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4609. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4610. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4611. #[cfg(feature = "diagnostics")]
  4612. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4613. format!("{flights} submissions sent ahead, settled together")
  4614. });
  4615. // SAFETY: a plain query.
  4616. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4617. let runs: Vec<&HostList> = items
  4618. .iter()
  4619. .filter_map(|i| match i {
  4620. Late::Run(f) => Some(f),
  4621. _ => None,
  4622. })
  4623. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4624. .collect();
  4625. fail(format_args!(
  4626. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4627. runs.len(),
  4628. self.removal_data(&runs),
  4629. last_notes(&runs)
  4630. ));
  4631. }
  4632. submitting(3, flights);
  4633. let copying = std::time::Instant::now();
  4634. let mut seen = std::collections::HashSet::new();
  4635. let mut back: Vec<Declared> = Vec::new();
  4636. for item in &items {
  4637. let Late::Run(flight) = item else {
  4638. continue;
  4639. };
  4640. if let Some(card) = &flight.card {
  4641. self.card_back(card, submitted, &mut seen);
  4642. }
  4643. for (shadow, ranges) in &flight.back {
  4644. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4645. Some((_, all)) => {
  4646. for range in ranges {
  4647. if !all.contains(range) {
  4648. all.push(*range);
  4649. }
  4650. }
  4651. }
  4652. None => back.push((shadow.clone(), ranges.clone())),
  4653. }
  4654. }
  4655. }
  4656. hand_back(&back);
  4657. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4658. }
  4659. // In the order given: what tells the title the card is done.
  4660. let mut last = 0;
  4661. let mut landed = Vec::new();
  4662. for item in items {
  4663. match item {
  4664. Late::Run(flight) => {
  4665. last = flight.number;
  4666. for &i in &flight.order {
  4667. read_backs(flight.lists[i].host());
  4668. }
  4669. if let Some(card) = flight.card {
  4670. self.card_done(card);
  4671. }
  4672. landed.push((flight.lists, flight.order));
  4673. }
  4674. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4675. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4676. }
  4677. }
  4678. if last > 0 {
  4679. FINISHED.store(last, Ordering::Release);
  4680. bury(last);
  4681. }
  4682. line().landed.extend(landed);
  4683. }
  4684. if counted {
  4685. self.log_messages();
  4686. submitting(0, 0);
  4687. // What was settled may be what a queue stands at, and the
  4688. // caller may not be one that looks (a read-back, a present).
  4689. if why != WHY_CARD_DONE {
  4690. line().poke = true;
  4691. LINE_MOVED.notify_one();
  4692. }
  4693. }
  4694. working(was_working);
  4695. }
  4696. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4697. /// copies, which flights may be writing and the title wrote too
  4698. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4699. /// those of the submission's one asking, which is made again.
  4700. ///
  4701. /// With [`card_steps`] only the flights that declared them: a range of
  4702. /// a copy nobody declared any more is refreshed like any other. What
  4703. /// they landed is title memory written, so everything is asked and
  4704. /// looked at again; what is left after three times waits as before.
  4705. fn settle_stale(
  4706. &self,
  4707. submitted: &mut u64,
  4708. runs: &[&HostList],
  4709. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4710. ranges: &[(usize, usize)],
  4711. ) {
  4712. if relay_exact() && card_steps::stage() > 0 {
  4713. for _ in 0..3 {
  4714. #[cfg(feature = "diagnostics")]
  4715. blame_stale(&stale);
  4716. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4717. crate::watch::ask_once(ranges);
  4718. stale = stale_under_flights(runs);
  4719. if stale.is_empty() {
  4720. return;
  4721. }
  4722. }
  4723. }
  4724. #[cfg(feature = "diagnostics")]
  4725. blame_stale(&stale);
  4726. self.settle(submitted, WHY_STALE);
  4727. crate::watch::ask_once(ranges);
  4728. }
  4729. /// [`Host::execute`], or with `late` the first half of
  4730. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4731. /// to be done once they have run comes back with the submission lock
  4732. /// still held.
  4733. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4734. #[cfg(feature = "diagnostics")]
  4735. let called = std::time::Instant::now();
  4736. #[cfg(feature = "diagnostics")]
  4737. crate::copystat::submission_begins();
  4738. // One submission at a time from preparation to copy-back: snapshots
  4739. // and the ranges shaders write are per host copy, not per submission.
  4740. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4741. let was_working = working(true);
  4742. submitting(1, runs.len());
  4743. #[cfg(feature = "diagnostics")]
  4744. let ahead = Split::begin();
  4745. #[cfg(feature = "diagnostics")]
  4746. SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed);
  4747. // Flights in the air ([`late`]): a submission that is waited for
  4748. // settles them first, one sent ahead only if preparing it reads
  4749. // what they write.
  4750. // Or the reads are done on the card, behind the flights.
  4751. let own = if late { self.card_steps(runs) } else { None };
  4752. #[cfg(feature = "diagnostics")]
  4753. ahead.part(12);
  4754. if !late {
  4755. self.settle(&mut submitted, WHY_SYNC);
  4756. } else if own.is_none()
  4757. && let Some(why) = late_blocked(runs)
  4758. {
  4759. if relay_exact() && why == WHY_READ {
  4760. // Only until the flights that may write what is read have
  4761. // landed: their copy-back's end, not the card's other work.
  4762. relay_wait(why, |line| {
  4763. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4764. });
  4765. } else {
  4766. self.settle(&mut submitted, why);
  4767. }
  4768. }
  4769. #[cfg(feature = "diagnostics")]
  4770. ahead.part(13);
  4771. // Descriptors the title copied into placed heaps directly, before
  4772. // command lists that index those slots are submitted.
  4773. let heaps_synced = crate::descriptor::begin_sync_heaps();
  4774. // That list runs first, and is one of the submission's from here on.
  4775. let with: Vec<&HostList>;
  4776. let runs = match &own {
  4777. Some(own) => {
  4778. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4779. &with[..]
  4780. }
  4781. None => runs,
  4782. };
  4783. let behind = late && flying();
  4784. // Before this submission counts as started: what the sweep lets go
  4785. // of is named by no list, and nothing runs now (behind flights the
  4786. // sweep waits for a submission that finds none in the air: there is
  4787. // one at every present).
  4788. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4789. if !behind {
  4790. if upcheck::on() {
  4791. upcheck::at_rest(self);
  4792. }
  4793. sweep();
  4794. SWEPT.store(now_ms(), Ordering::Relaxed);
  4795. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4796. // With the present sent ahead nothing else brings a moment
  4797. // with nothing in the air: one is made for the sweep.
  4798. self.settle(&mut submitted, WHY_SYNC);
  4799. if upcheck::on() {
  4800. upcheck::at_rest(self);
  4801. }
  4802. sweep();
  4803. SWEPT.store(now_ms(), Ordering::Relaxed);
  4804. }
  4805. let behind = late && flying();
  4806. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4807. // The ranges shaders write are counted for it (with the relay).
  4808. crate::shadow::preparing(this_submission);
  4809. let started = std::time::Instant::now();
  4810. #[cfg(feature = "diagnostics")]
  4811. ahead.part(14);
  4812. #[cfg(feature = "diagnostics")]
  4813. let lock = (started - called).as_micros() as u64;
  4814. #[cfg(feature = "diagnostics")]
  4815. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4816. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4817. // Where each run's lists start in `lists`.
  4818. let mut firsts = Vec::with_capacity(runs.len());
  4819. let mut batch = Batch::default();
  4820. #[cfg(feature = "diagnostics")]
  4821. let split = Split::begin();
  4822. // The time a settle of flights takes inside this preparing: the
  4823. // wait for the card and the copy-back have their own places on the
  4824. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4825. let mut settled = std::time::Duration::ZERO;
  4826. // One write-watch asking for everything the submission refreshes
  4827. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4828. if crate::watch::once() {
  4829. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  4830. for list in runs {
  4831. for step in &list.deferred().copies {
  4832. if let Step::Refresh(shadow, address, len) = step
  4833. && shadow.asked_ahead()
  4834. {
  4835. let span = spans
  4836. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4837. .or_insert((*address, *address + *len));
  4838. *span = (span.0.min(*address), span.1.max(*address + *len));
  4839. }
  4840. }
  4841. }
  4842. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4843. #[cfg(feature = "diagnostics")]
  4844. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  4845. crate::watch::ask_once(&ranges);
  4846. #[cfg(feature = "diagnostics")]
  4847. split.part(0);
  4848. // Behind flights: the title wrote memory that a flight's shaders
  4849. // may write too, and this submission refreshes it. The flights
  4850. // are settled, and the asking made again: the copy-back wrote
  4851. // title memory, which other copies of it must see.
  4852. if upcheck::on() {
  4853. upcheck::order(runs);
  4854. if behind {
  4855. upcheck::reads(runs);
  4856. }
  4857. }
  4858. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  4859. if !stale.is_empty() {
  4860. let settling = std::time::Instant::now();
  4861. self.settle_stale(&mut submitted, runs, stale, &ranges);
  4862. settled += settling.elapsed();
  4863. }
  4864. } else if behind && !stale_under_flights(runs).is_empty() {
  4865. let settling = std::time::Instant::now();
  4866. self.settle(&mut submitted, WHY_STALE);
  4867. settled += settling.elapsed();
  4868. }
  4869. #[cfg(feature = "diagnostics")]
  4870. split.part(1);
  4871. // What flights in the air may write.
  4872. let air = line().written.clone();
  4873. if ahead_of_writes() {
  4874. batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4875. }
  4876. for list in runs {
  4877. list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4878. firsts.push(lists.len());
  4879. if let Some(prelude) = list.prelude() {
  4880. lists.push(Some(prelude));
  4881. }
  4882. lists.push(list.list.cast().ok());
  4883. }
  4884. batch.fill();
  4885. batch.flush();
  4886. crate::watch::ask_once_end();
  4887. #[cfg(feature = "diagnostics")]
  4888. split.part(2);
  4889. // The snapshots of the ranges shaders may write, if they were left
  4890. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4891. // lists have not gone to the card.
  4892. {
  4893. #[cfg(feature = "diagnostics")]
  4894. let snapshots = std::time::Instant::now();
  4895. crate::shadow::take_snapshots();
  4896. #[cfg(feature = "diagnostics")]
  4897. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4898. }
  4899. #[cfg(feature = "diagnostics")]
  4900. split.part(3);
  4901. // Copies in the card's memory: what changed on their CPU side goes
  4902. // up ahead of the lists, and a compare of what the shaders may
  4903. // write follows them in the same submission.
  4904. let flown = late && relay();
  4905. if flown && self.card_results_low() {
  4906. let settling = std::time::Instant::now();
  4907. self.settle(&mut submitted, WHY_MOST);
  4908. settled += settling.elapsed();
  4909. }
  4910. // What shaders may write through views they pick: last, so that no
  4911. // refresh of this submission leaves it alone.
  4912. let picked = crate::picked::declare(runs);
  4913. for (shadow, at, len) in &picked.written {
  4914. shadow.writing(*at, *len);
  4915. }
  4916. let card = self.card_before(runs, &picked, flown);
  4917. // The sends are taken: from here on the references hold what the
  4918. // copies in the lists put.
  4919. for (shadow, at, bytes) in batch.placed.drain(..) {
  4920. shadow.placed_copy(at, &bytes);
  4921. }
  4922. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4923. lists.push(Some(check));
  4924. }
  4925. #[cfg(feature = "diagnostics")]
  4926. split.part(4);
  4927. drop(heaps_synced);
  4928. // The slots that waited for a texture's host copy, before the
  4929. // lists that may read them run.
  4930. crate::descriptor::make_waiting();
  4931. #[cfg(feature = "diagnostics")]
  4932. split.part(15);
  4933. let prepared = std::time::Instant::now();
  4934. if late {
  4935. *submitted += 1;
  4936. #[cfg(feature = "diagnostics")]
  4937. if let Some([front, behind]) = self.span_lists() {
  4938. lists.insert(0, Some(front));
  4939. lists.push(Some(behind));
  4940. }
  4941. // SAFETY: closed lists; the fence is ours.
  4942. let signalled = unsafe {
  4943. self.queue.ExecuteCommandLists(&lists);
  4944. self.queue.Signal(&self.fence, *submitted)
  4945. };
  4946. awake::sent(&self.device);
  4947. self.card_sent();
  4948. if let Err(e) = signalled {
  4949. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4950. }
  4951. #[cfg(feature = "diagnostics")]
  4952. split.part(5);
  4953. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4954. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4955. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4956. submitting(0, 0);
  4957. #[cfg(feature = "diagnostics")]
  4958. crate::copystat::submission_ends(lock);
  4959. let sent = Sent {
  4960. number: this_submission,
  4961. card,
  4962. back,
  4963. own,
  4964. writes,
  4965. };
  4966. working(was_working);
  4967. return Some((submitted, sent));
  4968. }
  4969. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4970. #[cfg(feature = "diagnostics")]
  4971. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4972. firsts
  4973. .iter()
  4974. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4975. .map(|(&a, &b)| &lists[a..b])
  4976. .collect()
  4977. } else {
  4978. vec![&lists[..]]
  4979. };
  4980. #[cfg(not(feature = "diagnostics"))]
  4981. let groups = [&lists[..]];
  4982. submitting(2, runs.len());
  4983. for (i, group) in groups.iter().enumerate() {
  4984. *submitted += 1;
  4985. let started = std::time::Instant::now();
  4986. // SAFETY: closed lists; the fence and event are ours.
  4987. unsafe {
  4988. self.queue.ExecuteCommandLists(group);
  4989. self.card_sent();
  4990. let waited = self
  4991. .queue
  4992. .Signal(&self.fence, *submitted)
  4993. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4994. match waited {
  4995. Ok(()) => {
  4996. working(false);
  4997. WaitForSingleObject(self.event, INFINITE);
  4998. stood(started);
  4999. working(true);
  5000. }
  5001. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  5002. }
  5003. }
  5004. // With timing on each group is one of `runs` (and the compare
  5005. // of copies in the card's memory, with the last): every
  5006. // command's time on the card goes to the sums by pipeline.
  5007. #[cfg(feature = "diagnostics")]
  5008. if timing() {
  5009. // SAFETY: a plain query.
  5010. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  5011. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  5012. crate::copystat::command_took(&op, ms);
  5013. }
  5014. }
  5015. // A submission of one list was never named here (`groups.len()
  5016. // > 1` was the test): the two 50 ms lists of the gameplay
  5017. // frame, each a submission of its own, printed nothing.
  5018. #[cfg(feature = "diagnostics")]
  5019. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  5020. // SAFETY: a plain query.
  5021. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  5022. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  5023. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  5024. for (ms, op) in runs[i].slowest(frequency, 6) {
  5025. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  5026. }
  5027. }
  5028. let _ = (i, started);
  5029. }
  5030. let _ = &firsts;
  5031. FINISHED.store(this_submission, Ordering::Release);
  5032. bury(this_submission);
  5033. let gpu = prepared.elapsed();
  5034. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  5035. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  5036. #[cfg(feature = "diagnostics")]
  5037. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  5038. let pipelines: std::collections::BTreeSet<String> = runs
  5039. .iter()
  5040. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  5041. .collect();
  5042. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  5043. text.chars().take(1200).collect()
  5044. });
  5045. // The host resets a device whose submission runs for about 2 s.
  5046. if gpu > std::time::Duration::from_millis(250) {
  5047. let pipelines: std::collections::BTreeSet<String> = runs
  5048. .iter()
  5049. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  5050. .collect();
  5051. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  5052. }
  5053. // SAFETY: a plain query.
  5054. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  5055. fail(format_args!(
  5056. "host GPU device removed after a submission of {} lists{}{}",
  5057. runs.len(),
  5058. self.removal_data(runs),
  5059. last_notes(runs)
  5060. ));
  5061. }
  5062. submitting(3, runs.len());
  5063. // What shaders wrote goes back before the bottom-of-pipe writes,
  5064. // which tell the title the GPU is done; each range once per
  5065. // submission, however many dispatches declared it (the world's
  5066. // passes declare the same big ranges dozens of times).
  5067. let copying = std::time::Instant::now();
  5068. // For copies in the card's memory the compare has run there: the
  5069. // pieces that differ are fetched and merged.
  5070. if let Some(card) = &card {
  5071. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  5072. }
  5073. let back = crate::picked::with(declared_writes(runs), &picked.written);
  5074. hand_back(&back);
  5075. if let Some(card) = card {
  5076. self.card_done(card);
  5077. }
  5078. #[cfg(feature = "diagnostics")]
  5079. if !back.is_empty() {
  5080. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  5081. }
  5082. // Nothing of this submission goes back to the title: no range of
  5083. // shader writes, no value written when it is done. The wait for
  5084. // such a one is only for order and for what the card still holds.
  5085. #[cfg(feature = "diagnostics")]
  5086. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  5087. use crate::copystat::{C, add};
  5088. add(C::NothingBack, 1);
  5089. add(C::NothingBackUs, gpu.as_micros() as u64);
  5090. }
  5091. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  5092. for list in runs {
  5093. // Read backs first: a value written at the bottom of the pipe
  5094. // may be what tells the title that they are there.
  5095. read_backs(list);
  5096. for &(at, what, bytes) in &list.deferred().writes {
  5097. what.write(at as *mut u8, bytes);
  5098. }
  5099. }
  5100. self.log_messages();
  5101. submitting(0, 0);
  5102. #[cfg(feature = "diagnostics")]
  5103. crate::copystat::submission_ends(lock);
  5104. // With the relay: nothing is in the air now, so no fetch still to
  5105. // be merged is older than the sends to card copies so far, and
  5106. // their notes can go.
  5107. if relay() {
  5108. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  5109. }
  5110. working(was_working);
  5111. None
  5112. }
  5113. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  5114. /// it lies in (by the names we give them) or the title memory copy just
  5115. /// below it; for each list that did not finish, the command it stopped
  5116. /// at and what the draws and dispatches in flight there run (or, in
  5117. /// lists that never started, the pipelines they bind).
  5118. fn removal_data(&self, runs: &[&HostList]) -> String {
  5119. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  5120. return String::new();
  5121. };
  5122. let mut text = String::new();
  5123. let mut fault_va = None;
  5124. // SAFETY: the outputs are the runtime's, valid while the device
  5125. // lives; nodes are walked as linked, histories have their counts.
  5126. unsafe {
  5127. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  5128. && fault.PageFaultVA != 0
  5129. {
  5130. let va = fault.PageFaultVA;
  5131. fault_va = Some(va);
  5132. text.push_str(&format!("; page fault at {va:#x}"));
  5133. for (what, head) in [
  5134. ("inside", fault.pHeadExistingAllocationNode),
  5135. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  5136. ] {
  5137. let mut names = Vec::new();
  5138. let mut node = head;
  5139. while let Some(n) = node.as_ref()
  5140. && names.len() < 8
  5141. {
  5142. let name = if n.ObjectNameW.is_null() {
  5143. "unnamed".to_owned()
  5144. } else {
  5145. n.ObjectNameW.to_string().unwrap_or_default()
  5146. };
  5147. names.push(format!("{name} (type {})", n.AllocationType.0));
  5148. node = n.pNext;
  5149. }
  5150. if !names.is_empty() {
  5151. text.push_str(&format!("; {what} {names:?}"));
  5152. }
  5153. }
  5154. text.push_str(&crate::shadow::near(va));
  5155. text.push_str(&crate::descriptor::host::near_heaps(va));
  5156. #[cfg(feature = "diagnostics")]
  5157. text.push_str(&crate::book::at_loss(va));
  5158. }
  5159. // The plain output: the extended one (with marker texts) came
  5160. // back without stopped lists on this host.
  5161. if dred_faults() {
  5162. return text;
  5163. }
  5164. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  5165. Ok(crumbs) => crumbs,
  5166. Err(e) => {
  5167. text.push_str(&format!("; no breadcrumbs ({e})"));
  5168. return text;
  5169. }
  5170. };
  5171. // Every list's progress (done/count), in the runtime's order.
  5172. let mut progress = Vec::new();
  5173. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  5174. while let Some(p) = node.as_ref() {
  5175. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5176. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  5177. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  5178. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  5179. node = p.pNext;
  5180. }
  5181. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  5182. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  5183. while let Some(p) = plain.as_ref() {
  5184. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5185. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  5186. let history =
  5187. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  5188. text.push_str(&format!(
  5189. "; a list stopped at command {done} of {} (op {})",
  5190. p.BreadcrumbCount, history[done as usize].0
  5191. ));
  5192. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  5193. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  5194. let named = [
  5195. (!p.pCommandListDebugNameW.is_null()).then(|| p.pCommandListDebugNameW.to_string().unwrap_or_default()),
  5196. (!p.pCommandListDebugNameA.is_null()).then(|| {
  5197. std::ffi::CStr::from_ptr(p.pCommandListDebugNameA.cast()).to_string_lossy().into_owned()
  5198. }),
  5199. ]
  5200. .into_iter()
  5201. .flatten()
  5202. .next()
  5203. .unwrap_or_default();
  5204. text.push_str(&format!(" of \"{named}\""));
  5205. // Not one of the caller's: by the name.
  5206. #[cfg(feature = "diagnostics")]
  5207. let by_name = list_number(&named).and_then(|n| {
  5208. let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  5209. all.get(&n).map(|(notes, pipelines, _)| (notes.upgrade(), pipelines.upgrade()))
  5210. });
  5211. #[cfg(feature = "diagnostics")]
  5212. let indirects = run.map(|r| r.indirects.clone()).or_else(|| {
  5213. let n = list_number(&named)?;
  5214. LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()).get(&n)?.2.upgrade()
  5215. });
  5216. #[cfg(not(feature = "diagnostics"))]
  5217. #[allow(clippy::type_complexity)]
  5218. let by_name: Option<(Option<()>, Option<std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>>)> = None;
  5219. #[cfg(feature = "diagnostics")]
  5220. let noted = run.map(|r| r.notes.clone()).or_else(|| by_name.as_ref().and_then(|b| b.0.clone()));
  5221. let bound = run.map(|r| r.pipelines.clone()).or_else(|| by_name.as_ref().and_then(|b| b.1.clone()));
  5222. // The k-th marker command is the k-th note.
  5223. #[cfg(feature = "diagnostics")]
  5224. let markers: Vec<(u32, String)> = noted.map_or_else(Vec::new, |notes| {
  5225. let notes = notes.lock().unwrap_or_else(|e| e.into_inner());
  5226. history
  5227. .iter()
  5228. .enumerate()
  5229. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  5230. .zip(notes.iter())
  5231. .map(|((at, _), (note, range))| {
  5232. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  5233. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  5234. })
  5235. .collect()
  5236. });
  5237. #[cfg(not(feature = "diagnostics"))]
  5238. let markers: Vec<(u32, String)> = Vec::new();
  5239. #[cfg(not(feature = "diagnostics"))]
  5240. let _ = fault_va;
  5241. if done > 0 {
  5242. text.push_str(&in_flight(history, &markers, done as usize));
  5243. }
  5244. #[cfg(feature = "diagnostics")]
  5245. if let Some(indirects) = indirects {
  5246. text.push_str(&indirects_around(history, done as usize, &indirects));
  5247. }
  5248. // (Without markers a list that stopped midway says what
  5249. // it may have been at only by what it binds.)
  5250. if (done == 0 || markers.is_empty())
  5251. && let Some(bound) = bound
  5252. {
  5253. let pipelines = bound.lock().unwrap_or_else(|e| e.into_inner());
  5254. text.push_str(&format!(", its pipelines {pipelines:?}"));
  5255. }
  5256. }
  5257. plain = p.pNext;
  5258. }
  5259. }
  5260. text
  5261. }
  5262. /// Moves the debug layer's messages into our log; returns the first
  5263. /// error among them.
  5264. pub(crate) fn log_messages(&self) -> Option<String> {
  5265. let Some(queue) = &self.messages else {
  5266. return None;
  5267. };
  5268. let mut first_error = None;
  5269. // SAFETY: each message is read into a buffer of the size the queue
  5270. // reports, then the queue is emptied.
  5271. unsafe {
  5272. for i in 0..queue.GetNumStoredMessages() {
  5273. let mut size = 0;
  5274. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  5275. continue;
  5276. }
  5277. let mut buffer = vec![0u64; size.div_ceil(8)];
  5278. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  5279. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  5280. let m = &*message;
  5281. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  5282. let text = String::from_utf8_lossy(text);
  5283. let text = text.trim_end_matches('\0');
  5284. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  5285. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  5286. first_error = Some(text.to_owned());
  5287. }
  5288. }
  5289. }
  5290. queue.ClearStoredMessages();
  5291. }
  5292. first_error
  5293. }
  5294. /// A host render target view of `resource`, valid until it is recorded.
  5295. pub(crate) fn rtv(
  5296. &self,
  5297. resource: Option<&ID3D12Resource>,
  5298. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  5299. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5300. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5301. // SAFETY: a slot of our heap and a live resource, or none with a
  5302. // description (a typed null view).
  5303. unsafe {
  5304. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  5305. handle.ptr += (slot * self.rtv_size) as usize;
  5306. self.device
  5307. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  5308. handle
  5309. }
  5310. }
  5311. /// A host depth view of `resource`, valid until it is recorded.
  5312. pub(crate) fn dsv(
  5313. &self,
  5314. resource: &ID3D12Resource,
  5315. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  5316. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5317. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5318. // SAFETY: a slot of our heap and a live resource.
  5319. unsafe {
  5320. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  5321. handle.ptr += (slot * self.dsv_size) as usize;
  5322. self.device
  5323. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  5324. handle
  5325. }
  5326. }
  5327. }
  5328. impl HostList {
  5329. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  5330. #[cfg(feature = "diagnostics")]
  5331. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  5332. if !timing() {
  5333. return None;
  5334. }
  5335. self.stamps
  5336. .get_or_init(|| {
  5337. let device = &host()?.device;
  5338. let mut heap: Option<ID3D12QueryHeap> = None;
  5339. let mut back: Option<ID3D12Resource> = None;
  5340. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  5341. let desc = D3D12_RESOURCE_DESC {
  5342. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5343. Width: u64::from(STAMPS) * 8,
  5344. Height: 1,
  5345. DepthOrArraySize: 1,
  5346. MipLevels: 1,
  5347. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  5348. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5349. ..Default::default()
  5350. };
  5351. // SAFETY: plain object creation.
  5352. unsafe {
  5353. device
  5354. .CreateQueryHeap(
  5355. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  5356. &mut heap,
  5357. )
  5358. .ok()?;
  5359. device
  5360. .CreateCommittedResource(
  5361. &readback,
  5362. D3D12_HEAP_FLAG_NONE,
  5363. &desc,
  5364. D3D12_RESOURCE_STATE_COPY_DEST,
  5365. None,
  5366. &mut back,
  5367. )
  5368. .ok()?;
  5369. }
  5370. Some((heap?, back?))
  5371. })
  5372. .as_ref()
  5373. }
  5374. /// The noted commands that took longest on the GPU, longest first, as
  5375. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  5376. #[cfg(feature = "diagnostics")]
  5377. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  5378. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  5379. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  5380. return Vec::new();
  5381. };
  5382. let mut data = std::ptr::null_mut();
  5383. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  5384. // SAFETY: a read-back buffer the finished list resolved into.
  5385. let stamps: Vec<u64> = unsafe {
  5386. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  5387. return Vec::new();
  5388. }
  5389. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  5390. back.Unmap(0, None);
  5391. s
  5392. };
  5393. let mut times: Vec<(f64, String)> = (0..count)
  5394. .map(|i| {
  5395. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5396. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5397. })
  5398. .collect();
  5399. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5400. times.truncate(n);
  5401. times
  5402. }
  5403. pub(crate) fn close(&self) {
  5404. self.twins_to_depth();
  5405. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5406. if let Some((scratch, _)) = scratch {
  5407. self.indirect_common(&scratch);
  5408. }
  5409. self.batches_common();
  5410. self.card_budget_out();
  5411. self.take_coming();
  5412. #[cfg(feature = "diagnostics")]
  5413. if let Some((heap, back)) = self.stamps() {
  5414. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5415. // SAFETY: an open list, our heap and read-back buffer.
  5416. unsafe {
  5417. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5418. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5419. }
  5420. }
  5421. // SAFETY: our list.
  5422. if let Err(e) = unsafe { self.list.Close() } {
  5423. fail(format_args!(
  5424. "a host command list did not close ({e}): a command recorded into it was invalid"
  5425. ));
  5426. }
  5427. }
  5428. /// `work` finds, on a thread of ours, refreshes that belong at this
  5429. /// place among the list's steps; they are there when the list is closed.
  5430. pub(crate) fn refreshes_coming(&self, work: impl FnOnce() -> Vec<aside::Refresh> + Send + 'static) {
  5431. self.take_coming();
  5432. let at = self.deferred().copies.len();
  5433. let coming = aside::begin(work);
  5434. *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = Some((at, coming));
  5435. }
  5436. /// The refreshes that were still to come are put among the steps.
  5437. fn take_coming(&self) {
  5438. let Some((at, coming)) = self.coming.lock().unwrap_or_else(|e| e.into_inner()).take() else {
  5439. return;
  5440. };
  5441. let found = coming.wait();
  5442. let mut deferred = self.deferred();
  5443. let at = at.min(deferred.copies.len());
  5444. deferred
  5445. .copies
  5446. .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize)));
  5447. }
  5448. /// Only after the list's last submission finished (every one is waited
  5449. /// for).
  5450. pub(crate) fn reset(&self) {
  5451. #[cfg(feature = "diagnostics")]
  5452. let started = std::time::Instant::now();
  5453. self._alive.used();
  5454. *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None;
  5455. *self.deferred() = Deferred::default();
  5456. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5457. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5458. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5459. #[cfg(feature = "diagnostics")]
  5460. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5461. #[cfg(feature = "diagnostics")]
  5462. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5463. {
  5464. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5465. (scratch.current, scratch.used) = (0, 0);
  5466. // Every submission of the list has run: nothing reads its
  5467. // scratch memory any more, and the next list to ask takes it.
  5468. if scratch_pool() {
  5469. give_chunks(std::mem::take(&mut scratch.chunks));
  5470. }
  5471. }
  5472. // SAFETY: the list is not executing.
  5473. let reset = unsafe {
  5474. self.allocator
  5475. .Reset()
  5476. .and_then(|()| self.list.Reset(&self.allocator, None))
  5477. };
  5478. if let Err(e) = reset {
  5479. fail(format_args!("a host command list did not reset ({e})"));
  5480. }
  5481. #[cfg(feature = "diagnostics")]
  5482. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5483. }
  5484. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5485. /// list: the host texture and the state it leaves, if that is a change.
  5486. /// The list's first use of a texture records nothing: its prelude brings
  5487. /// the texture there at submission.
  5488. pub(crate) fn transition(
  5489. &self,
  5490. resource: crate::object::This,
  5491. wanted: u32,
  5492. ) -> Option<(&'static ID3D12Resource, u32)> {
  5493. let copy = crate::resource::host_copy(resource)?;
  5494. // SAFETY: as in `crate::resource::host_resource`; the list's states
  5495. // hold the copy from here on.
  5496. let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(&copy.texture) };
  5497. let wanted = legal_state(texture, wanted);
  5498. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5499. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5500. std::collections::hash_map::Entry::Vacant(v) => {
  5501. v.insert((wanted, wanted, copy));
  5502. None
  5503. }
  5504. std::collections::hash_map::Entry::Occupied(mut o) => {
  5505. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5506. (before != wanted).then_some((texture, before))
  5507. }
  5508. }
  5509. }
  5510. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5511. /// as [`HostList::transition`] does a title resource's host copy, and
  5512. /// records the barrier: for textures that are not a title resource's
  5513. /// host copy (colour twins) and for the copies between the two.
  5514. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5515. let wanted = legal_state(&copy.texture, wanted);
  5516. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5517. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5518. std::collections::hash_map::Entry::Vacant(v) => {
  5519. v.insert((wanted, wanted, copy.clone()));
  5520. None
  5521. }
  5522. std::collections::hash_map::Entry::Occupied(mut o) => {
  5523. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5524. (before != wanted).then_some(before)
  5525. }
  5526. };
  5527. drop(states);
  5528. if let Some(before) = before {
  5529. let barrier = transition(
  5530. &copy.texture,
  5531. D3D12_RESOURCE_STATES(before as i32),
  5532. D3D12_RESOURCE_STATES(wanted as i32),
  5533. );
  5534. // SAFETY: an open list and a live texture.
  5535. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5536. }
  5537. }
  5538. /// A use of title texture `resource` about to be recorded, if it is a
  5539. /// depth texture with a colour twin (false if it is not): of the twin
  5540. /// (`colour`: unordered access) or of the depth texture (depth target,
  5541. /// clear, shader read, copy, resolve), writing it or only reading. The
  5542. /// side used is first brought up to date: by a copy recorded here if
  5543. /// this list wrote the other side since, by the list's prelude if the
  5544. /// list uses the side as it finds it. The twin is left in the
  5545. /// unordered access state; the caller moves the depth texture to the
  5546. /// state its use needs, as for any texture. A twin still ahead when the
  5547. /// list closes is copied then (`twins_to_depth`).
  5548. /// shortcut: every depth target bound for a draw counts as written
  5549. /// (also when the draw only tests), and every unordered access view a
  5550. /// shader names as written; views a shader picks from the heap by a
  5551. /// computed index are not seen here at all.
  5552. pub(crate) fn twin_use(
  5553. &self,
  5554. resource: crate::object::This,
  5555. colour: bool,
  5556. write: bool,
  5557. ) -> bool {
  5558. const UNORDERED_ACCESS: u32 = 0x8;
  5559. // Asked for every texture a draw reads: most have no twin.
  5560. let Some(twin) = crate::resource::twin(resource) else {
  5561. return false;
  5562. };
  5563. let Some(depth) = crate::resource::host_copy(resource) else {
  5564. return false;
  5565. };
  5566. let side = usize::from(colour);
  5567. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5568. let u = twins
  5569. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5570. .or_insert_with(|| TwinUse {
  5571. depth: depth.clone(),
  5572. twin: twin.clone(),
  5573. needs: [false; 2],
  5574. behind: [None; 2],
  5575. writing: false,
  5576. late: false,
  5577. });
  5578. let copy = match u.behind[side] {
  5579. Some(behind) => behind,
  5580. None => {
  5581. u.needs[side] = true;
  5582. false
  5583. }
  5584. };
  5585. u.behind[side] = Some(false);
  5586. match (write, colour) {
  5587. // Shaders write the twin when the draw or dispatch runs: what
  5588. // the same one reads of the depth texture is prepared before
  5589. // (`twins_written`).
  5590. (true, true) => u.writing = true,
  5591. (true, false) => u.behind[1] = Some(true),
  5592. (false, _) => {}
  5593. }
  5594. // shortcut: the depth plane's twin is not drawn into the plane
  5595. // here: the pass sets a pipeline and a target of ours, which a list
  5596. // still recording the title's commands cannot take. This use sees
  5597. // the plane as it was; the pass runs when the list closes
  5598. // (`twins_to_depth`). Counted.
  5599. if copy && !colour && twin.plane.is_some() {
  5600. u.late = true;
  5601. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5602. }
  5603. drop(twins);
  5604. if copy {
  5605. self.twin_copy(&depth, &twin, colour);
  5606. } else if colour {
  5607. self.settle(&twin.colour, UNORDERED_ACCESS);
  5608. }
  5609. // The depth plane's twin is written through unordered access too.
  5610. if colour && let Some(plane) = &twin.plane {
  5611. self.settle(plane, UNORDERED_ACCESS);
  5612. }
  5613. true
  5614. }
  5615. /// Records the pass that draws the twin of the depth plane of `depth`
  5616. /// into the plane, if `twin` has one, with the moves to the states the
  5617. /// pass needs; the twin is left in the unordered access state. Only
  5618. /// for a list that records nothing of the title's afterwards
  5619. /// (`record_plane_pass`).
  5620. fn pass_plane(
  5621. &self,
  5622. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5623. twin: &crate::resource::Twin,
  5624. ) {
  5625. const UNORDERED_ACCESS: u32 = 0x8;
  5626. const DEPTH_WRITE: u32 = 0x10;
  5627. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5628. let Some(plane) = &twin.plane else { return };
  5629. self.settle(depth, DEPTH_WRITE);
  5630. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5631. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5632. self.settle(plane, UNORDERED_ACCESS);
  5633. }
  5634. /// Records the copy of a depth texture into its colour twin (`colour`)
  5635. /// or of the twin into the depth texture, with the moves to the copy
  5636. /// states. The twin is left in the unordered access state.
  5637. fn twin_copy(
  5638. &self,
  5639. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5640. twin: &crate::resource::Twin,
  5641. colour: bool,
  5642. ) {
  5643. const UNORDERED_ACCESS: u32 = 0x8;
  5644. const COPY_DEST: u32 = 0x400;
  5645. const COPY_SOURCE: u32 = 0x800;
  5646. let (from, to) = if colour {
  5647. (depth, &twin.colour)
  5648. } else {
  5649. (&twin.colour, depth)
  5650. };
  5651. self.settle(from, COPY_SOURCE);
  5652. self.settle(to, COPY_DEST);
  5653. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5654. self.settle(&twin.colour, UNORDERED_ACCESS);
  5655. }
  5656. /// Before the list closes: the depth textures whose twins it wrote last
  5657. /// are given what was written, and left readable by shaders. Shaders
  5658. /// that pick a view from the heap by a computed index are not seen by
  5659. /// `twin_use` and read the depth texture in lists that never name it
  5660. /// (in a captured frame of the title no table names a shadow
  5661. /// map for reading but the pass that fills the next one).
  5662. fn twins_to_depth(&self) {
  5663. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5664. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5665. let written: Vec<_> = twins
  5666. .values_mut()
  5667. .filter(|u| u.behind[0] == Some(true) || u.late)
  5668. .map(|u| {
  5669. // Not copied again if the list copied since the last write
  5670. // and only the depth plane's pass is left.
  5671. let copy = u.behind[0] == Some(true);
  5672. u.behind[0] = Some(false);
  5673. u.late = false;
  5674. (u.depth.clone(), u.twin.clone(), copy)
  5675. })
  5676. .collect();
  5677. drop(twins);
  5678. for (depth, twin, copy) in &written {
  5679. if *copy {
  5680. self.twin_copy(depth, twin, false);
  5681. }
  5682. // Nothing of the title's is recorded after this: the pass may
  5683. // leave its own pipeline and target set.
  5684. self.pass_plane(depth, twin);
  5685. self.settle(depth, SHADER_RESOURCE);
  5686. }
  5687. }
  5688. /// The draw or dispatch just prepared is recorded: the twins it writes
  5689. /// now hold what their depth textures lack.
  5690. pub(crate) fn twins_written(&self) {
  5691. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5692. for u in twins.values_mut().filter(|u| u.writing) {
  5693. u.writing = false;
  5694. u.behind[0] = Some(true);
  5695. }
  5696. }
  5697. /// At submission: the list that moves each texture this list uses from
  5698. /// its real state to the one the list starts with; the textures' real
  5699. /// states become those the list ends with. For depth textures with a
  5700. /// colour twin it first copies the side the list uses as it finds it
  5701. /// from the other, if a list submitted earlier left it behind.
  5702. fn prelude(&self) -> Option<ID3D12CommandList> {
  5703. const COPY_DEST: u32 = 0x400;
  5704. const COPY_SOURCE: u32 = 0x800;
  5705. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5706. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5707. // The copies (depth texture, twin, whether into the twin); the
  5708. // sides are then as this list leaves them.
  5709. let mut syncs = Vec::new();
  5710. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5711. for u in twins.values() {
  5712. let real = u.twin.behind.load(Ordering::Relaxed);
  5713. let mut behind = [real & 1 != 0, real & 2 != 0];
  5714. for side in [0, 1] {
  5715. if u.needs[side] && behind[side] {
  5716. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5717. behind = [false; 2];
  5718. }
  5719. }
  5720. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5721. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5722. u.twin.behind.store(left, Ordering::Relaxed);
  5723. }
  5724. drop(twins);
  5725. // A copy runs with its textures in the copy states: each moves
  5726. // there from its real state, and from there to the state the list
  5727. // starts with (back to its real state if the list does not use it).
  5728. let mut to_copy = Vec::new();
  5729. let mut barriers = Vec::new();
  5730. let mut copying = std::collections::HashMap::new();
  5731. for (depth, twin, colour) in &syncs {
  5732. let (from, to) = if *colour {
  5733. (depth, &twin.colour)
  5734. } else {
  5735. (&twin.colour, depth)
  5736. };
  5737. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  5738. let key = std::sync::Arc::as_ptr(texture) as usize;
  5739. let real = texture.state.load(Ordering::Relaxed);
  5740. copying.insert(key, state);
  5741. if real != state {
  5742. to_copy.push(transition(
  5743. &texture.texture,
  5744. host_state(real),
  5745. host_state(state),
  5746. ));
  5747. if !states.contains_key(&key) {
  5748. barriers.push(transition(
  5749. &texture.texture,
  5750. host_state(state),
  5751. host_state(real),
  5752. ));
  5753. }
  5754. }
  5755. }
  5756. }
  5757. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5758. let real = copy.state.swap(*last, Ordering::Relaxed);
  5759. let real = copying.get(key).copied().unwrap_or(real);
  5760. (real != *first)
  5761. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5762. }));
  5763. if barriers.is_empty() && syncs.is_empty() {
  5764. return None;
  5765. }
  5766. let Some((allocator, list)) = self
  5767. .prelude
  5768. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5769. .as_ref()
  5770. else {
  5771. fail(format_args!("no host list for a state prelude"));
  5772. };
  5773. // SAFETY: the prelude is not executing (every submission is waited
  5774. // for); the textures are live.
  5775. let recorded = unsafe {
  5776. allocator.Reset().and_then(|()| {
  5777. list.Reset(allocator, None)?;
  5778. if !to_copy.is_empty() {
  5779. list.ResourceBarrier(&to_copy);
  5780. }
  5781. for (depth, twin, colour) in &syncs {
  5782. record_twin_copy(list, &depth.texture, twin, *colour);
  5783. }
  5784. if !barriers.is_empty() {
  5785. list.ResourceBarrier(&barriers);
  5786. }
  5787. list.Close()
  5788. })
  5789. };
  5790. if let Err(e) = recorded {
  5791. fail(format_args!("a host state prelude did not record ({e})"));
  5792. }
  5793. list.cast().ok()
  5794. }
  5795. /// Notes what the command about to be recorded does, as a marker
  5796. /// command whose text the list keeps (diagnostics, with device-removed
  5797. /// data on): the report pairs the breadcrumbs' marker commands with the
  5798. /// texts in order and names the commands a fault stopped among.
  5799. #[cfg(feature = "diagnostics")]
  5800. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5801. self.note(what, None);
  5802. }
  5803. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5804. /// `(address, bytes)`: the report places the faulting address in it.
  5805. #[cfg(feature = "diagnostics")]
  5806. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5807. self.note(what, Some(range));
  5808. }
  5809. #[cfg(feature = "diagnostics")]
  5810. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5811. if !dred_on() {
  5812. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5813. return;
  5814. }
  5815. {
  5816. let started = std::time::Instant::now();
  5817. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5818. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5819. // SAFETY: an open list and our query heap.
  5820. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5821. }
  5822. let what = what();
  5823. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5824. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5825. const UNICODE: u32 = 0;
  5826. // SAFETY: an open list; the marker is copied when recorded.
  5827. unsafe {
  5828. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5829. };
  5830. self.notes
  5831. .lock()
  5832. .unwrap_or_else(|e| e.into_inner())
  5833. .push((what, range));
  5834. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5835. }
  5836. }
  5837. /// Whether nothing recorded since the list was opened does any work:
  5838. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5839. /// upload or resolve (they defer a step or move a texture's state), no
  5840. /// bottom-of-pipe write. State set on the list does not count.
  5841. pub(crate) fn untouched(&self) -> bool {
  5842. {
  5843. let deferred = self.deferred();
  5844. if !(deferred.copies.is_empty()
  5845. && deferred.uploads.is_empty()
  5846. && deferred.kept.is_empty()
  5847. && deferred.textures.is_empty()
  5848. && deferred.writes.is_empty()
  5849. && deferred.backs.is_empty())
  5850. {
  5851. return false;
  5852. }
  5853. }
  5854. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5855. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5856. }
  5857. /// Notes an indirect execution, while device-removed data is kept
  5858. /// ([`indirects`]).
  5859. #[cfg(feature = "diagnostics")]
  5860. pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) {
  5861. if dred_on() || dred_light() {
  5862. self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user);
  5863. }
  5864. }
  5865. /// Notes a pipeline the list binds.
  5866. pub(crate) fn used_pipeline(&self, name: &str) {
  5867. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5868. if !pipelines.contains(name) {
  5869. pipelines.insert(name.to_owned());
  5870. }
  5871. }
  5872. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5873. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5874. }
  5875. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5876. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5877. let mut deferred = self.deferred();
  5878. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5879. // A copy that goes on where the one recorded just before it ended,
  5880. // source and destination both: with `join_copies` the two are one
  5881. // step.
  5882. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5883. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5884. {
  5885. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5886. if join_copies() {
  5887. *n += len;
  5888. return;
  5889. }
  5890. }
  5891. deferred
  5892. .copies
  5893. .push(Step::Copy(dst as usize, src as usize, len));
  5894. deferred.refreshed.clear();
  5895. }
  5896. /// Copies `len` bytes of title memory at `src` into the list's upload
  5897. /// memory at `dst` when the list is submitted.
  5898. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5899. self.deferred()
  5900. .copies
  5901. .push(Step::Fill(dst as usize, src as usize, len, None));
  5902. }
  5903. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5904. /// title heap's address, and the slot) shows.
  5905. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5906. self.deferred()
  5907. .copies
  5908. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  5909. }
  5910. /// As [`HostList::defer_fill`], for the beginning of a buffer
  5911. /// [`HostList::upload`] made.
  5912. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  5913. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  5914. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  5915. }
  5916. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5917. /// when the list is submitted (once per range until a title copy
  5918. /// intervenes), keeping the copy alive until the list is reset.
  5919. pub(crate) fn defer_refresh(
  5920. &self,
  5921. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5922. address: usize,
  5923. len: usize,
  5924. ) {
  5925. let mut deferred = self.deferred();
  5926. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5927. if deferred.refreshed.insert(key) {
  5928. deferred
  5929. .copies
  5930. .push(Step::Refresh(shadow.clone(), address, len));
  5931. }
  5932. }
  5933. /// Shaders of the list write `[address, address + len)` of a buffer's
  5934. /// host copy: copied back into title memory once the list has run.
  5935. pub(crate) fn defer_gpu_write(
  5936. &self,
  5937. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5938. address: usize,
  5939. len: usize,
  5940. ) {
  5941. self.deferred()
  5942. .copies
  5943. .push(Step::GpuWrite(shadow.clone(), address, len));
  5944. }
  5945. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5946. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5947. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5948. /// the list is reset.
  5949. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5950. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5951. }
  5952. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5953. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5954. self.deferred().writes.push((dst as usize, what, bytes));
  5955. }
  5956. /// A mapped upload buffer of `size` bytes, alive until the list is
  5957. /// reset.
  5958. ///
  5959. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5960. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5961. // With [`card_steps`] the card may be the one that fills it.
  5962. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  5963. name(&buffer, || format!("list upload {size:#x}"));
  5964. self.deferred().hold_upload(buffer.clone(), size);
  5965. Some((buffer, data))
  5966. }
  5967. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5968. /// reset: the host GPU address and the CPU pointer.
  5969. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5970. let (buffer, at, data) = self.scratch_at(len)?;
  5971. // SAFETY: a live buffer.
  5972. Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data))
  5973. }
  5974. /// [`HostList::scratch`] and the buffer it lies in, for a descriptor
  5975. /// slot to hold: the slot outlives the list's use of it.
  5976. pub(crate) fn scratch_held(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  5977. let (buffer, at, data) = self.scratch_at(len)?;
  5978. // SAFETY: a live buffer.
  5979. let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at;
  5980. Some((buffer, gpu, data))
  5981. }
  5982. /// [`HostList::scratch`]: the buffer, the offset in it and the CPU
  5983. /// pointer.
  5984. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  5985. let host = host()?;
  5986. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5987. let len = len.max(1).next_multiple_of(256);
  5988. if len > SCRATCH_CHUNK {
  5989. let (buffer, data) = host.upload_buffer(len)?;
  5990. name(&buffer, || format!("list scratch {len:#x}"));
  5991. self.deferred().hold_upload(buffer.clone(), len);
  5992. return Some((buffer, 0, data));
  5993. }
  5994. // The chunk in use while `len` fits in what is left of it, else the
  5995. // next one (a list's first chunk may be a small one).
  5996. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5997. (s.current, s.used) = (s.current + 1, 0);
  5998. }
  5999. if s.current == s.chunks.len() {
  6000. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  6001. SCRATCH_FIRST
  6002. } else {
  6003. SCRATCH_CHUNK
  6004. };
  6005. let chunk = take_chunk(host, size)?;
  6006. s.chunks.push((chunk, size));
  6007. s.used = 0;
  6008. }
  6009. let (data, buffer) = (s.chunks[s.current].0.data, s.chunks[s.current].0.buffer.clone());
  6010. let at = s.used;
  6011. s.used += len;
  6012. Some((buffer, at, (data + at as usize) as *mut u8))
  6013. }
  6014. /// The bytes of scratch chunks the list holds now (after a reset:
  6015. /// none while lists share their chunks).
  6016. pub(crate) fn scratch_kept(&self) -> u64 {
  6017. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  6018. scratch.chunks.iter().map(|c| c.1).sum()
  6019. }
  6020. /// The host address of the list's indirect-work budget, zeroed at each
  6021. /// submission of the list from the first use after a reset on.
  6022. pub(crate) fn budget(&self) -> Option<u64> {
  6023. let (buffer, data) = self
  6024. .budget
  6025. .get_or_init(|| {
  6026. let (b, d) = host()?.shared_buffer(256)?;
  6027. Some((b, d as usize))
  6028. })
  6029. .as_ref()?;
  6030. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  6031. let mut deferred = self.deferred();
  6032. if !deferred.budget_zeroed {
  6033. deferred.budget_zeroed = true;
  6034. let at = *data;
  6035. // SAFETY: the list's own mapped words, written before it runs.
  6036. // The words after the budget hold what the clamp noted about the
  6037. // list's last run (mesh dispatches: the largest group count
  6038. // asked for, the groups asked in all; with the card's copy, as
  6039. // the list's end copied them here): taken, then zeroed.
  6040. let notes = Box::new(move || unsafe {
  6041. let words = at as *mut u32;
  6042. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  6043. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  6044. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  6045. for k in 0..3 {
  6046. words.add(k).write_volatile(0);
  6047. }
  6048. });
  6049. deferred.copies.push(Step::Host(notes, (0, 0)));
  6050. drop(deferred);
  6051. if let Some(card) = card {
  6052. self.zero_card_budget(card);
  6053. }
  6054. }
  6055. // SAFETY: a live buffer.
  6056. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  6057. }
  6058. /// The budget's words in the card's own memory ([`card_budget`]), if
  6059. /// the list can zero them itself (`WriteBufferImmediate`).
  6060. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  6061. if !card_budget() {
  6062. return None;
  6063. }
  6064. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  6065. let buffer = host()?.uav_buffer(256)?;
  6066. name(&buffer, || "indirect budget".to_owned());
  6067. Some(buffer)
  6068. }
  6069. /// Records, before the list's first clamp, the zeroing of the card's
  6070. /// copy of the budget: common, written as a copy, then left for
  6071. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  6072. fn zero_card_budget(&self, card: &ID3D12Resource) {
  6073. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  6074. return;
  6075. };
  6076. // SAFETY: a live buffer.
  6077. let at = unsafe { card.GetGPUVirtualAddress() };
  6078. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  6079. Dest: at + offset,
  6080. Value: 0,
  6081. });
  6082. // SAFETY: an open list; the buffer is the list's own and in the
  6083. // common state at the start of every recording.
  6084. unsafe {
  6085. self.list.ResourceBarrier(&[transition(
  6086. card,
  6087. D3D12_RESOURCE_STATE_COMMON,
  6088. D3D12_RESOURCE_STATE_COPY_DEST,
  6089. )]);
  6090. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  6091. self.list.ResourceBarrier(&[transition(
  6092. card,
  6093. D3D12_RESOURCE_STATE_COPY_DEST,
  6094. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  6095. )]);
  6096. }
  6097. }
  6098. /// Before the list closes, if this recording charged the card's copy
  6099. /// of the budget: its notes on mesh records go to the mapped words
  6100. /// (read at the next submission), and it goes back to common.
  6101. fn card_budget_out(&self) {
  6102. if !self.deferred().budget_zeroed {
  6103. return;
  6104. }
  6105. let (Some(Some(card)), Some(Some((mapped, _)))) =
  6106. (self.card_budget.get(), self.budget.get())
  6107. else {
  6108. return;
  6109. };
  6110. // SAFETY: an open list; both buffers are the list's own. The
  6111. // mapped one is promoted from common to the copy destination.
  6112. unsafe {
  6113. self.list.ResourceBarrier(&[transition(
  6114. card,
  6115. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  6116. D3D12_RESOURCE_STATE_COPY_SOURCE,
  6117. )]);
  6118. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  6119. self.list.ResourceBarrier(&[transition(
  6120. card,
  6121. D3D12_RESOURCE_STATE_COPY_SOURCE,
  6122. D3D12_RESOURCE_STATE_COMMON,
  6123. )]);
  6124. }
  6125. }
  6126. /// A device-local unordered-access buffer of at least `size` bytes for
  6127. /// clamped indirect arguments, reused across executions and resets of the
  6128. /// list. Smaller buffers replaced mid-list stay alive until
  6129. /// [`HostList::reset`].
  6130. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  6131. let needed = size.max(64 << 10);
  6132. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  6133. if let Some((buffer, cap)) = &*slot
  6134. && *cap >= needed
  6135. {
  6136. return Some(buffer.clone());
  6137. }
  6138. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  6139. let alloc = prev
  6140. .saturating_mul(2)
  6141. .max(needed)
  6142. .next_multiple_of(64 << 10);
  6143. let buffer = host()?.uav_buffer(alloc)?;
  6144. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  6145. let old = slot.replace((buffer.clone(), alloc));
  6146. drop(slot);
  6147. if let Some((old_buf, _)) = old {
  6148. // It ends the list common, as every scratch buffer does.
  6149. self.indirect_common(&old_buf);
  6150. self.keep(&old_buf);
  6151. }
  6152. Some(buffer)
  6153. }
  6154. /// Where the next batch of clamped records goes: a device-local buffer
  6155. /// the list keeps from recording to recording, the batch's place in it
  6156. /// and the state the buffer is in. Every batch of a recording has a place
  6157. /// of its own: the executions before it may still read theirs.
  6158. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  6159. use crate::indirect::batch::{JOBS, SLOT};
  6160. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6161. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  6162. if buffer == args.0.len() {
  6163. let size = u64::from(BATCHES * JOBS * SLOT);
  6164. let made = host()?.uav_buffer(size)?;
  6165. name(&made, || format!("indirect batches {size:#x}"));
  6166. args.0.push(made);
  6167. }
  6168. args.1 += 1;
  6169. // (Its first batch finds it as the recording before left it:
  6170. // `batches_common`.)
  6171. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  6172. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  6173. }
  6174. /// Before the list closes: the scratch buffers of the batched clamps go
  6175. /// back to the common state, where the next recording expects them.
  6176. fn batches_common(&self) {
  6177. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  6178. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  6179. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  6180. .iter()
  6181. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  6182. .collect();
  6183. if !barriers.is_empty() {
  6184. // SAFETY: an open list and live buffers this recording left in
  6185. // `INDIRECT_ARGUMENT`.
  6186. unsafe { self.list.ResourceBarrier(&barriers) };
  6187. }
  6188. }
  6189. /// Moves `scratch` back to the common state if a clamp left it readable
  6190. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  6191. /// list's first clamp expects it. Done before the list closes and before
  6192. /// a bigger scratch buffer replaces it: one barrier per list (where
  6193. /// there was one per indirect execution), and the list ends as it
  6194. /// begins however it is submitted.
  6195. fn indirect_common(&self, scratch: &ID3D12Resource) {
  6196. {
  6197. let mut deferred = self.deferred();
  6198. if deferred.indirect_readable != scratch.as_raw() as usize {
  6199. return;
  6200. }
  6201. deferred.indirect_readable = 0;
  6202. }
  6203. let barrier = transition(
  6204. scratch,
  6205. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  6206. D3D12_RESOURCE_STATE_COMMON,
  6207. );
  6208. // SAFETY: an open list and a live buffer this recording left in
  6209. // `INDIRECT_ARGUMENT`.
  6210. unsafe { self.list.ResourceBarrier(&[barrier]) };
  6211. }
  6212. /// The state the list's indirect scratch buffer `scratch` is in at this
  6213. /// point of the recording: indirect arguments if a clamp in this
  6214. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  6215. /// common: the state a buffer is made in, and the one a recording
  6216. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  6217. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  6218. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  6219. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  6220. } else {
  6221. D3D12_RESOURCE_STATE_COMMON
  6222. }
  6223. }
  6224. /// A clamp recorded in this list left `scratch` readable as indirect
  6225. /// arguments. It stays so for every execution that reads it, until the
  6226. /// next clamp moves it back to unordered access.
  6227. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  6228. self.deferred().indirect_readable = scratch.as_raw() as usize;
  6229. }
  6230. /// Keeps `object` alive until the list is reset.
  6231. pub(crate) fn keep(&self, object: &impl Interface) {
  6232. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  6233. self.deferred().kept.push(object);
  6234. }
  6235. }
  6236. /// Whether this is the first time since the reset that the list asks
  6237. /// about `key` (a texture to bring up to date).
  6238. pub(crate) fn first_use(&self, key: usize) -> bool {
  6239. self.deferred().textures.insert(key)
  6240. }
  6241. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  6242. /// reset.
  6243. pub(crate) fn used(&self, key: usize) -> bool {
  6244. self.deferred().textures.contains(&key)
  6245. }
  6246. /// Runs `work` when the list is submitted, in order with its copies.
  6247. /// `work` may write title memory (refreshes after it copy again).
  6248. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  6249. self.deferred().copies.push(Step::Run(Box::new(work)));
  6250. self.deferred().refreshed.clear();
  6251. }
  6252. /// As [`HostList::defer`], for work that writes only host memory.
  6253. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  6254. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  6255. }
  6256. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  6257. /// memory at `from`.
  6258. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  6259. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  6260. }
  6261. /// Brings a texture's staging buffer up to date when the list is
  6262. /// submitted, keeping it alive until the list is reset.
  6263. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  6264. self.deferred().copies.push(Step::Texture(staging));
  6265. }
  6266. /// Runs the list's submission-time steps; refreshes go into `batch`
  6267. /// (the title's big buffers, a 174 MB one among them, are read by most
  6268. /// lists of a submission, through many ranges). Copies and fills that
  6269. /// `taken` names (by their place) are left out: they are done on the
  6270. /// card ([`card_steps`]).
  6271. fn run_deferred(&self, batch: &mut Batch, air: &[(usize, usize)], taken: impl Fn(usize) -> bool) {
  6272. #[cfg(feature = "diagnostics")]
  6273. use crate::copystat::{C, add};
  6274. // The time and the bytes of the copies and fills, some 13,000 a
  6275. // frame between 20,000 refreshes: summed here and added once.
  6276. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  6277. #[cfg(feature = "diagnostics")]
  6278. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  6279. for (i, step) in self.deferred().copies.iter().enumerate() {
  6280. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  6281. continue;
  6282. }
  6283. let (started, copied) = match step {
  6284. &Step::Copy(dst, src, len) => {
  6285. let started = std::time::Instant::now();
  6286. #[cfg(feature = "diagnostics")]
  6287. {
  6288. copies += 1;
  6289. }
  6290. batch.fill();
  6291. batch.title_written();
  6292. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  6293. // With the submission's one asking: the journal learns it.
  6294. crate::watch::wrote(dst, len);
  6295. // What the card holds there may be another value although
  6296. // ours did not change.
  6297. if send::own() {
  6298. crate::shadow::send_copied(dst, len);
  6299. }
  6300. (started, len)
  6301. }
  6302. &Step::Fill(dst, src, len, _) => {
  6303. #[cfg(feature = "diagnostics")]
  6304. {
  6305. copies += 1;
  6306. }
  6307. if wide_fills() {
  6308. batch.fills.push((dst, src, len));
  6309. bytes += len as u64;
  6310. continue;
  6311. }
  6312. let started = std::time::Instant::now();
  6313. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6314. (started, len)
  6315. }
  6316. Step::Placed(p) => {
  6317. let started = std::time::Instant::now();
  6318. let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len);
  6319. batch.fill();
  6320. if free {
  6321. batch.title_written();
  6322. }
  6323. if let Some(bytes) = p.prepare(free) {
  6324. batch.placed.push((p.shadow.clone(), p.dst, bytes));
  6325. }
  6326. (started, p.len)
  6327. }
  6328. Step::Refresh(shadow, address, len) => {
  6329. #[cfg(feature = "diagnostics")]
  6330. {
  6331. refreshes += 1;
  6332. refreshed += *len as u64;
  6333. }
  6334. batch.add(shadow, *address, *len);
  6335. continue;
  6336. }
  6337. Step::Run(work) | Step::Host(work, _) => {
  6338. batch.fill();
  6339. #[cfg(feature = "diagnostics")]
  6340. let started = std::time::Instant::now();
  6341. if matches!(step, Step::Run(_)) {
  6342. batch.title_written();
  6343. }
  6344. work();
  6345. // It wrote title memory, where is not known here: the
  6346. // submission's one asking ends, later refreshes ask anew.
  6347. if matches!(step, Step::Run(_)) {
  6348. crate::watch::ask_once_end();
  6349. }
  6350. #[cfg(feature = "diagnostics")]
  6351. {
  6352. add(C::Runs, 1);
  6353. add(C::RunUs, started.elapsed().as_micros() as u64);
  6354. }
  6355. continue;
  6356. }
  6357. Step::GpuWrite(shadow, address, len) => {
  6358. // The shaders start from the title's data: this copy's
  6359. // pending refresh first. The other copies' wait for
  6360. // the next flush of all (flushing all of them at every
  6361. // range a dispatch writes made thousands of write-watch
  6362. // askings a frame).
  6363. batch.flush_one(shadow);
  6364. #[cfg(feature = "diagnostics")]
  6365. let snapshot = std::time::Instant::now();
  6366. shadow.writing(*address, *len);
  6367. #[cfg(feature = "diagnostics")]
  6368. {
  6369. add(C::GpuWrites, 1);
  6370. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  6371. }
  6372. continue;
  6373. }
  6374. Step::Texture(staging) => {
  6375. if batch.texture_due(staging) {
  6376. batch.due.push(staging.clone());
  6377. if !wide_textures() {
  6378. batch.refresh_textures();
  6379. }
  6380. }
  6381. continue;
  6382. }
  6383. };
  6384. us += started.elapsed();
  6385. bytes += copied as u64;
  6386. }
  6387. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  6388. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  6389. #[cfg(feature = "diagnostics")]
  6390. {
  6391. add(C::Copies, copies);
  6392. add(C::CopyBytes, bytes);
  6393. add(C::Refreshes, refreshes);
  6394. add(C::RefreshBytes, refreshed);
  6395. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  6396. }
  6397. }
  6398. }
  6399. /// A table by a copy's address.
  6400. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  6401. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  6402. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  6403. /// but our own.
  6404. #[derive(Default)]
  6405. pub(crate) struct AddressHash(u64);
  6406. impl std::hash::Hasher for AddressHash {
  6407. fn finish(&self) -> u64 {
  6408. self.0
  6409. }
  6410. fn write(&mut self, bytes: &[u8]) {
  6411. for &b in bytes {
  6412. self.write_usize(usize::from(b));
  6413. }
  6414. }
  6415. fn write_usize(&mut self, n: usize) {
  6416. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  6417. self.0 = h ^ (h >> 32);
  6418. }
  6419. }
  6420. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  6421. /// preparing: the write-watch asking for a submission; the title's bytes put
  6422. /// in under flights' writes; the lists' steps, the refreshes among them; the
  6423. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  6424. /// of the steps: the refreshes, and the copies and fills (those with the
  6425. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  6426. /// is of. Of the refreshes, those before ranges are given to shaders, one
  6427. /// copy at a time: nanoseconds, and how many. Ahead of all that: the wait for
  6428. /// the submission lock, the steps done on the card planned ([`card_steps`]),
  6429. /// the flights waited for, the heaps' records and what is swept; and, at the
  6430. /// end, the wait for the heaps' records.
  6431. #[cfg(feature = "diagnostics")]
  6432. static SPLIT: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16];
  6433. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  6434. /// those known to copy nothing, and those done on several threads.
  6435. #[cfg(feature = "diagnostics")]
  6436. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  6437. /// Counts into [`SPLIT`].
  6438. #[cfg(feature = "diagnostics")]
  6439. struct Split(std::cell::Cell<std::time::Instant>);
  6440. #[cfg(feature = "diagnostics")]
  6441. impl Split {
  6442. fn begin() -> Split {
  6443. Split(std::cell::Cell::new(std::time::Instant::now()))
  6444. }
  6445. /// Nanoseconds since the last part.
  6446. fn so_far(&self) -> u64 {
  6447. self.0.get().elapsed().as_nanos() as u64
  6448. }
  6449. /// What came since the last part was part `i`.
  6450. fn part(&self, i: usize) {
  6451. let now = std::time::Instant::now();
  6452. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  6453. }
  6454. }
  6455. /// The split of the preparing, per frame, for the frame-rate line.
  6456. #[cfg(feature = "diagnostics")]
  6457. fn split_line(frames: f64) {
  6458. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6459. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  6460. let e: Vec<f64> = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect();
  6461. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  6462. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6463. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
  6464. tracing::info!(
  6465. "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' \
  6466. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  6467. 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 \
  6468. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the submission lock, {:.1} \
  6469. planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is swept; at the end {:.1} waiting \
  6470. for the heaps' records; asked early by a thread of its own {:.0} pieces of 2 MiB, {:.1} ms (VICTORY_ASK_EARLY)",
  6471. ms[0],
  6472. ms[8],
  6473. ms[1],
  6474. ms[2],
  6475. ms[6],
  6476. f[0],
  6477. f[1],
  6478. f[2],
  6479. f[3],
  6480. ms[9],
  6481. ms[10] * 1e6,
  6482. ms[7],
  6483. ms[3],
  6484. ms[4],
  6485. ms[5],
  6486. if crate::watch::light() { "on" } else { "off" },
  6487. ms[11],
  6488. ms[12],
  6489. ms[13],
  6490. ms[14],
  6491. ms[15],
  6492. e[0],
  6493. e[1] / 1e3,
  6494. );
  6495. tracing::info!(
  6496. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6497. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6498. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6499. waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
  6500. as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
  6501. a[0],
  6502. a[1] / 1024.0,
  6503. a[11] / 1e6,
  6504. a[12],
  6505. a[10],
  6506. a[9],
  6507. a[2],
  6508. a[3],
  6509. a[4],
  6510. a[5],
  6511. a[6],
  6512. a[7] / 1e6,
  6513. a[8] / 1e6,
  6514. s[0] / 1048576.0,
  6515. s[1] / 1048576.0,
  6516. s[2] / 1048576.0,
  6517. s[3],
  6518. );
  6519. tracing::info!(
  6520. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures; the \
  6521. first two beside the recording (VICTORY_HEAP_PASS_ASIDE), {:.1} ms waited for at the lists' close",
  6522. h[0],
  6523. h[1],
  6524. h[2],
  6525. aside::WAITED.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames,
  6526. );
  6527. }
  6528. /// Whether a submission's refreshes of host copies run on several threads,
  6529. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6530. ///
  6531. /// A submission brings some sixty copies up to date, one after the other
  6532. /// on the submitting thread: for each, the pages the title wrote are asked
  6533. /// for and read through the kernel into the copy. That is the frame line's
  6534. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6535. /// another: each refresh writes its own copy and its own notes, and reads
  6536. /// title memory. With the switch the copies of a flush (four or more) are
  6537. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6538. /// The write-watch journal and the guards are behind their own locks, as
  6539. /// they are for the title's threads.
  6540. fn wide_refresh() -> bool {
  6541. static ON: OnceLock<bool> = OnceLock::new();
  6542. *ON.get_or_init(|| {
  6543. wide_refresh_enabled(
  6544. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6545. std::thread::available_parallelism().ok().map(|n| n.get()),
  6546. )
  6547. })
  6548. }
  6549. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6550. match setting {
  6551. Some("1") => true,
  6552. Some("0") => false,
  6553. _ => logical_cpus.is_some_and(|n| n >= 4),
  6554. }
  6555. }
  6556. #[cfg(test)]
  6557. mod wide_refresh_tests {
  6558. use super::wide_refresh_enabled;
  6559. #[test]
  6560. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6561. assert!(wide_refresh_enabled(None, Some(4)));
  6562. assert!(wide_refresh_enabled(None, Some(16)));
  6563. assert!(!wide_refresh_enabled(None, Some(2)));
  6564. assert!(!wide_refresh_enabled(None, None));
  6565. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6566. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6567. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6568. }
  6569. }
  6570. /// A submission's refreshes not done yet, merged per buffer copy into the
  6571. /// range that covers them: done before a step that writes title memory or
  6572. /// gives a range to shaders, and before the lists run.
  6573. ///
  6574. /// Also the textures brought up to date in the submission so far: most
  6575. /// lists of a world submission sample the same textures, and a texture in
  6576. /// physical-page memory is hashed whole each time it is checked. Checked
  6577. /// once, it is checked again only after a step that writes title memory.
  6578. #[derive(Default)]
  6579. struct Batch {
  6580. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6581. /// Where each copy (by address) is in `refreshes`: the list that makes
  6582. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6583. /// for every refresh of a submission was tens of millions of
  6584. /// comparisons a frame.
  6585. index: ByCopy<usize>,
  6586. /// Staging buffers (by address) refreshed since the last title write,
  6587. /// or due to be.
  6588. textures: std::collections::HashSet<usize>,
  6589. /// Those due ([`Batch::refresh_textures`]).
  6590. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6591. /// What copies at their place in the submission's lists put into title
  6592. /// memory ([`place`]): the host copy, the title address, the bytes.
  6593. placed: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, Vec<u8>)>,
  6594. /// Fills not done yet (destination, source, bytes): [`wide_fills`].
  6595. fills: Vec<(usize, usize, usize)>,
  6596. /// Copies (by address) brought up to date ahead of the steps, and the
  6597. /// range (from, to) ([`Batch::refresh_ahead`]).
  6598. ahead: ByCopy<(usize, usize)>,
  6599. }
  6600. /// Whether the copies that a submission's shaders write are brought up to
  6601. /// date together, on several threads, ahead of its steps
  6602. /// (`VICTORY_REFRESH_AHEAD=0`: each before the step that gives it to them).
  6603. ///
  6604. /// 580 copies a frame, one after the other on the submitting thread, 3.4 to
  6605. /// 6.5 ms (session play-1125-0203).
  6606. fn ahead_of_writes() -> bool {
  6607. static ON: OnceLock<bool> = OnceLock::new();
  6608. *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_AHEAD").is_none_or(|v| v != "0") && wide_refresh() && crate::watch::light())
  6609. }
  6610. /// What a step is to the copies' refreshes, for [`written_spans`].
  6611. enum Touch {
  6612. /// A refresh of a copy (by address), from, to.
  6613. Refresh(usize, usize, usize),
  6614. /// The copy is given to shaders.
  6615. Write(usize),
  6616. /// Title memory is written.
  6617. Title,
  6618. Nothing,
  6619. }
  6620. /// Of `steps`, up to the first that writes title memory: the copies given to
  6621. /// shaders, each with the range its refreshes before that cover.
  6622. fn written_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> {
  6623. // (From, to, given to shaders.)
  6624. let mut spans: ByCopy<(usize, usize, bool)> = ByCopy::default();
  6625. for step in steps {
  6626. match step {
  6627. Touch::Refresh(copy, from, to) => {
  6628. let span = spans.entry(copy).or_insert((from, to, false));
  6629. if !span.2 {
  6630. (span.0, span.1) = (span.0.min(from), span.1.max(to));
  6631. }
  6632. }
  6633. // (Not refreshed before: nothing of it is due.)
  6634. Touch::Write(copy) => {
  6635. if let Some(span) = spans.get_mut(&copy) {
  6636. span.2 = true;
  6637. }
  6638. }
  6639. Touch::Title => break,
  6640. Touch::Nothing => {}
  6641. }
  6642. }
  6643. spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect()
  6644. }
  6645. #[cfg(test)]
  6646. mod written_spans_tests {
  6647. use super::{Touch, written_spans};
  6648. #[test]
  6649. fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() {
  6650. use Touch::{Nothing, Refresh, Title, Write};
  6651. let mut found = written_spans(
  6652. [
  6653. Refresh(1, 10, 20),
  6654. Refresh(2, 0, 5),
  6655. Nothing,
  6656. Refresh(1, 30, 40),
  6657. Write(1),
  6658. Refresh(1, 0, 100),
  6659. Write(3),
  6660. Refresh(3, 1, 2),
  6661. Refresh(4, 7, 9),
  6662. Write(4),
  6663. Title,
  6664. Write(2),
  6665. ]
  6666. .into_iter(),
  6667. );
  6668. found.sort_unstable();
  6669. assert_eq!(found, [(1, 10, 40), (4, 7, 9)]);
  6670. }
  6671. }
  6672. /// Whether the fills of a submission's upload memory are done together on
  6673. /// several threads (`VICTORY_WIDE_FILLS=0`: one after the other, where the
  6674. /// lists name them).
  6675. ///
  6676. /// They are 7,000 to 12,000 a frame, some 500 bytes each, 5 ms of the
  6677. /// submitting thread. Each reads title memory and writes memory of its own
  6678. /// that the card alone reads, when the lists run; they are done before the
  6679. /// next step that writes title memory or runs code of ours, and before the
  6680. /// submission goes on from its steps.
  6681. fn wide_fills() -> bool {
  6682. static ON: OnceLock<bool> = OnceLock::new();
  6683. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_FILLS").is_none_or(|v| v != "0") && wide_refresh())
  6684. }
  6685. /// Whether a submission's textures are brought up to date on several
  6686. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6687. /// name them, as before).
  6688. ///
  6689. /// They are read, hashed and, if they changed, detiled into their staging
  6690. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6691. /// its own buffer, notes and lock, and is refreshed by the title's own
  6692. /// threads as it is. They are done before the next step that writes title
  6693. /// memory, as the copies' refreshes are, and before the lists go to the
  6694. /// card. What is new: the note of a list that its upload takes what the
  6695. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6696. /// an earlier list of the submission asked for, not behind it. The texture
  6697. /// is then uploaded by a later list too, once more than needed.
  6698. fn wide_textures() -> bool {
  6699. static ON: OnceLock<bool> = OnceLock::new();
  6700. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6701. }
  6702. impl Batch {
  6703. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6704. let end = address + len;
  6705. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6706. if self.ahead.get(&key).is_some_and(|&(from, to)| from <= address && end <= to) {
  6707. return;
  6708. }
  6709. match self.index.get(&key) {
  6710. Some(&at) => {
  6711. let r = &mut self.refreshes[at];
  6712. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6713. }
  6714. None => {
  6715. self.index.insert(key, self.refreshes.len());
  6716. self.refreshes.push((shadow.clone(), address, end));
  6717. }
  6718. }
  6719. }
  6720. /// Before shaders are given a range of `shadow`'s copy: its pending
  6721. /// refresh is done, the others stay pending.
  6722. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  6723. // From here on it is refreshed around what the shaders write.
  6724. self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize));
  6725. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  6726. return;
  6727. };
  6728. let (shadow, from, to) = self.refreshes.swap_remove(at);
  6729. // The last entry took its place.
  6730. if let Some(moved) = self.refreshes.get(at) {
  6731. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  6732. }
  6733. #[cfg(feature = "diagnostics")]
  6734. let started = std::time::Instant::now();
  6735. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  6736. Self::update(&shadow, from, to);
  6737. }
  6738. #[cfg(feature = "diagnostics")]
  6739. {
  6740. let ns = started.elapsed().as_nanos() as u64;
  6741. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6742. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6743. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  6744. }
  6745. }
  6746. /// Brings `[from, to)` of a copy up to date, timed.
  6747. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  6748. let started = std::time::Instant::now();
  6749. let copied = shadow.update(from, to - from);
  6750. let us = started.elapsed().as_micros() as u64;
  6751. #[cfg(feature = "diagnostics")]
  6752. crate::copystat::range(from, to - from, us, 0);
  6753. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  6754. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  6755. }
  6756. /// Whether `staging` is still to be refreshed in this submission (and
  6757. /// notes it refreshed).
  6758. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  6759. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  6760. }
  6761. /// Before a step that writes title memory: pending refreshes are done
  6762. /// first, and textures are checked again after it.
  6763. fn title_written(&mut self) {
  6764. self.flush();
  6765. self.ahead.clear();
  6766. self.textures.clear();
  6767. }
  6768. /// Before the steps of `runs` ([`ahead_of_writes`]); copies and fills
  6769. /// that `taken` names are not done on the CPU.
  6770. fn refresh_ahead(&mut self, runs: &[&HostList], taken: impl Fn(&HostList, usize) -> bool) {
  6771. let mut copies: ByCopy<std::sync::Arc<crate::shadow::Shadow>> = ByCopy::default();
  6772. let mut touches = Vec::new();
  6773. 'steps: for list in runs {
  6774. for (i, step) in list.deferred().copies.iter().enumerate() {
  6775. touches.push(match step {
  6776. Step::Refresh(shadow, at, len) => {
  6777. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6778. copies.entry(key).or_insert_with(|| shadow.clone());
  6779. Touch::Refresh(key, *at, *at + *len)
  6780. }
  6781. Step::GpuWrite(shadow, ..) => Touch::Write(std::sync::Arc::as_ptr(shadow) as usize),
  6782. Step::Copy(..) if taken(list, i) => Touch::Nothing,
  6783. Step::Copy(..) | Step::Run(_) | Step::Placed(_) => break 'steps,
  6784. _ => Touch::Nothing,
  6785. });
  6786. }
  6787. }
  6788. let due: Vec<_> = written_spans(touches.into_iter())
  6789. .into_iter()
  6790. .filter_map(|(key, from, to)| Some((copies.get(&key)?.clone(), from, to)))
  6791. .collect();
  6792. for (shadow, from, to) in &due {
  6793. self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to));
  6794. }
  6795. #[cfg(feature = "diagnostics")]
  6796. let began = std::time::Instant::now();
  6797. let started = std::time::Instant::now();
  6798. let before = PREPARING[0].load(Ordering::Relaxed);
  6799. crate::shadow::wide_each(due.len(), move |i| {
  6800. let (shadow, from, to) = &due[i];
  6801. if !shadow.nothing_new(*from, *to - *from) {
  6802. Self::update(shadow, *from, *to);
  6803. }
  6804. });
  6805. // The time counted is the time it took, not the threads' sum.
  6806. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6807. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6808. #[cfg(feature = "diagnostics")]
  6809. {
  6810. let ns = began.elapsed().as_nanos() as u64;
  6811. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6812. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6813. }
  6814. }
  6815. /// The fills noted are done.
  6816. fn fill(&mut self) {
  6817. // Below this many the threads cost more than they save.
  6818. const FEW: usize = 96;
  6819. const PART: usize = 64;
  6820. if self.fills.is_empty() {
  6821. return;
  6822. }
  6823. let started = std::time::Instant::now();
  6824. if self.fills.len() < FEW {
  6825. for (dst, src, len) in self.fills.drain(..) {
  6826. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6827. }
  6828. } else {
  6829. let fills = std::mem::take(&mut self.fills);
  6830. crate::shadow::wide_each(fills.len().div_ceil(PART), move |i| {
  6831. for &(dst, src, len) in fills.iter().skip(i * PART).take(PART) {
  6832. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6833. }
  6834. });
  6835. }
  6836. let took = started.elapsed();
  6837. PREPARING[0].fetch_add(took.as_micros() as u64, Ordering::Relaxed);
  6838. #[cfg(feature = "diagnostics")]
  6839. SPLIT[7].fetch_add(took.as_nanos() as u64, Ordering::Relaxed);
  6840. }
  6841. /// The textures due are brought up to date.
  6842. fn refresh_textures(&mut self) {
  6843. if self.due.len() < 2 || !wide_textures() {
  6844. self.due.drain(..).for_each(|staging| staging.refresh());
  6845. return;
  6846. }
  6847. // The time counted is the time it took, not the threads' sum.
  6848. let started = std::time::Instant::now();
  6849. let before = PREPARING[2].load(Ordering::Relaxed);
  6850. let due = std::mem::take(&mut self.due);
  6851. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  6852. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  6853. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6854. }
  6855. fn flush(&mut self) {
  6856. self.refresh_textures();
  6857. self.index.clear();
  6858. if self.refreshes.is_empty() {
  6859. return;
  6860. }
  6861. #[cfg(feature = "diagnostics")]
  6862. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  6863. self.flush_all();
  6864. #[cfg(feature = "diagnostics")]
  6865. {
  6866. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6867. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  6868. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  6869. }
  6870. }
  6871. fn flush_all(&mut self) {
  6872. // Most of a flush's copies are as they were: they are told so here,
  6873. // from what the submission's asking found, before anything is asked
  6874. // and any thread woken. (Thousands of them, the heap's buffer views
  6875. // once a frame: on the threads, below.)
  6876. const FEW: usize = 256;
  6877. let light = crate::watch::light();
  6878. if light && self.refreshes.len() <= FEW {
  6879. let started = std::time::Instant::now();
  6880. #[cfg(feature = "diagnostics")]
  6881. let all = self.refreshes.len();
  6882. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  6883. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6884. #[cfg(feature = "diagnostics")]
  6885. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  6886. }
  6887. // One write-watch asking for the copies that lie close together,
  6888. // not one per copy.
  6889. let ahead = self.refreshes.len() > 1;
  6890. if ahead {
  6891. let started = std::time::Instant::now();
  6892. let ranges: Vec<(usize, usize)> = self
  6893. .refreshes
  6894. .iter()
  6895. .filter(|r| r.0.asked_ahead())
  6896. .map(|r| (r.1, r.2))
  6897. .collect();
  6898. crate::watch::ask_ahead(&ranges);
  6899. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6900. }
  6901. if wide_refresh() && self.refreshes.len() >= 4 {
  6902. // Each copy on its own, several at a time: a copy's refresh
  6903. // writes that copy and reads title memory, nothing of another's.
  6904. // The time counted is the time it took, not the threads' sum.
  6905. let started = std::time::Instant::now();
  6906. let before = PREPARING[0].load(Ordering::Relaxed);
  6907. #[cfg(feature = "diagnostics")]
  6908. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  6909. if light {
  6910. // A number to a free thread, not a job to each copy.
  6911. let refreshes = std::mem::take(&mut self.refreshes);
  6912. crate::shadow::wide_each(refreshes.len(), move |i| {
  6913. let (shadow, from, to) = &refreshes[i];
  6914. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  6915. #[cfg(feature = "diagnostics")]
  6916. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  6917. return;
  6918. }
  6919. Self::update(shadow, *from, *to);
  6920. });
  6921. } else {
  6922. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  6923. .refreshes
  6924. .drain(..)
  6925. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  6926. .collect();
  6927. crate::shadow::wide_run(jobs);
  6928. }
  6929. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6930. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6931. } else {
  6932. for (shadow, from, to) in self.refreshes.drain(..) {
  6933. Self::update(&shadow, from, to);
  6934. }
  6935. }
  6936. if ahead {
  6937. crate::watch::ask_ahead_done();
  6938. }
  6939. }
  6940. }
  6941. /// Copies title memory at submission. The ranges were checked against their
  6942. /// resources when recorded, but the title may since have unmapped pages of
  6943. /// them (tiled memory, page mappings), which read as zeros here; a title
  6944. /// destination (`title_dst`) that is not all mapped is left alone.
  6945. ///
  6946. /// The source is read through the kernel (`ReadProcessMemory`), which
  6947. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  6948. /// cost about 2 ms per copy in the title's big pools (it walks the page
  6949. /// tables to the region's end), which made copies run at 100-200 MB/s.
  6950. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  6951. #[cfg(feature = "diagnostics")]
  6952. match crate::copystat::mode() {
  6953. 1 => {
  6954. // SAFETY: timing only: the caller vouches for the source.
  6955. unsafe { std::ptr::copy(src, dst, len) };
  6956. return;
  6957. }
  6958. 2 => return,
  6959. _ => {}
  6960. }
  6961. if len == 0 {
  6962. return;
  6963. }
  6964. // A title destination that is not all mapped is left alone. Asking
  6965. // Windows first (`VirtualQuery`) walks the page tables to the end of
  6966. // the destination's region: in the title's big blocks that is
  6967. // milliseconds a copy, and it was a seventh of the submitting thread's
  6968. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  6969. // says the same when it fails, so the question is only asked then.
  6970. // `VICTORY_COPY_ASK=1` asks first, as before.
  6971. static ASK: OnceLock<bool> = OnceLock::new();
  6972. let ask_first = title_dst
  6973. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  6974. if ask_first && !crate::texture::committed(dst, len) {
  6975. return;
  6976. }
  6977. if title_dst {
  6978. // The kernel writes the destination: it must not be guarded.
  6979. crate::watch::writing(dst as usize, len);
  6980. }
  6981. #[cfg(feature = "diagnostics")]
  6982. let moved = std::time::Instant::now();
  6983. let since = crate::watch::changes();
  6984. // (A title destination that is away only while the runtime changes a
  6985. // mapping beside it is written when that is done.)
  6986. let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
  6987. #[cfg(feature = "diagnostics")]
  6988. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  6989. if whole {
  6990. return;
  6991. }
  6992. // The copy failed: a source page is not there, or the destination is
  6993. // not all mapped. Then the destination stays as it is (the kernel may
  6994. // have written its first pages).
  6995. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  6996. crate::watch::lost("a copy of the title's", dst as usize, len);
  6997. return;
  6998. }
  6999. #[cfg(feature = "diagnostics")]
  7000. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  7001. #[cfg(feature = "diagnostics")]
  7002. let sparse = std::time::Instant::now();
  7003. if !title_dst && len >= 64 << 10 {
  7004. read_sparse(src, dst, len);
  7005. } else {
  7006. read_pieces(src, dst, len);
  7007. }
  7008. #[cfg(feature = "diagnostics")]
  7009. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  7010. }
  7011. /// After a failed bulk read into host memory, skip contiguous holes. Never
  7012. /// cache the query across copies: the title may remap the same address.
  7013. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  7014. use windows_sys::Win32::System::Memory::{
  7015. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  7016. };
  7017. let mut offset = 0;
  7018. while offset < len {
  7019. let at = src.wrapping_add(offset);
  7020. let to = dst.wrapping_add(offset);
  7021. let remaining = len - offset;
  7022. // SAFETY: the query inspects an address and fills a local structure.
  7023. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  7024. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  7025. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  7026. .saturating_sub(at as usize).min(remaining);
  7027. if size != size_of_val(&info) || n == 0 {
  7028. read_pieces(at, to, remaining);
  7029. break;
  7030. }
  7031. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  7032. #[cfg(feature = "diagnostics")]
  7033. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  7034. // SAFETY: this path is only used with a writable host destination.
  7035. unsafe { to.write_bytes(0, n) };
  7036. } else if !read(at, to, n) {
  7037. // A mapping may change between query and read.
  7038. read_pieces(at, to, n);
  7039. }
  7040. offset += n;
  7041. }
  7042. }
  7043. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  7044. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  7045. // that fails), zeros for what cannot be read.
  7046. for_pieces(src as usize, len, 64 << 10, |at, n| {
  7047. let to = dst.wrapping_add(at - src as usize);
  7048. if !read(at as *const u8, to, n) {
  7049. for_pieces(at, n, 4 << 10, |at, n| {
  7050. let to = dst.wrapping_add(at - src as usize);
  7051. if !read(at as *const u8, to, n) {
  7052. #[cfg(feature = "diagnostics")]
  7053. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  7054. zero(to, n);
  7055. }
  7056. });
  7057. }
  7058. });
  7059. }
  7060. /// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
  7061. /// destination of a title's copy), which can go between the question whether
  7062. /// it is there and this.
  7063. fn zero(to: *mut u8, n: usize) {
  7064. static ZEROS: [u8; 4096] = [0; 4096];
  7065. if n <= ZEROS.len() && crate::safecopy::on() {
  7066. // SAFETY: a destination that is not there fails the copy.
  7067. if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
  7068. crate::watch::lost("zeros", to as usize, n);
  7069. }
  7070. return;
  7071. }
  7072. // SAFETY: inside the destination, which is mapped.
  7073. unsafe { to.write_bytes(0, n) };
  7074. }
  7075. /// Reads title memory at `src` into `dst`; false if a page of it is not
  7076. /// readable.
  7077. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  7078. read(src, dst.as_mut_ptr(), dst.len())
  7079. }
  7080. /// Reads what is there of the `dst.len()` bytes of title memory at `src`,
  7081. /// zeros for the rest; returns how many bytes were there. Safe while the
  7082. /// runtime remaps title memory (the kernel, or a copy that takes the fault,
  7083. /// reads). What the runtime's record says is mapped is read in one go each,
  7084. /// and by pieces where that fails; memory it has no record of by pieces.
  7085. pub(crate) fn read_there(src: *const u8, dst: &mut [u8]) -> usize {
  7086. dst.fill(0);
  7087. let (start, len) = (src as usize, dst.len());
  7088. let mut got = 0;
  7089. let mut runs = crate::inplace::shown_runs(start, len);
  7090. if runs.is_empty() {
  7091. runs.push((start, len));
  7092. }
  7093. for (at, n) in runs {
  7094. let piece = &mut dst[at - start..at - start + n];
  7095. if read_into(at as *const u8, piece) {
  7096. got += n;
  7097. continue;
  7098. }
  7099. // (What failed may have written its first pages.)
  7100. piece.fill(0);
  7101. for_pieces(at, n, 64 << 10, |from, n| {
  7102. let piece = &mut dst[from - start..from - start + n];
  7103. if read_into(from as *const u8, piece) {
  7104. got += n;
  7105. return;
  7106. }
  7107. piece.fill(0);
  7108. for_pieces(from, n, 4 << 10, |from, n| {
  7109. let piece = &mut dst[from - start..from - start + n];
  7110. if read_into(from as *const u8, piece) {
  7111. got += n;
  7112. } else {
  7113. piece.fill(0);
  7114. }
  7115. });
  7116. });
  7117. }
  7118. got
  7119. }
  7120. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  7121. /// readable.
  7122. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  7123. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  7124. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7125. if crate::safecopy::on() {
  7126. // SAFETY: the destination is mapped writable memory of `len` bytes;
  7127. // a source page that is not there fails the copy.
  7128. return unsafe { crate::safecopy::copy(dst, src, len) };
  7129. }
  7130. let mut done = 0;
  7131. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  7132. // kernel checks the source.
  7133. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  7134. }
  7135. #[link(name = "ntdll", kind = "raw-dylib")]
  7136. unsafe extern "system" {
  7137. /// The kernel's write into a process's memory, `(process, address,
  7138. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  7139. /// the range is not there or not writable. It changes no protection.
  7140. fn NtWriteVirtualMemory(
  7141. process: *mut std::ffi::c_void,
  7142. base: *mut std::ffi::c_void,
  7143. buffer: *const std::ffi::c_void,
  7144. size: usize,
  7145. written: *mut usize,
  7146. ) -> i32;
  7147. }
  7148. /// Whether title memory is written with the kernel's own call
  7149. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  7150. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  7151. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  7152. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  7153. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  7154. fn direct_writes() -> bool {
  7155. static ON: OnceLock<bool> = OnceLock::new();
  7156. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  7157. }
  7158. /// Copies host memory into title memory after a submission (what shaders
  7159. /// wrote), leaving pages that are not mapped alone.
  7160. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  7161. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  7162. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7163. let direct = direct_writes();
  7164. let since = crate::watch::changes();
  7165. let write = |at: usize, n: usize| {
  7166. let from = src.wrapping_add(at - dst as usize);
  7167. if crate::safecopy::on() {
  7168. // SAFETY: the source is ours; a destination page that is not
  7169. // there, or not writable, fails the copy.
  7170. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  7171. }
  7172. let mut done = 0;
  7173. if direct {
  7174. // SAFETY: as below; the kernel checks the destination and
  7175. // writes nothing it cannot (the caller opened its guards:
  7176. // `crate::watch::writing`).
  7177. return unsafe {
  7178. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  7179. };
  7180. }
  7181. // SAFETY: the source is our mapped host copy; the kernel checks the
  7182. // destination.
  7183. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  7184. };
  7185. if len == 0 || write(dst as usize, len) {
  7186. return;
  7187. }
  7188. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  7189. if !write(at, n) {
  7190. for_pieces(at, n, 4 << 10, |at, n| {
  7191. if write(at, n) {
  7192. return;
  7193. }
  7194. // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
  7195. // refresh guarded the block again since the caller opened
  7196. // it; and any where the runtime was changing a mapping.
  7197. crate::watch::writing(at, n);
  7198. if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
  7199. crate::watch::lost("a host copy's bytes", at, n);
  7200. }
  7201. });
  7202. }
  7203. });
  7204. }
  7205. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  7206. /// `step`.
  7207. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  7208. let end = start + len;
  7209. let mut at = start;
  7210. while at < end {
  7211. let next = ((at / step + 1) * step).min(end);
  7212. f(at, next - at);
  7213. at = next;
  7214. }
  7215. }
  7216. impl Host {
  7217. /// The queue everything of ours runs on, for a call that must go to it
  7218. /// in order with the lists (`crate::tiles`: a texture's levels are
  7219. /// given memory ahead of the list that uploads them).
  7220. pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
  7221. &self.queue
  7222. }
  7223. /// A buffer in the upload heap, mapped for writing.
  7224. /// A buffer of `size` bytes the card writes and we read (a read back),
  7225. /// in the state copies into it need.
  7226. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7227. let heap = D3D12_HEAP_PROPERTIES {
  7228. Type: D3D12_HEAP_TYPE_READBACK,
  7229. ..Default::default()
  7230. };
  7231. let desc = D3D12_RESOURCE_DESC {
  7232. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7233. Width: size.max(1),
  7234. Height: 1,
  7235. DepthOrArraySize: 1,
  7236. MipLevels: 1,
  7237. SampleDesc: DXGI_SAMPLE_DESC {
  7238. Count: 1,
  7239. Quality: 0,
  7240. },
  7241. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7242. ..Default::default()
  7243. };
  7244. let mut buffer: Option<ID3D12Resource> = None;
  7245. // SAFETY: plain creation of a read-back buffer.
  7246. let made = unsafe {
  7247. self.device.CreateCommittedResource(
  7248. &heap,
  7249. D3D12_HEAP_FLAG_NONE,
  7250. &desc,
  7251. D3D12_RESOURCE_STATE_COPY_DEST,
  7252. None,
  7253. &mut buffer,
  7254. )
  7255. };
  7256. match made {
  7257. Ok(()) => buffer,
  7258. Err(e) => {
  7259. tracing::warn!(error = %e, size, "no read-back buffer");
  7260. None
  7261. }
  7262. }
  7263. }
  7264. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7265. MADE[0].fetch_add(1, Ordering::Relaxed);
  7266. MADE[1].fetch_add(size, Ordering::Relaxed);
  7267. let heap = D3D12_HEAP_PROPERTIES {
  7268. Type: D3D12_HEAP_TYPE_UPLOAD,
  7269. ..Default::default()
  7270. };
  7271. let desc = D3D12_RESOURCE_DESC {
  7272. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7273. Width: size.max(1),
  7274. Height: 1,
  7275. DepthOrArraySize: 1,
  7276. MipLevels: 1,
  7277. SampleDesc: DXGI_SAMPLE_DESC {
  7278. Count: 1,
  7279. Quality: 0,
  7280. },
  7281. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7282. ..Default::default()
  7283. };
  7284. let mut buffer: Option<ID3D12Resource> = None;
  7285. let mut data = std::ptr::null_mut();
  7286. // SAFETY: plain creation and mapping of an upload buffer.
  7287. let made = unsafe {
  7288. self.device
  7289. .CreateCommittedResource(
  7290. &heap,
  7291. D3D12_HEAP_FLAG_NONE,
  7292. &desc,
  7293. D3D12_RESOURCE_STATE_GENERIC_READ,
  7294. None,
  7295. &mut buffer,
  7296. )
  7297. .and_then(|()| {
  7298. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7299. b.Map(0, None, Some(&mut data))
  7300. })
  7301. };
  7302. #[cfg(feature = "diagnostics")]
  7303. if made.is_ok()
  7304. && let Some(b) = &buffer
  7305. {
  7306. crate::book::made(b, || "an upload buffer".into());
  7307. }
  7308. match made {
  7309. Ok(()) => Some((buffer?, data.cast())),
  7310. Err(e) => {
  7311. tracing::warn!(error = %e, size, "no upload buffer");
  7312. None
  7313. }
  7314. }
  7315. }
  7316. }
  7317. /// The swap chain formats a presented texture can be copied into: its own
  7318. /// family's.
  7319. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  7320. Some(match format.0 {
  7321. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  7322. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  7323. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  7324. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  7325. _ => return None,
  7326. })
  7327. }
  7328. const BUFFERS: u32 = 2;
  7329. struct Presenter {
  7330. swap_chain: IDXGISwapChain3,
  7331. width: u32,
  7332. height: u32,
  7333. format: DXGI_FORMAT,
  7334. copy: HostList,
  7335. /// With presents sent ahead ([`late_free_present`]): a list for each
  7336. /// present in the air, and the submission it last flew as (it is used
  7337. /// again once that one has finished).
  7338. ahead: Vec<(HostList, u64)>,
  7339. hwnd: HWND,
  7340. meter: Meter,
  7341. }
  7342. /// The frame rate, shown in the window's caption every second and logged
  7343. /// every few seconds.
  7344. struct Meter {
  7345. since: std::time::Instant,
  7346. frames: u32,
  7347. #[cfg(feature = "diagnostics")]
  7348. copy_stats_frames: u64,
  7349. drawn: u64,
  7350. logged: std::time::Instant,
  7351. /// The caption the window had, once read.
  7352. caption: Option<Vec<u16>>,
  7353. }
  7354. impl Meter {
  7355. fn new() -> Self {
  7356. let now = std::time::Instant::now();
  7357. Meter {
  7358. since: now,
  7359. frames: 0,
  7360. #[cfg(feature = "diagnostics")]
  7361. copy_stats_frames: 0,
  7362. drawn: crate::draw::drawn(),
  7363. logged: now,
  7364. caption: None,
  7365. }
  7366. }
  7367. /// Counts a presented frame.
  7368. fn frame(&mut self, hwnd: HWND) {
  7369. #[cfg(feature = "diagnostics")]
  7370. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  7371. #[cfg(feature = "diagnostics")]
  7372. crate::copystat::presented();
  7373. self.frames += 1;
  7374. #[cfg(feature = "diagnostics")]
  7375. {
  7376. self.copy_stats_frames += 1;
  7377. }
  7378. let elapsed = self.since.elapsed();
  7379. if elapsed < std::time::Duration::from_secs(1) {
  7380. return;
  7381. }
  7382. let drawn = crate::draw::drawn();
  7383. let frames = f64::from(self.frames);
  7384. let fps = frames / elapsed.as_secs_f64();
  7385. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  7386. let draws = (drawn - self.drawn) as f64 / frames;
  7387. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  7388. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  7389. let [cpu, gpu] = [0, 1].map(|i| {
  7390. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  7391. });
  7392. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  7393. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  7394. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  7395. });
  7396. let [back_ms, back_mb] = [0, 1].map(|i| {
  7397. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  7398. });
  7399. let dropped = crate::draw::take_dropped() as f64 / frames;
  7400. let indirect = crate::list::take_indirect() as f64 / frames;
  7401. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  7402. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  7403. tracing::info!(
  7404. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  7405. );
  7406. crate::shadow::exact_line(frames);
  7407. crate::descriptor::sync_line(frames);
  7408. late_line(frames);
  7409. crate::queue::behind_line(frames);
  7410. card_clock_line(frames, ms);
  7411. #[cfg(feature = "diagnostics")]
  7412. spans::line(frames);
  7413. crate::shadow::back_line(frames);
  7414. #[cfg(feature = "diagnostics")]
  7415. split_line(frames);
  7416. {
  7417. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7418. if passes + compares > 0.0 {
  7419. tracing::info!(
  7420. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  7421. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  7422. if rehash_runs() { "on" } else { "off" }
  7423. );
  7424. }
  7425. }
  7426. {
  7427. let [own, asking, still, all] =
  7428. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  7429. if all >= 1.0 {
  7430. tracing::info!(
  7431. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  7432. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  7433. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  7434. );
  7435. }
  7436. let [through, left, filled, short] =
  7437. [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7438. if through + left + filled > 0.0 {
  7439. tracing::info!(
  7440. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  7441. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \
  7442. {filled:.1} first fillings from the pages there (VICTORY_TEXTURE_FILL=0: left empty), {short:.1} of them \
  7443. with less than was mapped (looked at again)"
  7444. );
  7445. }
  7446. }
  7447. {
  7448. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7449. if copies > 0.0 {
  7450. tracing::info!(
  7451. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  7452. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  7453. if join_copies() { "on" } else { "off" }
  7454. );
  7455. }
  7456. }
  7457. // Passes over the heap's buffer views for shaders that pick them by index.
  7458. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  7459. let picked_ms =
  7460. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  7461. // Copies between depth textures and their colour twins, each way.
  7462. let [twin_to_depth, twin_to_colour] =
  7463. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7464. // Depth planes drawn from their twins.
  7465. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  7466. // Copies in the card's memory (`crate::shadow::cards`).
  7467. let card = crate::shadow::card_stats();
  7468. #[cfg(feature = "diagnostics")]
  7469. let slow = crate::watch::slow_asks();
  7470. // Over the same frames as the counts above.
  7471. #[cfg(feature = "diagnostics")]
  7472. let drops = crate::pipeline::take_drops();
  7473. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  7474. self.logged = std::time::Instant::now();
  7475. tracing::info!(
  7476. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  7477. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  7478. );
  7479. crate::tiles::status();
  7480. {
  7481. let [queued, due, away, partly, oldest] =
  7482. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  7483. let [same, parts, tails] =
  7484. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  7485. tracing::info!(
  7486. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  7487. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  7488. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  7489. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  7490. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  7491. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  7492. {} made slots found unmapped and made null",
  7493. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  7494. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  7495. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  7496. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  7497. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  7498. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  7499. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  7500. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  7501. );
  7502. }
  7503. if crate::resource::held_only() {
  7504. let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed));
  7505. let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed));
  7506. tracing::info!(
  7507. "textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \
  7508. levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \
  7509. {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \
  7510. out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free; \
  7511. {} looks for textures to let go, {:.2} ms each, the longest {:.1}",
  7512. bytes >> 20,
  7513. whole >> 20,
  7514. crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed),
  7515. crate::pool::texture_room() >> 20,
  7516. crate::resource::SWEPT_US[0].load(Ordering::Relaxed),
  7517. crate::resource::SWEPT_US[1].load(Ordering::Relaxed) as f64
  7518. / 1e3
  7519. / crate::resource::SWEPT_US[0].load(Ordering::Relaxed).max(1) as f64,
  7520. crate::resource::SWEPT_US[2].load(Ordering::Relaxed) as f64 / 1e3
  7521. );
  7522. }
  7523. {
  7524. let mode = crate::watch::page_writes();
  7525. let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
  7526. let [kept, dropped, slots, uploaded] =
  7527. [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
  7528. tracing::info!(
  7529. "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)",
  7530. bytes >> 20,
  7531. if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
  7532. if mode & 4 != 0 { "told as well" } else { "counted only" },
  7533. if mode & 2 != 0 { "made due again" } else { "left as they were" }
  7534. );
  7535. }
  7536. #[cfg(feature = "diagnostics")]
  7537. tracing::info!(
  7538. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  7539. slow[0] as f64 / frames,
  7540. slow[1] as f64 / 1e3 / frames,
  7541. slow[2] as f64 / 1e3
  7542. );
  7543. if crate::shadow::cards() {
  7544. let per_frame = |i: usize| card[i] as f64 / frames;
  7545. tracing::info!(
  7546. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  7547. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  7548. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  7549. card[7],
  7550. card[8] >> 20,
  7551. card[9] >> 20,
  7552. per_frame(0) / 1e6,
  7553. per_frame(1),
  7554. per_frame(2),
  7555. per_frame(3),
  7556. per_frame(4) / 1e6,
  7557. per_frame(5),
  7558. per_frame(6) / 1e3
  7559. );
  7560. }
  7561. tracing::info!(
  7562. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  7563. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  7564. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  7565. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  7566. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  7567. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  7568. {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}",
  7569. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  7570. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  7571. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  7572. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  7573. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  7574. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  7575. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  7576. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  7577. refused = format!(
  7578. "{} ({} 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",
  7579. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  7580. crate::shadow::OWN_MADE.load(Ordering::Relaxed),
  7581. crate::resource::TWINS[0].load(Ordering::Relaxed),
  7582. crate::resource::TWINS[1].load(Ordering::Relaxed),
  7583. crate::resource::PLANES[1].load(Ordering::Relaxed),
  7584. crate::resource::PLANES[2].load(Ordering::Relaxed)
  7585. ),
  7586. making = crate::pipeline::making(),
  7587. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  7588. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  7589. );
  7590. #[cfg(feature = "diagnostics")]
  7591. {
  7592. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7593. tracing::info!(
  7594. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  7595. put[0],
  7596. put[1],
  7597. put[2] / 1e6,
  7598. put[3]
  7599. );
  7600. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  7601. for (why, n) in drops.iter().take(40) {
  7602. tracing::info!(
  7603. "dropped {:.1}/frame without a host pipeline: {why}",
  7604. *n as f64 / frames
  7605. );
  7606. }
  7607. }
  7608. }
  7609. if self.caption.is_none() {
  7610. // The window's own text, read without a message.
  7611. let mut buffer = vec![0u16; 512];
  7612. // SAFETY: a window handle and a buffer of that length.
  7613. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  7614. buffer.truncate(n.max(0) as usize);
  7615. self.caption = Some(buffer);
  7616. }
  7617. let Some(caption) = &self.caption else { return };
  7618. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  7619. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  7620. text.push(0);
  7621. // Setting the text waits for the window's thread (a title thread,
  7622. // which may not pump for a while), so a thread of ours does it and
  7623. // presenting never waits; it takes the newest text when free.
  7624. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  7625. static SETTER: std::sync::Once = std::sync::Once::new();
  7626. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  7627. SETTER.call_once(|| {
  7628. let _ = std::thread::Builder::new()
  7629. .name("victory-caption".into())
  7630. .spawn(|| {
  7631. loop {
  7632. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  7633. match next {
  7634. // SAFETY: a window handle and a NUL-terminated text.
  7635. Some((hwnd, text)) => unsafe {
  7636. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  7637. },
  7638. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  7639. }
  7640. }
  7641. });
  7642. });
  7643. }
  7644. }
  7645. impl Host {
  7646. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  7647. /// as frame `frame` (saved if captures are on). `None` if nothing was
  7648. /// shown; else, in diagnostics builds, whether the frame was black.
  7649. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  7650. // SAFETY: a live resource.
  7651. let desc = unsafe { texture.GetDesc() };
  7652. let Some(format) = swap_format(desc.Format) else {
  7653. tracing::warn!(format = desc.Format.0, "cannot present this format");
  7654. return None;
  7655. };
  7656. let (width, height) = (desc.Width as u32, desc.Height);
  7657. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  7658. if presenter.is_none() {
  7659. *presenter = match self.presenter(width, height, format) {
  7660. Ok(p) => Some(p),
  7661. Err(e) => {
  7662. tracing::warn!(error = %e, "no swap chain");
  7663. return None;
  7664. }
  7665. };
  7666. }
  7667. let p = presenter.as_mut()?;
  7668. if (p.width, p.height, p.format) != (width, height, format) {
  7669. // Presents sent ahead hold back buffers until they have run.
  7670. settle_now(WHY_SYNC);
  7671. // SAFETY: no back buffer is held; every submission was waited for.
  7672. let resized = unsafe {
  7673. p.swap_chain
  7674. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  7675. };
  7676. match resized {
  7677. Ok(()) => {
  7678. (p.width, p.height, p.format) = (width, height, format);
  7679. tracing::info!(
  7680. width,
  7681. height,
  7682. format = format.0,
  7683. frame,
  7684. "the swap chain's buffers were made again for another size or format"
  7685. );
  7686. self.log_video_memory("right after the swap chain's buffers were made again");
  7687. }
  7688. Err(e) => {
  7689. tracing::warn!(error = %e, width, height, "swap chain not resized");
  7690. return None;
  7691. }
  7692. }
  7693. }
  7694. let state = D3D12_RESOURCE_STATES(state as i32);
  7695. // SAFETY: our swap chain, list and a live source texture.
  7696. unsafe {
  7697. let index = p.swap_chain.GetCurrentBackBufferIndex();
  7698. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  7699. return None;
  7700. };
  7701. // Sent ahead ([`late_free_present`]) unless the frame is to be
  7702. // read back at once (a saved or listed frame): then a list of
  7703. // its own, one whose last flight has finished or a new one.
  7704. #[cfg(feature = "diagnostics")]
  7705. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  7706. #[cfg(not(feature = "diagnostics"))]
  7707. let read_now = false;
  7708. let slot = if late_free_present() && !read_now {
  7709. let finished = FINISHED.load(Ordering::Acquire);
  7710. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  7711. let list = self.new_list().ok()?;
  7712. list.close();
  7713. p.ahead.push((list, 0));
  7714. Some(p.ahead.len() - 1)
  7715. })
  7716. } else {
  7717. None
  7718. };
  7719. let copy = match slot {
  7720. Some(i) => &p.ahead[i].0,
  7721. None => &p.copy,
  7722. };
  7723. copy.reset();
  7724. let list = &copy.list;
  7725. list.ResourceBarrier(&[
  7726. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  7727. transition(
  7728. &back,
  7729. D3D12_RESOURCE_STATE_PRESENT,
  7730. D3D12_RESOURCE_STATE_COPY_DEST,
  7731. ),
  7732. ]);
  7733. list.CopyResource(&back, texture);
  7734. #[cfg(feature = "diagnostics")]
  7735. let capture = crate::capture::wanted(frame)
  7736. .then(|| crate::capture::read_back(&self.device, list, texture))
  7737. .flatten();
  7738. #[cfg(feature = "diagnostics")]
  7739. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  7740. #[cfg(not(feature = "diagnostics"))]
  7741. let _ = frame;
  7742. list.ResourceBarrier(&[
  7743. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  7744. transition(
  7745. &back,
  7746. D3D12_RESOURCE_STATE_COPY_DEST,
  7747. D3D12_RESOURCE_STATE_PRESENT,
  7748. ),
  7749. ]);
  7750. copy.close();
  7751. match slot {
  7752. Some(i) => {
  7753. let flown = self.execute_own(copy);
  7754. p.ahead[i].1 = flown;
  7755. }
  7756. None => self.execute(&[copy]),
  7757. }
  7758. #[cfg(feature = "diagnostics")]
  7759. if let Some((buffer, footprint)) = capture {
  7760. crate::capture::save_read_back(frame, &buffer, &footprint);
  7761. }
  7762. #[cfg(feature = "diagnostics")]
  7763. crate::replay::record::present(texture, state);
  7764. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  7765. p.meter.frame(p.hwnd);
  7766. #[cfg(feature = "diagnostics")]
  7767. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  7768. #[cfg(not(feature = "diagnostics"))]
  7769. Some(false)
  7770. }
  7771. }
  7772. fn presenter(
  7773. &self,
  7774. width: u32,
  7775. height: u32,
  7776. format: DXGI_FORMAT,
  7777. ) -> windows::core::Result<Presenter> {
  7778. let hwnd = match title_window() {
  7779. Some(hwnd) => hwnd,
  7780. None => window(width, height)?,
  7781. };
  7782. self.log_video_memory("right before the swap chain is made");
  7783. // SAFETY: plain object creation for our window.
  7784. unsafe {
  7785. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  7786. let desc = DXGI_SWAP_CHAIN_DESC1 {
  7787. Width: width,
  7788. Height: height,
  7789. Format: format,
  7790. SampleDesc: DXGI_SAMPLE_DESC {
  7791. Count: 1,
  7792. Quality: 0,
  7793. },
  7794. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  7795. BufferCount: BUFFERS,
  7796. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  7797. ..Default::default()
  7798. };
  7799. let swap_chain = factory
  7800. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  7801. .cast::<IDXGISwapChain3>()?;
  7802. let copy = self.new_list()?;
  7803. copy.close();
  7804. tracing::info!(width, height, format = format.0, "presenting to a window");
  7805. self.log_video_memory("right after the swap chain is made");
  7806. Ok(Presenter {
  7807. swap_chain,
  7808. width,
  7809. height,
  7810. format,
  7811. copy,
  7812. ahead: Vec::new(),
  7813. hwnd,
  7814. meter: Meter::new(),
  7815. })
  7816. }
  7817. }
  7818. }
  7819. /// A visible top-level window of this process: the one the title made, if
  7820. /// it made one.
  7821. fn title_window() -> Option<HWND> {
  7822. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  7823. let mut process = 0;
  7824. // SAFETY: a window handle from the enumeration; `found` is ours.
  7825. unsafe {
  7826. GetWindowThreadProcessId(hwnd, Some(&mut process));
  7827. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  7828. && IsWindowVisible(hwnd).as_bool()
  7829. {
  7830. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  7831. return false.into();
  7832. }
  7833. }
  7834. true.into()
  7835. }
  7836. let mut found: Option<HWND> = None;
  7837. // SAFETY: the callback only writes `found`, which outlives the call.
  7838. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  7839. found
  7840. }
  7841. /// `state` without the bits the host texture's flags forbid: the console
  7842. /// lets the title name states its own resources allow (unordered access on
  7843. /// a depth target, whose host copy cannot have both).
  7844. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  7845. // SAFETY: a plain query.
  7846. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  7847. }
  7848. /// [`legal_state`] for a texture with resource flags `flags`.
  7849. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  7850. // (flag, set or clear forbids, state bits): render target, unordered
  7851. // access, depth, denied shader resource.
  7852. const FORBIDDEN: [(u32, bool, u32); 4] = [
  7853. (0x1, false, 0x4),
  7854. (0x4, false, 0x8),
  7855. (0x2, false, 0x10 | 0x20),
  7856. (0x8, true, 0x40 | 0x80),
  7857. ];
  7858. FORBIDDEN
  7859. .iter()
  7860. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  7861. .fold(state, |s, &(_, _, bits)| s & !bits)
  7862. }
  7863. impl Host {
  7864. /// The card's memory as the system accounts it to this process, in
  7865. /// bytes: the budget and the use of the card's own memory, then of the
  7866. /// PC's memory shared with the card (where the system moves what does
  7867. /// not fit on the card).
  7868. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  7869. let adapter = self.adapter.as_ref()?;
  7870. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7871. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7872. // SAFETY: plain queries that fill our structures.
  7873. unsafe {
  7874. adapter
  7875. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7876. .ok()?;
  7877. adapter
  7878. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7879. .ok()?;
  7880. }
  7881. // The card's budget moved by 256 MB or more since the last look:
  7882. // said at once, with what was in use at the last look, so the log
  7883. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  7884. // the first world frame in runs 179 to 185, and the memory line,
  7885. // seconds later, was the first to show it. We reserve nothing
  7886. // and make the swap chain once, at the start.)
  7887. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  7888. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  7889. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  7890. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  7891. tracing::info!(
  7892. "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",
  7893. last[0] >> 20,
  7894. own.Budget >> 20,
  7895. crate::frame::current(),
  7896. last[1] >> 20,
  7897. last[2] >> 20
  7898. );
  7899. self.log_video_memory("right after that change");
  7900. }
  7901. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  7902. }
  7903. /// Both of the system's memory groups for this process, in bytes: for
  7904. /// the card's own memory and then for the PC's memory shared with the
  7905. /// card, the budget, the use, what could still be reserved and what
  7906. /// is reserved (the layer reserves none).
  7907. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  7908. let adapter = self.adapter.as_ref()?;
  7909. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7910. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7911. // SAFETY: plain queries that fill our structures.
  7912. unsafe {
  7913. adapter
  7914. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7915. .ok()?;
  7916. adapter
  7917. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7918. .ok()?;
  7919. }
  7920. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  7921. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  7922. };
  7923. Some([all(&own), all(&shared)])
  7924. }
  7925. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  7926. pub(crate) fn log_video_memory(&self, when: &str) {
  7927. let Some([own, shared]) = self.video_memory_groups() else {
  7928. return;
  7929. };
  7930. tracing::info!(
  7931. "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)",
  7932. when,
  7933. own[0] >> 20,
  7934. own[1] >> 20,
  7935. own[2] >> 20,
  7936. own[3] >> 20,
  7937. shared[0] >> 20,
  7938. shared[1] >> 20,
  7939. shared[2] >> 20,
  7940. shared[3] >> 20
  7941. );
  7942. }
  7943. /// A buffer in system memory that the CPU maps (write-back, so reading
  7944. /// it is fast too) and shaders read and write: for host copies of title
  7945. /// memory that shaders write, which upload memory cannot be. Starts in
  7946. /// the common state (buffers move out of it implicitly).
  7947. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7948. MADE[2].fetch_add(1, Ordering::Relaxed);
  7949. MADE[3].fetch_add(size, Ordering::Relaxed);
  7950. let heap = D3D12_HEAP_PROPERTIES {
  7951. Type: D3D12_HEAP_TYPE_CUSTOM,
  7952. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  7953. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  7954. ..Default::default()
  7955. };
  7956. let desc = D3D12_RESOURCE_DESC {
  7957. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7958. Width: size.max(1),
  7959. Height: 1,
  7960. DepthOrArraySize: 1,
  7961. MipLevels: 1,
  7962. SampleDesc: DXGI_SAMPLE_DESC {
  7963. Count: 1,
  7964. Quality: 0,
  7965. },
  7966. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7967. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7968. ..Default::default()
  7969. };
  7970. let mut buffer: Option<ID3D12Resource> = None;
  7971. let mut data = std::ptr::null_mut();
  7972. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7973. let made = unsafe {
  7974. self.device
  7975. .CreateCommittedResource(
  7976. &heap,
  7977. D3D12_HEAP_FLAG_NONE,
  7978. &desc,
  7979. D3D12_RESOURCE_STATE_COMMON,
  7980. None,
  7981. &mut buffer,
  7982. )
  7983. .and_then(|()| {
  7984. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7985. b.Map(0, None, Some(&mut data))
  7986. })
  7987. };
  7988. #[cfg(feature = "diagnostics")]
  7989. if made.is_ok()
  7990. && let Some(b) = &buffer
  7991. {
  7992. crate::book::made(b, || "a shared buffer".into());
  7993. }
  7994. match made {
  7995. Ok(()) => Some((buffer?, data.cast())),
  7996. Err(e) => {
  7997. tracing::warn!(error = %e, size, "no shared buffer");
  7998. None
  7999. }
  8000. }
  8001. }
  8002. /// Whether buffers can lie in the card's memory and be mapped by the CPU
  8003. /// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver
  8004. /// that offer it); logged once.
  8005. pub(crate) fn mapped_card_memory(&self) -> bool {
  8006. static THERE: OnceLock<bool> = OnceLock::new();
  8007. *THERE.get_or_init(|| {
  8008. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default();
  8009. // SAFETY: writes `options` of the given size.
  8010. let ok = unsafe {
  8011. self.device
  8012. .CheckFeatureSupport(
  8013. D3D12_FEATURE_D3D12_OPTIONS16,
  8014. (&raw mut options).cast(),
  8015. size_of_val(&options) as u32,
  8016. )
  8017. .is_ok()
  8018. };
  8019. let supported = ok && options.GPUUploadHeapSupported.as_bool();
  8020. tracing::info!(supported, "card memory the CPU maps");
  8021. supported
  8022. })
  8023. }
  8024. /// A buffer in the card's own memory that the CPU maps, shaders read and
  8025. /// (with `written`) may write. The CPU should only write it: a read of the
  8026. /// mapping crosses the bus a few bytes at a time.
  8027. pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> {
  8028. if !self.mapped_card_memory() {
  8029. return None;
  8030. }
  8031. MADE[4].fetch_add(1, Ordering::Relaxed);
  8032. MADE[5].fetch_add(size, Ordering::Relaxed);
  8033. let heap = D3D12_HEAP_PROPERTIES {
  8034. Type: D3D12_HEAP_TYPE_GPU_UPLOAD,
  8035. ..Default::default()
  8036. };
  8037. let desc = D3D12_RESOURCE_DESC {
  8038. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  8039. Width: size.max(1),
  8040. Height: 1,
  8041. DepthOrArraySize: 1,
  8042. MipLevels: 1,
  8043. SampleDesc: DXGI_SAMPLE_DESC {
  8044. Count: 1,
  8045. Quality: 0,
  8046. },
  8047. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  8048. Flags: if written {
  8049. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
  8050. } else {
  8051. D3D12_RESOURCE_FLAG_NONE
  8052. },
  8053. ..Default::default()
  8054. };
  8055. let mut buffer: Option<ID3D12Resource> = None;
  8056. let mut data = std::ptr::null_mut();
  8057. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  8058. let made = unsafe {
  8059. self.device
  8060. .CreateCommittedResource(
  8061. &heap,
  8062. D3D12_HEAP_FLAG_NONE,
  8063. &desc,
  8064. D3D12_RESOURCE_STATE_COMMON,
  8065. None,
  8066. &mut buffer,
  8067. )
  8068. .and_then(|()| {
  8069. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  8070. b.Map(0, None, Some(&mut data))
  8071. })
  8072. };
  8073. match made {
  8074. Ok(()) => Some((buffer?, data.cast())),
  8075. Err(e) => {
  8076. tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps");
  8077. None
  8078. }
  8079. }
  8080. }
  8081. /// A device-local buffer shaders may write (unordered access) and indirect
  8082. /// execution may read, starting in the common state.
  8083. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  8084. MADE[4].fetch_add(1, Ordering::Relaxed);
  8085. MADE[5].fetch_add(size, Ordering::Relaxed);
  8086. let heap = D3D12_HEAP_PROPERTIES {
  8087. Type: D3D12_HEAP_TYPE_DEFAULT,
  8088. ..Default::default()
  8089. };
  8090. let desc = D3D12_RESOURCE_DESC {
  8091. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  8092. Width: size.max(1),
  8093. Height: 1,
  8094. DepthOrArraySize: 1,
  8095. MipLevels: 1,
  8096. SampleDesc: DXGI_SAMPLE_DESC {
  8097. Count: 1,
  8098. Quality: 0,
  8099. },
  8100. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  8101. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  8102. ..Default::default()
  8103. };
  8104. let mut buffer: Option<ID3D12Resource> = None;
  8105. // SAFETY: plain creation of a device-local buffer.
  8106. let made = unsafe {
  8107. self.device.CreateCommittedResource(
  8108. &heap,
  8109. D3D12_HEAP_FLAG_NONE,
  8110. &desc,
  8111. D3D12_RESOURCE_STATE_COMMON,
  8112. None,
  8113. &mut buffer,
  8114. )
  8115. };
  8116. #[cfg(feature = "diagnostics")]
  8117. if let Some(b) = &buffer {
  8118. crate::book::made(b, || "an unordered access buffer".into());
  8119. }
  8120. match made {
  8121. Ok(()) => buffer,
  8122. Err(e) => {
  8123. tracing::warn!(error = %e, size, "no unordered-access buffer");
  8124. None
  8125. }
  8126. }
  8127. }
  8128. }
  8129. /// For adapters without device-removed data (the software one): the last
  8130. /// commands each list of the failed submission noted (diagnostics, with
  8131. /// `VICTORY_D3D12_DRED`).
  8132. fn last_notes(runs: &[&HostList]) -> String {
  8133. #[cfg(feature = "diagnostics")]
  8134. {
  8135. let mut text = String::new();
  8136. for (i, r) in runs.iter().enumerate() {
  8137. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  8138. for (n, _) in notes.iter().rev().take(6).rev() {
  8139. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  8140. }
  8141. }
  8142. text
  8143. }
  8144. #[cfg(not(feature = "diagnostics"))]
  8145. {
  8146. let _ = runs;
  8147. String::new()
  8148. }
  8149. }
  8150. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  8151. /// command reads (diagnostics).
  8152. #[cfg(feature = "diagnostics")]
  8153. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  8154. let end = start + bytes;
  8155. if va < start {
  8156. format!(" (fault {:#x} below its source)", start - va)
  8157. } else if va < end {
  8158. format!(" (fault at source +{:#x})", va - start)
  8159. } else {
  8160. format!(" (fault {:#x} past its source's end)", va - end)
  8161. }
  8162. }
  8163. /// The commands that may have been running where a list stopped at
  8164. /// command `done`: those between the barriers around it (work between
  8165. /// barriers overlaps on the GPU), by kind, and what the markers just
  8166. /// before them say (`HostList::note_op`: diagnostics builds with
  8167. /// device-removed data on).
  8168. /// For a list that stopped at command `done`: what the indirect executions
  8169. /// there ran, from the one before it to the next barrier (four at most), and
  8170. /// what the heap slots their user data names hold now.
  8171. #[cfg(feature = "diagnostics")]
  8172. fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &indirects::Shared) -> String {
  8173. let indirect = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT;
  8174. let all = all.lock().unwrap_or_else(|e| e.into_inner());
  8175. let mut text = String::new();
  8176. let mut shown = 0;
  8177. let mesh = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_DISPATCHMESH;
  8178. for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) {
  8179. if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) {
  8180. break;
  8181. }
  8182. if !indirect(op) && !mesh(op) {
  8183. continue;
  8184. }
  8185. shown += 1;
  8186. let direct = mesh(op);
  8187. let nth = if direct { indirects::before(history, at, mesh) } else { indirects::before(history, at, indirect) };
  8188. let Some((what, words)) = all.nth(nth, direct) else {
  8189. continue;
  8190. };
  8191. text.push_str(&format!("; command {at} ran {what}"));
  8192. for (word, slot, what) in crate::descriptor::host::describe_slots(words) {
  8193. text.push_str(&format!(", word {word} slot {slot}: {what}"));
  8194. }
  8195. }
  8196. text
  8197. }
  8198. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  8199. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  8200. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  8201. let to = history[done..]
  8202. .iter()
  8203. .position(barrier)
  8204. .map_or(history.len(), |b| (done + b).max(done + 1));
  8205. let mut text = format!(", commands {from}..{to} between its barriers:");
  8206. let mut shown = 0;
  8207. // From just before the command the GPU had not finished: the first
  8208. // twelve after the barrier named draws long done when a list of 79
  8209. // mesh draws stopped at its 45th (run 41).
  8210. for i in from.max(done.saturating_sub(4))..to {
  8211. let op = history[i];
  8212. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  8213. continue;
  8214. }
  8215. shown += 1;
  8216. let marker = i
  8217. .checked_sub(1)
  8218. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  8219. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  8220. .map_or("no marker", |(_, s)| s.as_str());
  8221. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  8222. }
  8223. text
  8224. }
  8225. pub(crate) fn transition(
  8226. resource: &ID3D12Resource,
  8227. before: D3D12_RESOURCE_STATES,
  8228. after: D3D12_RESOURCE_STATES,
  8229. ) -> D3D12_RESOURCE_BARRIER {
  8230. D3D12_RESOURCE_BARRIER {
  8231. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  8232. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  8233. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  8234. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  8235. // SAFETY: a borrowed pointer; the barrier never releases it.
  8236. pResource: unsafe { std::mem::transmute_copy(resource) },
  8237. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  8238. StateBefore: before,
  8239. StateAfter: after,
  8240. }),
  8241. },
  8242. }
  8243. }
  8244. /// A window of the given client size, owned by its own message thread.
  8245. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  8246. let (sender, receiver) = std::sync::mpsc::channel();
  8247. std::thread::Builder::new()
  8248. .name("victory-window".into())
  8249. .spawn(move || {
  8250. let made = make_window(width, height);
  8251. let ok = made.is_ok();
  8252. let _ = sender.send(made.map(|h| h.0 as usize));
  8253. if ok {
  8254. pump();
  8255. }
  8256. })
  8257. .map_err(|_| windows::core::Error::empty())?;
  8258. let hwnd = receiver
  8259. .recv()
  8260. .map_err(|_| windows::core::Error::empty())??;
  8261. Ok(HWND(hwnd as *mut _))
  8262. }
  8263. extern "system" fn window_proc(
  8264. hwnd: HWND,
  8265. message: u32,
  8266. wparam: WPARAM,
  8267. lparam: LPARAM,
  8268. ) -> LRESULT {
  8269. // SAFETY: the default handling for our window.
  8270. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  8271. }
  8272. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  8273. const CLASS: PCWSTR = w!("VIctory");
  8274. // SAFETY: registers our class once and creates a window of it.
  8275. unsafe {
  8276. let instance = GetModuleHandleW(None)?;
  8277. let class = WNDCLASSEXW {
  8278. cbSize: size_of::<WNDCLASSEXW>() as u32,
  8279. lpfnWndProc: Some(window_proc),
  8280. hInstance: instance.into(),
  8281. lpszClassName: CLASS,
  8282. hCursor: LoadCursorW(None, IDC_ARROW)?,
  8283. ..Default::default()
  8284. };
  8285. RegisterClassExW(&class);
  8286. let mut rect = RECT {
  8287. left: 0,
  8288. top: 0,
  8289. right: width as i32,
  8290. bottom: height as i32,
  8291. };
  8292. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  8293. CreateWindowExW(
  8294. WINDOW_EX_STYLE(0),
  8295. CLASS,
  8296. w!("VIctory"),
  8297. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  8298. CW_USEDEFAULT,
  8299. CW_USEDEFAULT,
  8300. rect.right - rect.left,
  8301. rect.bottom - rect.top,
  8302. None,
  8303. None,
  8304. Some(instance.into()),
  8305. None,
  8306. )
  8307. }
  8308. }
  8309. fn pump() {
  8310. let mut message = MSG::default();
  8311. // SAFETY: the standard message loop of this thread's window.
  8312. unsafe {
  8313. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  8314. let _ = TranslateMessage(&message);
  8315. DispatchMessageW(&message);
  8316. }
  8317. }
  8318. }
  8319. #[cfg(test)]
  8320. mod trail {
  8321. /// The trail keeps the newest things, and the report made when the
  8322. /// host device is removed says them and the pipeline library's state
  8323. /// (no card is asked for any of it).
  8324. #[test]
  8325. fn the_removal_report_says_the_newest_things_done() {
  8326. for n in 0..super::TRAIL_MOST + 5 {
  8327. super::trail(|| format!("thing {n} done"));
  8328. }
  8329. let text = super::removal_context();
  8330. assert!(text.contains("the submitting thread was"));
  8331. assert!(text.contains("pipeline library: no call running"));
  8332. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  8333. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  8334. }
  8335. }
  8336. #[cfg(test)]
  8337. mod spare {
  8338. use super::Spare;
  8339. /// Kept things come back by size, the last given first, and nothing is
  8340. /// kept past the limit.
  8341. #[test]
  8342. fn kept_things_come_back_by_size_within_the_limit() {
  8343. let mut spare: Spare<u32> = Spare::new();
  8344. assert_eq!(spare.take(4), None);
  8345. assert_eq!(spare.give(1, 4, 10), None);
  8346. assert_eq!(spare.give(2, 1, 10), None);
  8347. assert_eq!(spare.give(3, 4, 10), None);
  8348. assert_eq!(spare.bytes, 9);
  8349. // Past the limit: handed back, nothing changes.
  8350. assert_eq!(spare.give(4, 4, 10), Some(4));
  8351. assert_eq!(spare.bytes, 9);
  8352. assert_eq!(spare.take(2), None, "no thing of that size");
  8353. assert_eq!(spare.take(4), Some(3));
  8354. assert_eq!(spare.take(4), Some(1));
  8355. assert_eq!(spare.take(4), None);
  8356. assert_eq!(spare.take(1), Some(2));
  8357. assert_eq!(spare.bytes, 0);
  8358. assert!(spare.kept.is_empty());
  8359. }
  8360. }
  8361. #[cfg(test)]
  8362. mod refresh_tests {
  8363. use super::Batch;
  8364. use crate::shadow::Shadow;
  8365. use std::sync::Arc;
  8366. use windows_sys::Win32::System::Memory::{
  8367. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  8368. VirtualAlloc,
  8369. };
  8370. const PAGE: usize = 64 << 10;
  8371. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  8372. /// Title memory for the tests (never given back: copies of it stay in
  8373. /// the guards): write-watched, or a view of a section.
  8374. fn title(len: usize, view: bool) -> usize {
  8375. // SAFETY: plain allocations.
  8376. let at = unsafe {
  8377. if view {
  8378. let section =
  8379. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  8380. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  8381. // As the runtime tells of it.
  8382. crate::title_memory_section(section as usize, len as u64, true);
  8383. crate::title_memory_remapped(at, len);
  8384. crate::title_memory_view(at, len, section as usize, 0);
  8385. at
  8386. } else {
  8387. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  8388. }
  8389. };
  8390. assert_ne!(at, 0);
  8391. at
  8392. }
  8393. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  8394. /// and every fourth page not there: as a title that streams has it.
  8395. fn with_holes(blocks: usize) -> usize {
  8396. use windows_sys::Win32::System::Memory::{
  8397. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  8398. VirtualAlloc2, VirtualFree,
  8399. };
  8400. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  8401. // SAFETY: a placeholder and a section of our own.
  8402. unsafe {
  8403. let at = VirtualAlloc2(
  8404. GetCurrentProcess(),
  8405. std::ptr::null(),
  8406. blocks * PAGE,
  8407. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  8408. PAGE_NOACCESS,
  8409. std::ptr::null_mut(),
  8410. 0,
  8411. ) as usize;
  8412. assert_ne!(at, 0);
  8413. let len = blocks * PAGE;
  8414. let section =
  8415. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  8416. for block in (0..blocks).filter(|b| b % 4 != 3) {
  8417. let to = at + block * PAGE;
  8418. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  8419. let view = MapViewOfFile3(
  8420. section,
  8421. GetCurrentProcess(),
  8422. to as *const _,
  8423. (block * PAGE) as u64,
  8424. PAGE,
  8425. MEM_REPLACE_PLACEHOLDER,
  8426. PAGE_READWRITE,
  8427. std::ptr::null_mut(),
  8428. 0,
  8429. );
  8430. assert_eq!(view.Value as usize, to);
  8431. crate::title_memory_remapped(to, PAGE);
  8432. }
  8433. at
  8434. }
  8435. }
  8436. fn memory(len: usize) -> *mut u8 {
  8437. // SAFETY: a plain allocation.
  8438. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  8439. }
  8440. struct Random(u64);
  8441. impl Random {
  8442. fn below(&mut self, n: usize) -> usize {
  8443. self.0 ^= self.0 << 13;
  8444. self.0 ^= self.0 >> 7;
  8445. self.0 ^= self.0 << 17;
  8446. (self.0 >> 11) as usize % n
  8447. }
  8448. }
  8449. /// Prepares as a submission does: one asking for all the ranges, the
  8450. /// refreshes in several flushes, the asking's end.
  8451. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  8452. // One at a time, as submissions are.
  8453. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  8454. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  8455. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  8456. crate::watch::ask_once(&asked);
  8457. let mut batch = Batch::default();
  8458. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  8459. for (shadow, at, len) in part {
  8460. batch.add(shadow, *at, *len);
  8461. }
  8462. batch.flush();
  8463. }
  8464. crate::watch::ask_once_end();
  8465. }
  8466. /// Whatever is written where, by the title or by us, and whichever
  8467. /// copies (of both kinds of memory, over one another, none on a page
  8468. /// line) are refreshed in which ranges: a refreshed range holds what
  8469. /// title memory holds.
  8470. #[test]
  8471. fn refreshed_ranges_hold_title_memory() {
  8472. // SAFETY (all blocks): title memory and copies of the test's own,
  8473. // written by this thread and, in `Batch::flush`, by the threads that
  8474. // refresh, which are done when it returns.
  8475. let mut random = Random(0x1234_5678_9ABC_DEF1);
  8476. const LEN: usize = 24 * PAGE;
  8477. let regions = [title(LEN, false), title(LEN, true)];
  8478. let mut copies = Vec::new();
  8479. for &region in &regions {
  8480. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  8481. let data = memory(to - from);
  8482. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  8483. }
  8484. }
  8485. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  8486. for round in 0..600 {
  8487. for _ in 0..random.below(4) {
  8488. let at = regions[random.below(2)] + random.below(LEN - 64);
  8489. let n = 1 + random.below(60);
  8490. if random.below(3) == 0 {
  8491. // What shaders wrote.
  8492. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  8493. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  8494. Shadow::put(at, &was, &now);
  8495. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  8496. continue;
  8497. }
  8498. for i in 0..n {
  8499. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  8500. }
  8501. }
  8502. let mut ranges = Vec::new();
  8503. for (shadow, _) in &copies {
  8504. if random.below(3) == 0 {
  8505. continue;
  8506. }
  8507. let (start, len) = shadow.span();
  8508. let (start, len) = (start as usize, len as usize);
  8509. // Often the range of the time before, as a list's is.
  8510. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  8511. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  8512. ranges.push((shadow.clone(), start + from, n));
  8513. }
  8514. if ranges.is_empty() {
  8515. continue;
  8516. }
  8517. let flushes = 1 + random.below(3);
  8518. submission(&ranges, flushes);
  8519. for (shadow, at, n) in &ranges {
  8520. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  8521. let start = shadow.span().0 as usize;
  8522. let same = unsafe {
  8523. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  8524. };
  8525. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  8526. }
  8527. }
  8528. }
  8529. /// A copy in the card's memory, with the card's side and the sends to it
  8530. /// played by the test.
  8531. struct Carded {
  8532. shadow: Arc<Shadow>,
  8533. data: usize,
  8534. start: usize,
  8535. len: usize,
  8536. /// The last send, the last send every fetch to come is behind, and
  8537. /// the card's bytes: the queue's order is the order it is locked in.
  8538. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  8539. /// Whether a flight that writes it has not landed.
  8540. flying: std::sync::atomic::AtomicBool,
  8541. /// The dword of each eight its shaders write.
  8542. class: usize,
  8543. }
  8544. impl Carded {
  8545. fn new(start: usize, len: usize, class: usize) -> Carded {
  8546. let data = memory(len);
  8547. Carded {
  8548. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  8549. data: data as usize,
  8550. start,
  8551. len,
  8552. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  8553. flying: std::sync::atomic::AtomicBool::new(false),
  8554. class,
  8555. }
  8556. }
  8557. /// What changed on the CPU's side goes up.
  8558. fn send(&self) {
  8559. let mut card = self.card.lock().unwrap();
  8560. card.0 += 1;
  8561. let (number, merged) = (card.0, card.1);
  8562. for (a, b) in self.shadow.send_up(number, merged) {
  8563. // SAFETY: the copy's bytes; nothing writes those that are to
  8564. // go up.
  8565. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  8566. }
  8567. }
  8568. }
  8569. /// Everything at once: the title writes its memory on two threads, the
  8570. /// submitting thread puts its bytes in under shader writes
  8571. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  8572. /// the card's memory, one not), sends up what changed and declares what
  8573. /// the next flight's shaders write, and what flights wrote is landed
  8574. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  8575. /// still and the copies are refreshed once more, each of them, and the
  8576. /// card's side of those that have one, hold what title memory holds, and
  8577. /// title memory what was written last.
  8578. ///
  8579. /// Into the first copy shaders write besides through a view nobody
  8580. /// declared, words the title does not write: nothing that goes up ever
  8581. /// puts an older value over those.
  8582. ///
  8583. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  8584. /// only takes the block out of the guards' clean ones and leaves its bit,
  8585. /// or if a fault leaves the bit; in some thousand rounds,
  8586. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  8587. #[test]
  8588. fn landings_title_writes_and_light_refreshes_at_once() {
  8589. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  8590. assert!(crate::safecopy::on());
  8591. const LEN: usize = 24 * PAGE;
  8592. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  8593. let region = title(LEN, true);
  8594. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  8595. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  8596. let plain = {
  8597. let (start, len) = (region + 700, LEN - 9000);
  8598. let data = memory(len);
  8599. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  8600. };
  8601. // What was last written so, by offset.
  8602. let mut undeclared = std::collections::HashMap::new();
  8603. let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0");
  8604. let stop = AtomicBool::new(false);
  8605. // Also when an assertion fails on one of the threads.
  8606. struct Stop<'a>(&'a AtomicBool);
  8607. impl Drop for Stop<'_> {
  8608. fn drop(&mut self) {
  8609. self.0.store(true, Ordering::Relaxed);
  8610. }
  8611. }
  8612. // Held shared by who writes title memory, alone while it is looked at.
  8613. let still = std::sync::RwLock::new(());
  8614. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  8615. std::thread::scope(|s| {
  8616. for t in 0..2usize {
  8617. let (stop, still) = (&stop, &still);
  8618. s.spawn(move || {
  8619. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  8620. let mut value = 0u32;
  8621. while !stop.load(Ordering::Relaxed) {
  8622. {
  8623. let _moving = still.read().unwrap();
  8624. for _ in 0..3 {
  8625. value += 1;
  8626. // Of each eight dwords, one a thread.
  8627. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  8628. dword(at).store(value, Ordering::Relaxed);
  8629. }
  8630. }
  8631. std::thread::sleep(std::time::Duration::from_micros(20));
  8632. }
  8633. });
  8634. }
  8635. // Lands flights.
  8636. {
  8637. let (carded, stop) = (&carded, &stop);
  8638. s.spawn(move || {
  8639. let _stop = Stop(stop);
  8640. while let Ok((which, ranges, value)) = flights.recv() {
  8641. let c = &carded[which];
  8642. // Fetched: the card's bytes, behind every send so far.
  8643. let (after, now) = {
  8644. let card = c.card.lock().unwrap();
  8645. (card.0, card.2.clone())
  8646. };
  8647. // By piece: 64 KiB of title memory.
  8648. let mut pieces = Vec::new();
  8649. for &(from, to) in &ranges {
  8650. let mut at = from;
  8651. while at < to {
  8652. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  8653. pieces.push((at, next, now.as_ptr() as usize + at));
  8654. at = next;
  8655. }
  8656. }
  8657. let parts: Vec<_> = pieces.chunks(3).collect();
  8658. crate::land::each(parts.len(), &|i| {
  8659. let mut notes = crate::land::Notes::default();
  8660. // SAFETY: the bytes of `now`; each piece once.
  8661. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  8662. notes.flush();
  8663. });
  8664. for &(from, to) in &ranges {
  8665. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8666. // (The next fetch may have brought more.)
  8667. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  8668. }
  8669. }
  8670. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  8671. c.shadow.copy_back_done(&done);
  8672. c.card.lock().unwrap().1 = after;
  8673. c.flying.store(false, Ordering::Release);
  8674. }
  8675. });
  8676. }
  8677. let _stop = Stop(&stop);
  8678. let mut random = Random(0xABCD_EF01_2345_6789);
  8679. let check = |round: usize, random: &mut Random, quiet: bool| {
  8680. for c in &carded {
  8681. if c.shadow.writes_pending() {
  8682. let mut runs = usize::MAX;
  8683. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  8684. }
  8685. }
  8686. let mut ranges = Vec::new();
  8687. for (shadow, start, len) in
  8688. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  8689. {
  8690. // All of it, or a part; often the same part.
  8691. let (from, n) = match random.below(3) {
  8692. _ if quiet => (0, len),
  8693. 0 => (0, len),
  8694. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  8695. _ => {
  8696. let from = random.below(len / 4) * 4;
  8697. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  8698. }
  8699. };
  8700. ranges.push((shadow.clone(), start + from, n));
  8701. }
  8702. submission(&ranges, 1 + random.below(3));
  8703. carded.iter().for_each(Carded::send);
  8704. };
  8705. let mut value = 1u32;
  8706. for round in 0..rounds {
  8707. check(round, &mut random, false);
  8708. if exact {
  8709. let c = &carded[0];
  8710. let mut card = c.card.lock().unwrap();
  8711. for _ in 0..40 {
  8712. value += 1;
  8713. let at = random.below(LEN / 32) * 32 + 4 * 6;
  8714. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8715. undeclared.insert(at, value);
  8716. }
  8717. }
  8718. // The flight of this submission: its shaders' writes.
  8719. for (which, c) in carded.iter().enumerate() {
  8720. if c.flying.swap(true, Ordering::Acquire) {
  8721. continue;
  8722. }
  8723. value += 1;
  8724. let mut ranges: Vec<(usize, usize)> = Vec::new();
  8725. let first = random.below(6) * PAGE / 2;
  8726. for k in 0..2 {
  8727. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  8728. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  8729. if from < to {
  8730. ranges.push((from, to));
  8731. }
  8732. }
  8733. for &(from, to) in &ranges {
  8734. c.shadow.writing(c.start + from, to - from);
  8735. }
  8736. {
  8737. let mut card = c.card.lock().unwrap();
  8738. for &(from, to) in &ranges {
  8739. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8740. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8741. }
  8742. }
  8743. }
  8744. fly.send((which, ranges, value)).unwrap();
  8745. }
  8746. if round % 20 != 19 {
  8747. continue;
  8748. }
  8749. // Still: no flight in the air, no title write.
  8750. let _still = still.write().unwrap();
  8751. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  8752. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  8753. std::thread::yield_now();
  8754. }
  8755. check(round, &mut random, true);
  8756. // SAFETY: the test's own memory, written by nobody now.
  8757. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  8758. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  8759. for c in &carded {
  8760. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  8761. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  8762. let card = c.card.lock().unwrap();
  8763. let mut side = card.2.clone();
  8764. if c.class == carded[0].class {
  8765. // (They may have been landed meanwhile, by a flight
  8766. // that declared their range, and may not.)
  8767. for (&at, &value) in &undeclared {
  8768. let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
  8769. assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
  8770. side[at..at + 4].copy_from_slice(&there[at..at + 4]);
  8771. }
  8772. }
  8773. assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
  8774. }
  8775. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  8776. }
  8777. drop(fly);
  8778. });
  8779. }
  8780. /// The title's bytes put in under shader writes, for a copy of 174 MB
  8781. /// whose shader writes were declared as 40 ranges that overlap, with 12
  8782. /// pages written since. Run with `--ignored --nocapture`, and with
  8783. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8784. #[test]
  8785. #[ignore]
  8786. fn bytes_under_overlapping_ranges() {
  8787. const BIG: usize = 174 << 20;
  8788. let big = title(BIG, true);
  8789. // SAFETY (both): the test's own memory.
  8790. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  8791. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8792. copy.update(big, BIG);
  8793. copy.take_dirty();
  8794. for i in 0..40 {
  8795. copy.writing(big + i * 5920, BIG - i * 5920);
  8796. }
  8797. let mut best = f64::MAX;
  8798. for round in 0..30 {
  8799. for i in 0..12 {
  8800. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  8801. }
  8802. let started = std::time::Instant::now();
  8803. let mut runs = usize::MAX;
  8804. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  8805. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  8806. copy.take_dirty();
  8807. }
  8808. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  8809. }
  8810. /// A range nothing wrote is known to be as it was, at its ends too, and
  8811. /// is so no more once something wrote it.
  8812. #[test]
  8813. fn unchanged_ranges_are_known() {
  8814. for view in [false, true] {
  8815. let region = title(8 * PAGE, view);
  8816. // (A page read for the first time counts as written.)
  8817. // SAFETY: the test's own memory.
  8818. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  8819. let data = memory(8 * PAGE);
  8820. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  8821. // Ends in the middle of pages.
  8822. let (at, len) = (region + 500, 5 * PAGE);
  8823. let look = |expected: bool, what: &str| {
  8824. // The submission's one asking, which takes two ranges. (Again
  8825. // if a submission of another test ended it.)
  8826. let mut known = false;
  8827. for _ in 0..100 {
  8828. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  8829. known = copy.nothing_new(at, len);
  8830. if known || !expected {
  8831. break;
  8832. }
  8833. }
  8834. assert_eq!(known, expected, "view {view}: {what}");
  8835. let copied = copy.update(at, len);
  8836. crate::watch::ask_once_end();
  8837. copied
  8838. };
  8839. assert_eq!(look(false, "never taken"), len);
  8840. assert_eq!(look(true, "taken"), 0);
  8841. assert_eq!(look(true, "taken"), 0);
  8842. // SAFETY: the test's own memory.
  8843. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  8844. // (The kernel names the 4 KiB, the guards only the block.)
  8845. assert_eq!(look(false, "written at its end"), if view { PAGE } else { 4096 } - 500);
  8846. assert_eq!(look(true, "taken again"), 0);
  8847. // Outside the range, on its last page.
  8848. // SAFETY: as above.
  8849. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  8850. assert_eq!(look(false, "written on its last page"), 500);
  8851. // A longer range was never taken whole.
  8852. assert!(!copy.nothing_new(region, 6 * PAGE));
  8853. }
  8854. }
  8855. /// Of a copy in the card's memory only the dwords title memory changed go
  8856. /// up, and none beside them, not even between two in 64 bytes; a page
  8857. /// never taken goes up whole.
  8858. #[test]
  8859. fn only_what_differs_goes_up() {
  8860. let region = title(4 * PAGE, true);
  8861. let data = memory(4 * PAGE);
  8862. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  8863. copy.update(region, 4 * PAGE);
  8864. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  8865. // What the relay does: shader writes into title memory, and into the
  8866. // CPU's side.
  8867. crate::watch::landing(region + PAGE + 640, 64);
  8868. // SAFETY: the test's own memory.
  8869. unsafe {
  8870. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  8871. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  8872. }
  8873. copy.update(region, 4 * PAGE);
  8874. let again = copy.take_dirty();
  8875. // SAFETY: as above.
  8876. unsafe {
  8877. ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
  8878. ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
  8879. ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
  8880. // The value that was there.
  8881. ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
  8882. }
  8883. copy.update(region, 4 * PAGE);
  8884. let written = copy.take_dirty();
  8885. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") {
  8886. assert_eq!(again, []);
  8887. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
  8888. } else {
  8889. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  8890. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  8891. }
  8892. // SAFETY: as above.
  8893. assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
  8894. }
  8895. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  8896. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  8897. /// big copy that 55 landed pieces and 9 title writes opened, while a
  8898. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  8899. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8900. #[test]
  8901. #[ignore]
  8902. fn frame_of_refreshes() {
  8903. let mut random = Random(0x9876_5432_1234_5671);
  8904. const EACH: usize = 224 << 10;
  8905. const BIG: usize = 174 << 20;
  8906. let watched = title(3000 * EACH, false);
  8907. // `VICTORY_BENCH_HOLES=0`: views without holes.
  8908. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  8909. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  8910. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  8911. let big = title(BIG, true);
  8912. // SAFETY: the test's own memory.
  8913. unsafe {
  8914. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  8915. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  8916. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  8917. }
  8918. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  8919. }
  8920. let mut small = Vec::new();
  8921. for i in 0..4400 {
  8922. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  8923. let data = memory(EACH);
  8924. // The range views read, not all of the copy.
  8925. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  8926. }
  8927. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  8928. // The same memory, as another copy: what is landed is landed through
  8929. // it, and the refreshes are of the first.
  8930. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8931. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  8932. let (mut sum, mut landing) = (0.0, 0.0);
  8933. const FRAMES: usize = 12;
  8934. for frame in 0..FRAMES {
  8935. let mut took = [0f64; 2];
  8936. for i in 0..30 {
  8937. // The title's writes, and the relay's beside the submission.
  8938. for _ in 0..9 {
  8939. let at = views + random.below(1400 * EACH / 8) * 8;
  8940. if there(at) {
  8941. // SAFETY: the test's own memory.
  8942. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8943. }
  8944. }
  8945. for _ in 0..60 {
  8946. let at = watched + random.below(3000 * EACH / 8) * 8;
  8947. // SAFETY: the test's own memory.
  8948. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8949. }
  8950. let first = random.below(BIG / PAGE - 60);
  8951. let lands = lands.clone();
  8952. let land = std::thread::spawn(move || {
  8953. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  8954. let started = std::time::Instant::now();
  8955. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  8956. let pieces: Vec<_> =
  8957. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  8958. let mut notes = crate::land::Notes::default();
  8959. // SAFETY: the bytes of `now`; nothing else lands here.
  8960. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  8961. notes.flush();
  8962. }
  8963. started.elapsed().as_secs_f64() * 1e3
  8964. });
  8965. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  8966. small.iter().cloned().chain([heap.clone()]).collect()
  8967. } else {
  8968. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  8969. };
  8970. let started = std::time::Instant::now();
  8971. submission(&ranges, 3);
  8972. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  8973. let put = land.join().unwrap();
  8974. if frame >= 2 {
  8975. landing += put;
  8976. }
  8977. heap.0.take_dirty();
  8978. }
  8979. if frame >= 2 {
  8980. sum += took[0] + took[1];
  8981. for k in 0..2 {
  8982. best[k] = best[k].min(took[k]);
  8983. asking[k] += took[k];
  8984. }
  8985. }
  8986. }
  8987. println!(
  8988. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  8989. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  8990. crate::watch::light(),
  8991. sum / (FRAMES - 2) as f64,
  8992. asking[0] / (FRAMES - 2) as f64,
  8993. best[0],
  8994. asking[1] / (FRAMES - 2) as f64,
  8995. best[1],
  8996. landing / (FRAMES - 2) as f64,
  8997. );
  8998. #[cfg(feature = "diagnostics")]
  8999. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  9000. }
  9001. }
  9002. #[cfg(test)]
  9003. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  9004. use super::Batch;
  9005. use std::sync::Arc;
  9006. #[test]
  9007. fn a_texture_is_checked_once_per_submission() {
  9008. let mut batch = Batch::default();
  9009. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  9010. // The first list sampling each texture checks it ...
  9011. assert!(batch.texture_due(&a));
  9012. assert!(batch.texture_due(&b));
  9013. // ... later lists of the same submission do not.
  9014. assert!(!batch.texture_due(&a));
  9015. assert!(!batch.texture_due(&a.clone()));
  9016. assert!(!batch.texture_due(&b));
  9017. }
  9018. #[test]
  9019. fn title_writes_make_textures_due_again() {
  9020. let mut batch = Batch::default();
  9021. let a = Arc::new(1u32);
  9022. assert!(batch.texture_due(&a));
  9023. assert!(!batch.texture_due(&a));
  9024. // A copy into title memory or work that may write it may have
  9025. // changed the texture's memory.
  9026. batch.title_written();
  9027. assert!(batch.texture_due(&a));
  9028. assert!(!batch.texture_due(&a));
  9029. // A fresh submission starts over.
  9030. let mut next = Batch::default();
  9031. assert!(next.texture_due(&a));
  9032. }
  9033. /// The hashing a submission does for textures in physical-page memory,
  9034. /// with every list checking the textures it samples (before) and with
  9035. /// each checked once (after). Run with
  9036. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  9037. #[test]
  9038. #[ignore = "benchmark"]
  9039. fn texture_checks_per_submission() {
  9040. const TEXTURES: usize = 48;
  9041. const SIZE: usize = 4 << 20;
  9042. const LISTS: usize = 12;
  9043. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  9044. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  9045. .collect();
  9046. let submit = |dedupe: bool| {
  9047. let mut batch = Batch::default();
  9048. let mut hashed = 0usize;
  9049. let started = std::time::Instant::now();
  9050. for _ in 0..LISTS {
  9051. for t in &textures {
  9052. if !dedupe || batch.texture_due(t) {
  9053. std::hint::black_box(blake3::hash(t));
  9054. hashed += 1;
  9055. }
  9056. }
  9057. }
  9058. (started.elapsed(), hashed)
  9059. };
  9060. submit(false); // warm up
  9061. let (before, n_before) = submit(false);
  9062. let (after, n_after) = submit(true);
  9063. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  9064. println!(
  9065. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  9066. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  9067. SIZE >> 20,
  9068. before.as_secs_f64() / after.as_secs_f64()
  9069. );
  9070. }
  9071. #[test]
  9072. fn vram_idle_ms_scales_with_pressure() {
  9073. let vram_idle_ms = |memory| super::vram_idle_for(memory, false);
  9074. let keeps = |memory| super::vram_idle_for(memory, true);
  9075. let gib = 1024 * 1024 * 1024;
  9076. assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000);
  9077. assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000);
  9078. assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500);
  9079. assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000);
  9080. assert_eq!(keeps(None), 5_000);
  9081. // Normal (< 75%)
  9082. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  9083. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  9084. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  9085. // Moderate (75%..85%)
  9086. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  9087. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  9088. // High (>= 85%, including over-budget)
  9089. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  9090. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  9091. // Missing or zero budget falls back to normal
  9092. assert_eq!(vram_idle_ms(None), 5_000);
  9093. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  9094. }
  9095. #[test]
  9096. fn textures_are_kept_while_the_card_has_room() {
  9097. use super::vram_keep;
  9098. let gib = 1 << 30;
  9099. assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000);
  9100. // Past it: the longest idle ones, enough to come down to 85 %.
  9101. let (ms, bytes) = vram_keep(100 * gib, 90 * gib);
  9102. assert_eq!((ms, bytes), (5_000, 5 * gib));
  9103. assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib));
  9104. assert_eq!(vram_keep(0, 7).0, 5_000);
  9105. }
  9106. #[test]
  9107. fn ram_idle_ms_scales_with_pressure() {
  9108. let ram_idle_ms = |avail| super::ram_idle_for(avail, false);
  9109. assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000);
  9110. assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000);
  9111. assert_eq!(super::ram_idle_for(None, true), 10_000);
  9112. let gib = 1024 * 1024 * 1024;
  9113. // Normal (>= 4 GiB)
  9114. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  9115. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  9116. // Moderate (2 GiB..4 GiB)
  9117. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  9118. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  9119. // High (< 2 GiB)
  9120. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  9121. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  9122. // Missing falls back to normal
  9123. assert_eq!(ram_idle_ms(None), 10_000);
  9124. }
  9125. }