host.rs 382 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737
  1. //! The host GPU: one D3D12 device and direct queue (decision 0007), and a
  2. //! window to present on.
  3. //!
  4. //! shortcut: every submission is waited for, so CPU and GPU never overlap
  5. //! (unless `VICTORY_LATE_WAIT=1`, see [`late`]);
  6. //! overlap them with per-submission fences once more than clears run.
  7. use std::sync::atomic::{AtomicU32, Ordering};
  8. use std::sync::{Mutex, OnceLock};
  9. use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
  10. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  11. use windows::Win32::Graphics::Direct3D12::*;
  12. use windows::Win32::Graphics::Dxgi::Common::*;
  13. use windows::Win32::Graphics::Dxgi::*;
  14. use windows::Win32::System::LibraryLoader::GetModuleHandleW;
  15. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  16. use windows::Win32::UI::WindowsAndMessaging::*;
  17. use windows::core::{Interface, PCWSTR, w};
  18. /// Resource states without the console's own bits (compression hints from
  19. /// bit 25 up), which the host rejects.
  20. pub(crate) fn pc_state(state: u32) -> u32 {
  21. state & 0x01ff_ffff
  22. }
  23. /// A console state as a host texture state: PC bits only, and none of the
  24. /// buffer-only ones the console allows on textures (vertex, constant and
  25. /// index buffer, stream out, indirect arguments, as in "generic read").
  26. pub(crate) fn texture_state(state: u32) -> u32 {
  27. const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
  28. pc_state(state) & !BUFFER_ONLY
  29. }
  30. /// Render target views live only until their command is recorded, so a
  31. /// ring of host descriptors is enough.
  32. const RTV_RING: u32 = 1024;
  33. pub(crate) struct Host {
  34. pub(crate) device: ID3D12Device,
  35. queue: ID3D12CommandQueue,
  36. fence: ID3D12Fence,
  37. /// The last value signalled on `fence`, behind the submission lock.
  38. submitted: Mutex<u64>,
  39. event: HANDLE,
  40. rtvs: ID3D12DescriptorHeap,
  41. rtv_size: u32,
  42. /// A ring of depth views, used as `rtvs`.
  43. dsvs: ID3D12DescriptorHeap,
  44. dsv_size: u32,
  45. next_dsv: AtomicU32,
  46. /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug
  47. /// layer's messages.
  48. messages: Option<ID3D12InfoQueue>,
  49. next_rtv: AtomicU32,
  50. presenter: Mutex<Option<Presenter>>,
  51. /// The adapter the device is on, for its memory budget
  52. /// ([`Host::video_memory`]); `None` if the system does not name it.
  53. adapter: Option<IDXGIAdapter3>,
  54. }
  55. // SAFETY: D3D12 devices, queues, fences and descriptor heaps are
  56. // free-threaded; the event handle is only waited on under `submitted`.
  57. unsafe impl Send for Host {}
  58. // SAFETY: as above.
  59. unsafe impl Sync for Host {}
  60. /// Host objects the title let go of while a submission may still use them
  61. /// (a texture its descriptors name, a descriptor slot's old resource), by
  62. /// the submission count they wait for. The title's descriptor writes and
  63. /// releases reach the host at once, from its own threads, while the host
  64. /// runs a submission: freeing there is a GPU page fault on the freed
  65. /// texture (a device hang).
  66. static RETIRED: Mutex<Vec<(u64, Retired)>> = Mutex::new(Vec::new());
  67. /// Submissions started and finished (waited for).
  68. static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  69. static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  70. /// A retired object, dropped on whatever thread finishes the submission.
  71. struct Retired(#[allow(dead_code)] Box<dyn std::any::Any>);
  72. // SAFETY: what is retired is D3D12 objects (free-threaded) and the
  73. // reference-counted wrappers holding them, dropped once.
  74. unsafe impl Send for Retired {}
  75. /// Milliseconds since the first call.
  76. pub(crate) fn now_ms() -> u64 {
  77. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  78. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  79. }
  80. /// This moment, for telling later how long ago it was ([`long_ago`]): the
  81. /// frames begun so far (high half, `crate::frame::current`) and tenths of a
  82. /// second since the start. Host copies of title memory, staging buffers and
  83. /// host textures note when they were last used with it.
  84. pub(crate) fn moment() -> u64 {
  85. (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff)
  86. }
  87. /// Whether `moment` lies at least `ms` milliseconds and `frames` frames
  88. /// back. Both: at seconds per frame, what every frame uses is not touched
  89. /// for seconds, and at many frames per second not for many frames. (A title
  90. /// that never waits for frames has no frame count: nothing is then idle.)
  91. pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
  92. let now = self::moment();
  93. let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
  94. (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
  95. }
  96. /// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
  97. pub(crate) fn available_physical_ram() -> Option<u64> {
  98. use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
  99. // SAFETY: plain data the call fills in.
  100. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
  101. m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
  102. // SAFETY: a sized structure.
  103. let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
  104. ok.then_some(m.ullAvailPhys)
  105. }
  106. /// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
  107. /// scaled down under VRAM pressure. Never returns less than 1,000 ms so
  108. /// handles not yet recorded into a list or slot remain protected.
  109. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  110. const NORMAL_MS: u64 = 5_000;
  111. const MODERATE_MS: u64 = 2_500;
  112. const HIGH_MS: u64 = 1_000;
  113. let Some([budget, used, ..]) = video_memory else {
  114. return NORMAL_MS;
  115. };
  116. if budget == 0 {
  117. return NORMAL_MS;
  118. }
  119. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  120. if used_pct >= 85 {
  121. HIGH_MS
  122. } else if used_pct >= 75 {
  123. MODERATE_MS
  124. } else {
  125. NORMAL_MS
  126. }
  127. }
  128. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  129. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  130. /// when free physical RAM is low. Never returns less than 2,000 ms.
  131. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  132. const GIB: u64 = 1024 * 1024 * 1024;
  133. const NORMAL_MS: u64 = 10_000;
  134. const MODERATE_MS: u64 = 5_000;
  135. const HIGH_MS: u64 = 2_000;
  136. let Some(avail) = avail_phys else {
  137. return NORMAL_MS;
  138. };
  139. if avail < 2 * GIB {
  140. HIGH_MS
  141. } else if avail < 4 * GIB {
  142. MODERATE_MS
  143. } else {
  144. NORMAL_MS
  145. }
  146. }
  147. /// How many references are held on a host object (its COM count): ours
  148. /// all, since the host's views and commands hold none. A buffer or texture
  149. /// with one is held by its owner alone: no descriptor slot keeps it
  150. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  151. pub(crate) fn references(object: &impl Interface) -> u32 {
  152. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  153. let raw = object.as_raw();
  154. // SAFETY: a live COM object, whose first three methods are those of
  155. // `IUnknown` (query, add a reference, release one); the pair leaves the
  156. // count as it was, and the release returns it. The first is not called.
  157. unsafe {
  158. let methods = *raw.cast::<*const [Method; 3]>();
  159. ((*methods)[1])(raw);
  160. ((*methods)[2])(raw)
  161. }
  162. }
  163. /// Once a second, before a submission starts: lets go of what nothing
  164. /// names any more (copies of windows of title memory, staging buffers,
  165. /// host copies of textures the title fills).
  166. /// `VICTORY_SWEEP=0` keeps everything, as before.
  167. fn sweep() {
  168. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  169. crate::inplace::tick();
  170. static ON: OnceLock<bool> = OnceLock::new();
  171. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  172. return;
  173. }
  174. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  175. let now = now_ms();
  176. let last = LAST.load(Ordering::Relaxed);
  177. if now < last + 1000
  178. || LAST
  179. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  180. .is_err()
  181. {
  182. return;
  183. }
  184. crate::pipeline::trim_library();
  185. crate::shadow::let_go_idle();
  186. crate::texture::let_go_idle();
  187. crate::resource::let_go_idle();
  188. }
  189. /// Drops `object` once every submission running now has finished: at once
  190. /// if none is.
  191. pub(crate) fn retire<T: 'static>(object: T) {
  192. let started = STARTED.load(Ordering::Acquire);
  193. if started <= FINISHED.load(Ordering::Acquire) {
  194. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  195. drop(object);
  196. return;
  197. }
  198. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  199. RETIRED
  200. .lock()
  201. .unwrap_or_else(|e| e.into_inner())
  202. .push((started, Retired(Box::new(object))));
  203. }
  204. /// Drops what waited for submissions up to `finished`.
  205. fn bury(finished: u64) {
  206. let done: Vec<(u64, Retired)> = {
  207. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  208. if retired.is_empty() {
  209. return;
  210. }
  211. let (done, keep) = std::mem::take(&mut *retired)
  212. .into_iter()
  213. .partition(|(at, _)| *at <= finished);
  214. *retired = keep;
  215. done
  216. };
  217. drop(done);
  218. }
  219. /// Objects [`retire`] dropped at once (no submission was running) and
  220. /// kept until a running submission finished, since the start.
  221. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  222. /// What the layer did to the host's objects lately, newest last (sweeps
  223. /// that let host copies go, pipeline library calls, saves and trims): said
  224. /// once when the host device is removed ([`log_removal_context`]), with
  225. /// what the submitting thread and the pipeline workers were doing at that
  226. /// moment. A device the driver removes "internally" names no command, and
  227. /// the pass that happens to notice first names only the view it was at:
  228. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  229. /// pipeline library call that no line of the log tied to them.
  230. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  231. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  232. /// The entries kept.
  233. const TRAIL_MOST: usize = 96;
  234. fn trail_on() -> bool {
  235. static ON: OnceLock<bool> = OnceLock::new();
  236. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  237. }
  238. /// Microseconds since the first call.
  239. pub(crate) fn now_us() -> u64 {
  240. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  241. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  242. }
  243. /// The calling thread, as the log's other lines name threads.
  244. pub(crate) fn thread_id() -> u32 {
  245. // SAFETY: a plain query.
  246. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  247. }
  248. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  249. /// run when the trail is kept.
  250. pub(crate) fn trail(what: impl FnOnce() -> String) {
  251. if !trail_on() {
  252. return;
  253. }
  254. let entry = (now_us(), thread_id(), what());
  255. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  256. if trail.len() >= TRAIL_MOST {
  257. trail.pop_front();
  258. }
  259. trail.push_back(entry);
  260. }
  261. /// What the submitting thread is doing (0 nothing: between submissions,
  262. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  263. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  264. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  265. fn submitting(phase: u64, lists: usize) {
  266. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  267. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  268. SUBMITTING[0].store(phase, Ordering::Relaxed);
  269. }
  270. /// What was going on when the host device went: whether a submission was
  271. /// on the card, the pipeline library's state and the calls running in it,
  272. /// and the trail.
  273. pub(crate) fn removal_context() -> String {
  274. use std::fmt::Write;
  275. let now = now_us();
  276. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  277. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  278. 0 => "between submissions (nothing of ours was running on the card)",
  279. 1 => "preparing a submission (nothing of ours was running on the card)",
  280. 2 => "waiting for the card to run a submission",
  281. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  282. };
  283. let mut text = format!(
  284. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  285. SUBMITTING[1].load(Ordering::Relaxed),
  286. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  287. crate::pipeline::library_removal_note(),
  288. RETIREMENTS[0].load(Ordering::Relaxed),
  289. RETIREMENTS[1].load(Ordering::Relaxed),
  290. STARTED.load(Ordering::Relaxed),
  291. FINISHED.load(Ordering::Relaxed),
  292. );
  293. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  294. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  295. for (at, thread, what) in trail.iter() {
  296. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  297. }
  298. text
  299. }
  300. /// Says [`removal_context`] in the log, once: called by whoever finds the
  301. /// host device removed.
  302. pub(crate) fn log_removal_context() {
  303. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  304. if !trail_on() || SAID.swap(true, Ordering::Relaxed) {
  305. return;
  306. }
  307. tracing::error!("when the host device went: {}", removal_context());
  308. }
  309. /// Time spent in submissions since the last frame-rate line, in
  310. /// microseconds: preparing them on the CPU (title memory copies, texture
  311. /// detiling), then waiting for the GPU.
  312. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  313. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  314. /// After submissions: shader-written ranges compared and copied back into
  315. /// title memory (microseconds, bytes that differed), since the last
  316. /// frame-rate line.
  317. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  318. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  319. /// The card's clock, for the frame line of every run, in microseconds since
  320. /// the last one: how long the card had nothing of ours queued; how much of
  321. /// that while the thread that holds the submission lock was working (the
  322. /// card idle behind us: preparing and copying back are done with the card
  323. /// standing); and how long that thread stood waiting for the card.
  324. ///
  325. /// Every send of lists to the queue is followed by a signal on a fence of
  326. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  327. /// the newest signal and notes the moment the card reached it with nothing
  328. /// newer sent; the next send ends that idle stretch.
  329. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  330. /// Of the thread that holds the submission lock: the microseconds it has
  331. /// worked so far (preparing, copying back; not its waits for the card), and
  332. /// since when it works now ([`now_us`] plus one; 0: it does not).
  333. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  334. /// The thread that holds the submission lock starts (`on`) or stops
  335. /// working; whether it worked until now.
  336. fn working(on: bool) -> bool {
  337. let now = now_us() + 1;
  338. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  339. if since != 0 {
  340. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  341. }
  342. since != 0
  343. }
  344. /// [`WORKING`] as of now: microseconds worked so far.
  345. fn worked() -> u64 {
  346. let since = WORKING[1].load(Ordering::Relaxed);
  347. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  348. WORKING[0].load(Ordering::Relaxed) + now
  349. }
  350. /// The thread that holds the submission lock stood waiting for the card
  351. /// from `since` until now ([`CARD_CLOCK_US`]).
  352. fn stood(since: std::time::Instant) {
  353. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  354. }
  355. /// What [`CARD_CLOCK_US`] is measured with.
  356. struct CardClock {
  357. fence: ID3D12Fence,
  358. /// Signals sent so far; and, while the card has reached the last of
  359. /// them, since when and what [`worked`] said then.
  360. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  361. sent: std::sync::Condvar,
  362. }
  363. // SAFETY: a fence (free-threaded) behind a lock.
  364. unsafe impl Send for CardClock {}
  365. // SAFETY: as above.
  366. unsafe impl Sync for CardClock {}
  367. /// The clock's thread: waits for the newest signal sent and notes when the
  368. /// card got there with nothing newer behind it.
  369. fn card_clock_watch(clock: &'static CardClock) {
  370. // SAFETY: a plain event of our own.
  371. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  372. return;
  373. };
  374. let mut seen = 0;
  375. loop {
  376. let target = {
  377. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  378. while state.0 == seen {
  379. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  380. }
  381. state.0
  382. };
  383. // SAFETY: the clock's fence and this thread's event.
  384. unsafe {
  385. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  386. WaitForSingleObject(event, INFINITE);
  387. }
  388. }
  389. seen = target;
  390. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  391. if state.0 == target && state.1.is_none() {
  392. state.1 = Some((std::time::Instant::now(), worked()));
  393. }
  394. }
  395. }
  396. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  397. /// frame's time.
  398. fn card_clock_line(frames: f64, ms: f64) {
  399. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  400. tracing::info!(
  401. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  402. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  403. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  404. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  405. );
  406. }
  407. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  408. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  409. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  410. std::sync::atomic::AtomicU64::new(0),
  411. std::sync::atomic::AtomicU64::new(0),
  412. std::sync::atomic::AtomicU64::new(0),
  413. std::sync::atomic::AtomicU64::new(0),
  414. ];
  415. /// Host buffers made since the start, as (count, bytes): in the upload heap
  416. /// (staging, list scratch), shared with the processor (host copies of title
  417. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  418. /// For the memory line: against what is alive, they show what was let go.
  419. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  420. /// What of that is alive now, for the memory line (`MADE` counts what was
  421. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  422. /// and nothing said how many were alive): host lists; the lists' scratch
  423. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  424. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  425. /// instead of made, since the start; and the lists' other upload buffers
  426. /// (texture data copied from buffers, scratch too big for a chunk) and
  427. /// their bytes.
  428. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  429. /// About host lists, for the memory line: lists made by the host since the
  430. /// start; preludes made (a list's second allocator and list, made when it
  431. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  432. /// bytes the process's private memory grew by while lists were being made
  433. /// (what a list costs: host objects with the driver's command memory; 631
  434. /// lists were alive in run 65, each with a prelude it may never use).
  435. /// Then the lists alive that were never reset since they were made: the
  436. /// host sides of title lists the title made and has not used (a host list
  437. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  438. /// makes at its start).
  439. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  440. /// The process's private bytes (diagnostics: around the making of lists).
  441. #[cfg(feature = "diagnostics")]
  442. fn private_bytes() -> u64 {
  443. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  444. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  445. let mut c = PROCESS_MEMORY_COUNTERS {
  446. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  447. ..Default::default()
  448. };
  449. // SAFETY: our own process and a sized structure.
  450. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  451. c.PagefileUsage as u64
  452. }
  453. /// What the runtime does when the host GPU fails for good: report it like a
  454. /// crash and end the run. The console has no such state, and carrying on
  455. /// draws nothing at seconds per frame.
  456. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  457. /// Sets what a host GPU failure does (the runtime's crash report).
  458. pub fn on_failure(report: fn(&str) -> !) {
  459. let _ = ON_FAILURE.set(report);
  460. }
  461. /// Ends the run on a host GPU failure: what failed, the removal reason and
  462. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  463. /// diagnostics build names the command).
  464. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  465. let mut text = what.to_string();
  466. if let Some(host) = host() {
  467. // SAFETY: a plain query.
  468. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  469. text.push_str(&format!("; device removed: {e}"));
  470. log_removal_context();
  471. }
  472. match host.log_messages() {
  473. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  474. None if host.messages.is_none() => text.push_str(
  475. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  476. ),
  477. None => {}
  478. }
  479. }
  480. tracing::error!("{text}");
  481. // Tests have no log: the reason goes to their output.
  482. #[cfg(test)]
  483. eprintln!("host GPU failure: {text}");
  484. match ON_FAILURE.get() {
  485. Some(report) => report(&text),
  486. None => std::process::abort(),
  487. }
  488. }
  489. /// The host GPU, created on first use; `None` without one (a run then
  490. /// behaves as before: nothing executes).
  491. pub(crate) fn host() -> Option<&'static Host> {
  492. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  493. HOST.get_or_init(|| match create() {
  494. Ok(host) => Some(host),
  495. Err(e) => {
  496. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  497. None
  498. }
  499. })
  500. .as_ref()
  501. }
  502. fn create() -> windows::core::Result<Host> {
  503. // SAFETY: plain D3D12 object creation with valid descriptions.
  504. unsafe {
  505. // The debug layer only in builds with diagnostics.
  506. let debug =
  507. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some();
  508. if debug {
  509. let mut layer: Option<ID3D12Debug> = None;
  510. match D3D12GetDebugInterface(&mut layer) {
  511. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  512. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  513. }
  514. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  515. // descriptor heap indices and the like become messages naming
  516. // the command instead of page faults. Without state tracking
  517. // (directly indexed textures are not transitioned).
  518. if std::env::var_os("VICTORY_D3D12_GBV").is_some()
  519. && let Some(l) = &layer
  520. {
  521. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  522. d1.SetEnableGPUBasedValidation(true);
  523. }
  524. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  525. d2.SetGPUBasedValidationFlags(
  526. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  527. );
  528. }
  529. tracing::info!("GPU-based validation on");
  530. }
  531. }
  532. // Diagnostics: device-removed data (the command that faulted, the
  533. // faulting address), read when the device is removed.
  534. if dred_on() {
  535. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  536. if D3D12GetDebugInterface(&mut dred).is_ok()
  537. && let Some(dred) = dred
  538. {
  539. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  540. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  541. }
  542. }
  543. let mut device: Option<ID3D12Device> = None;
  544. // Diagnostics: the software adapter, on which a shader's wild access
  545. // is an access violation in this process (a crash report with the
  546. // address and instruction) instead of a GPU fault and driver reset.
  547. if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() {
  548. let adapter = warp_adapter()?;
  549. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  550. tracing::info!("host device on the software adapter (WARP)");
  551. } else {
  552. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  553. }
  554. let device = device.ok_or_else(windows::core::Error::empty)?;
  555. // Before anything is made with it (`VICTORY_RECORD`).
  556. #[cfg(feature = "diagnostics")]
  557. crate::replay::record::from_env(&device);
  558. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  559. // driver compiling shaders again on the "D3D Background Thread"s,
  560. // for minutes after pipelines were made or loaded) is switched off.
  561. // An experiment: while those threads ran, the same shot took
  562. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  563. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  564. // whether the card is slower with the shaders it then keeps is not
  565. // known.
  566. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  567. && let Ok(device6) = device.cast::<ID3D12Device6>()
  568. {
  569. let set = device6.SetBackgroundProcessingMode(
  570. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  571. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  572. None,
  573. None,
  574. );
  575. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  576. }
  577. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  578. // cross-lane code stays in 32-lane halves translated for waves of 32
  579. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  580. if device
  581. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  582. .is_ok()
  583. {
  584. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  585. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  586. }
  587. let messages = debug
  588. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  589. .flatten();
  590. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  591. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  592. ..Default::default()
  593. })?;
  594. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  595. let event = CreateEventW(None, false, false, None)?;
  596. let rtvs: ID3D12DescriptorHeap =
  597. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  598. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  599. NumDescriptors: RTV_RING,
  600. ..Default::default()
  601. })?;
  602. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  603. let dsvs: ID3D12DescriptorHeap =
  604. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  605. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  606. NumDescriptors: RTV_RING,
  607. ..Default::default()
  608. })?;
  609. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  610. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  611. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  612. .ok();
  613. tracing::info!("host D3D12 device ready");
  614. Ok(Host {
  615. device,
  616. queue,
  617. fence,
  618. submitted: Mutex::new(0),
  619. event,
  620. rtvs,
  621. rtv_size,
  622. dsvs,
  623. dsv_size,
  624. next_dsv: AtomicU32::new(0),
  625. messages,
  626. next_rtv: AtomicU32::new(0),
  627. presenter: Mutex::new(None),
  628. adapter,
  629. })
  630. }
  631. }
  632. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  633. /// Reject it before creating a device in diagnostics' software-only mode.
  634. pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  635. // SAFETY: plain DXGI adapter queries.
  636. unsafe {
  637. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  638. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  639. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  640. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  641. tracing::warn!(
  642. vendor = format_args!("{:#x}", desc.VendorId),
  643. flags = format_args!("{:#x}", desc.Flags),
  644. "DXGI did not identify the WARP adapter as software; refusing device"
  645. );
  646. return Err(windows::core::Error::from_hresult(
  647. windows::Win32::Foundation::E_FAIL,
  648. ));
  649. }
  650. Ok(adapter)
  651. }
  652. }
  653. #[cfg(test)]
  654. mod tests {
  655. /// What is there of a range some of whose pages are not: those bytes,
  656. /// counted, and zeros for the rest, whatever the buffer held.
  657. #[test]
  658. fn what_is_there_is_read_and_the_rest_is_zeros() {
  659. use windows_sys::Win32::System::Memory::*;
  660. const SIZE: usize = 0x8_0000;
  661. // SAFETY: a reservation of ours; only committed pages are written.
  662. unsafe {
  663. let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  664. assert!(!at.is_null());
  665. // 0-0x1_1000 and 0x3_0000-0x4_0000 are there.
  666. for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] {
  667. assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null());
  668. at.add(from).write_bytes(0x5a, len);
  669. }
  670. // From an address inside a page, as textures are packed.
  671. let mut out = vec![0x77u8; SIZE - 0x300];
  672. assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000);
  673. for (i, &b) in out.iter().enumerate() {
  674. let from = i + 0x300;
  675. let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from);
  676. assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}");
  677. }
  678. // All there: one read.
  679. let mut out = vec![0x77u8; 0x1_0000];
  680. assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000);
  681. assert!(out.iter().all(|&b| b == 0x5a));
  682. // Nothing there.
  683. let mut out = vec![0x77u8; 0x1_0000];
  684. assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0);
  685. assert!(out.iter().all(|&b| b == 0));
  686. assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0);
  687. }
  688. }
  689. /// Zeros for a title destination that went meanwhile are no fault.
  690. #[test]
  691. fn zeros_where_nothing_is_are_lost() {
  692. use windows_sys::Win32::System::Memory::*;
  693. // SAFETY: a reservation of ours, its first page committed.
  694. unsafe {
  695. let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  696. assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
  697. at.write_bytes(7, 4096);
  698. super::zero(at, 4096);
  699. assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
  700. super::zero(at.add(4096), 4096);
  701. VirtualFree(at.cast(), 0, MEM_RELEASE);
  702. }
  703. }
  704. #[test]
  705. fn sparse_copies_preserve_islands_and_observe_remaps() {
  706. use windows_sys::Win32::System::Memory::*;
  707. const N: usize = 5 << 16;
  708. // SAFETY: we reserve a private region, commit selected pages inside it,
  709. // and only directly access the pages while they are writable.
  710. unsafe {
  711. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  712. assert!(!base.is_null());
  713. let mut expected = vec![0; N];
  714. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  715. let at = base.add(offset);
  716. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  717. at.write_bytes(value, 4096);
  718. expected[offset..offset + 4096].fill(value);
  719. }
  720. for remap in [false, true] {
  721. if remap {
  722. let mut old = 0;
  723. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  724. expected[..4096].fill(0);
  725. let at = base.add(1 << 16);
  726. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  727. at.write_bytes(0xc7, 4096);
  728. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  729. }
  730. let mut out = vec![0xee; N];
  731. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  732. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  733. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  734. }
  735. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  736. }
  737. }
  738. use super::*;
  739. #[test]
  740. fn warp_adapter_accepts_only_software() {
  741. // This probes DXGI without creating a D3D12 device or running a title.
  742. // SAFETY: plain DXGI adapter queries.
  743. let raw = unsafe {
  744. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  745. else {
  746. return;
  747. };
  748. factory.EnumWarpAdapter::<IDXGIAdapter>()
  749. };
  750. let Ok(raw) = raw else { return };
  751. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  752. // IDXGIAdapter1; `raw` owns that interface.
  753. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  754. eprintln!(
  755. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  756. desc.VendorId, desc.Flags
  757. );
  758. assert_eq!(
  759. warp_adapter().is_ok(),
  760. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  761. );
  762. }
  763. }
  764. /// The batches of clamped records in one scratch buffer
  765. /// ([`HostList::batch_place`]).
  766. const BATCHES: u32 = 8;
  767. /// A host command list and its allocator, always used together.
  768. pub(crate) struct HostList {
  769. allocator: ID3D12CommandAllocator,
  770. pub(crate) list: ID3D12GraphicsCommandList,
  771. /// Work for submission time, in recorded order.
  772. deferred: Mutex<Deferred>,
  773. /// Upload memory for data the list's draws make (expanded vertices),
  774. /// reused after a reset.
  775. scratch: Mutex<Scratch>,
  776. /// Host texture states the list assumes, by host copy: at its start and
  777. /// at its end. Lists are recorded on many threads and run in submission
  778. /// order, so the transitions from a texture's real state are made at
  779. /// submission, in `prelude`. Holding the copies keeps every texture the
  780. /// list names alive until it is reset, even if the title releases the
  781. /// resource first.
  782. states: Mutex<States>,
  783. /// What the list does with depth textures that have a colour twin, by
  784. /// twin ([`TwinUse`]).
  785. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  786. /// The list that runs those transitions just before this one, made
  787. /// when the list first has such transitions ([`lazy_prelude`]).
  788. prelude: OnceLock<Option<Prelude>>,
  789. /// The pipelines the list binds, for reports of slow submissions.
  790. pipelines: Mutex<std::collections::BTreeSet<String>>,
  791. /// The work its indirect executions may still do (`indirect`): a
  792. /// shader-writable word, zeroed when the list is submitted, and after
  793. /// it what the clamp notes about mesh records. In memory the CPU maps.
  794. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  795. /// The same words in the card's own memory ([`card_budget`]), which the
  796. /// clamp uses instead when there is one: zeroed in the list before its
  797. /// first clamp, its notes copied to `budget` when the list closes.
  798. card_budget: OnceLock<Option<ID3D12Resource>>,
  799. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  800. /// grown to the largest indirect execution recorded on the list.
  801. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  802. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  803. /// how many batches of this recording have a place in them.
  804. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  805. /// Counts the list in [`ALIVE`] while it lives.
  806. _alive: Counted,
  807. /// The texts of the markers `note_op` set, in order (for device-removed
  808. /// data without marker texts), with the host GPU range a copy reads.
  809. #[cfg(feature = "diagnostics")]
  810. notes: Mutex<Vec<Note>>,
  811. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  812. /// and at the end, and where they are read back.
  813. #[cfg(feature = "diagnostics")]
  814. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  815. }
  816. /// A list's prelude: an allocator and a closed list.
  817. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  818. /// Whether a host list's prelude is made when the list first needs one. A
  819. /// prelude runs the texture transitions and twin copies a list needs before
  820. /// it; lists that name no texture never have one, and every host list was
  821. /// made with one all the same: twice the host objects per list, for the
  822. /// title's 630 lists and for every list made anew.
  823. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  824. fn lazy_prelude() -> bool {
  825. static ON: OnceLock<bool> = OnceLock::new();
  826. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  827. }
  828. /// Timestamps per list (diagnostics); commands past them are not timed.
  829. #[cfg(feature = "diagnostics")]
  830. const STAMPS: u32 = 4096;
  831. /// A marker's text and the host range its command reads (diagnostics).
  832. #[cfg(feature = "diagnostics")]
  833. type Note = (String, Option<(u64, u64)>);
  834. type States = std::collections::HashMap<
  835. usize,
  836. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  837. >;
  838. /// What a list does with a depth texture that has a colour twin
  839. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  840. /// in submission order, so a list cannot know which side an earlier list
  841. /// leaves behind: it notes which sides it uses as it finds them, and its
  842. /// prelude copies one side into the other at submission if that side is
  843. /// behind then. From its first use of a side on, the list knows.
  844. struct TwinUse {
  845. /// The depth texture (the title resource's host copy) and its twin.
  846. depth: std::sync::Arc<crate::resource::HostTexture>,
  847. twin: std::sync::Arc<crate::resource::Twin>,
  848. /// The sides (depth texture, twin) the list uses as it finds them.
  849. needs: [bool; 2],
  850. /// Whether each side lacks what the other was written last, where the
  851. /// list is now; `None`: as the list found it.
  852. behind: [Option<bool>; 2],
  853. /// The draw or dispatch being prepared writes the twin.
  854. writing: bool,
  855. /// The depth plane's twin holds what the plane lacks although the list
  856. /// copied the twins since: the plane's pass waits for the list's close.
  857. late: bool,
  858. }
  859. /// The pass that draws the twin of a depth plane into the plane: one
  860. /// triangle over each mip of each slice, its pixel shader writing the
  861. /// twin's texel as the depth, with the depth test "always" and no stencil
  862. /// (the stencil plane is copied through a buffer and not touched here).
  863. ///
  864. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  865. /// the step times the float nearest 1/65535 (0x37800080). That is how
  866. /// The title's tiled lighting computes the depth of the
  867. /// rectangles it then draws with the test "equal", one class of materials
  868. /// a draw (all six of its vertex shaders multiply the class number by that
  869. /// constant), so the pass and the draw give the host the same float, and
  870. /// the host turns the same float into the same 24 bits. The step divided
  871. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  872. /// and lands in another 24-bit step for 127 of them (none under 385).
  873. const PLANE_CORNERS: &str = r#"
  874. float4 corner(uint i : SV_VertexID) : SV_Position {
  875. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  876. }
  877. "#;
  878. const PLANE_STEPS: &str = r#"
  879. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  880. Texture2DArray<uint> twin : register(t0);
  881. [RootSignature(RS)]
  882. float plane(float4 p : SV_Position) : SV_Depth {
  883. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  884. }
  885. "#;
  886. const PLANE_FLOATS: &str = r#"
  887. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  888. Texture2DArray<float> twin : register(t0);
  889. [RootSignature(RS)]
  890. float plane(float4 p : SV_Position) : SV_Depth {
  891. return twin.Load(int4(int2(p.xy), 0, 0));
  892. }
  893. "#;
  894. /// Views of twins the pass reads, in a heap of ours used as a ring.
  895. /// shortcut: a view must last until its list has run; with one or two
  896. /// passes a frame the ring is far from coming round.
  897. const PLANE_VIEWS: u32 = 256;
  898. /// What the pass draws with: the heap of its views of twins, and per kind
  899. /// of twin (16-bit steps or floats) and depth format the root signature
  900. /// and pipeline, made when first needed (`None`: the host refused).
  901. struct PlanePass {
  902. views: ID3D12DescriptorHeap,
  903. cpu: usize,
  904. gpu: u64,
  905. step: u32,
  906. next: AtomicU32,
  907. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  908. }
  909. /// The pass's root signature and pipeline for one kind of twin and one
  910. /// depth format.
  911. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  912. // SAFETY: D3D12 objects are free-threaded.
  913. unsafe impl Send for PlanePass {}
  914. // SAFETY: as above.
  915. unsafe impl Sync for PlanePass {}
  916. fn plane_pass() -> Option<&'static PlanePass> {
  917. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  918. PASS.get_or_init(|| {
  919. let host = host()?;
  920. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  921. // SAFETY: plain heap creation and queries.
  922. unsafe {
  923. let views: ID3D12DescriptorHeap = host
  924. .device
  925. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  926. Type: kind,
  927. NumDescriptors: PLANE_VIEWS,
  928. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  929. NodeMask: 0,
  930. })
  931. .ok()?;
  932. Some(PlanePass {
  933. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  934. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  935. step: host.device.GetDescriptorHandleIncrementSize(kind),
  936. views,
  937. next: AtomicU32::new(0),
  938. made: Mutex::default(),
  939. })
  940. }
  941. })
  942. .as_ref()
  943. }
  944. /// Compiles function `entry` of `source` for `target` with the system's
  945. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  946. pub(crate) fn compile(
  947. source: &str,
  948. entry: windows::core::PCSTR,
  949. target: windows::core::PCSTR,
  950. ) -> windows::core::Result<Vec<u8>> {
  951. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  952. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  953. let mut code: Option<ID3DBlob> = None;
  954. let mut errors: Option<ID3DBlob> = None;
  955. // SAFETY: the source and names live through the call; out pointers ours.
  956. let compiled = unsafe {
  957. D3DCompile(
  958. source.as_ptr().cast(),
  959. source.len(),
  960. windows::core::s!("victory"),
  961. None,
  962. None,
  963. entry,
  964. target,
  965. 0,
  966. 0,
  967. &mut code,
  968. Some(&mut errors),
  969. )
  970. };
  971. if let Err(e) = compiled {
  972. if let Some(errors) = errors {
  973. // SAFETY: the blob's own bytes.
  974. let text = unsafe {
  975. std::slice::from_raw_parts(
  976. errors.GetBufferPointer().cast::<u8>(),
  977. errors.GetBufferSize(),
  978. )
  979. };
  980. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  981. }
  982. return Err(e);
  983. }
  984. let code = code.ok_or_else(windows::core::Error::empty)?;
  985. // SAFETY: the blob's own bytes.
  986. let bytes = unsafe {
  987. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  988. };
  989. Ok(bytes.to_vec())
  990. }
  991. impl PlanePass {
  992. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  993. /// or of floats and the depth format `format`.
  994. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  995. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  996. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  997. return pipeline.clone();
  998. }
  999. let pipeline = match Self::make(steps, format) {
  1000. Ok(pipeline) => Some(pipeline),
  1001. Err(e) => {
  1002. tracing::warn!(
  1003. error = %e,
  1004. steps,
  1005. format = format.0,
  1006. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  1007. );
  1008. None
  1009. }
  1010. };
  1011. made.push((steps, format.0, pipeline.clone()));
  1012. pipeline
  1013. }
  1014. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  1015. use windows::core::s;
  1016. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  1017. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  1018. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  1019. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  1020. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  1021. pShaderBytecode: bytes.as_ptr().cast(),
  1022. BytecodeLength: bytes.len(),
  1023. };
  1024. // SAFETY: the root signature is inside the pixel shader; the
  1025. // description points at live data and never releases its pointer.
  1026. unsafe {
  1027. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  1028. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1029. pRootSignature: std::mem::transmute_copy(&root),
  1030. VS: code(&vs[..]),
  1031. PS: code(&ps[..]),
  1032. SampleMask: u32::MAX,
  1033. RasterizerState: D3D12_RASTERIZER_DESC {
  1034. FillMode: D3D12_FILL_MODE_SOLID,
  1035. CullMode: D3D12_CULL_MODE_NONE,
  1036. DepthClipEnable: true.into(),
  1037. ..Default::default()
  1038. },
  1039. // Every texel is written; stencil stays off.
  1040. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1041. DepthEnable: true.into(),
  1042. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  1043. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1044. ..Default::default()
  1045. },
  1046. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1047. DSVFormat: format,
  1048. SampleDesc: DXGI_SAMPLE_DESC {
  1049. Count: 1,
  1050. Quality: 0,
  1051. },
  1052. ..Default::default()
  1053. };
  1054. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1055. Ok((root, pipeline))
  1056. }
  1057. }
  1058. }
  1059. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1060. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1061. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1062. /// heap, graphics root signature, pipeline, depth target, viewport,
  1063. /// scissor and topology and puts none of them back: it is for a list that
  1064. /// records nothing of the title's after it.
  1065. fn record_plane_pass(
  1066. list: &ID3D12GraphicsCommandList,
  1067. depth: &ID3D12Resource,
  1068. plane: &ID3D12Resource,
  1069. ) {
  1070. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1071. return;
  1072. };
  1073. // SAFETY: live resources.
  1074. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1075. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1076. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1077. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1078. let steps = twin.Format.0 == 53;
  1079. let format = DXGI_FORMAT(match of.Format.0 {
  1080. 44 => 45,
  1081. 19 => 20,
  1082. typed => typed,
  1083. });
  1084. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1085. return;
  1086. };
  1087. for slice in 0..u32::from(of.DepthOrArraySize) {
  1088. for mip in 0..u32::from(of.MipLevels) {
  1089. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1090. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1091. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1092. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1093. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1094. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1095. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1096. MostDetailedMip: mip,
  1097. MipLevels: 1,
  1098. FirstArraySlice: slice,
  1099. ArraySize: 1,
  1100. ..Default::default()
  1101. },
  1102. },
  1103. };
  1104. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1105. Format: format,
  1106. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1107. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1108. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1109. MipSlice: mip,
  1110. FirstArraySlice: slice,
  1111. ArraySize: 1,
  1112. },
  1113. },
  1114. ..Default::default()
  1115. };
  1116. let target = host.dsv(depth, Some(&target));
  1117. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1118. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1119. ptr: pass.cpu + (slot * pass.step) as usize,
  1120. };
  1121. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1122. ptr: pass.gpu + u64::from(slot * pass.step),
  1123. };
  1124. // SAFETY: an open list; a slot of our heap; live resources and
  1125. // objects (the pass's own live as long as the process).
  1126. unsafe {
  1127. host.device
  1128. .CreateShaderResourceView(plane, Some(&view), cpu);
  1129. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1130. list.SetGraphicsRootSignature(&root);
  1131. list.SetPipelineState(&pipeline);
  1132. list.SetGraphicsRootDescriptorTable(0, gpu);
  1133. list.OMSetRenderTargets(0, None, false, Some(&target));
  1134. list.RSSetViewports(&[D3D12_VIEWPORT {
  1135. TopLeftX: 0.0,
  1136. TopLeftY: 0.0,
  1137. Width: width as f32,
  1138. Height: height as f32,
  1139. MinDepth: 0.0,
  1140. MaxDepth: 1.0,
  1141. }]);
  1142. list.RSSetScissorRects(&[RECT {
  1143. left: 0,
  1144. top: 0,
  1145. right: width as i32,
  1146. bottom: height as i32,
  1147. }]);
  1148. list.IASetPrimitiveTopology(
  1149. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1150. );
  1151. list.DrawInstanced(3, 1, 0, 0);
  1152. }
  1153. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1154. }
  1155. }
  1156. }
  1157. /// Records into `list` the copy of a depth texture into its colour twin
  1158. /// (`colour`) or of the twin into the depth texture, both already in their
  1159. /// copy states: whole textures of one size in one format family, which the
  1160. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1161. /// alone, through the twin's buffer.
  1162. fn record_twin_copy(
  1163. list: &ID3D12GraphicsCommandList,
  1164. depth: &ID3D12Resource,
  1165. twin: &crate::resource::Twin,
  1166. colour: bool,
  1167. ) {
  1168. let (from, to) = if colour {
  1169. (depth, &twin.colour.texture)
  1170. } else {
  1171. (&twin.colour.texture, depth)
  1172. };
  1173. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1174. // shortcut: the depth plane's twin is not given the plane (that is a
  1175. // pass the other way: the plane read by a shader, the twin as its
  1176. // target). The twin then lacks what draws and clears wrote to the
  1177. // plane since shaders last wrote the twin. In the title
  1178. // nothing writes that plane but the twin's pass (its 192 draws against
  1179. // it only test, run 29), so the twin lacks nothing. Counted.
  1180. if colour && twin.plane.is_some() {
  1181. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1182. }
  1183. let Some(through) = &twin.through else {
  1184. // SAFETY: an open list and two live textures.
  1185. unsafe { list.CopyResource(to, from) };
  1186. return;
  1187. };
  1188. // A stencil plane and its twin: each mip and slice of the plane goes
  1189. // into the buffer, laid out as the host lays the plane out for copies,
  1190. // and from the buffer into the other texture, whole subresources both
  1191. // times. In the depth texture the stencil plane's subresources follow
  1192. // the depth plane's; the twin has the one plane.
  1193. let Some(host) = host() else { return };
  1194. // SAFETY: a live texture.
  1195. let of = unsafe { depth.GetDesc() };
  1196. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1197. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1198. // SAFETY: a plain query writing `planes` footprints.
  1199. unsafe {
  1200. host.device.GetCopyableFootprints(
  1201. &of,
  1202. planes,
  1203. planes,
  1204. 0,
  1205. Some(rows.as_mut_ptr()),
  1206. None,
  1207. None,
  1208. None,
  1209. );
  1210. }
  1211. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1212. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1213. // SAFETY: a borrowed pointer the location never releases.
  1214. pResource: unsafe { std::mem::transmute_copy(texture) },
  1215. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1216. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1217. SubresourceIndex: index,
  1218. },
  1219. };
  1220. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1221. // SAFETY: as above.
  1222. pResource: unsafe { std::mem::transmute_copy(through) },
  1223. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1224. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1225. PlacedFootprint: *row,
  1226. },
  1227. };
  1228. let (common, source, dest) = (
  1229. D3D12_RESOURCE_STATE_COMMON,
  1230. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1231. D3D12_RESOURCE_STATE_COPY_DEST,
  1232. );
  1233. // SAFETY: an open list and live resources; the buffer was made as big
  1234. // as these footprints, and rests in the common state between copies.
  1235. unsafe {
  1236. list.ResourceBarrier(&[transition(through, common, dest)]);
  1237. for (i, row) in rows.iter().enumerate() {
  1238. let index = first_from + i as u32;
  1239. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1240. }
  1241. list.ResourceBarrier(&[transition(through, dest, source)]);
  1242. for (i, row) in rows.iter().enumerate() {
  1243. let index = first_to + i as u32;
  1244. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1245. }
  1246. list.ResourceBarrier(&[transition(through, source, common)]);
  1247. }
  1248. }
  1249. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1250. /// builds).
  1251. pub(crate) fn dred_on() -> bool {
  1252. static ON: OnceLock<bool> = OnceLock::new();
  1253. *ON.get_or_init(|| {
  1254. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some()
  1255. })
  1256. }
  1257. /// Indirect mesh dispatches since the last frame line: the largest group
  1258. /// count a record asked for, and the groups asked in all (from the lists'
  1259. /// budget buffers, a run late).
  1260. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1261. /// Whether a list's indirect-work budget lives in the card's own memory
  1262. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1263. /// before). The clamp charges it with atomics, at least two in a row for
  1264. /// every clamp; in mapped memory on a card of its own each of them
  1265. /// crosses the bus.
  1266. fn card_budget() -> bool {
  1267. static ON: OnceLock<bool> = OnceLock::new();
  1268. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1269. }
  1270. /// Whether each list of a submission runs and is timed on its own, slow
  1271. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1272. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1273. #[cfg(feature = "diagnostics")]
  1274. fn timing() -> bool {
  1275. static ON: OnceLock<bool> = OnceLock::new();
  1276. *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some())
  1277. }
  1278. /// Names a host object for the device-removed report, which names the
  1279. /// allocations a page fault hit (only with device-removed data on), or for
  1280. /// the frame recorder (`VICTORY_RECORD`).
  1281. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1282. #[cfg(feature = "diagnostics")]
  1283. if crate::replay::record::on() {
  1284. let text = text();
  1285. crate::replay::record::name(object, &text);
  1286. if dred_on()
  1287. && let Ok(object) = object.cast::<ID3D12Object>()
  1288. {
  1289. // SAFETY: a plain call on a live object.
  1290. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1291. }
  1292. return;
  1293. }
  1294. if dred_on()
  1295. && let Ok(object) = object.cast::<ID3D12Object>()
  1296. {
  1297. // SAFETY: a plain call on a live object.
  1298. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1299. }
  1300. }
  1301. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1302. /// [`LISTS`]`[3]` until it is first reset.
  1303. struct Counted {
  1304. /// Not reset since it was made.
  1305. fresh: std::sync::atomic::AtomicBool,
  1306. }
  1307. impl Counted {
  1308. fn new() -> Counted {
  1309. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1310. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1311. Counted {
  1312. fresh: std::sync::atomic::AtomicBool::new(true),
  1313. }
  1314. }
  1315. /// The list is reset: it is in use.
  1316. fn used(&self) {
  1317. if self.fresh.swap(false, Ordering::Relaxed) {
  1318. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1319. }
  1320. }
  1321. }
  1322. impl Drop for Counted {
  1323. fn drop(&mut self) {
  1324. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1325. self.used();
  1326. }
  1327. }
  1328. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1329. /// mapping and its host GPU address.
  1330. struct Chunk {
  1331. _buffer: ID3D12Resource,
  1332. data: usize,
  1333. gpu: u64,
  1334. }
  1335. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1336. // written only by the list that holds the chunk.
  1337. unsafe impl Send for Chunk {}
  1338. /// Upload chunks handed out front to back: the chunks (each with its
  1339. /// bytes), the one in use and the bytes used in it.
  1340. #[derive(Default)]
  1341. struct Scratch {
  1342. chunks: Vec<(Chunk, u64)>,
  1343. current: usize,
  1344. used: u64,
  1345. }
  1346. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1347. unsafe impl Send for Scratch {}
  1348. impl Drop for Scratch {
  1349. fn drop(&mut self) {
  1350. give_chunks(std::mem::take(&mut self.chunks));
  1351. }
  1352. }
  1353. const SCRATCH_CHUNK: u64 = 4 << 20;
  1354. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1355. /// lists put a few constants or a rectangle's corners there, and every
  1356. /// list that did took 4 MiB of the PC's memory for it.
  1357. const SCRATCH_FIRST: u64 = 256 << 10;
  1358. /// The most bytes of chunks kept while no list holds them.
  1359. const SPARE_MOST: u64 = 128 << 20;
  1360. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1361. /// first needs one, a small one first, and gives all of them back when it
  1362. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1363. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1364. /// host lists of held submissions, which live for one submission, each
  1365. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1366. /// freed per frame of gameplay (run 60).
  1367. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1368. fn scratch_pool() -> bool {
  1369. static ON: OnceLock<bool> = OnceLock::new();
  1370. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1371. }
  1372. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1373. /// for one of the same size.
  1374. struct Spare<T> {
  1375. kept: Vec<(T, u64)>,
  1376. bytes: u64,
  1377. }
  1378. impl<T> Spare<T> {
  1379. const fn new() -> Self {
  1380. Spare { kept: Vec::new(), bytes: 0 }
  1381. }
  1382. /// A kept thing of `size` bytes, the one given last.
  1383. fn take(&mut self, size: u64) -> Option<T> {
  1384. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1385. self.bytes -= size;
  1386. Some(self.kept.remove(at).0)
  1387. }
  1388. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1389. /// `most`: then it comes back.
  1390. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1391. if self.bytes + size > most {
  1392. return Some(thing);
  1393. }
  1394. self.bytes += size;
  1395. self.kept.push((thing, size));
  1396. None
  1397. }
  1398. }
  1399. /// Scratch chunks no list holds.
  1400. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1401. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1402. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1403. if scratch_pool()
  1404. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1405. {
  1406. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1407. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1408. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1409. return Some(chunk);
  1410. }
  1411. let (buffer, data) = host.upload_buffer(size)?;
  1412. name(&buffer, || "list scratch".into());
  1413. // SAFETY: a live buffer.
  1414. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  1415. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1416. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1417. Some(Chunk {
  1418. _buffer: buffer,
  1419. data: data as usize,
  1420. gpu,
  1421. })
  1422. }
  1423. /// A list is done with `chunks` (it was reset after its submissions ran,
  1424. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1425. /// without the pool.
  1426. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1427. if chunks.is_empty() {
  1428. return;
  1429. }
  1430. let mut freed = Vec::new();
  1431. {
  1432. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1433. for (chunk, size) in chunks {
  1434. let back = if scratch_pool() {
  1435. spare.give(chunk, size, SPARE_MOST)
  1436. } else {
  1437. Some(chunk)
  1438. };
  1439. match back {
  1440. None => {
  1441. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1442. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1443. }
  1444. Some(chunk) => {
  1445. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1446. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1447. freed.push(chunk);
  1448. }
  1449. }
  1450. }
  1451. }
  1452. // Freed outside the lock.
  1453. drop(freed);
  1454. }
  1455. /// What the host keeps for copies in the card's own memory
  1456. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1457. struct CardWork {
  1458. /// Before a submission's lists: what changed on the copies' CPU side
  1459. /// goes to their card side. Those not in use: a plan takes one and
  1460. /// gives it back when its submission has run (`Host::card_done`), so
  1461. /// that submissions sent ahead ([`late`]) each have their own.
  1462. sync: Vec<Prelude>,
  1463. /// After them, in the same submission: the compare of the declared
  1464. /// ranges with their bytes from before. As `sync`.
  1465. check: Vec<Prelude>,
  1466. /// After it ran: the pieces that differ come down.
  1467. fetch: Prelude,
  1468. root: ID3D12RootSignature,
  1469. pso: ID3D12PipelineState,
  1470. /// One dword per piece compared, odd where the piece differs: PC
  1471. /// memory, mapped (buffer, mapping, bytes).
  1472. differs: (ID3D12Resource, usize, u64),
  1473. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1474. fetched: Option<(ID3D12Resource, usize, u64)>,
  1475. /// The dwords of `differs` taken by plans whose results were not read
  1476. /// yet.
  1477. taken: u32,
  1478. /// Plans made and not done with (`Host::card_done`).
  1479. out: u32,
  1480. }
  1481. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1482. // under the submission lock.
  1483. unsafe impl Send for CardWork {}
  1484. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1485. /// The compare of a declared range of a copy in the card's memory with
  1486. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1487. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1488. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1489. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1490. /// byte just outside the range costs a fetch that finds nothing.
  1491. ///
  1492. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1493. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1494. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1495. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1496. /// those steps.
  1497. pub(crate) const CARD_COMPARE: &str = r#"
  1498. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1499. cbuffer Span : register(b0) {
  1500. uint first; // the first piece
  1501. uint skew; // where the copy starts in its piece 0
  1502. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1503. uint pieces;
  1504. uint out_at; // the first piece's dword in `differs`, in bytes
  1505. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1506. };
  1507. ByteAddressBuffer now : register(t0);
  1508. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1509. // last sent up (or hashed whole, the first time).
  1510. RWByteAddressBuffer hashes : register(u0);
  1511. RWByteAddressBuffer differs : register(u1);
  1512. groupshared uint4 parts[64];
  1513. [RootSignature(RS)]
  1514. [numthreads(64, 1, 1)]
  1515. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1516. uint piece = first + id.x;
  1517. uint lo = piece * 65536u;
  1518. lo = lo > skew ? lo - skew : 0u;
  1519. uint hi = min((piece + 1u) * 65536u - skew, size);
  1520. lo = lo & ~15u;
  1521. hi = (hi + 15u) & ~15u;
  1522. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1523. [loop]
  1524. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1525. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1526. h = h.yzwx ^ (h >> 15);
  1527. }
  1528. parts[thread] = h;
  1529. GroupMemoryBarrierWithGroupSync();
  1530. if (thread != 0u) return;
  1531. h = parts[0];
  1532. [loop]
  1533. for (uint i = 1u; i < 64u; ++i) {
  1534. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1535. h = h.yzwx ^ (h >> 15);
  1536. }
  1537. if (compare != 0u) {
  1538. // The flag, and above it 31 bits of the hash (`torn`).
  1539. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1540. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1541. // With the copy-back on its own thread: the next compare of the
  1542. // piece finds what is written from here on.
  1543. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1544. } else {
  1545. hashes.Store4(piece * 16u, h);
  1546. }
  1547. }
  1548. "#;
  1549. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1550. #[cfg(test)]
  1551. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1552. torn::hash(bytes)
  1553. }
  1554. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1555. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1556. /// parts a dispatch can hold.
  1557. ///
  1558. /// # Safety
  1559. /// The list is open with the compare's root signature, pipeline and buffers
  1560. /// set, and the pieces lie in the buffer.
  1561. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1562. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1563. let mut done = 0;
  1564. while done < span.pieces {
  1565. let n = (span.pieces - done).min(MOST);
  1566. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1567. // SAFETY: the caller's.
  1568. unsafe {
  1569. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1570. list.Dispatch(n, 1, 1);
  1571. }
  1572. done += n;
  1573. }
  1574. }
  1575. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1576. /// the card's memory are hashed in runs of pieces that touch, each piece
  1577. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1578. /// per range sent up.
  1579. ///
  1580. /// These passes are ours, they run on the card before every submission's
  1581. /// lists: a pass takes the time of one piece however few its pieces are.
  1582. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1583. /// a piece hashed when it need not be, or not hashed when it should, costs
  1584. /// a fetch that finds nothing and loses no shader write.
  1585. fn rehash_runs() -> bool {
  1586. static ON: OnceLock<bool> = OnceLock::new();
  1587. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1588. }
  1589. /// Since the last frame-rate line, of our own passes over copies in the
  1590. /// card's memory: hash passes after ranges were sent up, the pieces they
  1591. /// hashed, and compare passes after the lists.
  1592. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1593. /// Whether what shaders wrote to copies in the card's memory is merged
  1594. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1595. /// default). The pieces the card's compare found differing come down in
  1596. /// one fetch and were then merged one after the other on the thread that
  1597. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1598. /// with the copy's CPU side byte by byte and put into title memory through
  1599. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1600. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1601. /// landings do not come here: `crate::land` has threads of its own.)
  1602. fn wide_merge() -> bool {
  1603. static ON: OnceLock<bool> = OnceLock::new();
  1604. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1605. }
  1606. /// One declared range of a copy in the card's memory, in a submission.
  1607. struct CardRange {
  1608. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1609. /// As declared (title addresses), for the statistics.
  1610. declared: (usize, usize),
  1611. span: crate::shadow::CardSpan,
  1612. /// Its first piece's dword in the compare's results.
  1613. at: u32,
  1614. /// Whether the card compares it; else every piece is fetched.
  1615. compared: bool,
  1616. /// Looked at by `crate::picked`, and not declared: what is found changed
  1617. /// there was written through a view nobody declared. Not landed.
  1618. picked: bool,
  1619. }
  1620. impl CardPlan {
  1621. /// `crate::picked` is told where what it looked at changed, by the
  1622. /// compare's results.
  1623. fn picked_found(&self, differs: &[u32]) {
  1624. for r in self.ranges.iter().filter(|r| r.picked) {
  1625. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1626. if let Some(p) = changed {
  1627. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1628. }
  1629. }
  1630. }
  1631. }
  1632. /// What a submission does for copies in the card's memory.
  1633. struct CardPlan {
  1634. ranges: Vec<CardRange>,
  1635. /// The compare, run after the submission's lists.
  1636. check: Option<ID3D12CommandList>,
  1637. /// The copies whose card side was brought up to date, alive until the
  1638. /// submission has run.
  1639. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1640. /// The lists of ours the plan recorded (whether the compare, the
  1641. /// list), given back by `Host::card_done`.
  1642. lists: Vec<(bool, Prelude)>,
  1643. /// With [`relay`]: the number of the send to copies in the card's memory
  1644. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1645. sent_as: u64,
  1646. /// With [`upcheck`]: the look at what it sent up.
  1647. looks: Option<upcheck::Looks>,
  1648. /// With [`send`]: the memory its sends come from.
  1649. sends: Option<send::Memory>,
  1650. }
  1651. /// One piece of submission-time work, in recorded order.
  1652. enum Step {
  1653. /// A copy into title memory (destination, source, bytes): the title's
  1654. /// buffer copies, which later refreshes must see.
  1655. Copy(usize, usize, usize),
  1656. /// A copy of title memory into the list's own upload memory, and how
  1657. /// the card could bring the bytes instead.
  1658. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  1659. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1660. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1661. /// intervenes.
  1662. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1663. /// Work that may write title memory.
  1664. Run(Box<dyn Fn() + Send>),
  1665. /// Work that writes host memory only, and the title memory it reads
  1666. /// (from, to; empty for none).
  1667. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1668. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1669. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1670. /// Brings a texture's staging buffer up to date: once per submission,
  1671. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1672. Texture(std::sync::Arc<crate::texture::Staging>),
  1673. }
  1674. /// What a list does on the CPU when it is submitted: copies between host
  1675. /// memory regions (title buffers, upload buffers and buffer copies), and
  1676. /// the upload buffers its GPU commands read, kept until the list is reset.
  1677. #[derive(Default)]
  1678. struct Deferred {
  1679. /// Destination, source, bytes.
  1680. copies: Vec<Step>,
  1681. uploads: Vec<ID3D12Resource>,
  1682. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1683. upload_bytes: u64,
  1684. /// Host objects the list's commands name (pipelines, root signatures,
  1685. /// descriptor heaps): the title may release its objects before it
  1686. /// submits the list.
  1687. kept: Vec<windows::core::IUnknown>,
  1688. /// Buffer ranges refreshed since the last title copy (host copy,
  1689. /// address, bytes): refreshing them again would find the same bytes.
  1690. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1691. /// Textures whose contents the list brings up to date.
  1692. textures: std::collections::HashSet<usize>,
  1693. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1694. /// bytes.
  1695. writes: Vec<(usize, crate::queue::Written, usize)>,
  1696. /// Textures read back (texture to buffer copies), done once the list
  1697. /// has run: the host buffer the list copies the texels into, the title
  1698. /// memory they go to, the bytes of a row, the rows, the title's row
  1699. /// pitch.
  1700. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1701. /// Whether the indirect-work budget is zeroed for this recording (a
  1702. /// step on the CPU, or in the list for the card's copy).
  1703. budget_zeroed: bool,
  1704. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1705. /// interface pointer) that a clamp in this recording left readable as
  1706. /// indirect arguments; 0 if none. It stays readable until the next
  1707. /// clamp into it ([`HostList::indirect_state`]).
  1708. indirect_readable: usize,
  1709. }
  1710. impl Deferred {
  1711. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1712. /// reset.
  1713. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1714. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1715. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1716. self.upload_bytes += size;
  1717. self.uploads.push(buffer);
  1718. }
  1719. }
  1720. impl Drop for Deferred {
  1721. fn drop(&mut self) {
  1722. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1723. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1724. }
  1725. }
  1726. /// Whether a queue's submissions go to the card without a wait for each
  1727. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1728. /// waits for every list on its own).
  1729. ///
  1730. /// Every submission was prepared, sent, waited for and copied back before
  1731. /// the next one was looked at, so the card stood idle while we prepared
  1732. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1733. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1734. /// other, on the one thread that submits.
  1735. ///
  1736. /// With the switch a queue's submission is sent and joins a line of
  1737. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1738. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1739. /// for the card, what their shaders wrote copied back once per byte, then
  1740. /// their bottom-of-pipe writes and the fence signals behind them, in
  1741. /// order) at the next point where the title, or our own preparing, can
  1742. /// observe what they do. Those points, exactly:
  1743. ///
  1744. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1745. /// read-back or map of a texture, a clear or upload run at once;
  1746. /// 2. the next submission reads title memory that a flight's shaders may
  1747. /// write: a title buffer copy, a fill of upload memory, a texture's
  1748. /// memory, any step that runs code of ours on title memory
  1749. /// ([`late_blocked`]);
  1750. /// 3. the next submission refreshes a range of a host copy that a flight's
  1751. /// shaders may write, and the title wrote a page of it since it was last
  1752. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1753. /// alone until the flight's writes are back, as it always did within a
  1754. /// submission;
  1755. /// 4. a queue stands at a wait for a memory value that no flight's
  1756. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1757. /// write ([`late_met`]);
  1758. /// 5. the title blocks on a fence without an event;
  1759. /// 6. the card has run every flight (a thread of ours waits for that:
  1760. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1761. ///
  1762. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1763. /// when the card has really run the work, later than before and never
  1764. /// earlier; a fence signalled on a queue while flights are in the air is
  1765. /// set behind them. A wait for a memory value that a flight's
  1766. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1767. /// the card behind that flight, which is the order the wait asks for.
  1768. ///
  1769. /// What it assumes beyond today: memory the title rewrites between two of
  1770. /// its submissions, without waiting for the first, may be seen by the
  1771. /// first's shaders (as on the console, where the card reads title memory
  1772. /// when it runs, not when the list is submitted).
  1773. pub(crate) fn late() -> bool {
  1774. late_stage() > 0
  1775. }
  1776. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1777. fn late_stage() -> u8 {
  1778. static STAGE: OnceLock<u8> = OnceLock::new();
  1779. *STAGE.get_or_init(|| {
  1780. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1781. return 0;
  1782. }
  1783. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1784. Ok("1") => 1,
  1785. Ok("2") => 2,
  1786. Ok("3") => 3,
  1787. // The relay alone: on top of stage 3.
  1788. Err(_) if crate::shadow::relay() => 3,
  1789. _ => 0,
  1790. }
  1791. })
  1792. }
  1793. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1794. /// longer a point. Where the title wrote a page that lies in a range a
  1795. /// flight's shaders may write, the bytes the title changed are found (the
  1796. /// page as it is now against what the copy held when the flight was
  1797. /// prepared) and put into the copy, and only those: what the flight's
  1798. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1799. /// flights are settled for it only where that cannot be done: memory that
  1800. /// is not write-watched, or a copy in the card's memory with more changed
  1801. /// runs than a submission should send up one by one.
  1802. ///
  1803. /// In run 92 (stage 1) this point settled the flights five times a frame
  1804. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1805. /// frame of waiting were left of 200.
  1806. ///
  1807. /// What differs from settling first: a byte both the title and a flight's
  1808. /// shader wrote is the title's if the shader wrote it first, the shader's
  1809. /// if it wrote it afterwards; settled first it was always the shader's.
  1810. /// The title writing a byte a shader of its own is writing is a race on
  1811. /// the console too.
  1812. fn late_exact() -> bool {
  1813. late_stage() > 1
  1814. }
  1815. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1816. /// no longer a point where flights are settled). The copy to the back
  1817. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1818. /// its own for each present in the air) and the swap chain is told to
  1819. /// present behind it; the queue's call returns, and the card finishes the
  1820. /// frame while the title records the next one. What the title is told
  1821. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1822. /// has run it, by the settling thread.
  1823. ///
  1824. /// What is left out with it: the look whether the presented frame is black
  1825. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1826. /// or listed is presented the old way. Once every second and a half a
  1827. /// submission settles the flights all the same, for the sweep that lets
  1828. /// idle host objects go (it needs nothing in the air).
  1829. pub(crate) fn late_free_present() -> bool {
  1830. late_stage() > 2
  1831. }
  1832. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1833. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1834. /// and is off with it, in the timing run and with kept snapshots).
  1835. ///
  1836. /// With [`late`] alone every settle does three things on the thread that
  1837. /// holds the submission lock: it waits for everything in the air, copies
  1838. /// back with the card standing, and only then goes on preparing. The frame
  1839. /// stays a relay: the card works about 242 ms of it and one thread
  1840. /// prepares, waits and copies back for about 220.
  1841. ///
  1842. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1843. /// soon as the card has run them, in the order they were sent and without
  1844. /// the submission lock: it fetches and merges what their shaders wrote to
  1845. /// copies in the card's memory, compares and merges the other copies,
  1846. /// frees the flights' ranges, and then does their read-backs, their
  1847. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1848. /// order. The submitting thread meanwhile prepares and sends the next
  1849. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  1850. /// that thread has landed everything in the air, at the same points as
  1851. /// before (the list in [`late`]), so whoever can observe title memory, a
  1852. /// fence or a present still does so only after the flights before it are
  1853. /// merged.
  1854. ///
  1855. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  1856. /// flight; a merge that never stores into memory the card may be writing;
  1857. /// sends to card copies numbered) and here: flights land in the order of
  1858. /// [`LINE`] by one thread, so a later flight's results never reach title
  1859. /// memory before an earlier flight's; the compare on the card stores the
  1860. /// hash it made, so each flight's compare flags exactly what changed since
  1861. /// the compare before it, however late the pieces are fetched; the fetch
  1862. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  1863. /// title bytes the card had received when it ran.
  1864. pub(crate) fn relay() -> bool {
  1865. static ON: OnceLock<bool> = OnceLock::new();
  1866. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  1867. }
  1868. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  1869. /// title memory a flight's shaders may write (a title buffer copy, a fill
  1870. /// of upload memory, a texture) waits only until the flights that declared
  1871. /// that memory have landed, not for everything in the air; and at
  1872. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  1873. /// both wait for everything.
  1874. fn relay_exact() -> bool {
  1875. static ON: OnceLock<bool> = OnceLock::new();
  1876. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  1877. // since the walls of the first room were found drawn in every run with
  1878. // this set and in fewer than half without it).
  1879. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  1880. }
  1881. /// Whether the pieces the relay fetches from the card's memory come over the
  1882. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  1883. /// draws.
  1884. ///
  1885. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  1886. /// and with the relay that is most of a frame: the thread that lands flights
  1887. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  1888. /// a few milliseconds of copying, and everything that waits for a landing
  1889. /// (the title's fences, reads of memory flights may write) waited with it.
  1890. ///
  1891. /// What changes: the fetch runs when its flights are done and beside later
  1892. /// submissions, so of the sends of title bytes it is only known to have run
  1893. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  1894. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  1895. /// the title's, newer than what the flights wrote. A later flight's bytes
  1896. /// may be in what is fetched, as before.
  1897. fn relay_copy() -> bool {
  1898. static ON: OnceLock<bool> = OnceLock::new();
  1899. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  1900. }
  1901. /// Told when something joins [`LINE`], for the thread that lands flights
  1902. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  1903. /// what queues hold.
  1904. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  1905. /// Told when flights have landed ([`relay`]): who waits for that looks
  1906. /// again.
  1907. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  1908. /// With [`relay`], the order of what we put on the queue: the number of
  1909. /// sends of changed ranges to copies in the card's memory so far
  1910. /// (`Host::card_before`). Held from the taking of the ranges until their
  1911. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  1912. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  1913. /// later one.
  1914. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  1915. /// Since the last frame-rate line, of the thread that lands flights
  1916. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  1917. /// card with nothing to land, microseconds it waited for fetches of card
  1918. /// copies' pieces, microseconds of landing in all.
  1919. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  1920. /// Of the line's things in order (a flight: the value signalled on the
  1921. /// host's fence behind it; a write or a signal behind a flight: `None`):
  1922. /// how many, from the front, can be landed when the card has reached
  1923. /// `completed`: everything ahead of the first flight it has not run. A
  1924. /// later flight never lands before an earlier one, and what follows a
  1925. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  1926. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  1927. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  1928. }
  1929. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  1930. /// holds, for every piece of every range of the plan, the copy, the
  1931. /// piece's number in the copy and whether the compare flagged it there (or
  1932. /// did not run). The pieces to fetch, under whichever range, in order: all
  1933. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  1934. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  1935. /// the hash, so the second of them may find it stored already and not
  1936. /// flag it.
  1937. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  1938. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  1939. pieces.sort_unstable();
  1940. pieces.dedup();
  1941. pieces
  1942. }
  1943. #[cfg(test)]
  1944. mod relay_tests {
  1945. use super::{flagged_pieces, landable};
  1946. /// Two flights and what follows each: nothing of the second lands
  1947. /// before the card has run it, and nothing behind a flight lands
  1948. /// before the flight.
  1949. #[test]
  1950. fn flights_land_in_the_order_they_were_sent() {
  1951. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  1952. let line = [Some(5), None, None, Some(6), None];
  1953. assert_eq!(landable(&line, 4), 0);
  1954. assert_eq!(landable(&line, 5), 3);
  1955. assert_eq!(landable(&line, 6), 5);
  1956. assert_eq!(landable(&line, u64::MAX), 5);
  1957. // Signals with no flight ahead land at once; behind one they wait.
  1958. assert_eq!(landable(&[None, None], 0), 2);
  1959. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  1960. assert_eq!(landable(&[], 3), 0);
  1961. // After the first three landed, the rest when its turn comes.
  1962. assert_eq!(landable(&line[3..], 5), 0);
  1963. assert_eq!(landable(&line[3..], 6), 2);
  1964. }
  1965. /// A piece flagged under one range of a plan is fetched under every
  1966. /// range that holds a part of it; pieces of other copies are not.
  1967. #[test]
  1968. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  1969. let (a, b) = (0x1000usize, 0x2000usize);
  1970. // Copy a: piece 3 under two ranges, flagged under the first only;
  1971. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  1972. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  1973. let fetch = flagged_pieces(&flags);
  1974. assert!(fetch.contains(&(a, 3)));
  1975. assert!(!fetch.contains(&(a, 4)));
  1976. assert!(!fetch.contains(&(b, 3)));
  1977. assert!(fetch.contains(&(b, 9)));
  1978. assert_eq!(fetch.len(), 2);
  1979. }
  1980. }
  1981. /// The most host lists in the air before the flights are settled
  1982. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  1983. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  1984. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  1985. /// 32 settled the flights three times a
  1986. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  1987. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  1988. /// descriptor slots, upload
  1989. /// memory and scratch chunks are held until then, and a frame's lists held
  1990. /// all at once ran the slots out before (run 45).
  1991. fn late_most() -> usize {
  1992. static MOST: OnceLock<usize> = OnceLock::new();
  1993. *MOST.get_or_init(|| {
  1994. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  1995. })
  1996. }
  1997. /// Whether a submission with bottom-of-pipe writes may fly
  1998. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  1999. /// the title is told at once, as before; for telling a title that polls
  2000. /// such a value from one that does not).
  2001. fn late_writes() -> bool {
  2002. static ON: OnceLock<bool> = OnceLock::new();
  2003. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  2004. }
  2005. /// Per host copy, the ranges a submission's shaders may write, as declared
  2006. /// (address, end).
  2007. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  2008. /// What [`Host::submit`] hands back for a submission it sent and did not
  2009. /// wait for.
  2010. struct Sent {
  2011. /// Its number among the submissions started.
  2012. number: u64,
  2013. card: Option<CardPlan>,
  2014. back: Vec<Declared>,
  2015. /// What was taken off it to be done on the card.
  2016. own: Option<card_steps::Taken>,
  2017. /// Its bottom-of-pipe writes.
  2018. writes: Vec<(usize, crate::queue::Written, usize)>,
  2019. }
  2020. /// A submission on the card that has not been waited for ([`late`]): its
  2021. /// host lists, taken from the title's (which it may reset meanwhile), and
  2022. /// what is to be done once it has run.
  2023. struct Flight {
  2024. number: u64,
  2025. /// The value signalled on the host's fence behind it.
  2026. fence: u64,
  2027. lists: Vec<crate::list::Detached>,
  2028. order: Vec<usize>,
  2029. card: Option<CardPlan>,
  2030. back: Vec<Declared>,
  2031. /// The list of ours that ran ahead of them ([`card_steps`]).
  2032. own: Option<card_steps::Taken>,
  2033. }
  2034. /// One thing in the line of what waits for the card, in order.
  2035. enum Late {
  2036. Run(Flight),
  2037. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  2038. Write(usize, crate::queue::Written, usize),
  2039. /// A fence (its address) signalled behind the flights before it.
  2040. Signal(usize, u64),
  2041. }
  2042. struct Line {
  2043. line: Vec<Late>,
  2044. /// The title memory the flights' shaders may write (address, end), in
  2045. /// order and joined.
  2046. written: Vec<(usize, usize)>,
  2047. /// Host lists in the flights.
  2048. lists: usize,
  2049. /// The value signalled on the host's fence behind the last flight.
  2050. target: u64,
  2051. /// A settle has taken the line and is not done: a signal still goes
  2052. /// behind it.
  2053. settling: bool,
  2054. /// Something was settled away from a queue's own calls: the helper
  2055. /// thread looks at what queues hold.
  2056. poke: bool,
  2057. /// Host lists of settled flights, reset and given back outside the
  2058. /// submission lock ([`land`]: a settle may run under a caller's own
  2059. /// locks).
  2060. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2061. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2062. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2063. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2064. /// With [`card_steps`]: what the flights being landed write.
  2065. landing: Vec<card_steps::Writer>,
  2066. }
  2067. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2068. // into; touched under the lock.
  2069. unsafe impl Send for Line {}
  2070. static LINE: Mutex<Line> = Mutex::new(Line {
  2071. line: Vec::new(),
  2072. written: Vec::new(),
  2073. lists: 0,
  2074. target: 0,
  2075. settling: false,
  2076. poke: false,
  2077. landed: Vec::new(),
  2078. in_hand: Vec::new(),
  2079. landing: Vec::new(),
  2080. });
  2081. /// Told when a flight joins [`LINE`] or it is poked.
  2082. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2083. fn line() -> std::sync::MutexGuard<'static, Line> {
  2084. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2085. }
  2086. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2087. const WHY_SYNC: usize = 2;
  2088. const WHY_CARD_DONE: usize = 3;
  2089. const WHY_VALUE: usize = 4;
  2090. const WHY_STALE: usize = 5;
  2091. const WHY_READ: usize = 6;
  2092. const WHY_RUN: usize = 7;
  2093. const WHY_MOST: usize = 8;
  2094. const WHY_WRITES: usize = 9;
  2095. const WHY_FENCE: usize = 10;
  2096. /// Since the last frame-rate line: submissions sent without a wait;
  2097. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2098. /// microseconds settles waited for the card; value waits met by a flight's
  2099. /// bottom-of-pipe write; fence signals set behind flights.
  2100. /// Then: the settles for title memory read, by what read it (a buffer
  2101. /// copy, a fill of upload memory, a texture).
  2102. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2103. /// Since the last frame-rate line: the microseconds settles waited for the
  2104. /// card, by why they settled (the `WHY_` places).
  2105. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2106. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2107. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2108. if from >= to {
  2109. return false;
  2110. }
  2111. let at = ranges.partition_point(|r| r.1 <= from);
  2112. ranges.get(at).is_some_and(|r| r.0 < to)
  2113. }
  2114. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2115. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2116. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2117. ranges.sort_unstable();
  2118. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2119. for &(from, to) in ranges.iter() {
  2120. match out.last_mut() {
  2121. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2122. _ => out.push((from, to)),
  2123. }
  2124. }
  2125. *ranges = out;
  2126. }
  2127. /// Whether anything is in the air.
  2128. fn flying() -> bool {
  2129. if !late() {
  2130. return false;
  2131. }
  2132. let line = line();
  2133. // (With the relay: also while flights are being landed.)
  2134. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2135. }
  2136. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2137. /// before they are settled, if so. Preparing reads title memory on the
  2138. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2139. /// runs steps of ours that may read or write it anywhere; what the
  2140. /// flights' shaders write is not there yet.
  2141. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2142. let (written, copies) = {
  2143. let line = line();
  2144. if line.written.is_empty() {
  2145. return None;
  2146. }
  2147. (line.written.clone(), card_steps::copies(&line))
  2148. };
  2149. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2150. }
  2151. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2152. /// flights when the title itself wrote the memory since they were given it
  2153. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2154. ///
  2155. /// The title's 174 MB heap is declared written as a whole (a root view has
  2156. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2157. /// bytes a frame, at a new place each time, waited for every flight's
  2158. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2159. /// named). The title writes those bytes just before the draw that reads
  2160. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2161. ///
  2162. /// Or no shader's write went into that page in the last 600 frames
  2163. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2164. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2165. /// before the page was taken.
  2166. ///
  2167. /// What can go wrong: a constant a flight's shader really writes, in a
  2168. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2169. /// for the first time, is read as it was before that flight.
  2170. fn fill_is_titles(src: usize, len: usize) -> bool {
  2171. const SMALL: usize = 64 << 10;
  2172. static ON: OnceLock<bool> = OnceLock::new();
  2173. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2174. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2175. }
  2176. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2177. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2178. /// in (start, bytes).
  2179. #[cfg(feature = "diagnostics")]
  2180. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2181. /// How often and how long, and the address the last one read.
  2182. #[cfg(feature = "diagnostics")]
  2183. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2184. /// What the wait that comes next is for, and why not on the card.
  2185. #[cfg(feature = "diagnostics")]
  2186. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2187. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2188. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2189. /// shaders.
  2190. #[cfg(feature = "diagnostics")]
  2191. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2192. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2193. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2194. /// raw address (1).
  2195. #[cfg(feature = "diagnostics")]
  2196. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2197. if len < 1 << 20 {
  2198. return;
  2199. }
  2200. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2201. let e = all
  2202. .get_or_insert_with(Default::default)
  2203. .entry((address as usize, (address + len) as usize, pipeline))
  2204. .or_insert_with(|| {
  2205. let shaders = match pipeline {
  2206. 0 => "a view in a table".into(),
  2207. 1 => "a raw address".into(),
  2208. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2209. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2210. }),
  2211. };
  2212. (0, shaders)
  2213. });
  2214. e.0 += 1;
  2215. }
  2216. #[cfg(feature = "diagnostics")]
  2217. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2218. let i = written.partition_point(|r| r.1 <= at);
  2219. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2220. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2221. let why = blamed.1;
  2222. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2223. }
  2224. /// Why [`card_steps`] left the submission to the wait that comes next.
  2225. #[cfg(feature = "diagnostics")]
  2226. fn refused(why: &'static str) {
  2227. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2228. }
  2229. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2230. #[cfg(feature = "diagnostics")]
  2231. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2232. if let Some((shadow, from, _)) = stale.first() {
  2233. let (start, len) = shadow.span();
  2234. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2235. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2236. }
  2237. }
  2238. /// The wait for what [`blame`] last named, or a wait of another reason than
  2239. /// title memory read, took `us`.
  2240. #[cfg(feature = "diagnostics")]
  2241. fn blamed(why: usize, us: u64) {
  2242. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2243. let (key, at) = match (why, named) {
  2244. (WHY_READ | WHY_STALE, Some(named)) => named,
  2245. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2246. _ => {
  2247. let kind = match why {
  2248. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2249. WHY_VALUE => "a memory value",
  2250. WHY_STALE => "title memory changed under shader writes",
  2251. WHY_RUN => "a step of ours",
  2252. WHY_MOST => "lists in the air",
  2253. WHY_FENCE => "a blocking fence wait",
  2254. _ => "another reason",
  2255. };
  2256. ((kind, "", 0, 0, 0), 0)
  2257. }
  2258. };
  2259. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2260. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2261. *e = (e.0 + 1, e.1 + us, at);
  2262. }
  2263. /// For the frame-rate line: the five that waited longest.
  2264. #[cfg(feature = "diagnostics")]
  2265. fn log_blame(frames: f64) {
  2266. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2267. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2268. let mut all: Vec<_> = all.into_iter().collect();
  2269. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2270. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2271. // The passes that declare it written, the ones that do so most.
  2272. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2273. for ((a, b, _), (n, shaders)) in &wide {
  2274. if *a < at + len && at < *b {
  2275. *passes.entry(shaders).or_default() += n;
  2276. }
  2277. }
  2278. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2279. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2280. let passes: Vec<String> =
  2281. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2282. tracing::info!(
  2283. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2284. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2285. us as f64 / 1e3 / frames,
  2286. n as f64 / frames,
  2287. passes.join(", "),
  2288. match (why.is_empty(), kind) {
  2289. (true, _) => "",
  2290. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2291. _ => "; not done on the card: ",
  2292. },
  2293. );
  2294. }
  2295. }
  2296. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2297. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2298. touches(written, src, src + len) && !fill_is_titles(src, len)
  2299. }
  2300. /// Whether they stop a title buffer copy, and if so whether by its source.
  2301. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2302. let read = read_blocked(written, src, len);
  2303. (read || touches(written, dst, dst + len)).then_some(read)
  2304. }
  2305. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2306. /// may write (in order, joined); `count` whether the kind of read is
  2307. /// counted for the frame line.
  2308. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2309. if written.is_empty() {
  2310. return None;
  2311. }
  2312. for list in runs {
  2313. for step in &list.deferred().copies {
  2314. match step {
  2315. &Step::Copy(dst, src, len) => {
  2316. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2317. if count {
  2318. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2319. #[cfg(feature = "diagnostics")]
  2320. if _read {
  2321. blame("a buffer copy's source", written, src, len);
  2322. } else {
  2323. blame("a buffer copy's destination", written, dst, len);
  2324. }
  2325. }
  2326. return Some(WHY_READ);
  2327. }
  2328. }
  2329. &Step::Fill(_, src, len, _) => {
  2330. if read_blocked(written, src, len) {
  2331. if count {
  2332. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2333. #[cfg(feature = "diagnostics")]
  2334. blame("a fill of upload memory", written, src, len);
  2335. }
  2336. return Some(WHY_READ);
  2337. }
  2338. }
  2339. Step::Texture(staging) => {
  2340. let (at, len) = staging.memory();
  2341. if touches(written, at, at + len) {
  2342. if count {
  2343. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2344. #[cfg(feature = "diagnostics")]
  2345. blame("a texture", written, at, len);
  2346. }
  2347. return Some(WHY_READ);
  2348. }
  2349. }
  2350. Step::Run(_) => return Some(WHY_RUN),
  2351. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2352. }
  2353. }
  2354. }
  2355. None
  2356. }
  2357. /// With flights in the air, after the submission's write-watch asking:
  2358. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2359. /// may write and that the title wrote since it was last copied. The
  2360. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2361. /// the title's bytes there would reach the card a submission late.
  2362. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2363. use std::sync::Arc;
  2364. // Per copy, the span of what is refreshed (a flush brings that much
  2365. // up to date at most).
  2366. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2367. // Where each copy is in it, if shaders may be writing it (none begins to
  2368. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2369. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2370. for list in runs {
  2371. for step in &list.deferred().copies {
  2372. if let Step::Refresh(shadow, address, len) = step {
  2373. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2374. shadow.writes_pending().then(|| {
  2375. spans.push((shadow.clone(), *address, *address + *len));
  2376. spans.len() - 1
  2377. })
  2378. });
  2379. if let Some(i) = *place {
  2380. let s = &mut spans[i];
  2381. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2382. }
  2383. }
  2384. }
  2385. }
  2386. if late_exact() {
  2387. // The title's bytes are put in beside the flights' writes; a
  2388. // settle is still due where that could not be done. At most this
  2389. // many changed runs go up to copies in the card's memory, each a
  2390. // copy of its own there. With [`card_steps`] the pages of the
  2391. // title's ring of constants come here too, which were waited for
  2392. // before: hundreds of short runs each, at about 1.5 us a run.
  2393. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2394. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2395. return spans;
  2396. }
  2397. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2398. spans
  2399. }
  2400. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2401. /// air, if there are any, and is set when they are settled. Whether it
  2402. /// did; if not the caller sets the fence now.
  2403. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2404. if !late() {
  2405. return false;
  2406. }
  2407. let mut line = line();
  2408. if line.line.is_empty() && !line.settling {
  2409. return false;
  2410. }
  2411. line.line.push(Late::Signal(fence, value));
  2412. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2413. drop(line);
  2414. // A signal alone (behind a settle under way) has no flight to wake
  2415. // the helper thread for it.
  2416. LINE_MOVED.notify_one();
  2417. RELAY_MOVED.notify_one();
  2418. true
  2419. }
  2420. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2421. /// whether it is met once the flights in the air have run. A flight's
  2422. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2423. /// for the card: the part behind the wait goes to the card behind that
  2424. /// flight, which is the order the wait asks for. If the flights may write
  2425. /// the value in a way not known here (shaders, a timestamp, another
  2426. /// width), they are settled and memory is asked again.
  2427. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2428. let (address, bytes) = wait.place();
  2429. {
  2430. let line = line();
  2431. if line.line.is_empty() && line.in_hand.is_empty() {
  2432. return false;
  2433. }
  2434. let mut unsure = touches(&line.written, address, address + bytes);
  2435. // (With the relay: first the writes of flights being landed.)
  2436. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2437. Late::Write(at, what, n) => Some((at, what, n)),
  2438. _ => None,
  2439. }));
  2440. for (at, what, n) in writes {
  2441. if *at >= address + bytes || address >= *at + *n {
  2442. continue;
  2443. }
  2444. match what {
  2445. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2446. if wait.holds_for(*v) {
  2447. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2448. return true;
  2449. }
  2450. }
  2451. _ => unsure = true,
  2452. }
  2453. }
  2454. if !unsure {
  2455. return false;
  2456. }
  2457. }
  2458. settle_now(WHY_VALUE);
  2459. wait.met()
  2460. }
  2461. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2462. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2463. pub(crate) fn settle_now(why: usize) {
  2464. if !late() {
  2465. return;
  2466. }
  2467. let Some(host) = host() else {
  2468. return;
  2469. };
  2470. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2471. host.settle(&mut submitted, why);
  2472. }
  2473. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2474. pub(crate) fn settle_for_present() {
  2475. settle_now(WHY_SYNC);
  2476. }
  2477. pub(crate) fn settle_for_fence() {
  2478. settle_now(WHY_FENCE);
  2479. }
  2480. /// Resets the host lists of settled flights and keeps them for reuse, as
  2481. /// a queue does for the lists it ran (`crate::list::recycle`).
  2482. fn land() {
  2483. let landed = std::mem::take(&mut line().landed);
  2484. for (lists, order) in landed {
  2485. crate::list::recycle(lists, &order);
  2486. }
  2487. }
  2488. /// The thread that settles the flights once the card has run them all
  2489. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2490. /// at the next call that settles, and a title thread that polls such a
  2491. /// value while the submitting thread waits for that thread would never
  2492. /// see it.
  2493. fn late_helper() {
  2494. let Some(host) = host() else {
  2495. return;
  2496. };
  2497. // SAFETY: a plain event of our own.
  2498. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2499. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2500. return;
  2501. };
  2502. loop {
  2503. let target = {
  2504. let mut line = line();
  2505. loop {
  2506. if line.poke {
  2507. line.poke = false;
  2508. break None;
  2509. }
  2510. // (With the relay the flights are another thread's.)
  2511. if !relay() && !line.line.is_empty() && !line.settling {
  2512. break Some(line.target);
  2513. }
  2514. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2515. }
  2516. };
  2517. let Some(target) = target else {
  2518. land();
  2519. crate::queue::release_held(false);
  2520. continue;
  2521. };
  2522. // The card first, without the submission lock: the submitting
  2523. // thread prepares and sends meanwhile.
  2524. // SAFETY: our fence and event.
  2525. unsafe {
  2526. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2527. WaitForSingleObject(event, INFINITE);
  2528. }
  2529. }
  2530. {
  2531. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2532. // Something newer went up meanwhile: the card is waited for
  2533. // again, the submitting thread is not held up for it.
  2534. if line().target != target {
  2535. continue;
  2536. }
  2537. host.settle(&mut submitted, WHY_CARD_DONE);
  2538. }
  2539. land();
  2540. crate::queue::release_held(false);
  2541. }
  2542. }
  2543. /// Starts the threads of [`late`], once: the one that settles flights when
  2544. /// the card has run them and looks at what queues hold, and with [`relay`]
  2545. /// the one that lands flights.
  2546. fn late_threads() {
  2547. static HELPER: std::sync::Once = std::sync::Once::new();
  2548. HELPER.call_once(|| {
  2549. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2550. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2551. }
  2552. tracing::info!(
  2553. most = late_most(),
  2554. writes = late_writes(),
  2555. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2556. );
  2557. if relay() {
  2558. // Without it nothing would ever land.
  2559. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2560. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2561. }
  2562. tracing::info!(
  2563. exact = relay_exact(),
  2564. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2565. );
  2566. }
  2567. });
  2568. }
  2569. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2570. /// time flights have landed. Counted as a settle for `why`, and its time
  2571. /// as waiting for the card. The caller may hold the submission lock: the
  2572. /// thread that lands flights never takes it.
  2573. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2574. let mut line = line();
  2575. if done(&line) {
  2576. return;
  2577. }
  2578. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2579. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2580. let was_working = working(false);
  2581. let waiting = std::time::Instant::now();
  2582. while !done(&line) {
  2583. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2584. }
  2585. drop(line);
  2586. stood(waiting);
  2587. working(was_working);
  2588. let us = waiting.elapsed().as_micros() as u64;
  2589. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2590. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2591. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2592. #[cfg(feature = "diagnostics")]
  2593. blamed(why, us);
  2594. }
  2595. /// What the thread that lands flights fetches card copies' pieces with
  2596. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2597. /// behind the submission lock), and the memory the pieces come down to.
  2598. struct RelayFetch {
  2599. list: Prelude,
  2600. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2601. queue: Option<ID3D12CommandQueue>,
  2602. fence: ID3D12Fence,
  2603. event: HANDLE,
  2604. /// The last value signalled on `fence`.
  2605. sent: u64,
  2606. /// Buffer, mapping, bytes.
  2607. buffer: Option<(ID3D12Resource, usize, u64)>,
  2608. /// Pieces caught while a later flight was writing them.
  2609. suspects: torn::Suspects,
  2610. /// What earlier fetches brought of flights not landed yet.
  2611. had: crate::land::Had,
  2612. }
  2613. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2614. /// the first flights of the line it takes them, with what follows them,
  2615. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2616. /// the card, or for a flight. It takes neither the submission lock nor
  2617. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2618. /// lists and looking at what queues hold are left to [`late_helper`].
  2619. fn relay_worker() {
  2620. let Some(host) = host() else {
  2621. return;
  2622. };
  2623. // SAFETY: a plain event of our own.
  2624. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2625. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2626. };
  2627. let mut fetch: Option<RelayFetch> = None;
  2628. loop {
  2629. let next = {
  2630. let mut line = line();
  2631. loop {
  2632. if line.line.is_empty() {
  2633. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2634. continue;
  2635. }
  2636. let fences: Vec<Option<u64>> = line
  2637. .line
  2638. .iter()
  2639. .map(|l| match l {
  2640. Late::Run(flight) => Some(flight.fence),
  2641. _ => None,
  2642. })
  2643. .collect();
  2644. // SAFETY: a plain query.
  2645. let completed = unsafe { host.fence.GetCompletedValue() };
  2646. let n = landable(&fences, completed);
  2647. if n == 0 {
  2648. // The first thing is a flight the card has not run.
  2649. break Err(fences[0].unwrap_or(0));
  2650. }
  2651. line.settling = true;
  2652. let items: Vec<Late> = line.line.drain(..n).collect();
  2653. line.in_hand = items
  2654. .iter()
  2655. .filter_map(|l| match l {
  2656. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2657. _ => None,
  2658. })
  2659. .collect();
  2660. if card_steps::stage() > 0 {
  2661. line.landing = card_steps::writers(&items);
  2662. }
  2663. break Ok(items);
  2664. }
  2665. };
  2666. match next {
  2667. Ok(items) => host.relay_land(items, &mut fetch),
  2668. Err(target) => {
  2669. let waiting = std::time::Instant::now();
  2670. // SAFETY: the host's fence and this thread's event.
  2671. let waited = unsafe {
  2672. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2673. WaitForSingleObject(event, INFINITE);
  2674. })
  2675. };
  2676. if waited.is_err() {
  2677. std::thread::sleep(std::time::Duration::from_millis(1));
  2678. }
  2679. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2680. }
  2681. }
  2682. }
  2683. }
  2684. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2685. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2686. /// once, the pieces that differ found on several threads; but the merge is
  2687. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2688. /// are not done with here (each flight's are, afterwards). In two steps:
  2689. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  2690. /// which needs nothing that the fetch from the card's memory brings), and
  2691. /// the merge.
  2692. struct RelayBack {
  2693. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  2694. found: Option<Vec<Vec<(usize, usize)>>>,
  2695. }
  2696. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  2697. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2698. for (shadow, declared) in back {
  2699. if shadow.carded() {
  2700. continue;
  2701. }
  2702. let mut spans: Vec<(usize, usize)> = Vec::new();
  2703. join_ranges(&mut spans, declared.iter().copied());
  2704. for &(from, to) in &spans {
  2705. shadow.relay_compared(from, to - from);
  2706. }
  2707. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2708. }
  2709. RelayBack { work, found: None }
  2710. }
  2711. impl RelayBack {
  2712. /// Looks the ranges through, once; its time counts as `stat`.
  2713. fn look(&mut self, stat: usize) {
  2714. if self.work.is_empty() || self.found.is_some() {
  2715. return;
  2716. }
  2717. let scanning = std::time::Instant::now();
  2718. // Looked through without a lock: a piece that changes meanwhile (a
  2719. // later flight writing, the title's bytes going in) is found now or
  2720. // by that flight's landing, and the merge looks again under the
  2721. // lock.
  2722. self.found = Some(crate::shadow::find_all(&self.work));
  2723. crate::land::spent(stat, scanning);
  2724. #[cfg(feature = "diagnostics")]
  2725. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2726. }
  2727. /// What differs goes into title memory.
  2728. fn merge(mut self) {
  2729. use crate::land;
  2730. self.look(land::stat::SCAN);
  2731. let Some(found) = self.found else {
  2732. return;
  2733. };
  2734. let merging = std::time::Instant::now();
  2735. let mut written: Vec<u64> = Vec::new();
  2736. if land::on() {
  2737. // Pieces in the same block of title memory in one job, in order.
  2738. let pieces: Vec<(usize, usize, usize)> =
  2739. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  2740. let start = |i: usize| self.work[i].0.span().0 as usize;
  2741. let mut order: Vec<usize> = (0..pieces.len()).collect();
  2742. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  2743. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  2744. let jobs = land::jobs(&cut);
  2745. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  2746. land::each(jobs.len(), &|j| {
  2747. let working = std::time::Instant::now();
  2748. let mut notes = land::Notes::default();
  2749. for &p in &order[jobs[j].clone()] {
  2750. let (i, at, n) = pieces[p];
  2751. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  2752. }
  2753. notes.flush();
  2754. land::spent(land::stat::BACK_ALL, working);
  2755. });
  2756. land::count(land::stat::JOBS, jobs.len() as u64);
  2757. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  2758. } else {
  2759. let (mut now, mut title) = (Vec::new(), Vec::new());
  2760. for ((shadow, ..), found) in self.work.iter().zip(found) {
  2761. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  2762. written.push(found.into_iter().map(merge).sum());
  2763. }
  2764. }
  2765. land::spent(land::stat::BACK, merging);
  2766. for ((_, from, to), written) in self.work.iter().zip(written) {
  2767. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  2768. #[cfg(feature = "diagnostics")]
  2769. crate::copystat::compared(*from, to - from, written as usize);
  2770. let _ = (from, to);
  2771. }
  2772. }
  2773. }
  2774. /// For the frame-rate line, with [`late`]: what the line of flights did
  2775. /// per frame since the last one.
  2776. fn late_line(frames: f64) {
  2777. if !late() {
  2778. return;
  2779. }
  2780. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2781. tracing::info!(
  2782. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2783. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2784. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2785. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2786. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2787. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2788. s[0],
  2789. s[1],
  2790. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2791. s[12] / 1000.0,
  2792. s[WHY_SYNC],
  2793. s[WHY_CARD_DONE],
  2794. s[WHY_VALUE],
  2795. s[WHY_STALE],
  2796. s[WHY_READ],
  2797. s[15],
  2798. s[16],
  2799. s[17],
  2800. s[WHY_RUN],
  2801. late_most(),
  2802. s[WHY_MOST],
  2803. s[WHY_WRITES],
  2804. s[WHY_FENCE],
  2805. s[13],
  2806. s[14],
  2807. );
  2808. {
  2809. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2810. tracing::info!(
  2811. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2812. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2813. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2814. w[WHY_SYNC],
  2815. w[WHY_CARD_DONE],
  2816. w[WHY_VALUE],
  2817. w[WHY_STALE],
  2818. w[WHY_READ],
  2819. w[WHY_RUN],
  2820. w[WHY_MOST],
  2821. w[WHY_WRITES],
  2822. w[WHY_FENCE],
  2823. );
  2824. }
  2825. if relay() {
  2826. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2827. tracing::info!(
  2828. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2829. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2830. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2831. \"settles\" above are waits of other threads for it)",
  2832. r[1],
  2833. r[0],
  2834. r[2] / 1000.0,
  2835. r[3] / 1000.0,
  2836. r[4] / 1000.0,
  2837. );
  2838. if send::own() {
  2839. let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2840. tracing::info!(
  2841. "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
  2842. taking them out of the CPU sides",
  2843. t[0] / (1 << 20) as f64,
  2844. t[1],
  2845. t[2],
  2846. t[3] / 1000.0,
  2847. );
  2848. }
  2849. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2850. if t[0] > 0.0 {
  2851. tracing::info!(
  2852. "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",
  2853. t[0],
  2854. t[1],
  2855. t[2],
  2856. );
  2857. }
  2858. }
  2859. crate::land::log(frames);
  2860. card_steps::log(frames);
  2861. crate::picked::log(frames);
  2862. #[cfg(feature = "diagnostics")]
  2863. log_blame(frames);
  2864. if late_exact() {
  2865. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  2866. tracing::info!(
  2867. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  2868. {runs:.0} changed runs, {:.2} MB",
  2869. bytes / (1 << 20) as f64
  2870. );
  2871. }
  2872. }
  2873. mod card_steps;
  2874. mod send;
  2875. mod torn;
  2876. pub(crate) mod upcheck;
  2877. #[cfg(test)]
  2878. mod late_tests {
  2879. use super::{continues, join_ranges, touches};
  2880. /// Copies join only when both ends continue and the whole does not
  2881. /// overlap itself.
  2882. #[test]
  2883. fn copies_join_only_end_to_end_and_apart() {
  2884. // (destination, source, bytes)
  2885. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  2886. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  2887. // A gap, or only one side continues.
  2888. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  2889. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  2890. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  2891. // Together they would overlap: the second reads what the first wrote.
  2892. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  2893. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  2894. // They touch without overlapping.
  2895. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  2896. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  2897. }
  2898. /// Ranges are found by what they hold, not by where they start, and a
  2899. /// range that only touches another's end does not touch it.
  2900. #[test]
  2901. fn ranges_touch_where_they_overlap() {
  2902. let mut ranges = Vec::new();
  2903. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  2904. assert_eq!(ranges, [(10, 25), (40, 60)]);
  2905. join_ranges(&mut ranges, [(25, 40)]);
  2906. assert_eq!(ranges, [(10, 60)]);
  2907. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  2908. for (from, to, hit) in [
  2909. (0, 10, false),
  2910. (0, 11, true),
  2911. (24, 25, true),
  2912. (25, 40, false),
  2913. (25, 41, true),
  2914. (59, 200, true),
  2915. (60, 100, false),
  2916. (100, 101, true),
  2917. (101, 500, false),
  2918. (30, 30, false),
  2919. (50, 50, false),
  2920. ] {
  2921. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  2922. }
  2923. assert!(!touches(&[], 0, usize::MAX));
  2924. }
  2925. }
  2926. /// Whether a title buffer copy that continues the one recorded before it
  2927. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  2928. /// default).
  2929. ///
  2930. /// Each copy is done at submission through the kernel, which reports a
  2931. /// page that is not there instead of faulting (`copy_mapped`), tells the
  2932. /// write watch and the guards, and ends the refreshes gathered so far: a
  2933. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  2934. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  2935. /// continue the one before is counted either way and said on its own line
  2936. /// with the frame rate; the switch is worth that many kernel calls.
  2937. ///
  2938. /// Joined, the same bytes move: [`continues`] joins only copies whose
  2939. /// ranges, taken together, do not overlap, and nothing is recorded between
  2940. /// two steps that follow each other. What differs: a page that is not
  2941. /// mapped now fails the joined copy as a whole (it then goes page by page,
  2942. /// zeros for what cannot be read, as a single copy does), where before
  2943. /// only the copy that held it did.
  2944. fn join_copies() -> bool {
  2945. static ON: OnceLock<bool> = OnceLock::new();
  2946. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  2947. }
  2948. /// Since the last frame-rate line: title buffer copies recorded, and those
  2949. /// that continue the one before ([`join_copies`]).
  2950. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  2951. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  2952. /// where `last` ended, source and destination both, and the two as one do
  2953. /// not overlap (source over destination): then one copy of both moves the
  2954. /// bytes the two would move in turn.
  2955. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  2956. let ((d, s, n), (dst, src, len)) = (last, next);
  2957. let Some(all) = n.checked_add(len) else {
  2958. return false;
  2959. };
  2960. d.checked_add(n) == Some(dst)
  2961. && s.checked_add(n) == Some(src)
  2962. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  2963. }
  2964. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  2965. /// One list's lock at a time: a submission may name a list twice.
  2966. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  2967. let mut back: Vec<Declared> = Vec::new();
  2968. // Where each copy is in it, and the ranges seen: dispatches declare the
  2969. // same ranges thousands of times a frame.
  2970. let mut places: ByCopy<usize> = ByCopy::default();
  2971. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  2972. for list in runs {
  2973. for step in &list.deferred().copies {
  2974. if let Step::GpuWrite(shadow, address, len) = step {
  2975. let key = std::sync::Arc::as_ptr(shadow) as usize;
  2976. if !seen.insert((key, *address, *len)) {
  2977. continue;
  2978. }
  2979. let i = *places.entry(key).or_insert_with(|| {
  2980. back.push((shadow.clone(), Vec::new()));
  2981. back.len() - 1
  2982. });
  2983. back[i].1.push((*address, *address + *len));
  2984. }
  2985. }
  2986. }
  2987. back
  2988. }
  2989. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  2990. /// lines that say what the title's CPU was given while it decided whether
  2991. /// the camera is in a room. The values of the small read-backs
  2992. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  2993. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  2994. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  2995. /// copies found stale after their refresh (`shadow.rs`; only with
  2996. /// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
  2997. /// runtime, the read requests that fail (with 2: every request).
  2998. pub(crate) fn walls_trace() -> bool {
  2999. static ON: OnceLock<bool> = OnceLock::new();
  3000. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  3001. }
  3002. /// After `list` has run: the texels its read-backs copied into host
  3003. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  3004. ///
  3005. /// A submission that is waited for did this itself. One sent ahead
  3006. /// ([`late`]) did not, at any stage: the flights' lists were settled
  3007. /// without it, so the title read a buffer nobody wrote, as before read-backs
  3008. /// were made (the exposure metering's two small float targets, every frame).
  3009. fn read_backs(list: &HostList) {
  3010. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  3011. let mut data = std::ptr::null_mut();
  3012. // SAFETY: a read-back buffer of ours, written by the list that has
  3013. // run; the title's destination holds every row (checked when the
  3014. // copy was recorded).
  3015. unsafe {
  3016. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  3017. let from = data.cast::<u8>().cast_const();
  3018. for line in 0..*rows {
  3019. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  3020. }
  3021. // The walls trace: what the title is handed (one row of at
  3022. // most 24 values: its 5x1 and 1x1 float targets).
  3023. if walls_trace() && *rows == 1 && *row <= 96 {
  3024. let mut values = [0f32; 24];
  3025. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  3026. tracing::info!(
  3027. frame = crate::frame::current(),
  3028. to = format_args!("{:#x}", *at),
  3029. bytes = *row,
  3030. values = ?&values[..*row / 4],
  3031. "walls trace: a read-back lands in title memory"
  3032. );
  3033. }
  3034. buffer.Unmap(0, None);
  3035. }
  3036. }
  3037. }
  3038. }
  3039. /// After the card ran what declared `back`: what shaders wrote there goes
  3040. /// into title memory, and the ranges are done with.
  3041. fn hand_back(back: &[Declared]) {
  3042. if crate::shadow::wide_back() {
  3043. // Every range first (the pieces that differ, found on several
  3044. // threads), then the merges, in order, as below.
  3045. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3046. for (shadow, declared) in back {
  3047. if shadow.carded() {
  3048. continue;
  3049. }
  3050. let mut sorted = declared.clone();
  3051. sorted.sort_unstable();
  3052. let mut spans: Vec<(usize, usize)> = Vec::new();
  3053. for (from, to) in sorted {
  3054. match spans.last_mut() {
  3055. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3056. _ => spans.push((from, to)),
  3057. }
  3058. }
  3059. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3060. }
  3061. #[cfg(feature = "diagnostics")]
  3062. let scanning = std::time::Instant::now();
  3063. let found = crate::shadow::find_all(&work);
  3064. #[cfg(feature = "diagnostics")]
  3065. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3066. for ((shadow, from, to), found) in work.iter().zip(found) {
  3067. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3068. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3069. #[cfg(feature = "diagnostics")]
  3070. crate::copystat::compared(*from, to - from, written);
  3071. }
  3072. for (shadow, declared) in back {
  3073. shadow.copy_back_done(declared);
  3074. }
  3075. return;
  3076. }
  3077. for (shadow, declared) in back {
  3078. if shadow.carded() {
  3079. // Done before (`Host::card_back`).
  3080. shadow.copy_back_done(declared);
  3081. continue;
  3082. }
  3083. // Each byte compared once: the world declares dozens of views
  3084. // of its 174 MB heap that overlap almost entirely, and comparing
  3085. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3086. // MB shaders wrote. Only ranges that overlap or touch are
  3087. // joined: what lies between two was not given to shaders (the
  3088. // snapshot does not hold it).
  3089. let mut sorted = declared.clone();
  3090. sorted.sort_unstable();
  3091. let mut spans: Vec<(usize, usize)> = Vec::new();
  3092. for (from, to) in sorted {
  3093. match spans.last_mut() {
  3094. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3095. _ => spans.push((from, to)),
  3096. }
  3097. }
  3098. for (from, to) in spans {
  3099. let written = shadow.copy_back(from, to - from);
  3100. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3101. #[cfg(feature = "diagnostics")]
  3102. crate::copystat::compared(from, to - from, written);
  3103. }
  3104. shadow.copy_back_done(declared);
  3105. }
  3106. }
  3107. impl Host {
  3108. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3109. /// mesh shaders need both); logged once.
  3110. pub(crate) fn mesh_shaders(&self) -> bool {
  3111. static MESH: OnceLock<bool> = OnceLock::new();
  3112. *MESH.get_or_init(|| {
  3113. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3114. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3115. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3116. };
  3117. // SAFETY: each query writes its own structure of the given size.
  3118. let ok = unsafe {
  3119. self.device
  3120. .CheckFeatureSupport(
  3121. D3D12_FEATURE_D3D12_OPTIONS7,
  3122. (&raw mut options).cast(),
  3123. size_of_val(&options) as u32,
  3124. )
  3125. .is_ok()
  3126. && self
  3127. .device
  3128. .CheckFeatureSupport(
  3129. D3D12_FEATURE_SHADER_MODEL,
  3130. (&raw mut model).cast(),
  3131. size_of_val(&model) as u32,
  3132. )
  3133. .is_ok()
  3134. };
  3135. let mesh = ok
  3136. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3137. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3138. tracing::info!(mesh, "host mesh shader support");
  3139. mesh
  3140. })
  3141. }
  3142. /// Whether the host GPU supports the depth bounds test; logged once.
  3143. pub(crate) fn depth_bounds(&self) -> bool {
  3144. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3145. *BOUNDS.get_or_init(|| {
  3146. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3147. // SAFETY: writes `options` of the given size.
  3148. let ok = unsafe {
  3149. self.device
  3150. .CheckFeatureSupport(
  3151. D3D12_FEATURE_D3D12_OPTIONS2,
  3152. (&raw mut options).cast(),
  3153. size_of_val(&options) as u32,
  3154. )
  3155. .is_ok()
  3156. };
  3157. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3158. tracing::info!(supported, "host depth bounds support");
  3159. supported
  3160. })
  3161. }
  3162. /// A new list, open for recording.
  3163. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3164. #[cfg(feature = "diagnostics")]
  3165. let started = std::time::Instant::now();
  3166. #[cfg(feature = "diagnostics")]
  3167. let before = private_bytes();
  3168. let list = self.make_list();
  3169. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3170. // (May shrink while a list is made, on another thread's account:
  3171. // added as it is, the sum is what counts.)
  3172. #[cfg(feature = "diagnostics")]
  3173. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3174. #[cfg(feature = "diagnostics")]
  3175. {
  3176. use crate::copystat::{C, add};
  3177. add(C::HostLists, 1);
  3178. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3179. }
  3180. list
  3181. }
  3182. /// An allocator and a closed list for a prelude.
  3183. fn make_prelude(&self) -> Option<Prelude> {
  3184. // SAFETY: plain object creation.
  3185. let made: windows::core::Result<Prelude> = unsafe {
  3186. (|| {
  3187. let allocator: ID3D12CommandAllocator =
  3188. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3189. let list: ID3D12GraphicsCommandList =
  3190. self.device
  3191. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3192. list.Close()?;
  3193. Ok((allocator, list))
  3194. })()
  3195. };
  3196. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3197. match made {
  3198. Ok(prelude) => Some(prelude),
  3199. Err(e) => {
  3200. tracing::warn!(error = %e, "no host list for a prelude");
  3201. None
  3202. }
  3203. }
  3204. }
  3205. fn make_list(&self) -> windows::core::Result<HostList> {
  3206. // SAFETY: plain object creation.
  3207. unsafe {
  3208. let allocator: ID3D12CommandAllocator = self
  3209. .device
  3210. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3211. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3212. 0,
  3213. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3214. &allocator,
  3215. None,
  3216. )?;
  3217. let prelude = OnceLock::new();
  3218. if !lazy_prelude() {
  3219. let _ = prelude.set(self.make_prelude());
  3220. }
  3221. Ok(HostList {
  3222. allocator,
  3223. list,
  3224. deferred: Mutex::default(),
  3225. scratch: Mutex::default(),
  3226. states: Mutex::default(),
  3227. twins: Mutex::default(),
  3228. prelude,
  3229. pipelines: Mutex::default(),
  3230. budget: OnceLock::new(),
  3231. card_budget: OnceLock::new(),
  3232. indirect_args: Mutex::default(),
  3233. batch_args: Mutex::default(),
  3234. _alive: Counted::new(),
  3235. #[cfg(feature = "diagnostics")]
  3236. notes: Mutex::default(),
  3237. #[cfg(feature = "diagnostics")]
  3238. stamps: OnceLock::new(),
  3239. })
  3240. }
  3241. }
  3242. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3243. fn card_clock(&self) -> Option<&'static CardClock> {
  3244. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3245. static WATCH: std::sync::Once = std::sync::Once::new();
  3246. let clock = CLOCK
  3247. .get_or_init(|| {
  3248. // SAFETY: a plain fence on our device.
  3249. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3250. Some(CardClock {
  3251. fence,
  3252. state: Mutex::new((0, None)),
  3253. sent: std::sync::Condvar::new(),
  3254. })
  3255. })
  3256. .as_ref()?;
  3257. WATCH.call_once(|| {
  3258. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3259. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3260. }
  3261. });
  3262. Some(clock)
  3263. }
  3264. /// Lists of ours just went to the queue: the clock's signal goes
  3265. /// behind them, and an idle stretch of the card, if one was under way,
  3266. /// ends here ([`CARD_CLOCK_US`]).
  3267. fn card_sent(&self) {
  3268. let Some(clock) = self.card_clock() else {
  3269. return;
  3270. };
  3271. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3272. state.0 += 1;
  3273. // SAFETY: our queue and the clock's fence.
  3274. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3275. if let Some((since, worked_then)) = state.1.take() {
  3276. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3277. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3278. }
  3279. drop(state);
  3280. clock.sent.notify_one();
  3281. }
  3282. /// Whether the host has what copies in the card's memory need (three
  3283. /// lists and the compare); made at the first ask. A copy goes to the
  3284. /// card's memory only if it has.
  3285. pub(crate) fn card_ready(&self) -> bool {
  3286. static READY: OnceLock<bool> = OnceLock::new();
  3287. *READY.get_or_init(|| match self.make_card_work() {
  3288. Ok(work) => {
  3289. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3290. true
  3291. }
  3292. Err(e) => {
  3293. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3294. false
  3295. }
  3296. })
  3297. }
  3298. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3299. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3300. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3301. let mut code: Option<ID3DBlob> = None;
  3302. // SAFETY: the source and names live through the call; the out
  3303. // pointer is ours.
  3304. unsafe {
  3305. D3DCompile(
  3306. CARD_COMPARE.as_ptr().cast(),
  3307. CARD_COMPARE.len(),
  3308. windows::core::s!("card compare"),
  3309. None,
  3310. None,
  3311. windows::core::s!("main"),
  3312. windows::core::s!("cs_5_1"),
  3313. 0,
  3314. 0,
  3315. &mut code,
  3316. None,
  3317. )?;
  3318. }
  3319. let code = code.ok_or_else(windows::core::Error::empty)?;
  3320. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3321. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3322. // in one submission.
  3323. const RESULTS: u64 = 1 << 20;
  3324. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3325. name(&differs, || "card compare results".into());
  3326. // SAFETY: the blob's own bytes; the root signature is inside the
  3327. // shader.
  3328. unsafe {
  3329. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3330. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3331. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3332. pRootSignature: std::mem::transmute_copy(&root),
  3333. CS: D3D12_SHADER_BYTECODE {
  3334. pShaderBytecode: bytes.as_ptr().cast(),
  3335. BytecodeLength: bytes.len(),
  3336. },
  3337. ..Default::default()
  3338. })?;
  3339. #[cfg(feature = "diagnostics")]
  3340. name(&pso, || crate::replay::play::COMPARE.into());
  3341. Ok(CardWork {
  3342. sync: vec![list()?],
  3343. check: vec![list()?],
  3344. fetch: list()?,
  3345. root,
  3346. pso,
  3347. differs: (differs, data as usize, RESULTS),
  3348. fetched: None,
  3349. taken: 0,
  3350. out: 0,
  3351. })
  3352. }
  3353. }
  3354. /// Before a submission's lists run, for copies in the card's memory
  3355. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3356. /// the last submission goes to their card side (a list of ours, run
  3357. /// now; the submission's lists follow it on the queue), and the ranges
  3358. /// this submission's shaders may write get a compare to run after its
  3359. /// lists. `None` if there is nothing to do.
  3360. ///
  3361. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3362. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3363. /// `relay`).
  3364. /// `picked`: ranges that may be written too, and ranges to look at
  3365. /// (`crate::picked`).
  3366. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3367. use std::sync::Arc;
  3368. if !crate::shadow::cards() {
  3369. return None;
  3370. }
  3371. // The ranges this submission's shaders may write, per copy.
  3372. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3373. for list in runs {
  3374. for step in &list.deferred().copies {
  3375. if let Step::GpuWrite(shadow, address, len) = step
  3376. && shadow.carded()
  3377. {
  3378. let range = (*address, *address + *len);
  3379. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3380. Some((_, ranges)) => {
  3381. if !ranges.contains(&range) {
  3382. ranges.push(range);
  3383. }
  3384. }
  3385. None => declared.push((shadow.clone(), vec![range])),
  3386. }
  3387. }
  3388. }
  3389. }
  3390. let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
  3391. // (Of a copy with a declared range here, that says it.)
  3392. let looked: Vec<&crate::picked::Range> =
  3393. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3394. // With the relay: the order of the queue is held from here until
  3395. // what is taken is on the queue, and the taking is numbered.
  3396. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3397. let sent_as = match order.as_mut() {
  3398. Some(order) => {
  3399. **order += 1;
  3400. **order
  3401. }
  3402. None => 0,
  3403. };
  3404. let mut dirty = crate::shadow::card_dirty(sent_as);
  3405. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3406. return None;
  3407. }
  3408. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3409. let work = work.as_mut()?;
  3410. // A copy whose shader writes are declared for the first time gets
  3411. // its bytes from before, whole.
  3412. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3413. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3414. if shadow.card_make_before(|size| {
  3415. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3416. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3417. Some(before)
  3418. }) {
  3419. whole.push(shadow.clone());
  3420. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3421. dirty.push((shadow.clone(), Vec::new()));
  3422. }
  3423. }
  3424. }
  3425. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3426. let mut looks = None;
  3427. // The bytes as they are now, whatever later submissions put there.
  3428. let own = if send::own() { send::take(self, &dirty) } else { None };
  3429. if !dirty.is_empty() {
  3430. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3431. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3432. };
  3433. let (allocator, list) = &sync;
  3434. // SAFETY: the list's last run finished (it ran ahead of a
  3435. // submission that was waited for, and came back after that);
  3436. // live buffers, and the ranges lie in them.
  3437. let recorded = unsafe {
  3438. (|| -> windows::core::Result<()> {
  3439. allocator.Reset()?;
  3440. list.Reset(allocator, None)?;
  3441. if upcheck::on() {
  3442. looks = upcheck::record(self, list, &dirty);
  3443. }
  3444. // Every copy first, then one barrier call, then every
  3445. // pass: a wait between each copy and its pass had the
  3446. // card do them one after the other.
  3447. let mut sent = Vec::new();
  3448. if let Some(own) = &own {
  3449. own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
  3450. }
  3451. for (shadow, ranges) in &dirty {
  3452. let Some((staging, before, _)) = shadow.card_sides() else {
  3453. continue;
  3454. };
  3455. for &(a, b) in ranges {
  3456. if own.is_none() {
  3457. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3458. }
  3459. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3460. }
  3461. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3462. if own.is_none() && before.is_some() && !ranges.is_empty() {
  3463. sent.push(transition(
  3464. &shadow.buffer,
  3465. D3D12_RESOURCE_STATE_COPY_DEST,
  3466. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3467. ));
  3468. }
  3469. }
  3470. if !sent.is_empty() {
  3471. list.ResourceBarrier(&sent);
  3472. }
  3473. list.SetComputeRootSignature(&work.root);
  3474. list.SetPipelineState(&work.pso);
  3475. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3476. for (shadow, ranges) in &dirty {
  3477. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3478. continue;
  3479. };
  3480. // No twin (it cost the card the copy's size again,
  3481. // 399 MB in run 75): `before` holds a 128-bit hash
  3482. // of each 64 KiB piece. The pieces just sent up are
  3483. // hashed again, all of them the first time; the
  3484. // compare after the lists hashes the declared
  3485. // pieces and flags those whose hash is another.
  3486. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3487. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3488. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3489. vec![shadow.card_run(0, usize::MAX)]
  3490. } else {
  3491. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3492. };
  3493. // The same pieces in fewer passes (`rehash_runs`).
  3494. let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3495. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3496. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3497. for run in runs {
  3498. card_pass(list, &run, size as u32, 0, 0);
  3499. }
  3500. }
  3501. list.Close()?;
  3502. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3503. Ok(())
  3504. })()
  3505. };
  3506. if let Err(e) = recorded {
  3507. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3508. }
  3509. used.push((false, sync));
  3510. }
  3511. drop(order);
  3512. let mut plan = CardPlan {
  3513. ranges: Vec::new(),
  3514. check: None,
  3515. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3516. lists: used,
  3517. sent_as,
  3518. looks,
  3519. sends: own.map(send::Own::memory),
  3520. };
  3521. // Each byte once, as the copy-back joins the declared ranges. The
  3522. // results go behind those of plans still in the air.
  3523. let mut at = work.taken;
  3524. for (shadow, ranges) in &declared {
  3525. let mut sorted = ranges.clone();
  3526. sorted.sort_unstable();
  3527. let mut spans: Vec<(usize, usize)> = Vec::new();
  3528. for (from, to) in sorted {
  3529. match spans.last_mut() {
  3530. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3531. _ => spans.push((from, to)),
  3532. }
  3533. }
  3534. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3535. for (from, to) in spans {
  3536. let Some(span) = shadow.card_span(from, to) else {
  3537. continue;
  3538. };
  3539. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3540. plan.ranges.push(CardRange {
  3541. shadow: shadow.clone(),
  3542. declared: (from, to),
  3543. span,
  3544. at,
  3545. compared,
  3546. picked: false,
  3547. });
  3548. if compared {
  3549. at += span.pieces;
  3550. }
  3551. }
  3552. }
  3553. for (shadow, from, len) in looked {
  3554. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3555. if let Some(span) = shadow.card_span(*from, from + len)
  3556. && twin
  3557. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3558. {
  3559. plan.ranges.push(CardRange {
  3560. shadow: shadow.clone(),
  3561. declared: (*from, from + len),
  3562. span,
  3563. at,
  3564. compared: true,
  3565. picked: true,
  3566. });
  3567. at += span.pieces;
  3568. }
  3569. }
  3570. work.taken = at;
  3571. if plan.ranges.iter().any(|r| r.compared) {
  3572. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3573. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3574. };
  3575. let (allocator, list) = &check;
  3576. // SAFETY: the list's last run finished (its submission was
  3577. // waited for, and it came back after that); live buffers; the
  3578. // compare's own root signature.
  3579. let recorded = unsafe {
  3580. (|| -> windows::core::Result<ID3D12CommandList> {
  3581. allocator.Reset()?;
  3582. list.Reset(allocator, None)?;
  3583. // What the submission's shaders wrote, first.
  3584. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3585. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3586. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3587. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3588. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3589. pResource: std::mem::ManuallyDrop::new(None),
  3590. }),
  3591. },
  3592. }]);
  3593. list.SetComputeRootSignature(&work.root);
  3594. list.SetPipelineState(&work.pso);
  3595. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3596. for r in plan.ranges.iter().filter(|r| r.compared) {
  3597. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3598. continue;
  3599. };
  3600. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3601. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3602. // (What is only looked at keeps its hashes: what
  3603. // changed there is the next declared range's to land.)
  3604. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  3605. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3606. }
  3607. list.Close()?;
  3608. list.cast()
  3609. })()
  3610. };
  3611. match recorded {
  3612. Ok(list) => plan.check = Some(list),
  3613. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3614. }
  3615. plan.lists.push((true, check));
  3616. }
  3617. work.out += 1;
  3618. Some(plan)
  3619. }
  3620. /// With [`relay`]: whether the compare's result area is half taken by
  3621. /// plans in the air. It starts from the beginning only when no plan is
  3622. /// out, so the caller lets the flights land first.
  3623. fn card_results_low(&self) -> bool {
  3624. CARD_WORK
  3625. .lock()
  3626. .unwrap_or_else(|e| e.into_inner())
  3627. .as_ref()
  3628. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3629. }
  3630. /// The plan's submission has run and its results were read
  3631. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3632. /// when nothing of ours is on the card, so the compare's results start
  3633. /// from the beginning again.
  3634. fn card_done(&self, plan: CardPlan) {
  3635. if let Some(looks) = plan.looks {
  3636. looks.read();
  3637. }
  3638. if let Some(memory) = plan.sends {
  3639. send::give_back(memory);
  3640. }
  3641. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3642. let Some(work) = work.as_mut() else {
  3643. return;
  3644. };
  3645. for (check, list) in plan.lists {
  3646. if check { work.check.push(list) } else { work.sync.push(list) }
  3647. }
  3648. work.out = work.out.saturating_sub(1);
  3649. // With the relay other plans may be on the card, their results
  3650. // not read yet: the area starts again only when none is out.
  3651. if !relay() || work.out == 0 {
  3652. work.taken = 0;
  3653. }
  3654. }
  3655. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3656. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3657. // SAFETY: plain object creation.
  3658. let copying = relay_copy().then(|| unsafe {
  3659. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3660. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3661. let list: ID3D12GraphicsCommandList =
  3662. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3663. list.Close()?;
  3664. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3665. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3666. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3667. ..Default::default()
  3668. })?;
  3669. Ok(((allocator, list), queue))
  3670. })()
  3671. });
  3672. let (list, queue) = match copying {
  3673. Some(Ok((list, queue))) => (list, Some(queue)),
  3674. Some(Err(e)) => {
  3675. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3676. (self.make_prelude()?, None)
  3677. }
  3678. None => (self.make_prelude()?, None),
  3679. };
  3680. // SAFETY: plain objects of our own.
  3681. unsafe {
  3682. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3683. let event = CreateEventW(None, false, false, None).ok()?;
  3684. Some(RelayFetch {
  3685. list,
  3686. queue,
  3687. fence,
  3688. event,
  3689. sent: 0,
  3690. buffer: None,
  3691. suspects: torn::Suspects::default(),
  3692. had: crate::land::Had::default(),
  3693. })
  3694. }
  3695. }
  3696. /// [`relay`], on the thread that lands flights: for the plans of the
  3697. /// flights being landed (the card has run them), the pieces their
  3698. /// compares flagged are fetched, once each, with a list and a wait of
  3699. /// this thread's own, and what shaders wrote in them goes into title
  3700. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3701. /// no submission lock; a piece flagged under one range of a plan is
  3702. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3703. /// whatever was sent meanwhile, so it may bring a later flight's
  3704. /// bytes, which that flight's landing then finds merged already; and
  3705. /// nothing is sent back up. `plans` come with the value signalled behind
  3706. /// their flight. `meanwhile` is called while the fetch is on its way, if
  3707. /// there is one.
  3708. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  3709. use crate::land;
  3710. let gathering = std::time::Instant::now();
  3711. let differs = {
  3712. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3713. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3714. };
  3715. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3716. let mut total = 0u64;
  3717. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  3718. fetch.had.landing(first);
  3719. }
  3720. // SAFETY: the mapping of the results. The compares of these plans
  3721. // have run, and their dwords are given to no other plan before these
  3722. // are done with (`card_done`).
  3723. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  3724. if let Some(differs) = differs {
  3725. // Pieces caught while a later flight was at them (`torn`).
  3726. let suspects = fetch.as_ref().map(|f| &f.suspects);
  3727. let mut seen = std::collections::HashSet::new();
  3728. for &(plan, behind) in plans {
  3729. plan.picked_found(differs);
  3730. let flags: Vec<(usize, u32, bool)> = plan
  3731. .ranges
  3732. .iter()
  3733. .filter(|r| !r.picked)
  3734. .flat_map(|r| {
  3735. (0..r.span.pieces).map(move |p| {
  3736. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  3737. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  3738. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  3739. })
  3740. })
  3741. .collect();
  3742. let fetched = flagged_pieces(&flags);
  3743. for r in plan.ranges.iter().filter(|r| !r.picked) {
  3744. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3745. if upcheck::on() {
  3746. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  3747. }
  3748. for p in 0..r.span.pieces {
  3749. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  3750. continue;
  3751. }
  3752. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3753. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  3754. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  3755. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  3756. land::count(land::stat::HAD, 1);
  3757. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  3758. if land::skip_on() {
  3759. continue;
  3760. }
  3761. }
  3762. if upcheck::on() {
  3763. upcheck::fetched(r.shadow.id(), lo);
  3764. }
  3765. seen.insert((copy, lo, hi));
  3766. pieces.push((r.shadow.clone(), lo, hi, total));
  3767. total += (hi - lo) as u64;
  3768. }
  3769. }
  3770. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3771. }
  3772. }
  3773. }
  3774. if land::on() {
  3775. // In the order they are landed, each byte of a copy once.
  3776. let keys: Vec<land::Piece> =
  3777. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  3778. total = 0;
  3779. pieces = land::ordered(&keys)
  3780. .into_iter()
  3781. .map(|(i, title, len)| {
  3782. let shadow = &pieces[i].0;
  3783. let lo = title - shadow.span().0 as usize;
  3784. let at = total;
  3785. total += len as u64;
  3786. (shadow.clone(), lo, lo + len, at)
  3787. })
  3788. .collect();
  3789. }
  3790. land::spent(land::stat::GATHER, gathering);
  3791. if fetch.is_none() {
  3792. *fetch = self.make_relay_fetch();
  3793. }
  3794. // On the copy queue a later flight may be at a piece while it is
  3795. // fetched: the pieces come down whole, to be hashed.
  3796. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  3797. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  3798. if let Some(check) = &check {
  3799. total = check.total;
  3800. }
  3801. // The sends these flights ran behind, all a fetch on the copy queue
  3802. // is known to have run behind.
  3803. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  3804. if pieces.is_empty() {
  3805. // Nothing to fetch: every send so far is older than the next
  3806. // fetch, if that goes to the queue the sends went to.
  3807. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  3808. true => behind,
  3809. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  3810. };
  3811. crate::shadow::relay_fetched(after);
  3812. return;
  3813. }
  3814. let Some(f) = fetch.as_mut() else {
  3815. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  3816. };
  3817. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  3818. let size = total.next_multiple_of(16 << 20);
  3819. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3820. }
  3821. let Some((buffer, data, _)) = f.buffer.clone() else {
  3822. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  3823. };
  3824. f.sent += 1;
  3825. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  3826. let copy_queue = f.queue.clone();
  3827. let waiting = std::time::Instant::now();
  3828. // The flights the fetch runs behind: those in the line by now have
  3829. // been given to the queue. On the copy queue, those landed here.
  3830. let ahead = match copy_queue {
  3831. Some(_) => 0,
  3832. None => line().target,
  3833. };
  3834. // SAFETY: the list's last run was waited for by this thread; live
  3835. // buffers (the copies are held by the plans); the fence and the
  3836. // event are this thread's.
  3837. let ran = unsafe {
  3838. (|| -> windows::core::Result<u64> {
  3839. allocator.Reset()?;
  3840. list.Reset(&allocator, None)?;
  3841. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  3842. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  3843. }
  3844. list.Close()?;
  3845. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  3846. if let Some(queue) = &copy_queue {
  3847. queue.ExecuteCommandLists(&lists);
  3848. queue.Signal(&fence, sent)?;
  3849. meanwhile();
  3850. fence.SetEventOnCompletion(sent, event)?;
  3851. WaitForSingleObject(event, INFINITE);
  3852. return Ok(behind);
  3853. }
  3854. // In the order of the queue: the sends of title bytes so
  3855. // far are ahead of this fetch, every later one behind it.
  3856. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  3857. self.queue.ExecuteCommandLists(&lists);
  3858. let after = *order;
  3859. drop(order);
  3860. self.card_sent();
  3861. self.queue.Signal(&fence, sent)?;
  3862. meanwhile();
  3863. fence.SetEventOnCompletion(sent, event)?;
  3864. WaitForSingleObject(event, INFINITE);
  3865. Ok(after)
  3866. })()
  3867. };
  3868. let after = match ran {
  3869. Ok(after) => after,
  3870. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  3871. };
  3872. let us = waiting.elapsed().as_micros() as u64;
  3873. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  3874. {
  3875. use crate::shadow::CARD_STATS;
  3876. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  3877. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  3878. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  3879. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  3880. }
  3881. let merging = std::time::Instant::now();
  3882. let mut written = 0;
  3883. if land::on() {
  3884. let titles: Vec<(usize, usize)> =
  3885. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  3886. let jobs = land::jobs(&titles);
  3887. let put = std::sync::atomic::AtomicU64::new(0);
  3888. land::each(jobs.len(), &|j| {
  3889. let working = std::time::Instant::now();
  3890. if let Some(check) = &check {
  3891. for i in jobs[j].clone() {
  3892. // SAFETY: as below.
  3893. unsafe { check.look(i, data) };
  3894. }
  3895. }
  3896. let mut notes = land::Notes::default();
  3897. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  3898. let addressed: Vec<(usize, usize, usize)> =
  3899. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  3900. // SAFETY: the mapping of the fetched bytes, `total` of
  3901. // them; the copy into it has run, and the next waits
  3902. // for this call.
  3903. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  3904. }
  3905. notes.flush();
  3906. land::spent(land::stat::CARD_ALL, working);
  3907. });
  3908. land::count(land::stat::JOBS, jobs.len() as u64);
  3909. written = put.into_inner();
  3910. } else {
  3911. let mut title = Vec::new();
  3912. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  3913. if let Some(check) = &check {
  3914. // SAFETY: as below.
  3915. unsafe { check.look(i, data) };
  3916. }
  3917. // SAFETY: the mapping of the fetched bytes, `total` of them;
  3918. // the copy into it has run.
  3919. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  3920. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  3921. shadow.walls_merged(gpu.len(), merged);
  3922. written += merged as u64;
  3923. }
  3924. }
  3925. land::spent(land::stat::CARD, merging);
  3926. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  3927. if let Some(f) = fetch.as_mut() {
  3928. if let Some(check) = &check {
  3929. check.done(&mut f.suspects);
  3930. }
  3931. f.had.fetched(
  3932. ahead,
  3933. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  3934. );
  3935. }
  3936. // Sends up to `after` are of no use to any later merge.
  3937. crate::shadow::relay_fetched(after);
  3938. }
  3939. /// [`relay`], on the thread that lands flights: `items` are the first
  3940. /// things of the line, flights the card has run and what follows them.
  3941. /// What their shaders wrote goes into title memory (copies in the
  3942. /// card's memory first, then the others, each byte once whichever
  3943. /// flights declared it); then every flight's ranges are done with;
  3944. /// then, in the line's order, each flight's read-backs, its
  3945. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  3946. /// is complete before the title is told anything.
  3947. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  3948. let landing = std::time::Instant::now();
  3949. {
  3950. let flights: Vec<&Flight> = items
  3951. .iter()
  3952. .filter_map(|l| match l {
  3953. Late::Run(flight) => Some(flight),
  3954. _ => None,
  3955. })
  3956. .collect();
  3957. if !flights.is_empty() {
  3958. // SAFETY: a plain query.
  3959. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  3960. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  3961. fail(format_args!(
  3962. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  3963. flights.len(),
  3964. runs.len(),
  3965. self.removal_data(&runs),
  3966. last_notes(&runs)
  3967. ));
  3968. }
  3969. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  3970. // (Each byte once: the ranges are joined.)
  3971. let mut back: Vec<Declared> = Vec::new();
  3972. for flight in &flights {
  3973. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  3974. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  3975. Some((_, all)) => all.extend_from_slice(ranges),
  3976. None => back.push((shadow.clone(), ranges.clone())),
  3977. }
  3978. }
  3979. }
  3980. let mut hand_back = relay_hand_back(&back);
  3981. self.relay_card_back(&plans, fetch, &mut || {
  3982. if crate::land::on() {
  3983. hand_back.look(crate::land::stat::SCAN_BESIDE);
  3984. }
  3985. });
  3986. hand_back.merge();
  3987. let finishing = std::time::Instant::now();
  3988. // Only now, and flight by flight: a range another flight
  3989. // in the air declared too stays closed to refreshes.
  3990. for flight in &flights {
  3991. for (shadow, ranges) in &flight.back {
  3992. shadow.copy_back_done(ranges);
  3993. }
  3994. }
  3995. crate::land::spent(crate::land::stat::DONE, finishing);
  3996. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  3997. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  3998. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  3999. }
  4000. }
  4001. // In the order given: what tells the title the card is done.
  4002. let mut last = 0;
  4003. let mut landed = Vec::new();
  4004. let mut telling = std::time::Instant::now();
  4005. for item in items {
  4006. telling = match item {
  4007. Late::Run(flight) => {
  4008. last = flight.number;
  4009. for &i in &flight.order {
  4010. read_backs(flight.lists[i].host());
  4011. }
  4012. if let Some(card) = flight.card {
  4013. self.card_done(card);
  4014. }
  4015. if let Some(own) = flight.own {
  4016. own.landed();
  4017. }
  4018. landed.push((flight.lists, flight.order));
  4019. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  4020. }
  4021. Late::Write(at, what, bytes) => {
  4022. what.write(at as *mut u8, bytes);
  4023. crate::land::spent(crate::land::stat::TOLD, telling)
  4024. }
  4025. Late::Signal(fence, value) => {
  4026. crate::fence::set(fence as crate::object::This, value);
  4027. crate::land::spent(crate::land::stat::TOLD, telling)
  4028. }
  4029. };
  4030. }
  4031. if last > 0 {
  4032. FINISHED.store(last, Ordering::Release);
  4033. bury(last);
  4034. }
  4035. self.log_messages();
  4036. crate::land::spent(crate::land::stat::REST, telling);
  4037. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4038. {
  4039. let mut line = line();
  4040. let Line {
  4041. line: items,
  4042. written,
  4043. lists,
  4044. settling,
  4045. poke,
  4046. landed: kept,
  4047. in_hand,
  4048. landing,
  4049. ..
  4050. } = &mut *line;
  4051. kept.extend(landed);
  4052. in_hand.clear();
  4053. landing.clear();
  4054. // What is still in the air, from the flights that are.
  4055. written.clear();
  4056. *lists = 0;
  4057. let mut ranges = Vec::new();
  4058. for item in items.iter() {
  4059. if let Late::Run(flight) = item {
  4060. *lists += flight.order.len().max(1);
  4061. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  4062. }
  4063. }
  4064. join_ranges(written, ranges);
  4065. *settling = false;
  4066. // The landed lists are reset, and what queues hold looked at,
  4067. // by the helper thread (they take locks a waiter may hold).
  4068. *poke = true;
  4069. }
  4070. LINE_MOVED.notify_all();
  4071. LINE_LANDED.notify_all();
  4072. }
  4073. /// After a submission ran, for copies in the card's memory: the pieces
  4074. /// of the declared ranges that the compare found differing (all of a
  4075. /// range it did not compare) are fetched, with one more wait for the
  4076. /// card, and what shaders wrote in them goes into title memory.
  4077. /// `submitted` is the last value signalled on the fence. `seen` holds
  4078. /// the pieces fetched already since the card was last waited for
  4079. /// (several submissions settled together name the same ones).
  4080. fn card_back(
  4081. &self,
  4082. plan: &CardPlan,
  4083. submitted: &mut u64,
  4084. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4085. ) {
  4086. if plan.ranges.is_empty() {
  4087. return;
  4088. }
  4089. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4090. let Some(work) = work.as_mut() else {
  4091. return;
  4092. };
  4093. // SAFETY: the mapping of the results, which the compare (it has
  4094. // run) wrote.
  4095. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4096. // The pieces to fetch: the range, the offsets in its copy, and
  4097. // where the bytes come down.
  4098. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4099. let mut total = 0u64;
  4100. plan.picked_found(differs);
  4101. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4102. for p in 0..r.span.pieces {
  4103. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4104. continue;
  4105. }
  4106. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4107. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4108. pieces.push((i, lo, hi, total));
  4109. total += (hi - lo) as u64;
  4110. }
  4111. }
  4112. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4113. }
  4114. let mut written = vec![0usize; plan.ranges.len()];
  4115. if !pieces.is_empty() {
  4116. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4117. let size = total.next_multiple_of(16 << 20);
  4118. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4119. }
  4120. let Some((fetched, data, _)) = &work.fetched else {
  4121. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4122. };
  4123. let waiting = std::time::Instant::now();
  4124. let (allocator, list) = &work.fetch;
  4125. // SAFETY: the list's last run was waited for; live buffers; the
  4126. // fence and event are ours, under the submission lock.
  4127. let ran = unsafe {
  4128. (|| -> windows::core::Result<()> {
  4129. allocator.Reset()?;
  4130. list.Reset(allocator, None)?;
  4131. for &(i, lo, hi, at) in &pieces {
  4132. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4133. }
  4134. list.Close()?;
  4135. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4136. self.card_sent();
  4137. *submitted += 1;
  4138. self.queue.Signal(&self.fence, *submitted)?;
  4139. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4140. let was_working = working(false);
  4141. WaitForSingleObject(self.event, INFINITE);
  4142. stood(waiting);
  4143. working(was_working);
  4144. Ok(())
  4145. })()
  4146. };
  4147. if let Err(e) = ran {
  4148. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4149. }
  4150. {
  4151. use crate::shadow::CARD_STATS;
  4152. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4153. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4154. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4155. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4156. }
  4157. if wide_merge() && pieces.len() >= 8 {
  4158. // The pieces are apart from one another (each its own bytes
  4159. // of its copy and of title memory): several at a time.
  4160. let fetched = *data;
  4161. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4162. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4163. let each = pieces.len().div_ceil(8);
  4164. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4165. .chunks(each)
  4166. .map(|chunk| {
  4167. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4168. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4169. let counts = counts.clone();
  4170. Box::new(move || {
  4171. let mut title = Vec::new();
  4172. for (shadow, i, lo, hi, at) in chunk {
  4173. // SAFETY: the mapping of the fetched bytes;
  4174. // the copy into it has run, and the caller
  4175. // waits for this job.
  4176. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4177. let merged = shadow.card_merge(lo, gpu, &mut title);
  4178. shadow.walls_merged(gpu.len(), merged);
  4179. counts[i].fetch_add(merged, Ordering::Relaxed);
  4180. }
  4181. }) as Box<dyn FnOnce() + Send>
  4182. })
  4183. .collect();
  4184. crate::shadow::wide_run(jobs);
  4185. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4186. *written += count.load(Ordering::Relaxed);
  4187. }
  4188. } else {
  4189. let mut title = Vec::new();
  4190. for &(i, lo, hi, at) in &pieces {
  4191. // SAFETY: the mapping of the fetched bytes, `total` of
  4192. // them; the copy into it has run.
  4193. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4194. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4195. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4196. written[i] += merged;
  4197. }
  4198. }
  4199. }
  4200. for (r, written) in plan.ranges.iter().zip(written) {
  4201. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4202. let (from, to) = r.declared;
  4203. #[cfg(feature = "diagnostics")]
  4204. crate::copystat::compared(from, to - from, written);
  4205. let _ = (from, to);
  4206. }
  4207. }
  4208. /// Runs closed lists and waits for them, and with [`late`] for
  4209. /// everything sent to the card before them, which is settled first.
  4210. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4211. let _ = self.submit(runs, false);
  4212. }
  4213. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4214. /// from the title's, go to the card in `order` and are not waited for.
  4215. /// They join the line of flights and are settled, with the others in
  4216. /// the air, at the next point where what they do can be observed
  4217. /// ([`late`] lists those points); their host lists are reset and kept
  4218. /// for reuse then, as a queue does for the lists it ran.
  4219. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4220. if order.is_empty() {
  4221. crate::list::recycle(lists, &order);
  4222. return;
  4223. }
  4224. late_threads();
  4225. let sent = {
  4226. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4227. self.submit(&runs, true)
  4228. };
  4229. let Some((mut submitted, sent)) = sent else {
  4230. // (Not reached: a submission sent ahead always comes back.)
  4231. crate::list::recycle(lists, &order);
  4232. return;
  4233. };
  4234. let told = !sent.writes.is_empty();
  4235. let most = {
  4236. let mut line = line();
  4237. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4238. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4239. *flying += order.len();
  4240. *target = *submitted;
  4241. items.push(Late::Run(Flight {
  4242. number: sent.number,
  4243. fence: *target,
  4244. lists,
  4245. order,
  4246. card: sent.card,
  4247. back: sent.back,
  4248. own: sent.own,
  4249. }));
  4250. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4251. *flying >= late_most()
  4252. };
  4253. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4254. RELAY_MOVED.notify_one();
  4255. if told && !late_writes() {
  4256. self.settle(&mut submitted, WHY_WRITES);
  4257. } else if most && relay_exact() {
  4258. // Until there are fewer, not until there are none.
  4259. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4260. } else if most {
  4261. self.settle(&mut submitted, WHY_MOST);
  4262. } else {
  4263. LINE_MOVED.notify_one();
  4264. }
  4265. drop(submitted);
  4266. land();
  4267. }
  4268. /// Sends `list`, a closed list of ours (the present's copy), as a
  4269. /// flight ([`late_free_present`]): not waited for, settled with the
  4270. /// others. The caller keeps the list and does not reset it before the
  4271. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4272. /// it ran and was waited for after all.
  4273. fn execute_own(&self, list: &HostList) -> u64 {
  4274. late_threads();
  4275. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4276. return 0;
  4277. };
  4278. let number = sent.number;
  4279. {
  4280. let mut line = line();
  4281. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4282. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4283. *flying += 1;
  4284. *target = *submitted;
  4285. items.push(Late::Run(Flight {
  4286. number,
  4287. fence: *target,
  4288. lists: Vec::new(),
  4289. order: Vec::new(),
  4290. card: sent.card,
  4291. back: sent.back,
  4292. own: sent.own,
  4293. }));
  4294. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4295. }
  4296. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4297. LINE_MOVED.notify_one();
  4298. RELAY_MOVED.notify_one();
  4299. drop(submitted);
  4300. number
  4301. }
  4302. /// Waits for the card to run every flight in the air ([`late`]) and
  4303. /// does what they left to do, as [`Host::execute`] does for one
  4304. /// submission after its wait: the pieces their shaders wrote in copies
  4305. /// in the card's memory are fetched and merged (each once), the ranges
  4306. /// they declared in the other copies are compared and copied back
  4307. /// (each byte once, whichever flights declared it), and then, in the
  4308. /// order they were given: their bottom-of-pipe writes and the fence
  4309. /// signals behind them. `submitted` is the submission lock's value;
  4310. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4311. ///
  4312. /// Everything in the air is settled, never the first flights alone:
  4313. /// the merge writes the copies' CPU side, which a flight still on the
  4314. /// card may be writing too.
  4315. fn settle(&self, submitted: &mut u64, why: usize) {
  4316. if !late() {
  4317. return;
  4318. }
  4319. if relay() {
  4320. // Nothing is settled here: the thread that lands flights does
  4321. // it, in order, and this waits until nothing is in the air and
  4322. // nothing is being landed. Every point that settled before
  4323. // comes here, so each still sees title memory, fences and
  4324. // bottom-of-pipe values as after a settle.
  4325. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4326. return;
  4327. }
  4328. let was_working = working(true);
  4329. let mut counted = false;
  4330. loop {
  4331. let items = {
  4332. let mut line = line();
  4333. if line.line.is_empty() {
  4334. line.settling = false;
  4335. break;
  4336. }
  4337. line.settling = true;
  4338. line.written.clear();
  4339. line.lists = 0;
  4340. std::mem::take(&mut line.line)
  4341. };
  4342. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4343. if !counted {
  4344. counted = true;
  4345. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4346. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4347. }
  4348. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4349. if flights > 0 {
  4350. submitting(2, flights);
  4351. let waiting = std::time::Instant::now();
  4352. // SAFETY: the fence and event are ours, under the
  4353. // submission lock; `submitted` is the last value signalled.
  4354. unsafe {
  4355. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4356. Ok(()) => {
  4357. working(false);
  4358. WaitForSingleObject(self.event, INFINITE);
  4359. stood(waiting);
  4360. working(true);
  4361. }
  4362. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4363. }
  4364. }
  4365. let gpu = waiting.elapsed();
  4366. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4367. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4368. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4369. #[cfg(feature = "diagnostics")]
  4370. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4371. format!("{flights} submissions sent ahead, settled together")
  4372. });
  4373. // SAFETY: a plain query.
  4374. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4375. let runs: Vec<&HostList> = items
  4376. .iter()
  4377. .filter_map(|i| match i {
  4378. Late::Run(f) => Some(f),
  4379. _ => None,
  4380. })
  4381. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4382. .collect();
  4383. fail(format_args!(
  4384. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4385. runs.len(),
  4386. self.removal_data(&runs),
  4387. last_notes(&runs)
  4388. ));
  4389. }
  4390. submitting(3, flights);
  4391. let copying = std::time::Instant::now();
  4392. let mut seen = std::collections::HashSet::new();
  4393. let mut back: Vec<Declared> = Vec::new();
  4394. for item in &items {
  4395. let Late::Run(flight) = item else {
  4396. continue;
  4397. };
  4398. if let Some(card) = &flight.card {
  4399. self.card_back(card, submitted, &mut seen);
  4400. }
  4401. for (shadow, ranges) in &flight.back {
  4402. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4403. Some((_, all)) => {
  4404. for range in ranges {
  4405. if !all.contains(range) {
  4406. all.push(*range);
  4407. }
  4408. }
  4409. }
  4410. None => back.push((shadow.clone(), ranges.clone())),
  4411. }
  4412. }
  4413. }
  4414. hand_back(&back);
  4415. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4416. }
  4417. // In the order given: what tells the title the card is done.
  4418. let mut last = 0;
  4419. let mut landed = Vec::new();
  4420. for item in items {
  4421. match item {
  4422. Late::Run(flight) => {
  4423. last = flight.number;
  4424. for &i in &flight.order {
  4425. read_backs(flight.lists[i].host());
  4426. }
  4427. if let Some(card) = flight.card {
  4428. self.card_done(card);
  4429. }
  4430. landed.push((flight.lists, flight.order));
  4431. }
  4432. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4433. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4434. }
  4435. }
  4436. if last > 0 {
  4437. FINISHED.store(last, Ordering::Release);
  4438. bury(last);
  4439. }
  4440. line().landed.extend(landed);
  4441. }
  4442. if counted {
  4443. self.log_messages();
  4444. submitting(0, 0);
  4445. // What was settled may be what a queue stands at, and the
  4446. // caller may not be one that looks (a read-back, a present).
  4447. if why != WHY_CARD_DONE {
  4448. line().poke = true;
  4449. LINE_MOVED.notify_one();
  4450. }
  4451. }
  4452. working(was_working);
  4453. }
  4454. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4455. /// copies, which flights may be writing and the title wrote too
  4456. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4457. /// those of the submission's one asking, which is made again.
  4458. ///
  4459. /// With [`card_steps`] only the flights that declared them: a range of
  4460. /// a copy nobody declared any more is refreshed like any other. What
  4461. /// they landed is title memory written, so everything is asked and
  4462. /// looked at again; what is left after three times waits as before.
  4463. fn settle_stale(
  4464. &self,
  4465. submitted: &mut u64,
  4466. runs: &[&HostList],
  4467. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4468. ranges: &[(usize, usize)],
  4469. ) {
  4470. if relay_exact() && card_steps::stage() > 0 {
  4471. for _ in 0..3 {
  4472. #[cfg(feature = "diagnostics")]
  4473. blame_stale(&stale);
  4474. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4475. crate::watch::ask_once(ranges);
  4476. stale = stale_under_flights(runs);
  4477. if stale.is_empty() {
  4478. return;
  4479. }
  4480. }
  4481. }
  4482. #[cfg(feature = "diagnostics")]
  4483. blame_stale(&stale);
  4484. self.settle(submitted, WHY_STALE);
  4485. crate::watch::ask_once(ranges);
  4486. }
  4487. /// [`Host::execute`], or with `late` the first half of
  4488. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4489. /// to be done once they have run comes back with the submission lock
  4490. /// still held.
  4491. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4492. #[cfg(feature = "diagnostics")]
  4493. let called = std::time::Instant::now();
  4494. #[cfg(feature = "diagnostics")]
  4495. crate::copystat::submission_begins();
  4496. // One submission at a time from preparation to copy-back: snapshots
  4497. // and the ranges shaders write are per host copy, not per submission.
  4498. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4499. let was_working = working(true);
  4500. submitting(1, runs.len());
  4501. // Flights in the air ([`late`]): a submission that is waited for
  4502. // settles them first, one sent ahead only if preparing it reads
  4503. // what they write.
  4504. // Or the reads are done on the card, behind the flights.
  4505. let own = if late { self.card_steps(runs) } else { None };
  4506. if !late {
  4507. self.settle(&mut submitted, WHY_SYNC);
  4508. } else if own.is_none()
  4509. && let Some(why) = late_blocked(runs)
  4510. {
  4511. if relay_exact() && why == WHY_READ {
  4512. // Only until the flights that may write what is read have
  4513. // landed: their copy-back's end, not the card's other work.
  4514. relay_wait(why, |line| {
  4515. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4516. });
  4517. } else {
  4518. self.settle(&mut submitted, why);
  4519. }
  4520. }
  4521. // Descriptors the title copied into placed heaps directly, before
  4522. // command lists that index those slots are submitted.
  4523. crate::descriptor::sync_heaps();
  4524. // That list runs first, and is one of the submission's from here on.
  4525. let with: Vec<&HostList>;
  4526. let runs = match &own {
  4527. Some(own) => {
  4528. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4529. &with[..]
  4530. }
  4531. None => runs,
  4532. };
  4533. let behind = late && flying();
  4534. // Before this submission counts as started: what the sweep lets go
  4535. // of is named by no list, and nothing runs now (behind flights the
  4536. // sweep waits for a submission that finds none in the air: there is
  4537. // one at every present).
  4538. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4539. if !behind {
  4540. if upcheck::on() {
  4541. upcheck::at_rest(self);
  4542. }
  4543. sweep();
  4544. SWEPT.store(now_ms(), Ordering::Relaxed);
  4545. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4546. // With the present sent ahead nothing else brings a moment
  4547. // with nothing in the air: one is made for the sweep.
  4548. self.settle(&mut submitted, WHY_SYNC);
  4549. if upcheck::on() {
  4550. upcheck::at_rest(self);
  4551. }
  4552. sweep();
  4553. SWEPT.store(now_ms(), Ordering::Relaxed);
  4554. }
  4555. let behind = late && flying();
  4556. // The slots that waited for a texture's host copy, before the
  4557. // lists that may read them run.
  4558. crate::descriptor::make_waiting();
  4559. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4560. // The ranges shaders write are counted for it (with the relay).
  4561. crate::shadow::preparing(this_submission);
  4562. let started = std::time::Instant::now();
  4563. #[cfg(feature = "diagnostics")]
  4564. let lock = (started - called).as_micros() as u64;
  4565. #[cfg(feature = "diagnostics")]
  4566. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4567. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4568. // Where each run's lists start in `lists`.
  4569. let mut firsts = Vec::with_capacity(runs.len());
  4570. let mut batch = Batch::default();
  4571. #[cfg(feature = "diagnostics")]
  4572. let split = Split::begin();
  4573. // The time a settle of flights takes inside this preparing: the
  4574. // wait for the card and the copy-back have their own places on the
  4575. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4576. let mut settled = std::time::Duration::ZERO;
  4577. // One write-watch asking for everything the submission refreshes
  4578. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4579. if crate::watch::once() {
  4580. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  4581. for list in runs {
  4582. for step in &list.deferred().copies {
  4583. if let Step::Refresh(shadow, address, len) = step
  4584. && shadow.asked_ahead()
  4585. {
  4586. let span = spans
  4587. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4588. .or_insert((*address, *address + *len));
  4589. *span = (span.0.min(*address), span.1.max(*address + *len));
  4590. }
  4591. }
  4592. }
  4593. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4594. #[cfg(feature = "diagnostics")]
  4595. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  4596. crate::watch::ask_once(&ranges);
  4597. #[cfg(feature = "diagnostics")]
  4598. split.part(0);
  4599. // Behind flights: the title wrote memory that a flight's shaders
  4600. // may write too, and this submission refreshes it. The flights
  4601. // are settled, and the asking made again: the copy-back wrote
  4602. // title memory, which other copies of it must see.
  4603. if upcheck::on() {
  4604. upcheck::order(runs);
  4605. if behind {
  4606. upcheck::reads(runs);
  4607. }
  4608. }
  4609. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  4610. if !stale.is_empty() {
  4611. let settling = std::time::Instant::now();
  4612. self.settle_stale(&mut submitted, runs, stale, &ranges);
  4613. settled += settling.elapsed();
  4614. }
  4615. } else if behind && !stale_under_flights(runs).is_empty() {
  4616. let settling = std::time::Instant::now();
  4617. self.settle(&mut submitted, WHY_STALE);
  4618. settled += settling.elapsed();
  4619. }
  4620. #[cfg(feature = "diagnostics")]
  4621. split.part(1);
  4622. for list in runs {
  4623. list.run_deferred(&mut batch, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4624. firsts.push(lists.len());
  4625. if let Some(prelude) = list.prelude() {
  4626. lists.push(Some(prelude));
  4627. }
  4628. lists.push(list.list.cast().ok());
  4629. }
  4630. batch.flush();
  4631. crate::watch::ask_once_end();
  4632. #[cfg(feature = "diagnostics")]
  4633. split.part(2);
  4634. // The snapshots of the ranges shaders may write, if they were left
  4635. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4636. // lists have not gone to the card.
  4637. {
  4638. #[cfg(feature = "diagnostics")]
  4639. let snapshots = std::time::Instant::now();
  4640. crate::shadow::take_snapshots();
  4641. #[cfg(feature = "diagnostics")]
  4642. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4643. }
  4644. #[cfg(feature = "diagnostics")]
  4645. split.part(3);
  4646. // Copies in the card's memory: what changed on their CPU side goes
  4647. // up ahead of the lists, and a compare of what the shaders may
  4648. // write follows them in the same submission.
  4649. let flown = late && relay();
  4650. if flown && self.card_results_low() {
  4651. let settling = std::time::Instant::now();
  4652. self.settle(&mut submitted, WHY_MOST);
  4653. settled += settling.elapsed();
  4654. }
  4655. // What shaders may write through views they pick: last, so that no
  4656. // refresh of this submission leaves it alone.
  4657. let picked = crate::picked::declare(runs);
  4658. for (shadow, at, len) in &picked.written {
  4659. shadow.writing(*at, *len);
  4660. }
  4661. let card = self.card_before(runs, &picked, flown);
  4662. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4663. lists.push(Some(check));
  4664. }
  4665. #[cfg(feature = "diagnostics")]
  4666. split.part(4);
  4667. let prepared = std::time::Instant::now();
  4668. if late {
  4669. *submitted += 1;
  4670. // SAFETY: closed lists; the fence is ours.
  4671. let signalled = unsafe {
  4672. self.queue.ExecuteCommandLists(&lists);
  4673. self.queue.Signal(&self.fence, *submitted)
  4674. };
  4675. self.card_sent();
  4676. if let Err(e) = signalled {
  4677. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4678. }
  4679. #[cfg(feature = "diagnostics")]
  4680. split.part(5);
  4681. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4682. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4683. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4684. submitting(0, 0);
  4685. #[cfg(feature = "diagnostics")]
  4686. crate::copystat::submission_ends(lock);
  4687. let sent = Sent {
  4688. number: this_submission,
  4689. card,
  4690. back,
  4691. own,
  4692. writes,
  4693. };
  4694. working(was_working);
  4695. return Some((submitted, sent));
  4696. }
  4697. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4698. #[cfg(feature = "diagnostics")]
  4699. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4700. firsts
  4701. .iter()
  4702. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4703. .map(|(&a, &b)| &lists[a..b])
  4704. .collect()
  4705. } else {
  4706. vec![&lists[..]]
  4707. };
  4708. #[cfg(not(feature = "diagnostics"))]
  4709. let groups = [&lists[..]];
  4710. submitting(2, runs.len());
  4711. for (i, group) in groups.iter().enumerate() {
  4712. *submitted += 1;
  4713. let started = std::time::Instant::now();
  4714. // SAFETY: closed lists; the fence and event are ours.
  4715. unsafe {
  4716. self.queue.ExecuteCommandLists(group);
  4717. self.card_sent();
  4718. let waited = self
  4719. .queue
  4720. .Signal(&self.fence, *submitted)
  4721. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4722. match waited {
  4723. Ok(()) => {
  4724. working(false);
  4725. WaitForSingleObject(self.event, INFINITE);
  4726. stood(started);
  4727. working(true);
  4728. }
  4729. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4730. }
  4731. }
  4732. // With timing on each group is one of `runs` (and the compare
  4733. // of copies in the card's memory, with the last): every
  4734. // command's time on the card goes to the sums by pipeline.
  4735. #[cfg(feature = "diagnostics")]
  4736. if timing() {
  4737. // SAFETY: a plain query.
  4738. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4739. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4740. crate::copystat::command_took(&op, ms);
  4741. }
  4742. }
  4743. // A submission of one list was never named here (`groups.len()
  4744. // > 1` was the test): the two 50 ms lists of the gameplay
  4745. // frame, each a submission of its own, printed nothing.
  4746. #[cfg(feature = "diagnostics")]
  4747. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4748. // SAFETY: a plain query.
  4749. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4750. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4751. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4752. for (ms, op) in runs[i].slowest(frequency, 6) {
  4753. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4754. }
  4755. }
  4756. let _ = (i, started);
  4757. }
  4758. let _ = &firsts;
  4759. FINISHED.store(this_submission, Ordering::Release);
  4760. bury(this_submission);
  4761. let gpu = prepared.elapsed();
  4762. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4763. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4764. #[cfg(feature = "diagnostics")]
  4765. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4766. let pipelines: std::collections::BTreeSet<String> = runs
  4767. .iter()
  4768. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4769. .collect();
  4770. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  4771. text.chars().take(1200).collect()
  4772. });
  4773. // The host resets a device whose submission runs for about 2 s.
  4774. if gpu > std::time::Duration::from_millis(250) {
  4775. let pipelines: std::collections::BTreeSet<String> = runs
  4776. .iter()
  4777. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4778. .collect();
  4779. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  4780. }
  4781. // SAFETY: a plain query.
  4782. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4783. fail(format_args!(
  4784. "host GPU device removed after a submission of {} lists{}{}",
  4785. runs.len(),
  4786. self.removal_data(runs),
  4787. last_notes(runs)
  4788. ));
  4789. }
  4790. submitting(3, runs.len());
  4791. // What shaders wrote goes back before the bottom-of-pipe writes,
  4792. // which tell the title the GPU is done; each range once per
  4793. // submission, however many dispatches declared it (the world's
  4794. // passes declare the same big ranges dozens of times).
  4795. let copying = std::time::Instant::now();
  4796. // For copies in the card's memory the compare has run there: the
  4797. // pieces that differ are fetched and merged.
  4798. if let Some(card) = &card {
  4799. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  4800. }
  4801. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4802. hand_back(&back);
  4803. if let Some(card) = card {
  4804. self.card_done(card);
  4805. }
  4806. #[cfg(feature = "diagnostics")]
  4807. if !back.is_empty() {
  4808. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  4809. }
  4810. // Nothing of this submission goes back to the title: no range of
  4811. // shader writes, no value written when it is done. The wait for
  4812. // such a one is only for order and for what the card still holds.
  4813. #[cfg(feature = "diagnostics")]
  4814. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  4815. use crate::copystat::{C, add};
  4816. add(C::NothingBack, 1);
  4817. add(C::NothingBackUs, gpu.as_micros() as u64);
  4818. }
  4819. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4820. for list in runs {
  4821. // Read backs first: a value written at the bottom of the pipe
  4822. // may be what tells the title that they are there.
  4823. read_backs(list);
  4824. for &(at, what, bytes) in &list.deferred().writes {
  4825. what.write(at as *mut u8, bytes);
  4826. }
  4827. }
  4828. self.log_messages();
  4829. submitting(0, 0);
  4830. #[cfg(feature = "diagnostics")]
  4831. crate::copystat::submission_ends(lock);
  4832. // With the relay: nothing is in the air now, so no fetch still to
  4833. // be merged is older than the sends to card copies so far, and
  4834. // their notes can go.
  4835. if relay() {
  4836. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  4837. }
  4838. working(was_working);
  4839. None
  4840. }
  4841. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  4842. /// it lies in (by the names we give them) or the title memory copy just
  4843. /// below it; for each list that did not finish, the command it stopped
  4844. /// at and what the draws and dispatches in flight there run (or, in
  4845. /// lists that never started, the pipelines they bind).
  4846. fn removal_data(&self, runs: &[&HostList]) -> String {
  4847. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  4848. return String::new();
  4849. };
  4850. let mut text = String::new();
  4851. let mut fault_va = None;
  4852. // SAFETY: the outputs are the runtime's, valid while the device
  4853. // lives; nodes are walked as linked, histories have their counts.
  4854. unsafe {
  4855. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  4856. && fault.PageFaultVA != 0
  4857. {
  4858. let va = fault.PageFaultVA;
  4859. fault_va = Some(va);
  4860. text.push_str(&format!("; page fault at {va:#x}"));
  4861. for (what, head) in [
  4862. ("inside", fault.pHeadExistingAllocationNode),
  4863. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  4864. ] {
  4865. let mut names = Vec::new();
  4866. let mut node = head;
  4867. while let Some(n) = node.as_ref()
  4868. && names.len() < 8
  4869. {
  4870. let name = if n.ObjectNameW.is_null() {
  4871. "unnamed".to_owned()
  4872. } else {
  4873. n.ObjectNameW.to_string().unwrap_or_default()
  4874. };
  4875. names.push(format!("{name} (type {})", n.AllocationType.0));
  4876. node = n.pNext;
  4877. }
  4878. if !names.is_empty() {
  4879. text.push_str(&format!("; {what} {names:?}"));
  4880. }
  4881. }
  4882. text.push_str(&crate::shadow::near(va));
  4883. text.push_str(&crate::descriptor::host::near_heaps(va));
  4884. }
  4885. // The plain output: the extended one (with marker texts) came
  4886. // back without stopped lists on this host.
  4887. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  4888. Ok(crumbs) => crumbs,
  4889. Err(e) => {
  4890. text.push_str(&format!("; no breadcrumbs ({e})"));
  4891. return text;
  4892. }
  4893. };
  4894. // Every list's progress (done/count), in the runtime's order.
  4895. let mut progress = Vec::new();
  4896. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  4897. while let Some(p) = node.as_ref() {
  4898. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4899. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  4900. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  4901. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  4902. node = p.pNext;
  4903. }
  4904. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  4905. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  4906. while let Some(p) = plain.as_ref() {
  4907. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  4908. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  4909. let history =
  4910. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  4911. text.push_str(&format!(
  4912. "; a list stopped at command {done} of {} (op {})",
  4913. p.BreadcrumbCount, history[done as usize].0
  4914. ));
  4915. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  4916. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  4917. // The k-th marker command is the k-th note.
  4918. #[cfg(feature = "diagnostics")]
  4919. let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| {
  4920. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  4921. history
  4922. .iter()
  4923. .enumerate()
  4924. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  4925. .zip(notes.iter())
  4926. .map(|((at, _), (note, range))| {
  4927. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  4928. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  4929. })
  4930. .collect()
  4931. });
  4932. #[cfg(not(feature = "diagnostics"))]
  4933. let markers: Vec<(u32, String)> = Vec::new();
  4934. #[cfg(not(feature = "diagnostics"))]
  4935. let _ = fault_va;
  4936. if done > 0 {
  4937. text.push_str(&in_flight(history, &markers, done as usize));
  4938. } else if let Some(r) = run {
  4939. let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  4940. text.push_str(&format!(", its pipelines {pipelines:?}"));
  4941. }
  4942. }
  4943. plain = p.pNext;
  4944. }
  4945. }
  4946. text
  4947. }
  4948. /// Moves the debug layer's messages into our log; returns the first
  4949. /// error among them.
  4950. pub(crate) fn log_messages(&self) -> Option<String> {
  4951. let Some(queue) = &self.messages else {
  4952. return None;
  4953. };
  4954. let mut first_error = None;
  4955. // SAFETY: each message is read into a buffer of the size the queue
  4956. // reports, then the queue is emptied.
  4957. unsafe {
  4958. for i in 0..queue.GetNumStoredMessages() {
  4959. let mut size = 0;
  4960. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  4961. continue;
  4962. }
  4963. let mut buffer = vec![0u64; size.div_ceil(8)];
  4964. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  4965. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  4966. let m = &*message;
  4967. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  4968. let text = String::from_utf8_lossy(text);
  4969. let text = text.trim_end_matches('\0');
  4970. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  4971. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  4972. first_error = Some(text.to_owned());
  4973. }
  4974. }
  4975. }
  4976. queue.ClearStoredMessages();
  4977. }
  4978. first_error
  4979. }
  4980. /// A host render target view of `resource`, valid until it is recorded.
  4981. pub(crate) fn rtv(
  4982. &self,
  4983. resource: Option<&ID3D12Resource>,
  4984. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  4985. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  4986. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  4987. // SAFETY: a slot of our heap and a live resource, or none with a
  4988. // description (a typed null view).
  4989. unsafe {
  4990. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  4991. handle.ptr += (slot * self.rtv_size) as usize;
  4992. self.device
  4993. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  4994. handle
  4995. }
  4996. }
  4997. /// A host depth view of `resource`, valid until it is recorded.
  4998. pub(crate) fn dsv(
  4999. &self,
  5000. resource: &ID3D12Resource,
  5001. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  5002. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5003. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5004. // SAFETY: a slot of our heap and a live resource.
  5005. unsafe {
  5006. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  5007. handle.ptr += (slot * self.dsv_size) as usize;
  5008. self.device
  5009. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  5010. handle
  5011. }
  5012. }
  5013. }
  5014. impl HostList {
  5015. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  5016. #[cfg(feature = "diagnostics")]
  5017. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  5018. if !timing() {
  5019. return None;
  5020. }
  5021. self.stamps
  5022. .get_or_init(|| {
  5023. let device = &host()?.device;
  5024. let mut heap: Option<ID3D12QueryHeap> = None;
  5025. let mut back: Option<ID3D12Resource> = None;
  5026. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  5027. let desc = D3D12_RESOURCE_DESC {
  5028. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5029. Width: u64::from(STAMPS) * 8,
  5030. Height: 1,
  5031. DepthOrArraySize: 1,
  5032. MipLevels: 1,
  5033. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  5034. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5035. ..Default::default()
  5036. };
  5037. // SAFETY: plain object creation.
  5038. unsafe {
  5039. device
  5040. .CreateQueryHeap(
  5041. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  5042. &mut heap,
  5043. )
  5044. .ok()?;
  5045. device
  5046. .CreateCommittedResource(
  5047. &readback,
  5048. D3D12_HEAP_FLAG_NONE,
  5049. &desc,
  5050. D3D12_RESOURCE_STATE_COPY_DEST,
  5051. None,
  5052. &mut back,
  5053. )
  5054. .ok()?;
  5055. }
  5056. Some((heap?, back?))
  5057. })
  5058. .as_ref()
  5059. }
  5060. /// The noted commands that took longest on the GPU, longest first, as
  5061. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  5062. #[cfg(feature = "diagnostics")]
  5063. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  5064. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  5065. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  5066. return Vec::new();
  5067. };
  5068. let mut data = std::ptr::null_mut();
  5069. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  5070. // SAFETY: a read-back buffer the finished list resolved into.
  5071. let stamps: Vec<u64> = unsafe {
  5072. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  5073. return Vec::new();
  5074. }
  5075. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  5076. back.Unmap(0, None);
  5077. s
  5078. };
  5079. let mut times: Vec<(f64, String)> = (0..count)
  5080. .map(|i| {
  5081. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5082. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5083. })
  5084. .collect();
  5085. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5086. times.truncate(n);
  5087. times
  5088. }
  5089. pub(crate) fn close(&self) {
  5090. self.twins_to_depth();
  5091. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5092. if let Some((scratch, _)) = scratch {
  5093. self.indirect_common(&scratch);
  5094. }
  5095. self.batches_common();
  5096. self.card_budget_out();
  5097. #[cfg(feature = "diagnostics")]
  5098. if let Some((heap, back)) = self.stamps() {
  5099. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5100. // SAFETY: an open list, our heap and read-back buffer.
  5101. unsafe {
  5102. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5103. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5104. }
  5105. }
  5106. // SAFETY: our list.
  5107. if let Err(e) = unsafe { self.list.Close() } {
  5108. fail(format_args!(
  5109. "a host command list did not close ({e}): a command recorded into it was invalid"
  5110. ));
  5111. }
  5112. }
  5113. /// Only after the list's last submission finished (every one is waited
  5114. /// for).
  5115. pub(crate) fn reset(&self) {
  5116. #[cfg(feature = "diagnostics")]
  5117. let started = std::time::Instant::now();
  5118. self._alive.used();
  5119. *self.deferred() = Deferred::default();
  5120. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5121. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5122. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5123. #[cfg(feature = "diagnostics")]
  5124. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5125. {
  5126. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5127. (scratch.current, scratch.used) = (0, 0);
  5128. // Every submission of the list has run: nothing reads its
  5129. // scratch memory any more, and the next list to ask takes it.
  5130. if scratch_pool() {
  5131. give_chunks(std::mem::take(&mut scratch.chunks));
  5132. }
  5133. }
  5134. // SAFETY: the list is not executing.
  5135. let reset = unsafe {
  5136. self.allocator
  5137. .Reset()
  5138. .and_then(|()| self.list.Reset(&self.allocator, None))
  5139. };
  5140. if let Err(e) = reset {
  5141. fail(format_args!("a host command list did not reset ({e})"));
  5142. }
  5143. #[cfg(feature = "diagnostics")]
  5144. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5145. }
  5146. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5147. /// list: the host texture and the state it leaves, if that is a change.
  5148. /// The list's first use of a texture records nothing: its prelude brings
  5149. /// the texture there at submission.
  5150. pub(crate) fn transition(
  5151. &self,
  5152. resource: crate::object::This,
  5153. wanted: u32,
  5154. ) -> Option<(&'static ID3D12Resource, u32)> {
  5155. let texture = crate::resource::host_resource(resource)?;
  5156. let copy = crate::resource::host_copy(resource)?;
  5157. let wanted = legal_state(texture, wanted);
  5158. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5159. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5160. std::collections::hash_map::Entry::Vacant(v) => {
  5161. v.insert((wanted, wanted, copy));
  5162. None
  5163. }
  5164. std::collections::hash_map::Entry::Occupied(mut o) => {
  5165. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5166. (before != wanted).then_some((texture, before))
  5167. }
  5168. }
  5169. }
  5170. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5171. /// as [`HostList::transition`] does a title resource's host copy, and
  5172. /// records the barrier: for textures that are not a title resource's
  5173. /// host copy (colour twins) and for the copies between the two.
  5174. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5175. let wanted = legal_state(&copy.texture, wanted);
  5176. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5177. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5178. std::collections::hash_map::Entry::Vacant(v) => {
  5179. v.insert((wanted, wanted, copy.clone()));
  5180. None
  5181. }
  5182. std::collections::hash_map::Entry::Occupied(mut o) => {
  5183. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5184. (before != wanted).then_some(before)
  5185. }
  5186. };
  5187. drop(states);
  5188. if let Some(before) = before {
  5189. let barrier = transition(
  5190. &copy.texture,
  5191. D3D12_RESOURCE_STATES(before as i32),
  5192. D3D12_RESOURCE_STATES(wanted as i32),
  5193. );
  5194. // SAFETY: an open list and a live texture.
  5195. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5196. }
  5197. }
  5198. /// A use of title texture `resource` about to be recorded, if it is a
  5199. /// depth texture with a colour twin (false if it is not): of the twin
  5200. /// (`colour`: unordered access) or of the depth texture (depth target,
  5201. /// clear, shader read, copy, resolve), writing it or only reading. The
  5202. /// side used is first brought up to date: by a copy recorded here if
  5203. /// this list wrote the other side since, by the list's prelude if the
  5204. /// list uses the side as it finds it. The twin is left in the
  5205. /// unordered access state; the caller moves the depth texture to the
  5206. /// state its use needs, as for any texture. A twin still ahead when the
  5207. /// list closes is copied then (`twins_to_depth`).
  5208. /// shortcut: every depth target bound for a draw counts as written
  5209. /// (also when the draw only tests), and every unordered access view a
  5210. /// shader names as written; views a shader picks from the heap by a
  5211. /// computed index are not seen here at all.
  5212. pub(crate) fn twin_use(
  5213. &self,
  5214. resource: crate::object::This,
  5215. colour: bool,
  5216. write: bool,
  5217. ) -> bool {
  5218. const UNORDERED_ACCESS: u32 = 0x8;
  5219. // Asked for every texture a draw reads: most have no twin.
  5220. let Some(twin) = crate::resource::twin(resource) else {
  5221. return false;
  5222. };
  5223. let Some(depth) = crate::resource::host_copy(resource) else {
  5224. return false;
  5225. };
  5226. let side = usize::from(colour);
  5227. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5228. let u = twins
  5229. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5230. .or_insert_with(|| TwinUse {
  5231. depth: depth.clone(),
  5232. twin: twin.clone(),
  5233. needs: [false; 2],
  5234. behind: [None; 2],
  5235. writing: false,
  5236. late: false,
  5237. });
  5238. let copy = match u.behind[side] {
  5239. Some(behind) => behind,
  5240. None => {
  5241. u.needs[side] = true;
  5242. false
  5243. }
  5244. };
  5245. u.behind[side] = Some(false);
  5246. match (write, colour) {
  5247. // Shaders write the twin when the draw or dispatch runs: what
  5248. // the same one reads of the depth texture is prepared before
  5249. // (`twins_written`).
  5250. (true, true) => u.writing = true,
  5251. (true, false) => u.behind[1] = Some(true),
  5252. (false, _) => {}
  5253. }
  5254. // shortcut: the depth plane's twin is not drawn into the plane
  5255. // here: the pass sets a pipeline and a target of ours, which a list
  5256. // still recording the title's commands cannot take. This use sees
  5257. // the plane as it was; the pass runs when the list closes
  5258. // (`twins_to_depth`). Counted.
  5259. if copy && !colour && twin.plane.is_some() {
  5260. u.late = true;
  5261. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5262. }
  5263. drop(twins);
  5264. if copy {
  5265. self.twin_copy(&depth, &twin, colour);
  5266. } else if colour {
  5267. self.settle(&twin.colour, UNORDERED_ACCESS);
  5268. }
  5269. // The depth plane's twin is written through unordered access too.
  5270. if colour && let Some(plane) = &twin.plane {
  5271. self.settle(plane, UNORDERED_ACCESS);
  5272. }
  5273. true
  5274. }
  5275. /// Records the pass that draws the twin of the depth plane of `depth`
  5276. /// into the plane, if `twin` has one, with the moves to the states the
  5277. /// pass needs; the twin is left in the unordered access state. Only
  5278. /// for a list that records nothing of the title's afterwards
  5279. /// (`record_plane_pass`).
  5280. fn pass_plane(
  5281. &self,
  5282. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5283. twin: &crate::resource::Twin,
  5284. ) {
  5285. const UNORDERED_ACCESS: u32 = 0x8;
  5286. const DEPTH_WRITE: u32 = 0x10;
  5287. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5288. let Some(plane) = &twin.plane else { return };
  5289. self.settle(depth, DEPTH_WRITE);
  5290. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5291. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5292. self.settle(plane, UNORDERED_ACCESS);
  5293. }
  5294. /// Records the copy of a depth texture into its colour twin (`colour`)
  5295. /// or of the twin into the depth texture, with the moves to the copy
  5296. /// states. The twin is left in the unordered access state.
  5297. fn twin_copy(
  5298. &self,
  5299. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5300. twin: &crate::resource::Twin,
  5301. colour: bool,
  5302. ) {
  5303. const UNORDERED_ACCESS: u32 = 0x8;
  5304. const COPY_DEST: u32 = 0x400;
  5305. const COPY_SOURCE: u32 = 0x800;
  5306. let (from, to) = if colour {
  5307. (depth, &twin.colour)
  5308. } else {
  5309. (&twin.colour, depth)
  5310. };
  5311. self.settle(from, COPY_SOURCE);
  5312. self.settle(to, COPY_DEST);
  5313. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5314. self.settle(&twin.colour, UNORDERED_ACCESS);
  5315. }
  5316. /// Before the list closes: the depth textures whose twins it wrote last
  5317. /// are given what was written, and left readable by shaders. Shaders
  5318. /// that pick a view from the heap by a computed index are not seen by
  5319. /// `twin_use` and read the depth texture in lists that never name it
  5320. /// (in a captured frame of the title no table names a shadow
  5321. /// map for reading but the pass that fills the next one).
  5322. fn twins_to_depth(&self) {
  5323. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5324. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5325. let written: Vec<_> = twins
  5326. .values_mut()
  5327. .filter(|u| u.behind[0] == Some(true) || u.late)
  5328. .map(|u| {
  5329. // Not copied again if the list copied since the last write
  5330. // and only the depth plane's pass is left.
  5331. let copy = u.behind[0] == Some(true);
  5332. u.behind[0] = Some(false);
  5333. u.late = false;
  5334. (u.depth.clone(), u.twin.clone(), copy)
  5335. })
  5336. .collect();
  5337. drop(twins);
  5338. for (depth, twin, copy) in &written {
  5339. if *copy {
  5340. self.twin_copy(depth, twin, false);
  5341. }
  5342. // Nothing of the title's is recorded after this: the pass may
  5343. // leave its own pipeline and target set.
  5344. self.pass_plane(depth, twin);
  5345. self.settle(depth, SHADER_RESOURCE);
  5346. }
  5347. }
  5348. /// The draw or dispatch just prepared is recorded: the twins it writes
  5349. /// now hold what their depth textures lack.
  5350. pub(crate) fn twins_written(&self) {
  5351. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5352. for u in twins.values_mut().filter(|u| u.writing) {
  5353. u.writing = false;
  5354. u.behind[0] = Some(true);
  5355. }
  5356. }
  5357. /// At submission: the list that moves each texture this list uses from
  5358. /// its real state to the one the list starts with; the textures' real
  5359. /// states become those the list ends with. For depth textures with a
  5360. /// colour twin it first copies the side the list uses as it finds it
  5361. /// from the other, if a list submitted earlier left it behind.
  5362. fn prelude(&self) -> Option<ID3D12CommandList> {
  5363. const COPY_DEST: u32 = 0x400;
  5364. const COPY_SOURCE: u32 = 0x800;
  5365. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5366. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5367. // The copies (depth texture, twin, whether into the twin); the
  5368. // sides are then as this list leaves them.
  5369. let mut syncs = Vec::new();
  5370. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5371. for u in twins.values() {
  5372. let real = u.twin.behind.load(Ordering::Relaxed);
  5373. let mut behind = [real & 1 != 0, real & 2 != 0];
  5374. for side in [0, 1] {
  5375. if u.needs[side] && behind[side] {
  5376. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5377. behind = [false; 2];
  5378. }
  5379. }
  5380. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5381. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5382. u.twin.behind.store(left, Ordering::Relaxed);
  5383. }
  5384. drop(twins);
  5385. // A copy runs with its textures in the copy states: each moves
  5386. // there from its real state, and from there to the state the list
  5387. // starts with (back to its real state if the list does not use it).
  5388. let mut to_copy = Vec::new();
  5389. let mut barriers = Vec::new();
  5390. let mut copying = std::collections::HashMap::new();
  5391. for (depth, twin, colour) in &syncs {
  5392. let (from, to) = if *colour {
  5393. (depth, &twin.colour)
  5394. } else {
  5395. (&twin.colour, depth)
  5396. };
  5397. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  5398. let key = std::sync::Arc::as_ptr(texture) as usize;
  5399. let real = texture.state.load(Ordering::Relaxed);
  5400. copying.insert(key, state);
  5401. if real != state {
  5402. to_copy.push(transition(
  5403. &texture.texture,
  5404. host_state(real),
  5405. host_state(state),
  5406. ));
  5407. if !states.contains_key(&key) {
  5408. barriers.push(transition(
  5409. &texture.texture,
  5410. host_state(state),
  5411. host_state(real),
  5412. ));
  5413. }
  5414. }
  5415. }
  5416. }
  5417. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5418. let real = copy.state.swap(*last, Ordering::Relaxed);
  5419. let real = copying.get(key).copied().unwrap_or(real);
  5420. (real != *first)
  5421. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5422. }));
  5423. if barriers.is_empty() && syncs.is_empty() {
  5424. return None;
  5425. }
  5426. let Some((allocator, list)) = self
  5427. .prelude
  5428. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5429. .as_ref()
  5430. else {
  5431. fail(format_args!("no host list for a state prelude"));
  5432. };
  5433. // SAFETY: the prelude is not executing (every submission is waited
  5434. // for); the textures are live.
  5435. let recorded = unsafe {
  5436. allocator.Reset().and_then(|()| {
  5437. list.Reset(allocator, None)?;
  5438. if !to_copy.is_empty() {
  5439. list.ResourceBarrier(&to_copy);
  5440. }
  5441. for (depth, twin, colour) in &syncs {
  5442. record_twin_copy(list, &depth.texture, twin, *colour);
  5443. }
  5444. if !barriers.is_empty() {
  5445. list.ResourceBarrier(&barriers);
  5446. }
  5447. list.Close()
  5448. })
  5449. };
  5450. if let Err(e) = recorded {
  5451. fail(format_args!("a host state prelude did not record ({e})"));
  5452. }
  5453. list.cast().ok()
  5454. }
  5455. /// Notes what the command about to be recorded does, as a marker
  5456. /// command whose text the list keeps (diagnostics, with device-removed
  5457. /// data on): the report pairs the breadcrumbs' marker commands with the
  5458. /// texts in order and names the commands a fault stopped among.
  5459. #[cfg(feature = "diagnostics")]
  5460. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5461. self.note(what, None);
  5462. }
  5463. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5464. /// `(address, bytes)`: the report places the faulting address in it.
  5465. #[cfg(feature = "diagnostics")]
  5466. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5467. self.note(what, Some(range));
  5468. }
  5469. #[cfg(feature = "diagnostics")]
  5470. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5471. if !dred_on() {
  5472. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5473. return;
  5474. }
  5475. {
  5476. let started = std::time::Instant::now();
  5477. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5478. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5479. // SAFETY: an open list and our query heap.
  5480. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5481. }
  5482. let what = what();
  5483. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5484. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5485. const UNICODE: u32 = 0;
  5486. // SAFETY: an open list; the marker is copied when recorded.
  5487. unsafe {
  5488. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5489. };
  5490. self.notes
  5491. .lock()
  5492. .unwrap_or_else(|e| e.into_inner())
  5493. .push((what, range));
  5494. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5495. }
  5496. }
  5497. /// Whether nothing recorded since the list was opened does any work:
  5498. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5499. /// upload or resolve (they defer a step or move a texture's state), no
  5500. /// bottom-of-pipe write. State set on the list does not count.
  5501. pub(crate) fn untouched(&self) -> bool {
  5502. {
  5503. let deferred = self.deferred();
  5504. if !(deferred.copies.is_empty()
  5505. && deferred.uploads.is_empty()
  5506. && deferred.kept.is_empty()
  5507. && deferred.textures.is_empty()
  5508. && deferred.writes.is_empty()
  5509. && deferred.backs.is_empty())
  5510. {
  5511. return false;
  5512. }
  5513. }
  5514. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5515. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5516. }
  5517. /// Notes a pipeline the list binds.
  5518. pub(crate) fn used_pipeline(&self, name: &str) {
  5519. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5520. if !pipelines.contains(name) {
  5521. pipelines.insert(name.to_owned());
  5522. }
  5523. }
  5524. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5525. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5526. }
  5527. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5528. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5529. let mut deferred = self.deferred();
  5530. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5531. // A copy that goes on where the one recorded just before it ended,
  5532. // source and destination both: with `join_copies` the two are one
  5533. // step.
  5534. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5535. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5536. {
  5537. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5538. if join_copies() {
  5539. *n += len;
  5540. return;
  5541. }
  5542. }
  5543. deferred
  5544. .copies
  5545. .push(Step::Copy(dst as usize, src as usize, len));
  5546. deferred.refreshed.clear();
  5547. }
  5548. /// Copies `len` bytes of title memory at `src` into the list's upload
  5549. /// memory at `dst` when the list is submitted.
  5550. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5551. self.deferred()
  5552. .copies
  5553. .push(Step::Fill(dst as usize, src as usize, len, None));
  5554. }
  5555. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5556. /// title heap's address, and the slot) shows.
  5557. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5558. self.deferred()
  5559. .copies
  5560. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  5561. }
  5562. /// As [`HostList::defer_fill`], for the beginning of a buffer
  5563. /// [`HostList::upload`] made.
  5564. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  5565. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  5566. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  5567. }
  5568. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5569. /// when the list is submitted (once per range until a title copy
  5570. /// intervenes), keeping the copy alive until the list is reset.
  5571. pub(crate) fn defer_refresh(
  5572. &self,
  5573. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5574. address: usize,
  5575. len: usize,
  5576. ) {
  5577. let mut deferred = self.deferred();
  5578. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5579. if deferred.refreshed.insert(key) {
  5580. deferred
  5581. .copies
  5582. .push(Step::Refresh(shadow.clone(), address, len));
  5583. }
  5584. }
  5585. /// Shaders of the list write `[address, address + len)` of a buffer's
  5586. /// host copy: copied back into title memory once the list has run.
  5587. pub(crate) fn defer_gpu_write(
  5588. &self,
  5589. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5590. address: usize,
  5591. len: usize,
  5592. ) {
  5593. self.deferred()
  5594. .copies
  5595. .push(Step::GpuWrite(shadow.clone(), address, len));
  5596. }
  5597. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5598. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5599. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5600. /// the list is reset.
  5601. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5602. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5603. }
  5604. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5605. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5606. self.deferred().writes.push((dst as usize, what, bytes));
  5607. }
  5608. /// A mapped upload buffer of `size` bytes, alive until the list is
  5609. /// reset.
  5610. ///
  5611. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5612. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5613. // With [`card_steps`] the card may be the one that fills it.
  5614. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  5615. name(&buffer, || format!("list upload {size:#x}"));
  5616. self.deferred().hold_upload(buffer.clone(), size);
  5617. Some((buffer, data))
  5618. }
  5619. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5620. /// reset: the host GPU address and the CPU pointer.
  5621. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5622. let host = host()?;
  5623. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5624. let len = len.max(1).next_multiple_of(256);
  5625. if len > SCRATCH_CHUNK {
  5626. let (buffer, data) = host.upload_buffer(len)?;
  5627. name(&buffer, || format!("list scratch {len:#x}"));
  5628. // SAFETY: a live buffer.
  5629. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  5630. self.deferred().hold_upload(buffer, len);
  5631. return Some((gpu, data));
  5632. }
  5633. // The chunk in use while `len` fits in what is left of it, else the
  5634. // next one (a list's first chunk may be a small one).
  5635. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5636. (s.current, s.used) = (s.current + 1, 0);
  5637. }
  5638. if s.current == s.chunks.len() {
  5639. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  5640. SCRATCH_FIRST
  5641. } else {
  5642. SCRATCH_CHUNK
  5643. };
  5644. let chunk = take_chunk(host, size)?;
  5645. s.chunks.push((chunk, size));
  5646. s.used = 0;
  5647. }
  5648. let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu);
  5649. let at = s.used;
  5650. s.used += len;
  5651. Some((gpu + at, (data + at as usize) as *mut u8))
  5652. }
  5653. /// The bytes of scratch chunks the list holds now (after a reset:
  5654. /// none while lists share their chunks).
  5655. pub(crate) fn scratch_kept(&self) -> u64 {
  5656. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5657. scratch.chunks.iter().map(|c| c.1).sum()
  5658. }
  5659. /// The host address of the list's indirect-work budget, zeroed at each
  5660. /// submission of the list from the first use after a reset on.
  5661. pub(crate) fn budget(&self) -> Option<u64> {
  5662. let (buffer, data) = self
  5663. .budget
  5664. .get_or_init(|| {
  5665. let (b, d) = host()?.shared_buffer(256)?;
  5666. Some((b, d as usize))
  5667. })
  5668. .as_ref()?;
  5669. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5670. let mut deferred = self.deferred();
  5671. if !deferred.budget_zeroed {
  5672. deferred.budget_zeroed = true;
  5673. let at = *data;
  5674. // SAFETY: the list's own mapped words, written before it runs.
  5675. // The words after the budget hold what the clamp noted about the
  5676. // list's last run (mesh dispatches: the largest group count
  5677. // asked for, the groups asked in all; with the card's copy, as
  5678. // the list's end copied them here): taken, then zeroed.
  5679. let notes = Box::new(move || unsafe {
  5680. let words = at as *mut u32;
  5681. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  5682. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  5683. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  5684. for k in 0..3 {
  5685. words.add(k).write_volatile(0);
  5686. }
  5687. });
  5688. deferred.copies.push(Step::Host(notes, (0, 0)));
  5689. drop(deferred);
  5690. if let Some(card) = card {
  5691. self.zero_card_budget(card);
  5692. }
  5693. }
  5694. // SAFETY: a live buffer.
  5695. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  5696. }
  5697. /// The budget's words in the card's own memory ([`card_budget`]), if
  5698. /// the list can zero them itself (`WriteBufferImmediate`).
  5699. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  5700. if !card_budget() {
  5701. return None;
  5702. }
  5703. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  5704. let buffer = host()?.uav_buffer(256)?;
  5705. name(&buffer, || "indirect budget".to_owned());
  5706. Some(buffer)
  5707. }
  5708. /// Records, before the list's first clamp, the zeroing of the card's
  5709. /// copy of the budget: common, written as a copy, then left for
  5710. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  5711. fn zero_card_budget(&self, card: &ID3D12Resource) {
  5712. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  5713. return;
  5714. };
  5715. // SAFETY: a live buffer.
  5716. let at = unsafe { card.GetGPUVirtualAddress() };
  5717. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  5718. Dest: at + offset,
  5719. Value: 0,
  5720. });
  5721. // SAFETY: an open list; the buffer is the list's own and in the
  5722. // common state at the start of every recording.
  5723. unsafe {
  5724. self.list.ResourceBarrier(&[transition(
  5725. card,
  5726. D3D12_RESOURCE_STATE_COMMON,
  5727. D3D12_RESOURCE_STATE_COPY_DEST,
  5728. )]);
  5729. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  5730. self.list.ResourceBarrier(&[transition(
  5731. card,
  5732. D3D12_RESOURCE_STATE_COPY_DEST,
  5733. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5734. )]);
  5735. }
  5736. }
  5737. /// Before the list closes, if this recording charged the card's copy
  5738. /// of the budget: its notes on mesh records go to the mapped words
  5739. /// (read at the next submission), and it goes back to common.
  5740. fn card_budget_out(&self) {
  5741. if !self.deferred().budget_zeroed {
  5742. return;
  5743. }
  5744. let (Some(Some(card)), Some(Some((mapped, _)))) =
  5745. (self.card_budget.get(), self.budget.get())
  5746. else {
  5747. return;
  5748. };
  5749. // SAFETY: an open list; both buffers are the list's own. The
  5750. // mapped one is promoted from common to the copy destination.
  5751. unsafe {
  5752. self.list.ResourceBarrier(&[transition(
  5753. card,
  5754. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5755. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5756. )]);
  5757. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  5758. self.list.ResourceBarrier(&[transition(
  5759. card,
  5760. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5761. D3D12_RESOURCE_STATE_COMMON,
  5762. )]);
  5763. }
  5764. }
  5765. /// A device-local unordered-access buffer of at least `size` bytes for
  5766. /// clamped indirect arguments, reused across executions and resets of the
  5767. /// list. Smaller buffers replaced mid-list stay alive until
  5768. /// [`HostList::reset`].
  5769. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  5770. let needed = size.max(64 << 10);
  5771. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  5772. if let Some((buffer, cap)) = &*slot
  5773. && *cap >= needed
  5774. {
  5775. return Some(buffer.clone());
  5776. }
  5777. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  5778. let alloc = prev
  5779. .saturating_mul(2)
  5780. .max(needed)
  5781. .next_multiple_of(64 << 10);
  5782. let buffer = host()?.uav_buffer(alloc)?;
  5783. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  5784. let old = slot.replace((buffer.clone(), alloc));
  5785. drop(slot);
  5786. if let Some((old_buf, _)) = old {
  5787. // It ends the list common, as every scratch buffer does.
  5788. self.indirect_common(&old_buf);
  5789. self.keep(&old_buf);
  5790. }
  5791. Some(buffer)
  5792. }
  5793. /// Where the next batch of clamped records goes: a device-local buffer
  5794. /// the list keeps from recording to recording, the batch's place in it
  5795. /// and the state the buffer is in. Every batch of a recording has a place
  5796. /// of its own: the executions before it may still read theirs.
  5797. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  5798. use crate::indirect::batch::{JOBS, SLOT};
  5799. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5800. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  5801. if buffer == args.0.len() {
  5802. let size = u64::from(BATCHES * JOBS * SLOT);
  5803. let made = host()?.uav_buffer(size)?;
  5804. name(&made, || format!("indirect batches {size:#x}"));
  5805. args.0.push(made);
  5806. }
  5807. args.1 += 1;
  5808. // (Its first batch finds it as the recording before left it:
  5809. // `batches_common`.)
  5810. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  5811. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  5812. }
  5813. /// Before the list closes: the scratch buffers of the batched clamps go
  5814. /// back to the common state, where the next recording expects them.
  5815. fn batches_common(&self) {
  5816. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5817. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  5818. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  5819. .iter()
  5820. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  5821. .collect();
  5822. if !barriers.is_empty() {
  5823. // SAFETY: an open list and live buffers this recording left in
  5824. // `INDIRECT_ARGUMENT`.
  5825. unsafe { self.list.ResourceBarrier(&barriers) };
  5826. }
  5827. }
  5828. /// Moves `scratch` back to the common state if a clamp left it readable
  5829. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  5830. /// list's first clamp expects it. Done before the list closes and before
  5831. /// a bigger scratch buffer replaces it: one barrier per list (where
  5832. /// there was one per indirect execution), and the list ends as it
  5833. /// begins however it is submitted.
  5834. fn indirect_common(&self, scratch: &ID3D12Resource) {
  5835. {
  5836. let mut deferred = self.deferred();
  5837. if deferred.indirect_readable != scratch.as_raw() as usize {
  5838. return;
  5839. }
  5840. deferred.indirect_readable = 0;
  5841. }
  5842. let barrier = transition(
  5843. scratch,
  5844. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  5845. D3D12_RESOURCE_STATE_COMMON,
  5846. );
  5847. // SAFETY: an open list and a live buffer this recording left in
  5848. // `INDIRECT_ARGUMENT`.
  5849. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5850. }
  5851. /// The state the list's indirect scratch buffer `scratch` is in at this
  5852. /// point of the recording: indirect arguments if a clamp in this
  5853. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  5854. /// common: the state a buffer is made in, and the one a recording
  5855. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  5856. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  5857. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  5858. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  5859. } else {
  5860. D3D12_RESOURCE_STATE_COMMON
  5861. }
  5862. }
  5863. /// A clamp recorded in this list left `scratch` readable as indirect
  5864. /// arguments. It stays so for every execution that reads it, until the
  5865. /// next clamp moves it back to unordered access.
  5866. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  5867. self.deferred().indirect_readable = scratch.as_raw() as usize;
  5868. }
  5869. /// Keeps `object` alive until the list is reset.
  5870. pub(crate) fn keep(&self, object: &impl Interface) {
  5871. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  5872. self.deferred().kept.push(object);
  5873. }
  5874. }
  5875. /// Whether this is the first time since the reset that the list asks
  5876. /// about `key` (a texture to bring up to date).
  5877. pub(crate) fn first_use(&self, key: usize) -> bool {
  5878. self.deferred().textures.insert(key)
  5879. }
  5880. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  5881. /// reset.
  5882. pub(crate) fn used(&self, key: usize) -> bool {
  5883. self.deferred().textures.contains(&key)
  5884. }
  5885. /// Runs `work` when the list is submitted, in order with its copies.
  5886. /// `work` may write title memory (refreshes after it copy again).
  5887. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  5888. self.deferred().copies.push(Step::Run(Box::new(work)));
  5889. self.deferred().refreshed.clear();
  5890. }
  5891. /// As [`HostList::defer`], for work that writes only host memory.
  5892. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  5893. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  5894. }
  5895. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  5896. /// memory at `from`.
  5897. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  5898. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  5899. }
  5900. /// Brings a texture's staging buffer up to date when the list is
  5901. /// submitted, keeping it alive until the list is reset.
  5902. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  5903. self.deferred().copies.push(Step::Texture(staging));
  5904. }
  5905. /// Runs the list's submission-time steps; refreshes go into `batch`
  5906. /// (the title's big buffers, a 174 MB one among them, are read by most
  5907. /// lists of a submission, through many ranges). Copies and fills that
  5908. /// `taken` names (by their place) are left out: they are done on the
  5909. /// card ([`card_steps`]).
  5910. fn run_deferred(&self, batch: &mut Batch, taken: impl Fn(usize) -> bool) {
  5911. #[cfg(feature = "diagnostics")]
  5912. use crate::copystat::{C, add};
  5913. // The time and the bytes of the copies and fills, some 13,000 a
  5914. // frame between 20,000 refreshes: summed here and added once.
  5915. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  5916. #[cfg(feature = "diagnostics")]
  5917. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  5918. for (i, step) in self.deferred().copies.iter().enumerate() {
  5919. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  5920. continue;
  5921. }
  5922. let (started, copied) = match step {
  5923. &Step::Copy(dst, src, len) => {
  5924. let started = std::time::Instant::now();
  5925. #[cfg(feature = "diagnostics")]
  5926. {
  5927. copies += 1;
  5928. }
  5929. batch.title_written();
  5930. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  5931. // With the submission's one asking: the journal learns it.
  5932. crate::watch::wrote(dst, len);
  5933. // What the card holds there may be another value although
  5934. // ours did not change.
  5935. if send::own() {
  5936. crate::shadow::send_copied(dst, len);
  5937. }
  5938. (started, len)
  5939. }
  5940. &Step::Fill(dst, src, len, _) => {
  5941. let started = std::time::Instant::now();
  5942. #[cfg(feature = "diagnostics")]
  5943. {
  5944. copies += 1;
  5945. }
  5946. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  5947. (started, len)
  5948. }
  5949. Step::Refresh(shadow, address, len) => {
  5950. #[cfg(feature = "diagnostics")]
  5951. {
  5952. refreshes += 1;
  5953. refreshed += *len as u64;
  5954. }
  5955. batch.add(shadow, *address, *len);
  5956. continue;
  5957. }
  5958. Step::Run(work) | Step::Host(work, _) => {
  5959. #[cfg(feature = "diagnostics")]
  5960. let started = std::time::Instant::now();
  5961. if matches!(step, Step::Run(_)) {
  5962. batch.title_written();
  5963. }
  5964. work();
  5965. // It wrote title memory, where is not known here: the
  5966. // submission's one asking ends, later refreshes ask anew.
  5967. if matches!(step, Step::Run(_)) {
  5968. crate::watch::ask_once_end();
  5969. }
  5970. #[cfg(feature = "diagnostics")]
  5971. {
  5972. add(C::Runs, 1);
  5973. add(C::RunUs, started.elapsed().as_micros() as u64);
  5974. }
  5975. continue;
  5976. }
  5977. Step::GpuWrite(shadow, address, len) => {
  5978. // The shaders start from the title's data: this copy's
  5979. // pending refresh first. The other copies' wait for
  5980. // the next flush of all (flushing all of them at every
  5981. // range a dispatch writes made thousands of write-watch
  5982. // askings a frame).
  5983. batch.flush_one(shadow);
  5984. #[cfg(feature = "diagnostics")]
  5985. let snapshot = std::time::Instant::now();
  5986. shadow.writing(*address, *len);
  5987. #[cfg(feature = "diagnostics")]
  5988. {
  5989. add(C::GpuWrites, 1);
  5990. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  5991. }
  5992. continue;
  5993. }
  5994. Step::Texture(staging) => {
  5995. if batch.texture_due(staging) {
  5996. batch.due.push(staging.clone());
  5997. if !wide_textures() {
  5998. batch.refresh_textures();
  5999. }
  6000. }
  6001. continue;
  6002. }
  6003. };
  6004. us += started.elapsed();
  6005. bytes += copied as u64;
  6006. }
  6007. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  6008. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  6009. #[cfg(feature = "diagnostics")]
  6010. {
  6011. add(C::Copies, copies);
  6012. add(C::CopyBytes, bytes);
  6013. add(C::Refreshes, refreshes);
  6014. add(C::RefreshBytes, refreshed);
  6015. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  6016. }
  6017. }
  6018. }
  6019. /// A table by a copy's address.
  6020. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  6021. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  6022. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  6023. /// but our own.
  6024. #[derive(Default)]
  6025. pub(crate) struct AddressHash(u64);
  6026. impl std::hash::Hasher for AddressHash {
  6027. fn finish(&self) -> u64 {
  6028. self.0
  6029. }
  6030. fn write(&mut self, bytes: &[u8]) {
  6031. for &b in bytes {
  6032. self.write_usize(usize::from(b));
  6033. }
  6034. }
  6035. fn write_usize(&mut self, n: usize) {
  6036. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  6037. self.0 = h ^ (h >> 32);
  6038. }
  6039. }
  6040. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  6041. /// preparing: the write-watch asking for a submission; the title's bytes put
  6042. /// in under flights' writes; the lists' steps, the refreshes among them; the
  6043. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  6044. /// of the steps: the refreshes, and the copies and fills (those with the
  6045. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  6046. /// is of. Of the refreshes, those before ranges are given to shaders, one
  6047. /// copy at a time: nanoseconds, and how many.
  6048. #[cfg(feature = "diagnostics")]
  6049. static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  6050. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  6051. /// those known to copy nothing, and those done on several threads.
  6052. #[cfg(feature = "diagnostics")]
  6053. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  6054. /// Counts into [`SPLIT`].
  6055. #[cfg(feature = "diagnostics")]
  6056. struct Split(std::cell::Cell<std::time::Instant>);
  6057. #[cfg(feature = "diagnostics")]
  6058. impl Split {
  6059. fn begin() -> Split {
  6060. Split(std::cell::Cell::new(std::time::Instant::now()))
  6061. }
  6062. /// Nanoseconds since the last part.
  6063. fn so_far(&self) -> u64 {
  6064. self.0.get().elapsed().as_nanos() as u64
  6065. }
  6066. /// What came since the last part was part `i`.
  6067. fn part(&self, i: usize) {
  6068. let now = std::time::Instant::now();
  6069. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  6070. }
  6071. }
  6072. /// The split of the preparing, per frame, for the frame-rate line.
  6073. #[cfg(feature = "diagnostics")]
  6074. fn split_line(frames: f64) {
  6075. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6076. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  6077. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  6078. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6079. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
  6080. tracing::info!(
  6081. "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' \
  6082. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  6083. 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 \
  6084. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
  6085. ms[0],
  6086. ms[8],
  6087. ms[1],
  6088. ms[2],
  6089. ms[6],
  6090. f[0],
  6091. f[1],
  6092. f[2],
  6093. f[3],
  6094. ms[9],
  6095. ms[10] * 1e6,
  6096. ms[7],
  6097. ms[3],
  6098. ms[4],
  6099. ms[5],
  6100. if crate::watch::light() { "on" } else { "off" },
  6101. );
  6102. tracing::info!(
  6103. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6104. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6105. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6106. waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
  6107. as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
  6108. a[0],
  6109. a[1] / 1024.0,
  6110. a[11] / 1e6,
  6111. a[12],
  6112. a[10],
  6113. a[9],
  6114. a[2],
  6115. a[3],
  6116. a[4],
  6117. a[5],
  6118. a[6],
  6119. a[7] / 1e6,
  6120. a[8] / 1e6,
  6121. s[0] / 1048576.0,
  6122. s[1] / 1048576.0,
  6123. s[2] / 1048576.0,
  6124. s[3],
  6125. );
  6126. tracing::info!(
  6127. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures",
  6128. h[0],
  6129. h[1],
  6130. h[2],
  6131. );
  6132. }
  6133. /// Whether a submission's refreshes of host copies run on several threads,
  6134. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6135. ///
  6136. /// A submission brings some sixty copies up to date, one after the other
  6137. /// on the submitting thread: for each, the pages the title wrote are asked
  6138. /// for and read through the kernel into the copy. That is the frame line's
  6139. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6140. /// another: each refresh writes its own copy and its own notes, and reads
  6141. /// title memory. With the switch the copies of a flush (four or more) are
  6142. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6143. /// The write-watch journal and the guards are behind their own locks, as
  6144. /// they are for the title's threads.
  6145. fn wide_refresh() -> bool {
  6146. static ON: OnceLock<bool> = OnceLock::new();
  6147. *ON.get_or_init(|| {
  6148. wide_refresh_enabled(
  6149. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6150. std::thread::available_parallelism().ok().map(|n| n.get()),
  6151. )
  6152. })
  6153. }
  6154. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6155. match setting {
  6156. Some("1") => true,
  6157. Some("0") => false,
  6158. _ => logical_cpus.is_some_and(|n| n >= 4),
  6159. }
  6160. }
  6161. #[cfg(test)]
  6162. mod wide_refresh_tests {
  6163. use super::wide_refresh_enabled;
  6164. #[test]
  6165. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6166. assert!(wide_refresh_enabled(None, Some(4)));
  6167. assert!(wide_refresh_enabled(None, Some(16)));
  6168. assert!(!wide_refresh_enabled(None, Some(2)));
  6169. assert!(!wide_refresh_enabled(None, None));
  6170. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6171. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6172. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6173. }
  6174. }
  6175. /// A submission's refreshes not done yet, merged per buffer copy into the
  6176. /// range that covers them: done before a step that writes title memory or
  6177. /// gives a range to shaders, and before the lists run.
  6178. ///
  6179. /// Also the textures brought up to date in the submission so far: most
  6180. /// lists of a world submission sample the same textures, and a texture in
  6181. /// physical-page memory is hashed whole each time it is checked. Checked
  6182. /// once, it is checked again only after a step that writes title memory.
  6183. #[derive(Default)]
  6184. struct Batch {
  6185. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6186. /// Where each copy (by address) is in `refreshes`: the list that makes
  6187. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6188. /// for every refresh of a submission was tens of millions of
  6189. /// comparisons a frame.
  6190. index: ByCopy<usize>,
  6191. /// Staging buffers (by address) refreshed since the last title write,
  6192. /// or due to be.
  6193. textures: std::collections::HashSet<usize>,
  6194. /// Those due ([`Batch::refresh_textures`]).
  6195. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6196. }
  6197. /// Whether a submission's textures are brought up to date on several
  6198. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6199. /// name them, as before).
  6200. ///
  6201. /// They are read, hashed and, if they changed, detiled into their staging
  6202. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6203. /// its own buffer, notes and lock, and is refreshed by the title's own
  6204. /// threads as it is. They are done before the next step that writes title
  6205. /// memory, as the copies' refreshes are, and before the lists go to the
  6206. /// card. What is new: the note of a list that its upload takes what the
  6207. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6208. /// an earlier list of the submission asked for, not behind it. The texture
  6209. /// is then uploaded by a later list too, once more than needed.
  6210. fn wide_textures() -> bool {
  6211. static ON: OnceLock<bool> = OnceLock::new();
  6212. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6213. }
  6214. impl Batch {
  6215. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6216. let end = address + len;
  6217. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6218. match self.index.get(&key) {
  6219. Some(&at) => {
  6220. let r = &mut self.refreshes[at];
  6221. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6222. }
  6223. None => {
  6224. self.index.insert(key, self.refreshes.len());
  6225. self.refreshes.push((shadow.clone(), address, end));
  6226. }
  6227. }
  6228. }
  6229. /// Before shaders are given a range of `shadow`'s copy: its pending
  6230. /// refresh is done, the others stay pending.
  6231. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  6232. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  6233. return;
  6234. };
  6235. let (shadow, from, to) = self.refreshes.swap_remove(at);
  6236. // The last entry took its place.
  6237. if let Some(moved) = self.refreshes.get(at) {
  6238. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  6239. }
  6240. #[cfg(feature = "diagnostics")]
  6241. let started = std::time::Instant::now();
  6242. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  6243. Self::update(&shadow, from, to);
  6244. }
  6245. #[cfg(feature = "diagnostics")]
  6246. {
  6247. let ns = started.elapsed().as_nanos() as u64;
  6248. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6249. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6250. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  6251. }
  6252. }
  6253. /// Brings `[from, to)` of a copy up to date, timed.
  6254. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  6255. let started = std::time::Instant::now();
  6256. let copied = shadow.update(from, to - from);
  6257. let us = started.elapsed().as_micros() as u64;
  6258. #[cfg(feature = "diagnostics")]
  6259. crate::copystat::range(from, to - from, us, 0);
  6260. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  6261. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  6262. }
  6263. /// Whether `staging` is still to be refreshed in this submission (and
  6264. /// notes it refreshed).
  6265. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  6266. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  6267. }
  6268. /// Before a step that writes title memory: pending refreshes are done
  6269. /// first, and textures are checked again after it.
  6270. fn title_written(&mut self) {
  6271. self.flush();
  6272. self.textures.clear();
  6273. }
  6274. /// The textures due are brought up to date.
  6275. fn refresh_textures(&mut self) {
  6276. if self.due.len() < 2 || !wide_textures() {
  6277. self.due.drain(..).for_each(|staging| staging.refresh());
  6278. return;
  6279. }
  6280. // The time counted is the time it took, not the threads' sum.
  6281. let started = std::time::Instant::now();
  6282. let before = PREPARING[2].load(Ordering::Relaxed);
  6283. let due = std::mem::take(&mut self.due);
  6284. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  6285. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  6286. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6287. }
  6288. fn flush(&mut self) {
  6289. self.refresh_textures();
  6290. self.index.clear();
  6291. if self.refreshes.is_empty() {
  6292. return;
  6293. }
  6294. #[cfg(feature = "diagnostics")]
  6295. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  6296. self.flush_all();
  6297. #[cfg(feature = "diagnostics")]
  6298. {
  6299. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6300. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  6301. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  6302. }
  6303. }
  6304. fn flush_all(&mut self) {
  6305. // Most of a flush's copies are as they were: they are told so here,
  6306. // from what the submission's asking found, before anything is asked
  6307. // and any thread woken. (Thousands of them, the heap's buffer views
  6308. // once a frame: on the threads, below.)
  6309. const FEW: usize = 256;
  6310. let light = crate::watch::light();
  6311. if light && self.refreshes.len() <= FEW {
  6312. let started = std::time::Instant::now();
  6313. #[cfg(feature = "diagnostics")]
  6314. let all = self.refreshes.len();
  6315. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  6316. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6317. #[cfg(feature = "diagnostics")]
  6318. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  6319. }
  6320. // One write-watch asking for the copies that lie close together,
  6321. // not one per copy.
  6322. let ahead = self.refreshes.len() > 1;
  6323. if ahead {
  6324. let started = std::time::Instant::now();
  6325. let ranges: Vec<(usize, usize)> = self
  6326. .refreshes
  6327. .iter()
  6328. .filter(|r| r.0.asked_ahead())
  6329. .map(|r| (r.1, r.2))
  6330. .collect();
  6331. crate::watch::ask_ahead(&ranges);
  6332. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6333. }
  6334. if wide_refresh() && self.refreshes.len() >= 4 {
  6335. // Each copy on its own, several at a time: a copy's refresh
  6336. // writes that copy and reads title memory, nothing of another's.
  6337. // The time counted is the time it took, not the threads' sum.
  6338. let started = std::time::Instant::now();
  6339. let before = PREPARING[0].load(Ordering::Relaxed);
  6340. #[cfg(feature = "diagnostics")]
  6341. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  6342. if light {
  6343. // A number to a free thread, not a job to each copy.
  6344. let refreshes = std::mem::take(&mut self.refreshes);
  6345. crate::shadow::wide_each(refreshes.len(), move |i| {
  6346. let (shadow, from, to) = &refreshes[i];
  6347. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  6348. #[cfg(feature = "diagnostics")]
  6349. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  6350. return;
  6351. }
  6352. Self::update(shadow, *from, *to);
  6353. });
  6354. } else {
  6355. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  6356. .refreshes
  6357. .drain(..)
  6358. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  6359. .collect();
  6360. crate::shadow::wide_run(jobs);
  6361. }
  6362. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6363. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6364. } else {
  6365. for (shadow, from, to) in self.refreshes.drain(..) {
  6366. Self::update(&shadow, from, to);
  6367. }
  6368. }
  6369. if ahead {
  6370. crate::watch::ask_ahead_done();
  6371. }
  6372. }
  6373. }
  6374. /// Copies title memory at submission. The ranges were checked against their
  6375. /// resources when recorded, but the title may since have unmapped pages of
  6376. /// them (tiled memory, page mappings), which read as zeros here; a title
  6377. /// destination (`title_dst`) that is not all mapped is left alone.
  6378. ///
  6379. /// The source is read through the kernel (`ReadProcessMemory`), which
  6380. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  6381. /// cost about 2 ms per copy in the title's big pools (it walks the page
  6382. /// tables to the region's end), which made copies run at 100-200 MB/s.
  6383. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  6384. #[cfg(feature = "diagnostics")]
  6385. match crate::copystat::mode() {
  6386. 1 => {
  6387. // SAFETY: timing only: the caller vouches for the source.
  6388. unsafe { std::ptr::copy(src, dst, len) };
  6389. return;
  6390. }
  6391. 2 => return,
  6392. _ => {}
  6393. }
  6394. if len == 0 {
  6395. return;
  6396. }
  6397. // A title destination that is not all mapped is left alone. Asking
  6398. // Windows first (`VirtualQuery`) walks the page tables to the end of
  6399. // the destination's region: in the title's big blocks that is
  6400. // milliseconds a copy, and it was a seventh of the submitting thread's
  6401. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  6402. // says the same when it fails, so the question is only asked then.
  6403. // `VICTORY_COPY_ASK=1` asks first, as before.
  6404. static ASK: OnceLock<bool> = OnceLock::new();
  6405. let ask_first = title_dst
  6406. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  6407. if ask_first && !crate::texture::committed(dst, len) {
  6408. return;
  6409. }
  6410. if title_dst {
  6411. // The kernel writes the destination: it must not be guarded.
  6412. crate::watch::writing(dst as usize, len);
  6413. }
  6414. #[cfg(feature = "diagnostics")]
  6415. let moved = std::time::Instant::now();
  6416. let since = crate::watch::changes();
  6417. // (A title destination that is away only while the runtime changes a
  6418. // mapping beside it is written when that is done.)
  6419. let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
  6420. #[cfg(feature = "diagnostics")]
  6421. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  6422. if whole {
  6423. return;
  6424. }
  6425. // The copy failed: a source page is not there, or the destination is
  6426. // not all mapped. Then the destination stays as it is (the kernel may
  6427. // have written its first pages).
  6428. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  6429. crate::watch::lost("a copy of the title's", dst as usize, len);
  6430. return;
  6431. }
  6432. #[cfg(feature = "diagnostics")]
  6433. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  6434. #[cfg(feature = "diagnostics")]
  6435. let sparse = std::time::Instant::now();
  6436. if !title_dst && len >= 64 << 10 {
  6437. read_sparse(src, dst, len);
  6438. } else {
  6439. read_pieces(src, dst, len);
  6440. }
  6441. #[cfg(feature = "diagnostics")]
  6442. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  6443. }
  6444. /// After a failed bulk read into host memory, skip contiguous holes. Never
  6445. /// cache the query across copies: the title may remap the same address.
  6446. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  6447. use windows_sys::Win32::System::Memory::{
  6448. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  6449. };
  6450. let mut offset = 0;
  6451. while offset < len {
  6452. let at = src.wrapping_add(offset);
  6453. let to = dst.wrapping_add(offset);
  6454. let remaining = len - offset;
  6455. // SAFETY: the query inspects an address and fills a local structure.
  6456. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  6457. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  6458. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  6459. .saturating_sub(at as usize).min(remaining);
  6460. if size != size_of_val(&info) || n == 0 {
  6461. read_pieces(at, to, remaining);
  6462. break;
  6463. }
  6464. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  6465. #[cfg(feature = "diagnostics")]
  6466. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6467. // SAFETY: this path is only used with a writable host destination.
  6468. unsafe { to.write_bytes(0, n) };
  6469. } else if !read(at, to, n) {
  6470. // A mapping may change between query and read.
  6471. read_pieces(at, to, n);
  6472. }
  6473. offset += n;
  6474. }
  6475. }
  6476. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  6477. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  6478. // that fails), zeros for what cannot be read.
  6479. for_pieces(src as usize, len, 64 << 10, |at, n| {
  6480. let to = dst.wrapping_add(at - src as usize);
  6481. if !read(at as *const u8, to, n) {
  6482. for_pieces(at, n, 4 << 10, |at, n| {
  6483. let to = dst.wrapping_add(at - src as usize);
  6484. if !read(at as *const u8, to, n) {
  6485. #[cfg(feature = "diagnostics")]
  6486. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6487. zero(to, n);
  6488. }
  6489. });
  6490. }
  6491. });
  6492. }
  6493. /// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
  6494. /// destination of a title's copy), which can go between the question whether
  6495. /// it is there and this.
  6496. fn zero(to: *mut u8, n: usize) {
  6497. static ZEROS: [u8; 4096] = [0; 4096];
  6498. if n <= ZEROS.len() && crate::safecopy::on() {
  6499. // SAFETY: a destination that is not there fails the copy.
  6500. if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
  6501. crate::watch::lost("zeros", to as usize, n);
  6502. }
  6503. return;
  6504. }
  6505. // SAFETY: inside the destination, which is mapped.
  6506. unsafe { to.write_bytes(0, n) };
  6507. }
  6508. /// Reads title memory at `src` into `dst`; false if a page of it is not
  6509. /// readable.
  6510. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  6511. read(src, dst.as_mut_ptr(), dst.len())
  6512. }
  6513. /// Reads what is there of the `dst.len()` bytes of title memory at `src`,
  6514. /// zeros for the rest; returns how many bytes were there. Safe while the
  6515. /// runtime remaps title memory (the kernel, or a copy that takes the fault,
  6516. /// reads). What the runtime's record says is mapped is read in one go each,
  6517. /// and by pieces where that fails; memory it has no record of by pieces.
  6518. pub(crate) fn read_there(src: *const u8, dst: &mut [u8]) -> usize {
  6519. dst.fill(0);
  6520. let (start, len) = (src as usize, dst.len());
  6521. let mut got = 0;
  6522. let mut runs = crate::inplace::shown_runs(start, len);
  6523. if runs.is_empty() {
  6524. runs.push((start, len));
  6525. }
  6526. for (at, n) in runs {
  6527. let piece = &mut dst[at - start..at - start + n];
  6528. if read_into(at as *const u8, piece) {
  6529. got += n;
  6530. continue;
  6531. }
  6532. // (What failed may have written its first pages.)
  6533. piece.fill(0);
  6534. for_pieces(at, n, 64 << 10, |from, n| {
  6535. let piece = &mut dst[from - start..from - start + n];
  6536. if read_into(from as *const u8, piece) {
  6537. got += n;
  6538. return;
  6539. }
  6540. piece.fill(0);
  6541. for_pieces(from, n, 4 << 10, |from, n| {
  6542. let piece = &mut dst[from - start..from - start + n];
  6543. if read_into(from as *const u8, piece) {
  6544. got += n;
  6545. } else {
  6546. piece.fill(0);
  6547. }
  6548. });
  6549. });
  6550. }
  6551. got
  6552. }
  6553. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  6554. /// readable.
  6555. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  6556. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  6557. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6558. if crate::safecopy::on() {
  6559. // SAFETY: the destination is mapped writable memory of `len` bytes;
  6560. // a source page that is not there fails the copy.
  6561. return unsafe { crate::safecopy::copy(dst, src, len) };
  6562. }
  6563. let mut done = 0;
  6564. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  6565. // kernel checks the source.
  6566. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  6567. }
  6568. #[link(name = "ntdll", kind = "raw-dylib")]
  6569. unsafe extern "system" {
  6570. /// The kernel's write into a process's memory, `(process, address,
  6571. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  6572. /// the range is not there or not writable. It changes no protection.
  6573. fn NtWriteVirtualMemory(
  6574. process: *mut std::ffi::c_void,
  6575. base: *mut std::ffi::c_void,
  6576. buffer: *const std::ffi::c_void,
  6577. size: usize,
  6578. written: *mut usize,
  6579. ) -> i32;
  6580. }
  6581. /// Whether title memory is written with the kernel's own call
  6582. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  6583. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  6584. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  6585. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  6586. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  6587. fn direct_writes() -> bool {
  6588. static ON: OnceLock<bool> = OnceLock::new();
  6589. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  6590. }
  6591. /// Copies host memory into title memory after a submission (what shaders
  6592. /// wrote), leaving pages that are not mapped alone.
  6593. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  6594. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  6595. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6596. let direct = direct_writes();
  6597. let since = crate::watch::changes();
  6598. let write = |at: usize, n: usize| {
  6599. let from = src.wrapping_add(at - dst as usize);
  6600. if crate::safecopy::on() {
  6601. // SAFETY: the source is ours; a destination page that is not
  6602. // there, or not writable, fails the copy.
  6603. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  6604. }
  6605. let mut done = 0;
  6606. if direct {
  6607. // SAFETY: as below; the kernel checks the destination and
  6608. // writes nothing it cannot (the caller opened its guards:
  6609. // `crate::watch::writing`).
  6610. return unsafe {
  6611. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  6612. };
  6613. }
  6614. // SAFETY: the source is our mapped host copy; the kernel checks the
  6615. // destination.
  6616. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  6617. };
  6618. if len == 0 || write(dst as usize, len) {
  6619. return;
  6620. }
  6621. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  6622. if !write(at, n) {
  6623. for_pieces(at, n, 4 << 10, |at, n| {
  6624. if write(at, n) {
  6625. return;
  6626. }
  6627. // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
  6628. // refresh guarded the block again since the caller opened
  6629. // it; and any where the runtime was changing a mapping.
  6630. crate::watch::writing(at, n);
  6631. if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
  6632. crate::watch::lost("a host copy's bytes", at, n);
  6633. }
  6634. });
  6635. }
  6636. });
  6637. }
  6638. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  6639. /// `step`.
  6640. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  6641. let end = start + len;
  6642. let mut at = start;
  6643. while at < end {
  6644. let next = ((at / step + 1) * step).min(end);
  6645. f(at, next - at);
  6646. at = next;
  6647. }
  6648. }
  6649. impl Host {
  6650. /// The queue everything of ours runs on, for a call that must go to it
  6651. /// in order with the lists (`crate::tiles`: a texture's levels are
  6652. /// given memory ahead of the list that uploads them).
  6653. pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
  6654. &self.queue
  6655. }
  6656. /// A buffer in the upload heap, mapped for writing.
  6657. /// A buffer of `size` bytes the card writes and we read (a read back),
  6658. /// in the state copies into it need.
  6659. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  6660. let heap = D3D12_HEAP_PROPERTIES {
  6661. Type: D3D12_HEAP_TYPE_READBACK,
  6662. ..Default::default()
  6663. };
  6664. let desc = D3D12_RESOURCE_DESC {
  6665. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6666. Width: size.max(1),
  6667. Height: 1,
  6668. DepthOrArraySize: 1,
  6669. MipLevels: 1,
  6670. SampleDesc: DXGI_SAMPLE_DESC {
  6671. Count: 1,
  6672. Quality: 0,
  6673. },
  6674. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6675. ..Default::default()
  6676. };
  6677. let mut buffer: Option<ID3D12Resource> = None;
  6678. // SAFETY: plain creation of a read-back buffer.
  6679. let made = unsafe {
  6680. self.device.CreateCommittedResource(
  6681. &heap,
  6682. D3D12_HEAP_FLAG_NONE,
  6683. &desc,
  6684. D3D12_RESOURCE_STATE_COPY_DEST,
  6685. None,
  6686. &mut buffer,
  6687. )
  6688. };
  6689. match made {
  6690. Ok(()) => buffer,
  6691. Err(e) => {
  6692. tracing::warn!(error = %e, size, "no read-back buffer");
  6693. None
  6694. }
  6695. }
  6696. }
  6697. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6698. MADE[0].fetch_add(1, Ordering::Relaxed);
  6699. MADE[1].fetch_add(size, Ordering::Relaxed);
  6700. let heap = D3D12_HEAP_PROPERTIES {
  6701. Type: D3D12_HEAP_TYPE_UPLOAD,
  6702. ..Default::default()
  6703. };
  6704. let desc = D3D12_RESOURCE_DESC {
  6705. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6706. Width: size.max(1),
  6707. Height: 1,
  6708. DepthOrArraySize: 1,
  6709. MipLevels: 1,
  6710. SampleDesc: DXGI_SAMPLE_DESC {
  6711. Count: 1,
  6712. Quality: 0,
  6713. },
  6714. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6715. ..Default::default()
  6716. };
  6717. let mut buffer: Option<ID3D12Resource> = None;
  6718. let mut data = std::ptr::null_mut();
  6719. // SAFETY: plain creation and mapping of an upload buffer.
  6720. let made = unsafe {
  6721. self.device
  6722. .CreateCommittedResource(
  6723. &heap,
  6724. D3D12_HEAP_FLAG_NONE,
  6725. &desc,
  6726. D3D12_RESOURCE_STATE_GENERIC_READ,
  6727. None,
  6728. &mut buffer,
  6729. )
  6730. .and_then(|()| {
  6731. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  6732. b.Map(0, None, Some(&mut data))
  6733. })
  6734. };
  6735. match made {
  6736. Ok(()) => Some((buffer?, data.cast())),
  6737. Err(e) => {
  6738. tracing::warn!(error = %e, size, "no upload buffer");
  6739. None
  6740. }
  6741. }
  6742. }
  6743. }
  6744. /// The swap chain formats a presented texture can be copied into: its own
  6745. /// family's.
  6746. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  6747. Some(match format.0 {
  6748. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  6749. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  6750. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  6751. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  6752. _ => return None,
  6753. })
  6754. }
  6755. const BUFFERS: u32 = 2;
  6756. struct Presenter {
  6757. swap_chain: IDXGISwapChain3,
  6758. width: u32,
  6759. height: u32,
  6760. format: DXGI_FORMAT,
  6761. copy: HostList,
  6762. /// With presents sent ahead ([`late_free_present`]): a list for each
  6763. /// present in the air, and the submission it last flew as (it is used
  6764. /// again once that one has finished).
  6765. ahead: Vec<(HostList, u64)>,
  6766. hwnd: HWND,
  6767. meter: Meter,
  6768. }
  6769. /// The frame rate, shown in the window's caption every second and logged
  6770. /// every few seconds.
  6771. struct Meter {
  6772. since: std::time::Instant,
  6773. frames: u32,
  6774. #[cfg(feature = "diagnostics")]
  6775. copy_stats_frames: u64,
  6776. drawn: u64,
  6777. logged: std::time::Instant,
  6778. /// The caption the window had, once read.
  6779. caption: Option<Vec<u16>>,
  6780. }
  6781. impl Meter {
  6782. fn new() -> Self {
  6783. let now = std::time::Instant::now();
  6784. Meter {
  6785. since: now,
  6786. frames: 0,
  6787. #[cfg(feature = "diagnostics")]
  6788. copy_stats_frames: 0,
  6789. drawn: crate::draw::drawn(),
  6790. logged: now,
  6791. caption: None,
  6792. }
  6793. }
  6794. /// Counts a presented frame.
  6795. fn frame(&mut self, hwnd: HWND) {
  6796. #[cfg(feature = "diagnostics")]
  6797. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  6798. #[cfg(feature = "diagnostics")]
  6799. crate::copystat::presented();
  6800. self.frames += 1;
  6801. #[cfg(feature = "diagnostics")]
  6802. {
  6803. self.copy_stats_frames += 1;
  6804. }
  6805. let elapsed = self.since.elapsed();
  6806. if elapsed < std::time::Duration::from_secs(1) {
  6807. return;
  6808. }
  6809. let drawn = crate::draw::drawn();
  6810. let frames = f64::from(self.frames);
  6811. let fps = frames / elapsed.as_secs_f64();
  6812. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  6813. let draws = (drawn - self.drawn) as f64 / frames;
  6814. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  6815. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  6816. let [cpu, gpu] = [0, 1].map(|i| {
  6817. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  6818. });
  6819. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  6820. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  6821. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  6822. });
  6823. let [back_ms, back_mb] = [0, 1].map(|i| {
  6824. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  6825. });
  6826. let dropped = crate::draw::take_dropped() as f64 / frames;
  6827. let indirect = crate::list::take_indirect() as f64 / frames;
  6828. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  6829. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  6830. tracing::info!(
  6831. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  6832. );
  6833. crate::shadow::exact_line(frames);
  6834. crate::descriptor::sync_line(frames);
  6835. late_line(frames);
  6836. card_clock_line(frames, ms);
  6837. crate::shadow::back_line(frames);
  6838. #[cfg(feature = "diagnostics")]
  6839. split_line(frames);
  6840. {
  6841. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6842. if passes + compares > 0.0 {
  6843. tracing::info!(
  6844. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  6845. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  6846. if rehash_runs() { "on" } else { "off" }
  6847. );
  6848. }
  6849. }
  6850. {
  6851. let [own, asking, still, all] =
  6852. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  6853. if all >= 1.0 {
  6854. tracing::info!(
  6855. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  6856. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  6857. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  6858. );
  6859. }
  6860. let [through, left, filled, short] =
  6861. [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6862. if through + left + filled > 0.0 {
  6863. tracing::info!(
  6864. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  6865. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \
  6866. {filled:.1} first fillings from the pages there (VICTORY_TEXTURE_FILL=0: left empty), {short:.1} of them \
  6867. with less than was mapped (looked at again)"
  6868. );
  6869. }
  6870. }
  6871. {
  6872. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6873. if copies > 0.0 {
  6874. tracing::info!(
  6875. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  6876. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  6877. if join_copies() { "on" } else { "off" }
  6878. );
  6879. }
  6880. }
  6881. // Passes over the heap's buffer views for shaders that pick them by index.
  6882. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  6883. let picked_ms =
  6884. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  6885. // Copies between depth textures and their colour twins, each way.
  6886. let [twin_to_depth, twin_to_colour] =
  6887. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6888. // Depth planes drawn from their twins.
  6889. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  6890. // Copies in the card's memory (`crate::shadow::cards`).
  6891. let card = crate::shadow::card_stats();
  6892. #[cfg(feature = "diagnostics")]
  6893. let slow = crate::watch::slow_asks();
  6894. // Over the same frames as the counts above.
  6895. #[cfg(feature = "diagnostics")]
  6896. let drops = crate::pipeline::take_drops();
  6897. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  6898. self.logged = std::time::Instant::now();
  6899. tracing::info!(
  6900. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  6901. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  6902. );
  6903. crate::tiles::status();
  6904. {
  6905. let [queued, due, away, partly, oldest] =
  6906. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  6907. let [same, parts, tails] =
  6908. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  6909. tracing::info!(
  6910. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  6911. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  6912. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  6913. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  6914. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  6915. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  6916. {} made slots found unmapped and made null",
  6917. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  6918. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  6919. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  6920. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  6921. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  6922. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  6923. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  6924. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  6925. );
  6926. }
  6927. {
  6928. let mode = crate::watch::page_writes();
  6929. let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
  6930. let [kept, dropped, slots, uploaded] =
  6931. [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
  6932. tracing::info!(
  6933. "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)",
  6934. bytes >> 20,
  6935. if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
  6936. if mode & 4 != 0 { "told as well" } else { "counted only" },
  6937. if mode & 2 != 0 { "made due again" } else { "left as they were" }
  6938. );
  6939. }
  6940. #[cfg(feature = "diagnostics")]
  6941. tracing::info!(
  6942. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  6943. slow[0] as f64 / frames,
  6944. slow[1] as f64 / 1e3 / frames,
  6945. slow[2] as f64 / 1e3
  6946. );
  6947. if crate::shadow::cards() {
  6948. let per_frame = |i: usize| card[i] as f64 / frames;
  6949. tracing::info!(
  6950. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  6951. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  6952. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  6953. card[7],
  6954. card[8] >> 20,
  6955. card[9] >> 20,
  6956. per_frame(0) / 1e6,
  6957. per_frame(1),
  6958. per_frame(2),
  6959. per_frame(3),
  6960. per_frame(4) / 1e6,
  6961. per_frame(5),
  6962. per_frame(6) / 1e3
  6963. );
  6964. }
  6965. tracing::info!(
  6966. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  6967. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  6968. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  6969. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  6970. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  6971. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  6972. {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}",
  6973. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  6974. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  6975. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  6976. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  6977. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  6978. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  6979. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  6980. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  6981. refused = format!(
  6982. "{} ({} 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",
  6983. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  6984. crate::shadow::OWN_MADE.load(Ordering::Relaxed),
  6985. crate::resource::TWINS[0].load(Ordering::Relaxed),
  6986. crate::resource::TWINS[1].load(Ordering::Relaxed),
  6987. crate::resource::PLANES[1].load(Ordering::Relaxed),
  6988. crate::resource::PLANES[2].load(Ordering::Relaxed)
  6989. ),
  6990. making = crate::pipeline::making(),
  6991. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  6992. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  6993. );
  6994. #[cfg(feature = "diagnostics")]
  6995. {
  6996. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  6997. tracing::info!(
  6998. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  6999. put[0],
  7000. put[1],
  7001. put[2] / 1e6,
  7002. put[3]
  7003. );
  7004. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  7005. for (why, n) in drops.iter().take(40) {
  7006. tracing::info!(
  7007. "dropped {:.1}/frame without a host pipeline: {why}",
  7008. *n as f64 / frames
  7009. );
  7010. }
  7011. }
  7012. }
  7013. if self.caption.is_none() {
  7014. // The window's own text, read without a message.
  7015. let mut buffer = vec![0u16; 512];
  7016. // SAFETY: a window handle and a buffer of that length.
  7017. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  7018. buffer.truncate(n.max(0) as usize);
  7019. self.caption = Some(buffer);
  7020. }
  7021. let Some(caption) = &self.caption else { return };
  7022. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  7023. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  7024. text.push(0);
  7025. // Setting the text waits for the window's thread (a title thread,
  7026. // which may not pump for a while), so a thread of ours does it and
  7027. // presenting never waits; it takes the newest text when free.
  7028. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  7029. static SETTER: std::sync::Once = std::sync::Once::new();
  7030. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  7031. SETTER.call_once(|| {
  7032. let _ = std::thread::Builder::new()
  7033. .name("victory-caption".into())
  7034. .spawn(|| {
  7035. loop {
  7036. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  7037. match next {
  7038. // SAFETY: a window handle and a NUL-terminated text.
  7039. Some((hwnd, text)) => unsafe {
  7040. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  7041. },
  7042. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  7043. }
  7044. }
  7045. });
  7046. });
  7047. }
  7048. }
  7049. impl Host {
  7050. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  7051. /// as frame `frame` (saved if captures are on). `None` if nothing was
  7052. /// shown; else, in diagnostics builds, whether the frame was black.
  7053. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  7054. // SAFETY: a live resource.
  7055. let desc = unsafe { texture.GetDesc() };
  7056. let Some(format) = swap_format(desc.Format) else {
  7057. tracing::warn!(format = desc.Format.0, "cannot present this format");
  7058. return None;
  7059. };
  7060. let (width, height) = (desc.Width as u32, desc.Height);
  7061. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  7062. if presenter.is_none() {
  7063. *presenter = match self.presenter(width, height, format) {
  7064. Ok(p) => Some(p),
  7065. Err(e) => {
  7066. tracing::warn!(error = %e, "no swap chain");
  7067. return None;
  7068. }
  7069. };
  7070. }
  7071. let p = presenter.as_mut()?;
  7072. if (p.width, p.height, p.format) != (width, height, format) {
  7073. // Presents sent ahead hold back buffers until they have run.
  7074. settle_now(WHY_SYNC);
  7075. // SAFETY: no back buffer is held; every submission was waited for.
  7076. let resized = unsafe {
  7077. p.swap_chain
  7078. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  7079. };
  7080. match resized {
  7081. Ok(()) => {
  7082. (p.width, p.height, p.format) = (width, height, format);
  7083. tracing::info!(
  7084. width,
  7085. height,
  7086. format = format.0,
  7087. frame,
  7088. "the swap chain's buffers were made again for another size or format"
  7089. );
  7090. self.log_video_memory("right after the swap chain's buffers were made again");
  7091. }
  7092. Err(e) => {
  7093. tracing::warn!(error = %e, width, height, "swap chain not resized");
  7094. return None;
  7095. }
  7096. }
  7097. }
  7098. let state = D3D12_RESOURCE_STATES(state as i32);
  7099. // SAFETY: our swap chain, list and a live source texture.
  7100. unsafe {
  7101. let index = p.swap_chain.GetCurrentBackBufferIndex();
  7102. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  7103. return None;
  7104. };
  7105. // Sent ahead ([`late_free_present`]) unless the frame is to be
  7106. // read back at once (a saved or listed frame): then a list of
  7107. // its own, one whose last flight has finished or a new one.
  7108. #[cfg(feature = "diagnostics")]
  7109. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  7110. #[cfg(not(feature = "diagnostics"))]
  7111. let read_now = false;
  7112. let slot = if late_free_present() && !read_now {
  7113. let finished = FINISHED.load(Ordering::Acquire);
  7114. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  7115. let list = self.new_list().ok()?;
  7116. list.close();
  7117. p.ahead.push((list, 0));
  7118. Some(p.ahead.len() - 1)
  7119. })
  7120. } else {
  7121. None
  7122. };
  7123. let copy = match slot {
  7124. Some(i) => &p.ahead[i].0,
  7125. None => &p.copy,
  7126. };
  7127. copy.reset();
  7128. let list = &copy.list;
  7129. list.ResourceBarrier(&[
  7130. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  7131. transition(
  7132. &back,
  7133. D3D12_RESOURCE_STATE_PRESENT,
  7134. D3D12_RESOURCE_STATE_COPY_DEST,
  7135. ),
  7136. ]);
  7137. list.CopyResource(&back, texture);
  7138. #[cfg(feature = "diagnostics")]
  7139. let capture = crate::capture::wanted(frame)
  7140. .then(|| crate::capture::read_back(&self.device, list, texture))
  7141. .flatten();
  7142. #[cfg(feature = "diagnostics")]
  7143. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  7144. #[cfg(not(feature = "diagnostics"))]
  7145. let _ = frame;
  7146. list.ResourceBarrier(&[
  7147. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  7148. transition(
  7149. &back,
  7150. D3D12_RESOURCE_STATE_COPY_DEST,
  7151. D3D12_RESOURCE_STATE_PRESENT,
  7152. ),
  7153. ]);
  7154. copy.close();
  7155. match slot {
  7156. Some(i) => {
  7157. let flown = self.execute_own(copy);
  7158. p.ahead[i].1 = flown;
  7159. }
  7160. None => self.execute(&[copy]),
  7161. }
  7162. #[cfg(feature = "diagnostics")]
  7163. if let Some((buffer, footprint)) = capture {
  7164. crate::capture::save_read_back(frame, &buffer, &footprint);
  7165. }
  7166. #[cfg(feature = "diagnostics")]
  7167. crate::replay::record::present(texture, state);
  7168. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  7169. p.meter.frame(p.hwnd);
  7170. #[cfg(feature = "diagnostics")]
  7171. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  7172. #[cfg(not(feature = "diagnostics"))]
  7173. Some(false)
  7174. }
  7175. }
  7176. fn presenter(
  7177. &self,
  7178. width: u32,
  7179. height: u32,
  7180. format: DXGI_FORMAT,
  7181. ) -> windows::core::Result<Presenter> {
  7182. let hwnd = match title_window() {
  7183. Some(hwnd) => hwnd,
  7184. None => window(width, height)?,
  7185. };
  7186. self.log_video_memory("right before the swap chain is made");
  7187. // SAFETY: plain object creation for our window.
  7188. unsafe {
  7189. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  7190. let desc = DXGI_SWAP_CHAIN_DESC1 {
  7191. Width: width,
  7192. Height: height,
  7193. Format: format,
  7194. SampleDesc: DXGI_SAMPLE_DESC {
  7195. Count: 1,
  7196. Quality: 0,
  7197. },
  7198. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  7199. BufferCount: BUFFERS,
  7200. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  7201. ..Default::default()
  7202. };
  7203. let swap_chain = factory
  7204. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  7205. .cast::<IDXGISwapChain3>()?;
  7206. let copy = self.new_list()?;
  7207. copy.close();
  7208. tracing::info!(width, height, format = format.0, "presenting to a window");
  7209. self.log_video_memory("right after the swap chain is made");
  7210. Ok(Presenter {
  7211. swap_chain,
  7212. width,
  7213. height,
  7214. format,
  7215. copy,
  7216. ahead: Vec::new(),
  7217. hwnd,
  7218. meter: Meter::new(),
  7219. })
  7220. }
  7221. }
  7222. }
  7223. /// A visible top-level window of this process: the one the title made, if
  7224. /// it made one.
  7225. fn title_window() -> Option<HWND> {
  7226. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  7227. let mut process = 0;
  7228. // SAFETY: a window handle from the enumeration; `found` is ours.
  7229. unsafe {
  7230. GetWindowThreadProcessId(hwnd, Some(&mut process));
  7231. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  7232. && IsWindowVisible(hwnd).as_bool()
  7233. {
  7234. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  7235. return false.into();
  7236. }
  7237. }
  7238. true.into()
  7239. }
  7240. let mut found: Option<HWND> = None;
  7241. // SAFETY: the callback only writes `found`, which outlives the call.
  7242. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  7243. found
  7244. }
  7245. /// `state` without the bits the host texture's flags forbid: the console
  7246. /// lets the title name states its own resources allow (unordered access on
  7247. /// a depth target, whose host copy cannot have both).
  7248. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  7249. // SAFETY: a plain query.
  7250. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  7251. }
  7252. /// [`legal_state`] for a texture with resource flags `flags`.
  7253. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  7254. // (flag, set or clear forbids, state bits): render target, unordered
  7255. // access, depth, denied shader resource.
  7256. const FORBIDDEN: [(u32, bool, u32); 4] = [
  7257. (0x1, false, 0x4),
  7258. (0x4, false, 0x8),
  7259. (0x2, false, 0x10 | 0x20),
  7260. (0x8, true, 0x40 | 0x80),
  7261. ];
  7262. FORBIDDEN
  7263. .iter()
  7264. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  7265. .fold(state, |s, &(_, _, bits)| s & !bits)
  7266. }
  7267. impl Host {
  7268. /// The card's memory as the system accounts it to this process, in
  7269. /// bytes: the budget and the use of the card's own memory, then of the
  7270. /// PC's memory shared with the card (where the system moves what does
  7271. /// not fit on the card).
  7272. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  7273. let adapter = self.adapter.as_ref()?;
  7274. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7275. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7276. // SAFETY: plain queries that fill our structures.
  7277. unsafe {
  7278. adapter
  7279. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7280. .ok()?;
  7281. adapter
  7282. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7283. .ok()?;
  7284. }
  7285. // The card's budget moved by 256 MB or more since the last look:
  7286. // said at once, with what was in use at the last look, so the log
  7287. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  7288. // the first world frame in runs 179 to 185, and the memory line,
  7289. // seconds later, was the first to show it. We reserve nothing
  7290. // and make the swap chain once, at the start.)
  7291. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  7292. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  7293. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  7294. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  7295. tracing::info!(
  7296. "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",
  7297. last[0] >> 20,
  7298. own.Budget >> 20,
  7299. crate::frame::current(),
  7300. last[1] >> 20,
  7301. last[2] >> 20
  7302. );
  7303. self.log_video_memory("right after that change");
  7304. }
  7305. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  7306. }
  7307. /// Both of the system's memory groups for this process, in bytes: for
  7308. /// the card's own memory and then for the PC's memory shared with the
  7309. /// card, the budget, the use, what could still be reserved and what
  7310. /// is reserved (the layer reserves none).
  7311. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  7312. let adapter = self.adapter.as_ref()?;
  7313. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7314. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7315. // SAFETY: plain queries that fill our structures.
  7316. unsafe {
  7317. adapter
  7318. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7319. .ok()?;
  7320. adapter
  7321. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7322. .ok()?;
  7323. }
  7324. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  7325. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  7326. };
  7327. Some([all(&own), all(&shared)])
  7328. }
  7329. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  7330. pub(crate) fn log_video_memory(&self, when: &str) {
  7331. let Some([own, shared]) = self.video_memory_groups() else {
  7332. return;
  7333. };
  7334. tracing::info!(
  7335. "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)",
  7336. when,
  7337. own[0] >> 20,
  7338. own[1] >> 20,
  7339. own[2] >> 20,
  7340. own[3] >> 20,
  7341. shared[0] >> 20,
  7342. shared[1] >> 20,
  7343. shared[2] >> 20,
  7344. shared[3] >> 20
  7345. );
  7346. }
  7347. /// A buffer in system memory that the CPU maps (write-back, so reading
  7348. /// it is fast too) and shaders read and write: for host copies of title
  7349. /// memory that shaders write, which upload memory cannot be. Starts in
  7350. /// the common state (buffers move out of it implicitly).
  7351. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7352. MADE[2].fetch_add(1, Ordering::Relaxed);
  7353. MADE[3].fetch_add(size, Ordering::Relaxed);
  7354. let heap = D3D12_HEAP_PROPERTIES {
  7355. Type: D3D12_HEAP_TYPE_CUSTOM,
  7356. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  7357. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  7358. ..Default::default()
  7359. };
  7360. let desc = D3D12_RESOURCE_DESC {
  7361. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7362. Width: size.max(1),
  7363. Height: 1,
  7364. DepthOrArraySize: 1,
  7365. MipLevels: 1,
  7366. SampleDesc: DXGI_SAMPLE_DESC {
  7367. Count: 1,
  7368. Quality: 0,
  7369. },
  7370. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7371. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7372. ..Default::default()
  7373. };
  7374. let mut buffer: Option<ID3D12Resource> = None;
  7375. let mut data = std::ptr::null_mut();
  7376. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7377. let made = unsafe {
  7378. self.device
  7379. .CreateCommittedResource(
  7380. &heap,
  7381. D3D12_HEAP_FLAG_NONE,
  7382. &desc,
  7383. D3D12_RESOURCE_STATE_COMMON,
  7384. None,
  7385. &mut buffer,
  7386. )
  7387. .and_then(|()| {
  7388. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7389. b.Map(0, None, Some(&mut data))
  7390. })
  7391. };
  7392. match made {
  7393. Ok(()) => Some((buffer?, data.cast())),
  7394. Err(e) => {
  7395. tracing::warn!(error = %e, size, "no shared buffer");
  7396. None
  7397. }
  7398. }
  7399. }
  7400. /// A device-local buffer shaders may write (unordered access) and indirect
  7401. /// execution may read, starting in the common state.
  7402. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7403. MADE[4].fetch_add(1, Ordering::Relaxed);
  7404. MADE[5].fetch_add(size, Ordering::Relaxed);
  7405. let heap = D3D12_HEAP_PROPERTIES {
  7406. Type: D3D12_HEAP_TYPE_DEFAULT,
  7407. ..Default::default()
  7408. };
  7409. let desc = D3D12_RESOURCE_DESC {
  7410. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7411. Width: size.max(1),
  7412. Height: 1,
  7413. DepthOrArraySize: 1,
  7414. MipLevels: 1,
  7415. SampleDesc: DXGI_SAMPLE_DESC {
  7416. Count: 1,
  7417. Quality: 0,
  7418. },
  7419. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7420. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7421. ..Default::default()
  7422. };
  7423. let mut buffer: Option<ID3D12Resource> = None;
  7424. // SAFETY: plain creation of a device-local buffer.
  7425. let made = unsafe {
  7426. self.device.CreateCommittedResource(
  7427. &heap,
  7428. D3D12_HEAP_FLAG_NONE,
  7429. &desc,
  7430. D3D12_RESOURCE_STATE_COMMON,
  7431. None,
  7432. &mut buffer,
  7433. )
  7434. };
  7435. match made {
  7436. Ok(()) => buffer,
  7437. Err(e) => {
  7438. tracing::warn!(error = %e, size, "no unordered-access buffer");
  7439. None
  7440. }
  7441. }
  7442. }
  7443. }
  7444. /// For adapters without device-removed data (the software one): the last
  7445. /// commands each list of the failed submission noted (diagnostics, with
  7446. /// `VICTORY_D3D12_DRED`).
  7447. fn last_notes(runs: &[&HostList]) -> String {
  7448. #[cfg(feature = "diagnostics")]
  7449. {
  7450. let mut text = String::new();
  7451. for (i, r) in runs.iter().enumerate() {
  7452. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  7453. for (n, _) in notes.iter().rev().take(6).rev() {
  7454. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  7455. }
  7456. }
  7457. text
  7458. }
  7459. #[cfg(not(feature = "diagnostics"))]
  7460. {
  7461. let _ = runs;
  7462. String::new()
  7463. }
  7464. }
  7465. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  7466. /// command reads (diagnostics).
  7467. #[cfg(feature = "diagnostics")]
  7468. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  7469. let end = start + bytes;
  7470. if va < start {
  7471. format!(" (fault {:#x} below its source)", start - va)
  7472. } else if va < end {
  7473. format!(" (fault at source +{:#x})", va - start)
  7474. } else {
  7475. format!(" (fault {:#x} past its source's end)", va - end)
  7476. }
  7477. }
  7478. /// The commands that may have been running where a list stopped at
  7479. /// command `done`: those between the barriers around it (work between
  7480. /// barriers overlaps on the GPU), by kind, and what the markers just
  7481. /// before them say (`HostList::note_op`: diagnostics builds with
  7482. /// device-removed data on).
  7483. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  7484. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  7485. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  7486. let to = history[done..]
  7487. .iter()
  7488. .position(barrier)
  7489. .map_or(history.len(), |b| (done + b).max(done + 1));
  7490. let mut text = format!(", commands {from}..{to} between its barriers:");
  7491. let mut shown = 0;
  7492. // From just before the command the GPU had not finished: the first
  7493. // twelve after the barrier named draws long done when a list of 79
  7494. // mesh draws stopped at its 45th (run 41).
  7495. for i in from.max(done.saturating_sub(4))..to {
  7496. let op = history[i];
  7497. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  7498. continue;
  7499. }
  7500. shown += 1;
  7501. let marker = i
  7502. .checked_sub(1)
  7503. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  7504. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  7505. .map_or("no marker", |(_, s)| s.as_str());
  7506. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  7507. }
  7508. text
  7509. }
  7510. pub(crate) fn transition(
  7511. resource: &ID3D12Resource,
  7512. before: D3D12_RESOURCE_STATES,
  7513. after: D3D12_RESOURCE_STATES,
  7514. ) -> D3D12_RESOURCE_BARRIER {
  7515. D3D12_RESOURCE_BARRIER {
  7516. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  7517. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  7518. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  7519. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  7520. // SAFETY: a borrowed pointer; the barrier never releases it.
  7521. pResource: unsafe { std::mem::transmute_copy(resource) },
  7522. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  7523. StateBefore: before,
  7524. StateAfter: after,
  7525. }),
  7526. },
  7527. }
  7528. }
  7529. /// A window of the given client size, owned by its own message thread.
  7530. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7531. let (sender, receiver) = std::sync::mpsc::channel();
  7532. std::thread::Builder::new()
  7533. .name("victory-window".into())
  7534. .spawn(move || {
  7535. let made = make_window(width, height);
  7536. let ok = made.is_ok();
  7537. let _ = sender.send(made.map(|h| h.0 as usize));
  7538. if ok {
  7539. pump();
  7540. }
  7541. })
  7542. .map_err(|_| windows::core::Error::empty())?;
  7543. let hwnd = receiver
  7544. .recv()
  7545. .map_err(|_| windows::core::Error::empty())??;
  7546. Ok(HWND(hwnd as *mut _))
  7547. }
  7548. extern "system" fn window_proc(
  7549. hwnd: HWND,
  7550. message: u32,
  7551. wparam: WPARAM,
  7552. lparam: LPARAM,
  7553. ) -> LRESULT {
  7554. // SAFETY: the default handling for our window.
  7555. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  7556. }
  7557. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7558. const CLASS: PCWSTR = w!("VIctory");
  7559. // SAFETY: registers our class once and creates a window of it.
  7560. unsafe {
  7561. let instance = GetModuleHandleW(None)?;
  7562. let class = WNDCLASSEXW {
  7563. cbSize: size_of::<WNDCLASSEXW>() as u32,
  7564. lpfnWndProc: Some(window_proc),
  7565. hInstance: instance.into(),
  7566. lpszClassName: CLASS,
  7567. hCursor: LoadCursorW(None, IDC_ARROW)?,
  7568. ..Default::default()
  7569. };
  7570. RegisterClassExW(&class);
  7571. let mut rect = RECT {
  7572. left: 0,
  7573. top: 0,
  7574. right: width as i32,
  7575. bottom: height as i32,
  7576. };
  7577. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  7578. CreateWindowExW(
  7579. WINDOW_EX_STYLE(0),
  7580. CLASS,
  7581. w!("VIctory"),
  7582. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  7583. CW_USEDEFAULT,
  7584. CW_USEDEFAULT,
  7585. rect.right - rect.left,
  7586. rect.bottom - rect.top,
  7587. None,
  7588. None,
  7589. Some(instance.into()),
  7590. None,
  7591. )
  7592. }
  7593. }
  7594. fn pump() {
  7595. let mut message = MSG::default();
  7596. // SAFETY: the standard message loop of this thread's window.
  7597. unsafe {
  7598. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  7599. let _ = TranslateMessage(&message);
  7600. DispatchMessageW(&message);
  7601. }
  7602. }
  7603. }
  7604. #[cfg(test)]
  7605. mod trail {
  7606. /// The trail keeps the newest things, and the report made when the
  7607. /// host device is removed says them and the pipeline library's state
  7608. /// (no card is asked for any of it).
  7609. #[test]
  7610. fn the_removal_report_says_the_newest_things_done() {
  7611. for n in 0..super::TRAIL_MOST + 5 {
  7612. super::trail(|| format!("thing {n} done"));
  7613. }
  7614. let text = super::removal_context();
  7615. assert!(text.contains("the submitting thread was"));
  7616. assert!(text.contains("pipeline library: no call running"));
  7617. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  7618. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  7619. }
  7620. }
  7621. #[cfg(test)]
  7622. mod spare {
  7623. use super::Spare;
  7624. /// Kept things come back by size, the last given first, and nothing is
  7625. /// kept past the limit.
  7626. #[test]
  7627. fn kept_things_come_back_by_size_within_the_limit() {
  7628. let mut spare: Spare<u32> = Spare::new();
  7629. assert_eq!(spare.take(4), None);
  7630. assert_eq!(spare.give(1, 4, 10), None);
  7631. assert_eq!(spare.give(2, 1, 10), None);
  7632. assert_eq!(spare.give(3, 4, 10), None);
  7633. assert_eq!(spare.bytes, 9);
  7634. // Past the limit: handed back, nothing changes.
  7635. assert_eq!(spare.give(4, 4, 10), Some(4));
  7636. assert_eq!(spare.bytes, 9);
  7637. assert_eq!(spare.take(2), None, "no thing of that size");
  7638. assert_eq!(spare.take(4), Some(3));
  7639. assert_eq!(spare.take(4), Some(1));
  7640. assert_eq!(spare.take(4), None);
  7641. assert_eq!(spare.take(1), Some(2));
  7642. assert_eq!(spare.bytes, 0);
  7643. assert!(spare.kept.is_empty());
  7644. }
  7645. }
  7646. #[cfg(test)]
  7647. mod refresh_tests {
  7648. use super::Batch;
  7649. use crate::shadow::Shadow;
  7650. use std::sync::Arc;
  7651. use windows_sys::Win32::System::Memory::{
  7652. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  7653. VirtualAlloc,
  7654. };
  7655. const PAGE: usize = 64 << 10;
  7656. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  7657. /// Title memory for the tests (never given back: copies of it stay in
  7658. /// the guards): write-watched, or a view of a section.
  7659. fn title(len: usize, view: bool) -> usize {
  7660. // SAFETY: plain allocations.
  7661. let at = unsafe {
  7662. if view {
  7663. let section =
  7664. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  7665. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  7666. // As the runtime tells of it.
  7667. crate::title_memory_section(section as usize, len as u64, true);
  7668. crate::title_memory_remapped(at, len);
  7669. crate::title_memory_view(at, len, section as usize, 0);
  7670. at
  7671. } else {
  7672. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  7673. }
  7674. };
  7675. assert_ne!(at, 0);
  7676. at
  7677. }
  7678. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  7679. /// and every fourth page not there: as a title that streams has it.
  7680. fn with_holes(blocks: usize) -> usize {
  7681. use windows_sys::Win32::System::Memory::{
  7682. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  7683. VirtualAlloc2, VirtualFree,
  7684. };
  7685. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7686. // SAFETY: a placeholder and a section of our own.
  7687. unsafe {
  7688. let at = VirtualAlloc2(
  7689. GetCurrentProcess(),
  7690. std::ptr::null(),
  7691. blocks * PAGE,
  7692. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  7693. PAGE_NOACCESS,
  7694. std::ptr::null_mut(),
  7695. 0,
  7696. ) as usize;
  7697. assert_ne!(at, 0);
  7698. let len = blocks * PAGE;
  7699. let section =
  7700. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  7701. for block in (0..blocks).filter(|b| b % 4 != 3) {
  7702. let to = at + block * PAGE;
  7703. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  7704. let view = MapViewOfFile3(
  7705. section,
  7706. GetCurrentProcess(),
  7707. to as *const _,
  7708. (block * PAGE) as u64,
  7709. PAGE,
  7710. MEM_REPLACE_PLACEHOLDER,
  7711. PAGE_READWRITE,
  7712. std::ptr::null_mut(),
  7713. 0,
  7714. );
  7715. assert_eq!(view.Value as usize, to);
  7716. crate::title_memory_remapped(to, PAGE);
  7717. }
  7718. at
  7719. }
  7720. }
  7721. fn memory(len: usize) -> *mut u8 {
  7722. // SAFETY: a plain allocation.
  7723. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  7724. }
  7725. struct Random(u64);
  7726. impl Random {
  7727. fn below(&mut self, n: usize) -> usize {
  7728. self.0 ^= self.0 << 13;
  7729. self.0 ^= self.0 >> 7;
  7730. self.0 ^= self.0 << 17;
  7731. (self.0 >> 11) as usize % n
  7732. }
  7733. }
  7734. /// Prepares as a submission does: one asking for all the ranges, the
  7735. /// refreshes in several flushes, the asking's end.
  7736. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  7737. // One at a time, as submissions are.
  7738. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  7739. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  7740. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  7741. crate::watch::ask_once(&asked);
  7742. let mut batch = Batch::default();
  7743. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  7744. for (shadow, at, len) in part {
  7745. batch.add(shadow, *at, *len);
  7746. }
  7747. batch.flush();
  7748. }
  7749. crate::watch::ask_once_end();
  7750. }
  7751. /// Whatever is written where, by the title or by us, and whichever
  7752. /// copies (of both kinds of memory, over one another, none on a page
  7753. /// line) are refreshed in which ranges: a refreshed range holds what
  7754. /// title memory holds.
  7755. #[test]
  7756. fn refreshed_ranges_hold_title_memory() {
  7757. // SAFETY (all blocks): title memory and copies of the test's own,
  7758. // written by this thread and, in `Batch::flush`, by the threads that
  7759. // refresh, which are done when it returns.
  7760. let mut random = Random(0x1234_5678_9ABC_DEF1);
  7761. const LEN: usize = 24 * PAGE;
  7762. let regions = [title(LEN, false), title(LEN, true)];
  7763. let mut copies = Vec::new();
  7764. for &region in &regions {
  7765. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  7766. let data = memory(to - from);
  7767. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  7768. }
  7769. }
  7770. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  7771. for round in 0..600 {
  7772. for _ in 0..random.below(4) {
  7773. let at = regions[random.below(2)] + random.below(LEN - 64);
  7774. let n = 1 + random.below(60);
  7775. if random.below(3) == 0 {
  7776. // What shaders wrote.
  7777. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  7778. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  7779. Shadow::put(at, &was, &now);
  7780. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  7781. continue;
  7782. }
  7783. for i in 0..n {
  7784. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  7785. }
  7786. }
  7787. let mut ranges = Vec::new();
  7788. for (shadow, _) in &copies {
  7789. if random.below(3) == 0 {
  7790. continue;
  7791. }
  7792. let (start, len) = shadow.span();
  7793. let (start, len) = (start as usize, len as usize);
  7794. // Often the range of the time before, as a list's is.
  7795. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  7796. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  7797. ranges.push((shadow.clone(), start + from, n));
  7798. }
  7799. if ranges.is_empty() {
  7800. continue;
  7801. }
  7802. let flushes = 1 + random.below(3);
  7803. submission(&ranges, flushes);
  7804. for (shadow, at, n) in &ranges {
  7805. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  7806. let start = shadow.span().0 as usize;
  7807. let same = unsafe {
  7808. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  7809. };
  7810. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  7811. }
  7812. }
  7813. }
  7814. /// A copy in the card's memory, with the card's side and the sends to it
  7815. /// played by the test.
  7816. struct Carded {
  7817. shadow: Arc<Shadow>,
  7818. data: usize,
  7819. start: usize,
  7820. len: usize,
  7821. /// The last send, the last send every fetch to come is behind, and
  7822. /// the card's bytes: the queue's order is the order it is locked in.
  7823. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  7824. /// Whether a flight that writes it has not landed.
  7825. flying: std::sync::atomic::AtomicBool,
  7826. /// The dword of each eight its shaders write.
  7827. class: usize,
  7828. }
  7829. impl Carded {
  7830. fn new(start: usize, len: usize, class: usize) -> Carded {
  7831. let data = memory(len);
  7832. Carded {
  7833. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  7834. data: data as usize,
  7835. start,
  7836. len,
  7837. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  7838. flying: std::sync::atomic::AtomicBool::new(false),
  7839. class,
  7840. }
  7841. }
  7842. /// What changed on the CPU's side goes up.
  7843. fn send(&self) {
  7844. let mut card = self.card.lock().unwrap();
  7845. card.0 += 1;
  7846. let (number, merged) = (card.0, card.1);
  7847. for (a, b) in self.shadow.send_up(number, merged) {
  7848. // SAFETY: the copy's bytes; nothing writes those that are to
  7849. // go up.
  7850. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  7851. }
  7852. }
  7853. }
  7854. /// Everything at once: the title writes its memory on two threads, the
  7855. /// submitting thread puts its bytes in under shader writes
  7856. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  7857. /// the card's memory, one not), sends up what changed and declares what
  7858. /// the next flight's shaders write, and what flights wrote is landed
  7859. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  7860. /// still and the copies are refreshed once more, each of them, and the
  7861. /// card's side of those that have one, hold what title memory holds, and
  7862. /// title memory what was written last.
  7863. ///
  7864. /// Into the first copy shaders write besides through a view nobody
  7865. /// declared, words the title does not write: nothing that goes up ever
  7866. /// puts an older value over those.
  7867. ///
  7868. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  7869. /// only takes the block out of the guards' clean ones and leaves its bit,
  7870. /// or if a fault leaves the bit; in some thousand rounds,
  7871. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  7872. #[test]
  7873. fn landings_title_writes_and_light_refreshes_at_once() {
  7874. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  7875. assert!(crate::safecopy::on());
  7876. const LEN: usize = 24 * PAGE;
  7877. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  7878. let region = title(LEN, true);
  7879. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  7880. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  7881. let plain = {
  7882. let (start, len) = (region + 700, LEN - 9000);
  7883. let data = memory(len);
  7884. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  7885. };
  7886. // What was last written so, by offset.
  7887. let mut undeclared = std::collections::HashMap::new();
  7888. let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0");
  7889. let stop = AtomicBool::new(false);
  7890. // Also when an assertion fails on one of the threads.
  7891. struct Stop<'a>(&'a AtomicBool);
  7892. impl Drop for Stop<'_> {
  7893. fn drop(&mut self) {
  7894. self.0.store(true, Ordering::Relaxed);
  7895. }
  7896. }
  7897. // Held shared by who writes title memory, alone while it is looked at.
  7898. let still = std::sync::RwLock::new(());
  7899. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  7900. std::thread::scope(|s| {
  7901. for t in 0..2usize {
  7902. let (stop, still) = (&stop, &still);
  7903. s.spawn(move || {
  7904. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  7905. let mut value = 0u32;
  7906. while !stop.load(Ordering::Relaxed) {
  7907. {
  7908. let _moving = still.read().unwrap();
  7909. for _ in 0..3 {
  7910. value += 1;
  7911. // Of each eight dwords, one a thread.
  7912. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  7913. dword(at).store(value, Ordering::Relaxed);
  7914. }
  7915. }
  7916. std::thread::sleep(std::time::Duration::from_micros(20));
  7917. }
  7918. });
  7919. }
  7920. // Lands flights.
  7921. {
  7922. let (carded, stop) = (&carded, &stop);
  7923. s.spawn(move || {
  7924. let _stop = Stop(stop);
  7925. while let Ok((which, ranges, value)) = flights.recv() {
  7926. let c = &carded[which];
  7927. // Fetched: the card's bytes, behind every send so far.
  7928. let (after, now) = {
  7929. let card = c.card.lock().unwrap();
  7930. (card.0, card.2.clone())
  7931. };
  7932. // By piece: 64 KiB of title memory.
  7933. let mut pieces = Vec::new();
  7934. for &(from, to) in &ranges {
  7935. let mut at = from;
  7936. while at < to {
  7937. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  7938. pieces.push((at, next, now.as_ptr() as usize + at));
  7939. at = next;
  7940. }
  7941. }
  7942. let parts: Vec<_> = pieces.chunks(3).collect();
  7943. crate::land::each(parts.len(), &|i| {
  7944. let mut notes = crate::land::Notes::default();
  7945. // SAFETY: the bytes of `now`; each piece once.
  7946. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  7947. notes.flush();
  7948. });
  7949. for &(from, to) in &ranges {
  7950. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  7951. // (The next fetch may have brought more.)
  7952. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  7953. }
  7954. }
  7955. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  7956. c.shadow.copy_back_done(&done);
  7957. c.card.lock().unwrap().1 = after;
  7958. c.flying.store(false, Ordering::Release);
  7959. }
  7960. });
  7961. }
  7962. let _stop = Stop(&stop);
  7963. let mut random = Random(0xABCD_EF01_2345_6789);
  7964. let check = |round: usize, random: &mut Random, quiet: bool| {
  7965. for c in &carded {
  7966. if c.shadow.writes_pending() {
  7967. let mut runs = usize::MAX;
  7968. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  7969. }
  7970. }
  7971. let mut ranges = Vec::new();
  7972. for (shadow, start, len) in
  7973. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  7974. {
  7975. // All of it, or a part; often the same part.
  7976. let (from, n) = match random.below(3) {
  7977. _ if quiet => (0, len),
  7978. 0 => (0, len),
  7979. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  7980. _ => {
  7981. let from = random.below(len / 4) * 4;
  7982. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  7983. }
  7984. };
  7985. ranges.push((shadow.clone(), start + from, n));
  7986. }
  7987. submission(&ranges, 1 + random.below(3));
  7988. carded.iter().for_each(Carded::send);
  7989. };
  7990. let mut value = 1u32;
  7991. for round in 0..rounds {
  7992. check(round, &mut random, false);
  7993. if exact {
  7994. let c = &carded[0];
  7995. let mut card = c.card.lock().unwrap();
  7996. for _ in 0..40 {
  7997. value += 1;
  7998. let at = random.below(LEN / 32) * 32 + 4 * 6;
  7999. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8000. undeclared.insert(at, value);
  8001. }
  8002. }
  8003. // The flight of this submission: its shaders' writes.
  8004. for (which, c) in carded.iter().enumerate() {
  8005. if c.flying.swap(true, Ordering::Acquire) {
  8006. continue;
  8007. }
  8008. value += 1;
  8009. let mut ranges: Vec<(usize, usize)> = Vec::new();
  8010. let first = random.below(6) * PAGE / 2;
  8011. for k in 0..2 {
  8012. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  8013. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  8014. if from < to {
  8015. ranges.push((from, to));
  8016. }
  8017. }
  8018. for &(from, to) in &ranges {
  8019. c.shadow.writing(c.start + from, to - from);
  8020. }
  8021. {
  8022. let mut card = c.card.lock().unwrap();
  8023. for &(from, to) in &ranges {
  8024. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8025. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8026. }
  8027. }
  8028. }
  8029. fly.send((which, ranges, value)).unwrap();
  8030. }
  8031. if round % 20 != 19 {
  8032. continue;
  8033. }
  8034. // Still: no flight in the air, no title write.
  8035. let _still = still.write().unwrap();
  8036. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  8037. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  8038. std::thread::yield_now();
  8039. }
  8040. check(round, &mut random, true);
  8041. // SAFETY: the test's own memory, written by nobody now.
  8042. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  8043. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  8044. for c in &carded {
  8045. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  8046. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  8047. let card = c.card.lock().unwrap();
  8048. let mut side = card.2.clone();
  8049. if c.class == carded[0].class {
  8050. // (They may have been landed meanwhile, by a flight
  8051. // that declared their range, and may not.)
  8052. for (&at, &value) in &undeclared {
  8053. let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
  8054. assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
  8055. side[at..at + 4].copy_from_slice(&there[at..at + 4]);
  8056. }
  8057. }
  8058. assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
  8059. }
  8060. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  8061. }
  8062. drop(fly);
  8063. });
  8064. }
  8065. /// The title's bytes put in under shader writes, for a copy of 174 MB
  8066. /// whose shader writes were declared as 40 ranges that overlap, with 12
  8067. /// pages written since. Run with `--ignored --nocapture`, and with
  8068. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8069. #[test]
  8070. #[ignore]
  8071. fn bytes_under_overlapping_ranges() {
  8072. const BIG: usize = 174 << 20;
  8073. let big = title(BIG, true);
  8074. // SAFETY (both): the test's own memory.
  8075. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  8076. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8077. copy.update(big, BIG);
  8078. copy.take_dirty();
  8079. for i in 0..40 {
  8080. copy.writing(big + i * 5920, BIG - i * 5920);
  8081. }
  8082. let mut best = f64::MAX;
  8083. for round in 0..30 {
  8084. for i in 0..12 {
  8085. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  8086. }
  8087. let started = std::time::Instant::now();
  8088. let mut runs = usize::MAX;
  8089. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  8090. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  8091. copy.take_dirty();
  8092. }
  8093. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  8094. }
  8095. /// A range nothing wrote is known to be as it was, at its ends too, and
  8096. /// is so no more once something wrote it.
  8097. #[test]
  8098. fn unchanged_ranges_are_known() {
  8099. for view in [false, true] {
  8100. let region = title(8 * PAGE, view);
  8101. // (A page read for the first time counts as written.)
  8102. // SAFETY: the test's own memory.
  8103. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  8104. let data = memory(8 * PAGE);
  8105. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  8106. // Ends in the middle of pages.
  8107. let (at, len) = (region + 500, 5 * PAGE);
  8108. let look = |expected: bool, what: &str| {
  8109. // The submission's one asking, which takes two ranges. (Again
  8110. // if a submission of another test ended it.)
  8111. let mut known = false;
  8112. for _ in 0..100 {
  8113. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  8114. known = copy.nothing_new(at, len);
  8115. if known || !expected {
  8116. break;
  8117. }
  8118. }
  8119. assert_eq!(known, expected, "view {view}: {what}");
  8120. let copied = copy.update(at, len);
  8121. crate::watch::ask_once_end();
  8122. copied
  8123. };
  8124. assert_eq!(look(false, "never taken"), len);
  8125. assert_eq!(look(true, "taken"), 0);
  8126. assert_eq!(look(true, "taken"), 0);
  8127. // SAFETY: the test's own memory.
  8128. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  8129. assert_eq!(look(false, "written at its end"), PAGE - 500);
  8130. assert_eq!(look(true, "taken again"), 0);
  8131. // Outside the range, on its last page.
  8132. // SAFETY: as above.
  8133. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  8134. assert_eq!(look(false, "written on its last page"), 500);
  8135. // A longer range was never taken whole.
  8136. assert!(!copy.nothing_new(region, 6 * PAGE));
  8137. }
  8138. }
  8139. /// Of a copy in the card's memory only the dwords title memory changed go
  8140. /// up, and none beside them, not even between two in 64 bytes; a page
  8141. /// never taken goes up whole.
  8142. #[test]
  8143. fn only_what_differs_goes_up() {
  8144. let region = title(4 * PAGE, true);
  8145. let data = memory(4 * PAGE);
  8146. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  8147. copy.update(region, 4 * PAGE);
  8148. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  8149. // What the relay does: shader writes into title memory, and into the
  8150. // CPU's side.
  8151. crate::watch::landing(region + PAGE + 640, 64);
  8152. // SAFETY: the test's own memory.
  8153. unsafe {
  8154. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  8155. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  8156. }
  8157. copy.update(region, 4 * PAGE);
  8158. let again = copy.take_dirty();
  8159. // SAFETY: as above.
  8160. unsafe {
  8161. ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
  8162. ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
  8163. ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
  8164. // The value that was there.
  8165. ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
  8166. }
  8167. copy.update(region, 4 * PAGE);
  8168. let written = copy.take_dirty();
  8169. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") {
  8170. assert_eq!(again, []);
  8171. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
  8172. } else {
  8173. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  8174. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  8175. }
  8176. // SAFETY: as above.
  8177. assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
  8178. }
  8179. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  8180. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  8181. /// big copy that 55 landed pieces and 9 title writes opened, while a
  8182. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  8183. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8184. #[test]
  8185. #[ignore]
  8186. fn frame_of_refreshes() {
  8187. let mut random = Random(0x9876_5432_1234_5671);
  8188. const EACH: usize = 224 << 10;
  8189. const BIG: usize = 174 << 20;
  8190. let watched = title(3000 * EACH, false);
  8191. // `VICTORY_BENCH_HOLES=0`: views without holes.
  8192. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  8193. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  8194. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  8195. let big = title(BIG, true);
  8196. // SAFETY: the test's own memory.
  8197. unsafe {
  8198. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  8199. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  8200. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  8201. }
  8202. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  8203. }
  8204. let mut small = Vec::new();
  8205. for i in 0..4400 {
  8206. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  8207. let data = memory(EACH);
  8208. // The range views read, not all of the copy.
  8209. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  8210. }
  8211. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  8212. // The same memory, as another copy: what is landed is landed through
  8213. // it, and the refreshes are of the first.
  8214. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8215. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  8216. let (mut sum, mut landing) = (0.0, 0.0);
  8217. const FRAMES: usize = 12;
  8218. for frame in 0..FRAMES {
  8219. let mut took = [0f64; 2];
  8220. for i in 0..30 {
  8221. // The title's writes, and the relay's beside the submission.
  8222. for _ in 0..9 {
  8223. let at = views + random.below(1400 * EACH / 8) * 8;
  8224. if there(at) {
  8225. // SAFETY: the test's own memory.
  8226. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8227. }
  8228. }
  8229. for _ in 0..60 {
  8230. let at = watched + random.below(3000 * EACH / 8) * 8;
  8231. // SAFETY: the test's own memory.
  8232. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8233. }
  8234. let first = random.below(BIG / PAGE - 60);
  8235. let lands = lands.clone();
  8236. let land = std::thread::spawn(move || {
  8237. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  8238. let started = std::time::Instant::now();
  8239. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  8240. let pieces: Vec<_> =
  8241. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  8242. let mut notes = crate::land::Notes::default();
  8243. // SAFETY: the bytes of `now`; nothing else lands here.
  8244. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  8245. notes.flush();
  8246. }
  8247. started.elapsed().as_secs_f64() * 1e3
  8248. });
  8249. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  8250. small.iter().cloned().chain([heap.clone()]).collect()
  8251. } else {
  8252. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  8253. };
  8254. let started = std::time::Instant::now();
  8255. submission(&ranges, 3);
  8256. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  8257. let put = land.join().unwrap();
  8258. if frame >= 2 {
  8259. landing += put;
  8260. }
  8261. heap.0.take_dirty();
  8262. }
  8263. if frame >= 2 {
  8264. sum += took[0] + took[1];
  8265. for k in 0..2 {
  8266. best[k] = best[k].min(took[k]);
  8267. asking[k] += took[k];
  8268. }
  8269. }
  8270. }
  8271. println!(
  8272. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  8273. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  8274. crate::watch::light(),
  8275. sum / (FRAMES - 2) as f64,
  8276. asking[0] / (FRAMES - 2) as f64,
  8277. best[0],
  8278. asking[1] / (FRAMES - 2) as f64,
  8279. best[1],
  8280. landing / (FRAMES - 2) as f64,
  8281. );
  8282. #[cfg(feature = "diagnostics")]
  8283. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  8284. }
  8285. }
  8286. #[cfg(test)]
  8287. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  8288. use super::Batch;
  8289. use std::sync::Arc;
  8290. #[test]
  8291. fn a_texture_is_checked_once_per_submission() {
  8292. let mut batch = Batch::default();
  8293. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  8294. // The first list sampling each texture checks it ...
  8295. assert!(batch.texture_due(&a));
  8296. assert!(batch.texture_due(&b));
  8297. // ... later lists of the same submission do not.
  8298. assert!(!batch.texture_due(&a));
  8299. assert!(!batch.texture_due(&a.clone()));
  8300. assert!(!batch.texture_due(&b));
  8301. }
  8302. #[test]
  8303. fn title_writes_make_textures_due_again() {
  8304. let mut batch = Batch::default();
  8305. let a = Arc::new(1u32);
  8306. assert!(batch.texture_due(&a));
  8307. assert!(!batch.texture_due(&a));
  8308. // A copy into title memory or work that may write it may have
  8309. // changed the texture's memory.
  8310. batch.title_written();
  8311. assert!(batch.texture_due(&a));
  8312. assert!(!batch.texture_due(&a));
  8313. // A fresh submission starts over.
  8314. let mut next = Batch::default();
  8315. assert!(next.texture_due(&a));
  8316. }
  8317. /// The hashing a submission does for textures in physical-page memory,
  8318. /// with every list checking the textures it samples (before) and with
  8319. /// each checked once (after). Run with
  8320. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  8321. #[test]
  8322. #[ignore = "benchmark"]
  8323. fn texture_checks_per_submission() {
  8324. const TEXTURES: usize = 48;
  8325. const SIZE: usize = 4 << 20;
  8326. const LISTS: usize = 12;
  8327. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  8328. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  8329. .collect();
  8330. let submit = |dedupe: bool| {
  8331. let mut batch = Batch::default();
  8332. let mut hashed = 0usize;
  8333. let started = std::time::Instant::now();
  8334. for _ in 0..LISTS {
  8335. for t in &textures {
  8336. if !dedupe || batch.texture_due(t) {
  8337. std::hint::black_box(blake3::hash(t));
  8338. hashed += 1;
  8339. }
  8340. }
  8341. }
  8342. (started.elapsed(), hashed)
  8343. };
  8344. submit(false); // warm up
  8345. let (before, n_before) = submit(false);
  8346. let (after, n_after) = submit(true);
  8347. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  8348. println!(
  8349. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  8350. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  8351. SIZE >> 20,
  8352. before.as_secs_f64() / after.as_secs_f64()
  8353. );
  8354. }
  8355. #[test]
  8356. fn vram_idle_ms_scales_with_pressure() {
  8357. use super::vram_idle_ms;
  8358. let gib = 1024 * 1024 * 1024;
  8359. // Normal (< 75%)
  8360. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  8361. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  8362. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  8363. // Moderate (75%..85%)
  8364. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  8365. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  8366. // High (>= 85%, including over-budget)
  8367. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  8368. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  8369. // Missing or zero budget falls back to normal
  8370. assert_eq!(vram_idle_ms(None), 5_000);
  8371. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  8372. }
  8373. #[test]
  8374. fn ram_idle_ms_scales_with_pressure() {
  8375. use super::ram_idle_ms;
  8376. let gib = 1024 * 1024 * 1024;
  8377. // Normal (>= 4 GiB)
  8378. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  8379. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  8380. // Moderate (2 GiB..4 GiB)
  8381. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  8382. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  8383. // High (< 2 GiB)
  8384. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  8385. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  8386. // Missing falls back to normal
  8387. assert_eq!(ram_idle_ms(None), 10_000);
  8388. }
  8389. }