host.rs 395 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016
  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. ///
  110. /// With room on the card nothing has to go: in session play-1125-0127 88,000
  111. /// of them (31 GB) went after 5 s with 7 GB of the card free, and 24,700
  112. /// (12 GB) had to be made and uploaded again.
  113. /// `VICTORY_TEXTURE_KEEP=0`: 5 s there too, as before.
  114. pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
  115. static KEEP: OnceLock<bool> = OnceLock::new();
  116. let keep = *KEEP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_KEEP").is_none_or(|v| v != "0"));
  117. vram_idle_for(video_memory, keep)
  118. }
  119. fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 {
  120. const KEPT_MS: u64 = 600_000;
  121. const LONG_MS: u64 = 30_000;
  122. const NORMAL_MS: u64 = 5_000;
  123. const MODERATE_MS: u64 = 2_500;
  124. const HIGH_MS: u64 = 1_000;
  125. let Some([budget, used, ..]) = video_memory else {
  126. return NORMAL_MS;
  127. };
  128. if budget == 0 {
  129. return NORMAL_MS;
  130. }
  131. let used_pct = (u128::from(used) * 100) / u128::from(budget);
  132. if used_pct >= 85 {
  133. HIGH_MS
  134. } else if used_pct >= 75 {
  135. MODERATE_MS
  136. } else if !keep {
  137. NORMAL_MS
  138. } else if used_pct >= 68 {
  139. LONG_MS
  140. } else {
  141. KEPT_MS
  142. }
  143. }
  144. /// Effective idle timeout (in milliseconds) for system-RAM caches (staging
  145. /// buffers, loose shadows, and the mapped pipeline library), scaled down
  146. /// when free physical RAM is low. Never returns less than 2,000 ms.
  147. pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
  148. const GIB: u64 = 1024 * 1024 * 1024;
  149. const NORMAL_MS: u64 = 10_000;
  150. const MODERATE_MS: u64 = 5_000;
  151. const HIGH_MS: u64 = 2_000;
  152. let Some(avail) = avail_phys else {
  153. return NORMAL_MS;
  154. };
  155. if avail < 2 * GIB {
  156. HIGH_MS
  157. } else if avail < 4 * GIB {
  158. MODERATE_MS
  159. } else {
  160. NORMAL_MS
  161. }
  162. }
  163. /// How many references are held on a host object (its COM count): ours
  164. /// all, since the host's views and commands hold none. A buffer or texture
  165. /// with one is held by its owner alone: no descriptor slot keeps it
  166. /// (`HostHeap::kept`) and no list (`HostList::keep`).
  167. pub(crate) fn references(object: &impl Interface) -> u32 {
  168. type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
  169. let raw = object.as_raw();
  170. // SAFETY: a live COM object, whose first three methods are those of
  171. // `IUnknown` (query, add a reference, release one); the pair leaves the
  172. // count as it was, and the release returns it. The first is not called.
  173. unsafe {
  174. let methods = *raw.cast::<*const [Method; 3]>();
  175. ((*methods)[1])(raw);
  176. ((*methods)[2])(raw)
  177. }
  178. }
  179. /// Once a second, before a submission starts: lets go of what nothing
  180. /// names any more (copies of windows of title memory, staging buffers,
  181. /// host copies of textures the title fills).
  182. /// `VICTORY_SWEEP=0` keeps everything, as before.
  183. fn sweep() {
  184. // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
  185. crate::inplace::tick();
  186. static ON: OnceLock<bool> = OnceLock::new();
  187. if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
  188. return;
  189. }
  190. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  191. let now = now_ms();
  192. let last = LAST.load(Ordering::Relaxed);
  193. if now < last + 1000
  194. || LAST
  195. .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
  196. .is_err()
  197. {
  198. return;
  199. }
  200. crate::pipeline::trim_library();
  201. crate::shadow::let_go_idle();
  202. crate::texture::let_go_idle();
  203. crate::resource::let_go_idle();
  204. }
  205. /// Drops `object` once every submission running now has finished: at once
  206. /// if none is.
  207. pub(crate) fn retire<T: 'static>(object: T) {
  208. let started = STARTED.load(Ordering::Acquire);
  209. if started <= FINISHED.load(Ordering::Acquire) {
  210. RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
  211. drop(object);
  212. return;
  213. }
  214. RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
  215. RETIRED
  216. .lock()
  217. .unwrap_or_else(|e| e.into_inner())
  218. .push((started, Retired(Box::new(object))));
  219. }
  220. /// Drops what waited for submissions up to `finished`.
  221. fn bury(finished: u64) {
  222. let done: Vec<(u64, Retired)> = {
  223. let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
  224. if retired.is_empty() {
  225. return;
  226. }
  227. let (done, keep) = std::mem::take(&mut *retired)
  228. .into_iter()
  229. .partition(|(at, _)| *at <= finished);
  230. *retired = keep;
  231. done
  232. };
  233. drop(done);
  234. }
  235. /// Objects [`retire`] dropped at once (no submission was running) and
  236. /// kept until a running submission finished, since the start.
  237. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  238. /// What the layer did to the host's objects lately, newest last (sweeps
  239. /// that let host copies go, pipeline library calls, saves and trims): said
  240. /// once when the host device is removed ([`log_removal_context`]), with
  241. /// what the submitting thread and the pipeline workers were doing at that
  242. /// moment. A device the driver removes "internally" names no command, and
  243. /// the pass that happens to notice first names only the view it was at:
  244. /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
  245. /// pipeline library call that no line of the log tied to them.
  246. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
  247. static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new());
  248. /// The entries kept.
  249. const TRAIL_MOST: usize = 96;
  250. fn trail_on() -> bool {
  251. static ON: OnceLock<bool> = OnceLock::new();
  252. *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
  253. }
  254. /// Microseconds since the first call.
  255. pub(crate) fn now_us() -> u64 {
  256. static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
  257. EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
  258. }
  259. /// The calling thread, as the log's other lines name threads.
  260. pub(crate) fn thread_id() -> u32 {
  261. // SAFETY: a plain query.
  262. unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
  263. }
  264. /// Notes something done to the host's objects ([`TRAIL`]); `what` is only
  265. /// run when the trail is kept.
  266. pub(crate) fn trail(what: impl FnOnce() -> String) {
  267. if !trail_on() {
  268. return;
  269. }
  270. let entry = (now_us(), thread_id(), what());
  271. let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  272. if trail.len() >= TRAIL_MOST {
  273. trail.pop_front();
  274. }
  275. trail.push_back(entry);
  276. }
  277. /// What the submitting thread is doing (0 nothing: between submissions,
  278. /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
  279. /// it wrote), the lists of that submission, and since when ([`now_us`]).
  280. static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  281. fn submitting(phase: u64, lists: usize) {
  282. SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
  283. SUBMITTING[2].store(now_us(), Ordering::Relaxed);
  284. SUBMITTING[0].store(phase, Ordering::Relaxed);
  285. }
  286. /// What was going on when the host device went: whether a submission was
  287. /// on the card, the pipeline library's state and the calls running in it,
  288. /// and the trail.
  289. pub(crate) fn removal_context() -> String {
  290. use std::fmt::Write;
  291. let now = now_us();
  292. let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
  293. let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
  294. 0 => "between submissions (nothing of ours was running on the card)",
  295. 1 => "preparing a submission (nothing of ours was running on the card)",
  296. 2 => "waiting for the card to run a submission",
  297. _ => "copying back what a submission wrote (nothing of ours was running on the card)",
  298. };
  299. let mut text = format!(
  300. "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
  301. SUBMITTING[1].load(Ordering::Relaxed),
  302. ms(SUBMITTING[2].load(Ordering::Relaxed)),
  303. crate::pipeline::library_removal_note(),
  304. RETIREMENTS[0].load(Ordering::Relaxed),
  305. RETIREMENTS[1].load(Ordering::Relaxed),
  306. STARTED.load(Ordering::Relaxed),
  307. FINISHED.load(Ordering::Relaxed),
  308. );
  309. let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
  310. let _ = write!(text, "; the last {} things done, newest last:", trail.len());
  311. for (at, thread, what) in trail.iter() {
  312. let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
  313. }
  314. text
  315. }
  316. /// Says [`removal_context`] in the log, once: called by whoever finds the
  317. /// host device removed.
  318. pub(crate) fn log_removal_context() {
  319. static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  320. if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) {
  321. return;
  322. }
  323. tracing::error!("when the host device went: {}", removal_context());
  324. if dred_any() {
  325. let data = host().map(|h| h.removal_data(&[])).unwrap_or_default();
  326. tracing::error!("device-removed data{}", if data.is_empty() { "; none" } else { &data });
  327. }
  328. }
  329. /// Time spent in submissions since the last frame-rate line, in
  330. /// microseconds: preparing them on the CPU (title memory copies, texture
  331. /// detiling), then waiting for the GPU.
  332. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  333. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  334. /// After submissions: shader-written ranges compared and copied back into
  335. /// title memory (microseconds, bytes that differed), since the last
  336. /// frame-rate line.
  337. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  338. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  339. /// The card's clock, for the frame line of every run, in microseconds since
  340. /// the last one: how long the card had nothing of ours queued; how much of
  341. /// that while the thread that holds the submission lock was working (the
  342. /// card idle behind us: preparing and copying back are done with the card
  343. /// standing); and how long that thread stood waiting for the card.
  344. ///
  345. /// Every send of lists to the queue is followed by a signal on a fence of
  346. /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
  347. /// the newest signal and notes the moment the card reached it with nothing
  348. /// newer sent; the next send ends that idle stretch.
  349. static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  350. /// Of the thread that holds the submission lock: the microseconds it has
  351. /// worked so far (preparing, copying back; not its waits for the card), and
  352. /// since when it works now ([`now_us`] plus one; 0: it does not).
  353. static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  354. /// The thread that holds the submission lock starts (`on`) or stops
  355. /// working; whether it worked until now.
  356. fn working(on: bool) -> bool {
  357. let now = now_us() + 1;
  358. let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
  359. if since != 0 {
  360. WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
  361. }
  362. since != 0
  363. }
  364. /// [`WORKING`] as of now: microseconds worked so far.
  365. fn worked() -> u64 {
  366. let since = WORKING[1].load(Ordering::Relaxed);
  367. let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
  368. WORKING[0].load(Ordering::Relaxed) + now
  369. }
  370. /// The thread that holds the submission lock stood waiting for the card
  371. /// from `since` until now ([`CARD_CLOCK_US`]).
  372. fn stood(since: std::time::Instant) {
  373. CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  374. }
  375. /// What [`CARD_CLOCK_US`] is measured with.
  376. struct CardClock {
  377. fence: ID3D12Fence,
  378. /// Signals sent so far; and, while the card has reached the last of
  379. /// them, since when and what [`worked`] said then.
  380. state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
  381. sent: std::sync::Condvar,
  382. }
  383. // SAFETY: a fence (free-threaded) behind a lock.
  384. unsafe impl Send for CardClock {}
  385. // SAFETY: as above.
  386. unsafe impl Sync for CardClock {}
  387. /// The clock's thread: waits for the newest signal sent and notes when the
  388. /// card got there with nothing newer behind it.
  389. fn card_clock_watch(clock: &'static CardClock) {
  390. // SAFETY: a plain event of our own.
  391. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  392. return;
  393. };
  394. let mut seen = 0;
  395. loop {
  396. let target = {
  397. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  398. while state.0 == seen {
  399. state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
  400. }
  401. state.0
  402. };
  403. // SAFETY: the clock's fence and this thread's event.
  404. unsafe {
  405. if clock.fence.SetEventOnCompletion(target, event).is_ok() {
  406. WaitForSingleObject(event, INFINITE);
  407. }
  408. }
  409. seen = target;
  410. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  411. if state.0 == target && state.1.is_none() {
  412. state.1 = Some((std::time::Instant::now(), worked()));
  413. }
  414. }
  415. }
  416. /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
  417. /// frame's time.
  418. fn card_clock_line(frames: f64, ms: f64) {
  419. let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  420. tracing::info!(
  421. "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
  422. {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
  423. had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
  424. if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
  425. );
  426. }
  427. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  428. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  429. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  430. std::sync::atomic::AtomicU64::new(0),
  431. std::sync::atomic::AtomicU64::new(0),
  432. std::sync::atomic::AtomicU64::new(0),
  433. std::sync::atomic::AtomicU64::new(0),
  434. ];
  435. /// Host buffers made since the start, as (count, bytes): in the upload heap
  436. /// (staging, list scratch), shared with the processor (host copies of title
  437. /// memory) and the graphics card's own (indirect arguments, twins' copies).
  438. /// For the memory line: against what is alive, they show what was let go.
  439. pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
  440. /// What of that is alive now, for the memory line (`MADE` counts what was
  441. /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
  442. /// and nothing said how many were alive): host lists; the lists' scratch
  443. /// chunks and their bytes; of those, the chunks no list holds (kept for the
  444. /// next list, [`Spare`]) and their bytes; chunks taken from those kept
  445. /// instead of made, since the start; and the lists' other upload buffers
  446. /// (texture data copied from buffers, scratch too big for a chunk) and
  447. /// their bytes.
  448. pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
  449. /// About host lists, for the memory line: lists made by the host since the
  450. /// start; preludes made (a list's second allocator and list, made when it
  451. /// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
  452. /// bytes the process's private memory grew by while lists were being made
  453. /// (what a list costs: host objects with the driver's command memory; 631
  454. /// lists were alive in run 65, each with a prelude it may never use).
  455. /// Then the lists alive that were never reset since they were made: the
  456. /// host sides of title lists the title made and has not used (a host list
  457. /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
  458. /// makes at its start).
  459. pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  460. /// The process's private bytes (diagnostics: around the making of lists).
  461. #[cfg(feature = "diagnostics")]
  462. fn private_bytes() -> u64 {
  463. use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
  464. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  465. let mut c = PROCESS_MEMORY_COUNTERS {
  466. cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
  467. ..Default::default()
  468. };
  469. // SAFETY: our own process and a sized structure.
  470. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
  471. c.PagefileUsage as u64
  472. }
  473. /// What the runtime does when the host GPU fails for good: report it like a
  474. /// crash and end the run. The console has no such state, and carrying on
  475. /// draws nothing at seconds per frame.
  476. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  477. /// Sets what a host GPU failure does (the runtime's crash report).
  478. pub fn on_failure(report: fn(&str) -> !) {
  479. let _ = ON_FAILURE.set(report);
  480. }
  481. /// Ends the run on a host GPU failure: what failed, the removal reason and
  482. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  483. /// diagnostics build names the command).
  484. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  485. let mut text = what.to_string();
  486. if let Some(host) = host() {
  487. // SAFETY: a plain query.
  488. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  489. text.push_str(&format!("; device removed: {e}"));
  490. log_removal_context();
  491. }
  492. match host.log_messages() {
  493. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  494. None if host.messages.is_none() => text.push_str(
  495. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  496. ),
  497. None => {}
  498. }
  499. }
  500. tracing::error!("{text}");
  501. // Tests have no log: the reason goes to their output.
  502. #[cfg(test)]
  503. eprintln!("host GPU failure: {text}");
  504. match ON_FAILURE.get() {
  505. Some(report) => report(&text),
  506. None => std::process::abort(),
  507. }
  508. }
  509. /// The host GPU, created on first use; `None` without one (a run then
  510. /// behaves as before: nothing executes).
  511. pub(crate) fn host() -> Option<&'static Host> {
  512. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  513. HOST.get_or_init(|| match create() {
  514. Ok(host) => Some(host),
  515. Err(e) => {
  516. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  517. None
  518. }
  519. })
  520. .as_ref()
  521. }
  522. fn create() -> windows::core::Result<Host> {
  523. // SAFETY: plain D3D12 object creation with valid descriptions.
  524. unsafe {
  525. // The debug layer only in builds with diagnostics.
  526. let debug = cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DEBUG");
  527. if debug {
  528. let mut layer: Option<ID3D12Debug> = None;
  529. match D3D12GetDebugInterface(&mut layer) {
  530. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  531. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  532. }
  533. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  534. // descriptor heap indices and the like become messages naming
  535. // the command instead of page faults. Without state tracking
  536. // (directly indexed textures are not transitioned).
  537. if crate::switch::on("VICTORY_D3D12_GBV")
  538. && let Some(l) = &layer
  539. {
  540. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  541. d1.SetEnableGPUBasedValidation(true);
  542. }
  543. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  544. d2.SetGPUBasedValidationFlags(
  545. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  546. );
  547. }
  548. tracing::info!("GPU-based validation on");
  549. }
  550. }
  551. // Diagnostics: device-removed data (the command that faulted, the
  552. // faulting address), read when the device is removed.
  553. if dred_any() {
  554. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  555. if D3D12GetDebugInterface(&mut dred).is_ok()
  556. && let Some(dred) = dred
  557. {
  558. if dred_on() || dred_light() {
  559. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  560. }
  561. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  562. tracing::info!(
  563. breadcrumbs = dred_on() || dred_light(),
  564. markers = dred_on(),
  565. "crash tracing on (device-removed data)"
  566. );
  567. } else {
  568. tracing::warn!("crash tracing asked for and not there: no device-removed data settings");
  569. }
  570. }
  571. let mut device: Option<ID3D12Device> = None;
  572. // Diagnostics: the software adapter, on which a shader's wild access
  573. // is an access violation in this process (a crash report with the
  574. // address and instruction) instead of a GPU fault and driver reset.
  575. if cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_WARP") {
  576. let adapter = warp_adapter()?;
  577. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  578. tracing::info!("host device on the software adapter (WARP)");
  579. } else {
  580. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  581. // Whether a GPU hang ends the run or freezes the PC (#1054).
  582. crate::tdr::log();
  583. }
  584. let device = device.ok_or_else(windows::core::Error::empty)?;
  585. // Before anything is made with it (`VICTORY_RECORD`).
  586. #[cfg(feature = "diagnostics")]
  587. crate::replay::record::from_env(&device);
  588. // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
  589. // driver compiling shaders again on the "D3D Background Thread"s,
  590. // for minutes after pipelines were made or loaded) is switched off.
  591. // An experiment: while those threads ran, the same shot took
  592. // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
  593. // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
  594. // whether the card is slower with the shaders it then keeps is not
  595. // known.
  596. if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
  597. && let Ok(device6) = device.cast::<ID3D12Device6>()
  598. {
  599. let set = device6.SetBackgroundProcessingMode(
  600. D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
  601. D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
  602. None,
  603. None,
  604. );
  605. tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
  606. }
  607. // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
  608. // cross-lane code stays in 32-lane halves translated for waves of 32
  609. let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
  610. if device
  611. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
  612. .is_ok()
  613. {
  614. tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
  615. victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
  616. }
  617. let messages = debug
  618. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  619. .flatten();
  620. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  621. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  622. ..Default::default()
  623. })?;
  624. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  625. let event = CreateEventW(None, false, false, None)?;
  626. let rtvs: ID3D12DescriptorHeap =
  627. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  628. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  629. NumDescriptors: RTV_RING,
  630. ..Default::default()
  631. })?;
  632. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  633. let dsvs: ID3D12DescriptorHeap =
  634. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  635. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  636. NumDescriptors: RTV_RING,
  637. ..Default::default()
  638. })?;
  639. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  640. let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  641. .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
  642. .ok();
  643. tracing::info!("host D3D12 device ready");
  644. Ok(Host {
  645. device,
  646. queue,
  647. fence,
  648. submitted: Mutex::new(0),
  649. event,
  650. rtvs,
  651. rtv_size,
  652. dsvs,
  653. dsv_size,
  654. next_dsv: AtomicU32::new(0),
  655. messages,
  656. next_rtv: AtomicU32::new(0),
  657. presenter: Mutex::new(None),
  658. adapter,
  659. })
  660. }
  661. }
  662. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  663. /// Reject it before creating a device in diagnostics' software-only mode.
  664. pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  665. // SAFETY: plain DXGI adapter queries.
  666. unsafe {
  667. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  668. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  669. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  670. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  671. tracing::warn!(
  672. vendor = format_args!("{:#x}", desc.VendorId),
  673. flags = format_args!("{:#x}", desc.Flags),
  674. "DXGI did not identify the WARP adapter as software; refusing device"
  675. );
  676. return Err(windows::core::Error::from_hresult(
  677. windows::Win32::Foundation::E_FAIL,
  678. ));
  679. }
  680. Ok(adapter)
  681. }
  682. }
  683. #[cfg(test)]
  684. mod tests {
  685. /// A list of ours is found by its name, with the debug layer's note or not.
  686. #[cfg(feature = "diagnostics")]
  687. #[test]
  688. fn a_list_is_found_by_the_number_in_its_name() {
  689. assert_eq!(super::list_number("victory host list 7"), Some(7));
  690. assert_eq!(super::list_number("victory host list 158 (debug layer indirect)"), Some(158));
  691. assert_eq!(super::list_number("victory host list 7x"), None);
  692. assert_eq!(super::list_number("victory host list 7 x"), None);
  693. assert_eq!(super::list_number("another list 7"), None);
  694. assert_eq!(super::list_number(""), None);
  695. }
  696. /// What is there of a range some of whose pages are not: those bytes,
  697. /// counted, and zeros for the rest, whatever the buffer held.
  698. #[test]
  699. fn what_is_there_is_read_and_the_rest_is_zeros() {
  700. use windows_sys::Win32::System::Memory::*;
  701. const SIZE: usize = 0x8_0000;
  702. // SAFETY: a reservation of ours; only committed pages are written.
  703. unsafe {
  704. let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  705. assert!(!at.is_null());
  706. // 0-0x1_1000 and 0x3_0000-0x4_0000 are there.
  707. for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] {
  708. assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null());
  709. at.add(from).write_bytes(0x5a, len);
  710. }
  711. // From an address inside a page, as textures are packed.
  712. let mut out = vec![0x77u8; SIZE - 0x300];
  713. assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000);
  714. for (i, &b) in out.iter().enumerate() {
  715. let from = i + 0x300;
  716. let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from);
  717. assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}");
  718. }
  719. // All there: one read.
  720. let mut out = vec![0x77u8; 0x1_0000];
  721. assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000);
  722. assert!(out.iter().all(|&b| b == 0x5a));
  723. // Nothing there.
  724. let mut out = vec![0x77u8; 0x1_0000];
  725. assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0);
  726. assert!(out.iter().all(|&b| b == 0));
  727. assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0);
  728. }
  729. }
  730. /// Zeros for a title destination that went meanwhile are no fault.
  731. #[test]
  732. fn zeros_where_nothing_is_are_lost() {
  733. use windows_sys::Win32::System::Memory::*;
  734. // SAFETY: a reservation of ours, its first page committed.
  735. unsafe {
  736. let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  737. assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
  738. at.write_bytes(7, 4096);
  739. super::zero(at, 4096);
  740. assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
  741. super::zero(at.add(4096), 4096);
  742. VirtualFree(at.cast(), 0, MEM_RELEASE);
  743. }
  744. }
  745. #[test]
  746. fn sparse_copies_preserve_islands_and_observe_remaps() {
  747. use windows_sys::Win32::System::Memory::*;
  748. const N: usize = 5 << 16;
  749. // SAFETY: we reserve a private region, commit selected pages inside it,
  750. // and only directly access the pages while they are writable.
  751. unsafe {
  752. let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  753. assert!(!base.is_null());
  754. let mut expected = vec![0; N];
  755. for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
  756. let at = base.add(offset);
  757. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  758. at.write_bytes(value, 4096);
  759. expected[offset..offset + 4096].fill(value);
  760. }
  761. for remap in [false, true] {
  762. if remap {
  763. let mut old = 0;
  764. assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
  765. expected[..4096].fill(0);
  766. let at = base.add(1 << 16);
  767. assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
  768. at.write_bytes(0xc7, 4096);
  769. expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
  770. }
  771. let mut out = vec![0xee; N];
  772. super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
  773. assert_eq!(out[27..N - 27], expected[27..N - 27]);
  774. assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
  775. }
  776. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  777. }
  778. }
  779. use super::*;
  780. #[test]
  781. fn warp_adapter_accepts_only_software() {
  782. // This probes DXGI without creating a D3D12 device or running a title.
  783. // SAFETY: plain DXGI adapter queries.
  784. let raw = unsafe {
  785. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  786. else {
  787. return;
  788. };
  789. factory.EnumWarpAdapter::<IDXGIAdapter>()
  790. };
  791. let Ok(raw) = raw else { return };
  792. // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
  793. // IDXGIAdapter1; `raw` owns that interface.
  794. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  795. eprintln!(
  796. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  797. desc.VendorId, desc.Flags
  798. );
  799. assert_eq!(
  800. warp_adapter().is_ok(),
  801. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  802. );
  803. }
  804. }
  805. /// The batches of clamped records in one scratch buffer
  806. /// ([`HostList::batch_place`]).
  807. const BATCHES: u32 = 8;
  808. /// A host command list and its allocator, always used together.
  809. pub(crate) struct HostList {
  810. allocator: ID3D12CommandAllocator,
  811. pub(crate) list: ID3D12GraphicsCommandList,
  812. /// Work for submission time, in recorded order.
  813. deferred: Mutex<Deferred>,
  814. /// Upload memory for data the list's draws make (expanded vertices),
  815. /// reused after a reset.
  816. scratch: Mutex<Scratch>,
  817. /// Host texture states the list assumes, by host copy: at its start and
  818. /// at its end. Lists are recorded on many threads and run in submission
  819. /// order, so the transitions from a texture's real state are made at
  820. /// submission, in `prelude`. Holding the copies keeps every texture the
  821. /// list names alive until it is reset, even if the title releases the
  822. /// resource first.
  823. states: Mutex<States>,
  824. /// What the list does with depth textures that have a colour twin, by
  825. /// twin ([`TwinUse`]).
  826. twins: Mutex<std::collections::HashMap<usize, TwinUse>>,
  827. /// The list that runs those transitions just before this one, made
  828. /// when the list first has such transitions ([`lazy_prelude`]).
  829. prelude: OnceLock<Option<Prelude>>,
  830. /// The pipelines the list binds, for reports of slow submissions.
  831. pipelines: std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>,
  832. /// The work its indirect executions may still do (`indirect`): a
  833. /// shader-writable word, zeroed when the list is submitted, and after
  834. /// it what the clamp notes about mesh records. In memory the CPU maps.
  835. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  836. /// The same words in the card's own memory ([`card_budget`]), which the
  837. /// clamp uses instead when there is one: zeroed in the list before its
  838. /// first clamp, its notes copied to `budget` when the list closes.
  839. card_budget: OnceLock<Option<ID3D12Resource>>,
  840. /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
  841. /// grown to the largest indirect execution recorded on the list.
  842. indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
  843. /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
  844. /// how many batches of this recording have a place in them.
  845. batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
  846. /// Counts the list in [`ALIVE`] while it lives.
  847. _alive: Counted,
  848. /// The texts of the markers `note_op` set, in order (for device-removed
  849. /// data without marker texts), with the host GPU range a copy reads.
  850. #[cfg(feature = "diagnostics")]
  851. notes: std::sync::Arc<Mutex<Vec<Note>>>,
  852. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  853. /// and at the end, and where they are read back.
  854. #[cfg(feature = "diagnostics")]
  855. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  856. }
  857. /// A list's prelude: an allocator and a closed list.
  858. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
  859. /// Whether a host list's prelude is made when the list first needs one. A
  860. /// prelude runs the texture transitions and twin copies a list needs before
  861. /// it; lists that name no texture never have one, and every host list was
  862. /// made with one all the same: twice the host objects per list, for the
  863. /// title's 630 lists and for every list made anew.
  864. /// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
  865. fn lazy_prelude() -> bool {
  866. static ON: OnceLock<bool> = OnceLock::new();
  867. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
  868. }
  869. /// Timestamps per list (diagnostics); commands past them are not timed.
  870. #[cfg(feature = "diagnostics")]
  871. const STAMPS: u32 = 4096;
  872. /// A marker's text and the host range its command reads (diagnostics).
  873. #[cfg(feature = "diagnostics")]
  874. type Note = (String, Option<(u64, u64)>);
  875. type States = std::collections::HashMap<
  876. usize,
  877. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  878. >;
  879. /// What a list does with a depth texture that has a colour twin
  880. /// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
  881. /// in submission order, so a list cannot know which side an earlier list
  882. /// leaves behind: it notes which sides it uses as it finds them, and its
  883. /// prelude copies one side into the other at submission if that side is
  884. /// behind then. From its first use of a side on, the list knows.
  885. struct TwinUse {
  886. /// The depth texture (the title resource's host copy) and its twin.
  887. depth: std::sync::Arc<crate::resource::HostTexture>,
  888. twin: std::sync::Arc<crate::resource::Twin>,
  889. /// The sides (depth texture, twin) the list uses as it finds them.
  890. needs: [bool; 2],
  891. /// Whether each side lacks what the other was written last, where the
  892. /// list is now; `None`: as the list found it.
  893. behind: [Option<bool>; 2],
  894. /// The draw or dispatch being prepared writes the twin.
  895. writing: bool,
  896. /// The depth plane's twin holds what the plane lacks although the list
  897. /// copied the twins since: the plane's pass waits for the list's close.
  898. late: bool,
  899. }
  900. /// The pass that draws the twin of a depth plane into the plane: one
  901. /// triangle over each mip of each slice, its pixel shader writing the
  902. /// twin's texel as the depth, with the depth test "always" and no stencil
  903. /// (the stencil plane is copied through a buffer and not touched here).
  904. ///
  905. /// A 16-bit twin holds whole steps of 1/65535, and the depth written is
  906. /// the step times the float nearest 1/65535 (0x37800080). That is how
  907. /// The title's tiled lighting computes the depth of the
  908. /// rectangles it then draws with the test "equal", one class of materials
  909. /// a draw (all six of its vertex shaders multiply the class number by that
  910. /// constant), so the pass and the draw give the host the same float, and
  911. /// the host turns the same float into the same 24 bits. The step divided
  912. /// by 65535 is another float for 512 of the 65,536 steps (none under 257),
  913. /// and lands in another 24-bit step for 127 of them (none under 385).
  914. const PLANE_CORNERS: &str = r#"
  915. float4 corner(uint i : SV_VertexID) : SV_Position {
  916. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
  917. }
  918. "#;
  919. const PLANE_STEPS: &str = r#"
  920. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  921. Texture2DArray<uint> twin : register(t0);
  922. [RootSignature(RS)]
  923. float plane(float4 p : SV_Position) : SV_Depth {
  924. return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
  925. }
  926. "#;
  927. const PLANE_FLOATS: &str = r#"
  928. #define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
  929. Texture2DArray<float> twin : register(t0);
  930. [RootSignature(RS)]
  931. float plane(float4 p : SV_Position) : SV_Depth {
  932. return twin.Load(int4(int2(p.xy), 0, 0));
  933. }
  934. "#;
  935. /// Views of twins the pass reads, in a heap of ours used as a ring.
  936. /// shortcut: a view must last until its list has run; with one or two
  937. /// passes a frame the ring is far from coming round.
  938. const PLANE_VIEWS: u32 = 256;
  939. /// What the pass draws with: the heap of its views of twins, and per kind
  940. /// of twin (16-bit steps or floats) and depth format the root signature
  941. /// and pipeline, made when first needed (`None`: the host refused).
  942. struct PlanePass {
  943. views: ID3D12DescriptorHeap,
  944. cpu: usize,
  945. gpu: u64,
  946. step: u32,
  947. next: AtomicU32,
  948. made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>,
  949. }
  950. /// The pass's root signature and pipeline for one kind of twin and one
  951. /// depth format.
  952. type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
  953. // SAFETY: D3D12 objects are free-threaded.
  954. unsafe impl Send for PlanePass {}
  955. // SAFETY: as above.
  956. unsafe impl Sync for PlanePass {}
  957. fn plane_pass() -> Option<&'static PlanePass> {
  958. static PASS: OnceLock<Option<PlanePass>> = OnceLock::new();
  959. PASS.get_or_init(|| {
  960. let host = host()?;
  961. let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  962. // SAFETY: plain heap creation and queries.
  963. unsafe {
  964. let views: ID3D12DescriptorHeap = host
  965. .device
  966. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  967. Type: kind,
  968. NumDescriptors: PLANE_VIEWS,
  969. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  970. NodeMask: 0,
  971. })
  972. .ok()?;
  973. Some(PlanePass {
  974. cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
  975. gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
  976. step: host.device.GetDescriptorHandleIncrementSize(kind),
  977. views,
  978. next: AtomicU32::new(0),
  979. made: Mutex::default(),
  980. })
  981. }
  982. })
  983. .as_ref()
  984. }
  985. /// Compiles function `entry` of `source` for `target` with the system's
  986. /// compiler, as the indirect-argument clamp is (`crate::indirect`).
  987. pub(crate) fn compile(
  988. source: &str,
  989. entry: windows::core::PCSTR,
  990. target: windows::core::PCSTR,
  991. ) -> windows::core::Result<Vec<u8>> {
  992. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  993. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  994. let mut code: Option<ID3DBlob> = None;
  995. let mut errors: Option<ID3DBlob> = None;
  996. // SAFETY: the source and names live through the call; out pointers ours.
  997. let compiled = unsafe {
  998. D3DCompile(
  999. source.as_ptr().cast(),
  1000. source.len(),
  1001. windows::core::s!("victory"),
  1002. None,
  1003. None,
  1004. entry,
  1005. target,
  1006. 0,
  1007. 0,
  1008. &mut code,
  1009. Some(&mut errors),
  1010. )
  1011. };
  1012. if let Err(e) = compiled {
  1013. if let Some(errors) = errors {
  1014. // SAFETY: the blob's own bytes.
  1015. let text = unsafe {
  1016. std::slice::from_raw_parts(
  1017. errors.GetBufferPointer().cast::<u8>(),
  1018. errors.GetBufferSize(),
  1019. )
  1020. };
  1021. tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
  1022. }
  1023. return Err(e);
  1024. }
  1025. let code = code.ok_or_else(windows::core::Error::empty)?;
  1026. // SAFETY: the blob's own bytes.
  1027. let bytes = unsafe {
  1028. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  1029. };
  1030. Ok(bytes.to_vec())
  1031. }
  1032. impl PlanePass {
  1033. /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
  1034. /// or of floats and the depth format `format`.
  1035. fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> {
  1036. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1037. if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
  1038. return pipeline.clone();
  1039. }
  1040. let pipeline = match Self::make(steps, format) {
  1041. Ok(pipeline) => Some(pipeline),
  1042. Err(e) => {
  1043. tracing::warn!(
  1044. error = %e,
  1045. steps,
  1046. format = format.0,
  1047. "no pipeline to draw a depth plane from its twin: such planes stay as they are"
  1048. );
  1049. None
  1050. }
  1051. };
  1052. made.push((steps, format.0, pipeline.clone()));
  1053. pipeline
  1054. }
  1055. fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> {
  1056. use windows::core::s;
  1057. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  1058. let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?;
  1059. let source = if steps { PLANE_STEPS } else { PLANE_FLOATS };
  1060. let ps = compile(source, s!("plane"), s!("ps_5_1"))?;
  1061. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  1062. pShaderBytecode: bytes.as_ptr().cast(),
  1063. BytecodeLength: bytes.len(),
  1064. };
  1065. // SAFETY: the root signature is inside the pixel shader; the
  1066. // description points at live data and never releases its pointer.
  1067. unsafe {
  1068. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?;
  1069. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1070. pRootSignature: std::mem::transmute_copy(&root),
  1071. VS: code(&vs[..]),
  1072. PS: code(&ps[..]),
  1073. SampleMask: u32::MAX,
  1074. RasterizerState: D3D12_RASTERIZER_DESC {
  1075. FillMode: D3D12_FILL_MODE_SOLID,
  1076. CullMode: D3D12_CULL_MODE_NONE,
  1077. DepthClipEnable: true.into(),
  1078. ..Default::default()
  1079. },
  1080. // Every texel is written; stencil stays off.
  1081. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  1082. DepthEnable: true.into(),
  1083. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  1084. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1085. ..Default::default()
  1086. },
  1087. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1088. DSVFormat: format,
  1089. SampleDesc: DXGI_SAMPLE_DESC {
  1090. Count: 1,
  1091. Quality: 0,
  1092. },
  1093. ..Default::default()
  1094. };
  1095. let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?;
  1096. Ok((root, pipeline))
  1097. }
  1098. }
  1099. }
  1100. /// Records into `list` the pass that draws `plane`, the twin of the depth
  1101. /// plane of `depth`, into that plane: `depth` in the depth-write state,
  1102. /// `plane` readable by pixel shaders. The pass sets the list's descriptor
  1103. /// heap, graphics root signature, pipeline, depth target, viewport,
  1104. /// scissor and topology and puts none of them back: it is for a list that
  1105. /// records nothing of the title's after it.
  1106. fn record_plane_pass(
  1107. list: &ID3D12GraphicsCommandList,
  1108. depth: &ID3D12Resource,
  1109. plane: &ID3D12Resource,
  1110. ) {
  1111. let (Some(host), Some(pass)) = (host(), plane_pass()) else {
  1112. return;
  1113. };
  1114. // SAFETY: live resources.
  1115. let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) };
  1116. // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32
  1117. // typeless one floats, read as R32_FLOAT (41). The depth view names
  1118. // the depth-stencil format of the texture's family (44: 45, 19: 20).
  1119. let steps = twin.Format.0 == 53;
  1120. let format = DXGI_FORMAT(match of.Format.0 {
  1121. 44 => 45,
  1122. 19 => 20,
  1123. typed => typed,
  1124. });
  1125. let Some((root, pipeline)) = pass.pipeline(steps, format) else {
  1126. return;
  1127. };
  1128. for slice in 0..u32::from(of.DepthOrArraySize) {
  1129. for mip in 0..u32::from(of.MipLevels) {
  1130. let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS;
  1131. let view = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1132. Format: DXGI_FORMAT(if steps { 57 } else { 41 }),
  1133. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
  1134. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1135. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1136. Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
  1137. MostDetailedMip: mip,
  1138. MipLevels: 1,
  1139. FirstArraySlice: slice,
  1140. ArraySize: 1,
  1141. ..Default::default()
  1142. },
  1143. },
  1144. };
  1145. let target = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1146. Format: format,
  1147. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY,
  1148. Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 {
  1149. Texture2DArray: D3D12_TEX2D_ARRAY_DSV {
  1150. MipSlice: mip,
  1151. FirstArraySlice: slice,
  1152. ArraySize: 1,
  1153. },
  1154. },
  1155. ..Default::default()
  1156. };
  1157. let target = host.dsv(depth, Some(&target));
  1158. let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1));
  1159. let cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
  1160. ptr: pass.cpu + (slot * pass.step) as usize,
  1161. };
  1162. let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
  1163. ptr: pass.gpu + u64::from(slot * pass.step),
  1164. };
  1165. // SAFETY: an open list; a slot of our heap; live resources and
  1166. // objects (the pass's own live as long as the process).
  1167. unsafe {
  1168. host.device
  1169. .CreateShaderResourceView(plane, Some(&view), cpu);
  1170. list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
  1171. list.SetGraphicsRootSignature(&root);
  1172. list.SetPipelineState(&pipeline);
  1173. list.SetGraphicsRootDescriptorTable(0, gpu);
  1174. list.OMSetRenderTargets(0, None, false, Some(&target));
  1175. list.RSSetViewports(&[D3D12_VIEWPORT {
  1176. TopLeftX: 0.0,
  1177. TopLeftY: 0.0,
  1178. Width: width as f32,
  1179. Height: height as f32,
  1180. MinDepth: 0.0,
  1181. MaxDepth: 1.0,
  1182. }]);
  1183. list.RSSetScissorRects(&[RECT {
  1184. left: 0,
  1185. top: 0,
  1186. right: width as i32,
  1187. bottom: height as i32,
  1188. }]);
  1189. list.IASetPrimitiveTopology(
  1190. windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4),
  1191. );
  1192. list.DrawInstanced(3, 1, 0, 0);
  1193. }
  1194. crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed);
  1195. }
  1196. }
  1197. }
  1198. /// Records into `list` the copy of a depth texture into its colour twin
  1199. /// (`colour`) or of the twin into the depth texture, both already in their
  1200. /// copy states: whole textures of one size in one format family, which the
  1201. /// host copies as they are; or, for the twin of a stencil plane, that plane
  1202. /// alone, through the twin's buffer.
  1203. fn record_twin_copy(
  1204. list: &ID3D12GraphicsCommandList,
  1205. depth: &ID3D12Resource,
  1206. twin: &crate::resource::Twin,
  1207. colour: bool,
  1208. ) {
  1209. let (from, to) = if colour {
  1210. (depth, &twin.colour.texture)
  1211. } else {
  1212. (&twin.colour.texture, depth)
  1213. };
  1214. crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed);
  1215. // shortcut: the depth plane's twin is not given the plane (that is a
  1216. // pass the other way: the plane read by a shader, the twin as its
  1217. // target). The twin then lacks what draws and clears wrote to the
  1218. // plane since shaders last wrote the twin. In the title
  1219. // nothing writes that plane but the twin's pass (its 192 draws against
  1220. // it only test, run 29), so the twin lacks nothing. Counted.
  1221. if colour && twin.plane.is_some() {
  1222. crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed);
  1223. }
  1224. let Some(through) = &twin.through else {
  1225. // SAFETY: an open list and two live textures.
  1226. unsafe { list.CopyResource(to, from) };
  1227. return;
  1228. };
  1229. // A stencil plane and its twin: each mip and slice of the plane goes
  1230. // into the buffer, laid out as the host lays the plane out for copies,
  1231. // and from the buffer into the other texture, whole subresources both
  1232. // times. In the depth texture the stencil plane's subresources follow
  1233. // the depth plane's; the twin has the one plane.
  1234. let Some(host) = host() else { return };
  1235. // SAFETY: a live texture.
  1236. let of = unsafe { depth.GetDesc() };
  1237. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  1238. let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize];
  1239. // SAFETY: a plain query writing `planes` footprints.
  1240. unsafe {
  1241. host.device.GetCopyableFootprints(
  1242. &of,
  1243. planes,
  1244. planes,
  1245. 0,
  1246. Some(rows.as_mut_ptr()),
  1247. None,
  1248. None,
  1249. None,
  1250. );
  1251. }
  1252. let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) };
  1253. let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  1254. // SAFETY: a borrowed pointer the location never releases.
  1255. pResource: unsafe { std::mem::transmute_copy(texture) },
  1256. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1257. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1258. SubresourceIndex: index,
  1259. },
  1260. };
  1261. let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  1262. // SAFETY: as above.
  1263. pResource: unsafe { std::mem::transmute_copy(through) },
  1264. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1265. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1266. PlacedFootprint: *row,
  1267. },
  1268. };
  1269. let (common, source, dest) = (
  1270. D3D12_RESOURCE_STATE_COMMON,
  1271. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1272. D3D12_RESOURCE_STATE_COPY_DEST,
  1273. );
  1274. // SAFETY: an open list and live resources; the buffer was made as big
  1275. // as these footprints, and rests in the common state between copies.
  1276. unsafe {
  1277. list.ResourceBarrier(&[transition(through, common, dest)]);
  1278. for (i, row) in rows.iter().enumerate() {
  1279. let index = first_from + i as u32;
  1280. list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None);
  1281. }
  1282. list.ResourceBarrier(&[transition(through, dest, source)]);
  1283. for (i, row) in rows.iter().enumerate() {
  1284. let index = first_to + i as u32;
  1285. list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None);
  1286. }
  1287. list.ResourceBarrier(&[transition(through, source, common)]);
  1288. }
  1289. }
  1290. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  1291. /// builds).
  1292. pub(crate) fn dred_on() -> bool {
  1293. static ON: OnceLock<bool> = OnceLock::new();
  1294. *ON.get_or_init(|| cfg!(feature = "diagnostics") && crate::switch::on("VICTORY_D3D12_DRED") && !dred_faults() && !dred_light())
  1295. }
  1296. /// Breadcrumbs and the faulting address, but no markers and no texts
  1297. /// (`VICTORY_D3D12_DRED=light`): which list a removed device stopped in, at
  1298. /// which of its commands, and the pipelines the list binds; formatting a text
  1299. /// for every command is what makes the whole of it slow.
  1300. pub(crate) fn dred_light() -> bool {
  1301. static ON: OnceLock<bool> = OnceLock::new();
  1302. *ON.get_or_init(|| {
  1303. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "light")
  1304. })
  1305. }
  1306. /// Any of the three.
  1307. pub(crate) fn dred_any() -> bool {
  1308. dred_on() || dred_light() || dred_faults()
  1309. }
  1310. /// Whether only the faulting address of a removed device is kept
  1311. /// (`VICTORY_D3D12_DRED=faults`): no breadcrumbs, no markers and no texts, so
  1312. /// it costs next to nothing and can stay on while the title is played.
  1313. pub(crate) fn dred_faults() -> bool {
  1314. static ON: OnceLock<bool> = OnceLock::new();
  1315. *ON.get_or_init(|| {
  1316. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some_and(|v| v == "faults")
  1317. })
  1318. }
  1319. /// The lists alive while device-removed data is on, by the number their name
  1320. /// ends in, with their marker texts and the pipelines they bind: a report made
  1321. /// on another thread than the one that submits has no lists of its own.
  1322. #[cfg(feature = "diagnostics")]
  1323. #[allow(clippy::type_complexity)]
  1324. static LIST_NOTES: Mutex<
  1325. std::collections::BTreeMap<u32, (std::sync::Weak<Mutex<Vec<Note>>>, std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>)>,
  1326. > = Mutex::new(std::collections::BTreeMap::new());
  1327. /// The number in the name of a list of ours ("victory host list 7", which the
  1328. /// debug layer ends with a note of its own in brackets).
  1329. #[cfg(feature = "diagnostics")]
  1330. fn list_number(name: &str) -> Option<u32> {
  1331. let rest = name.strip_prefix("victory host list ")?;
  1332. let digits = rest.split(' ').next()?;
  1333. (rest.len() == digits.len() || rest[digits.len()..].starts_with(" (")).then(|| digits.parse().ok()).flatten()
  1334. }
  1335. /// Indirect mesh dispatches since the last frame line: the largest group
  1336. /// count a record asked for, and the groups asked in all (from the lists'
  1337. /// budget buffers, a run late).
  1338. static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  1339. /// Whether a list's indirect-work budget lives in the card's own memory
  1340. /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as
  1341. /// before). The clamp charges it with atomics, at least two in a row for
  1342. /// every clamp; in mapped memory on a card of its own each of them
  1343. /// crosses the bus.
  1344. fn card_budget() -> bool {
  1345. static ON: OnceLock<bool> = OnceLock::new();
  1346. *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0"))
  1347. }
  1348. /// Whether each list of a submission runs and is timed on its own, slow
  1349. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  1350. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  1351. #[cfg(feature = "diagnostics")]
  1352. fn timing() -> bool {
  1353. static ON: OnceLock<bool> = OnceLock::new();
  1354. *ON.get_or_init(|| crate::switch::on("VICTORY_GPU_TIMING"))
  1355. }
  1356. /// Names a host object for the device-removed report, which names the
  1357. /// allocations a page fault hit (only with device-removed data on), or for
  1358. /// the frame recorder (`VICTORY_RECORD`).
  1359. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  1360. #[cfg(feature = "diagnostics")]
  1361. if crate::replay::record::on() {
  1362. let text = text();
  1363. crate::replay::record::name(object, &text);
  1364. if dred_any()
  1365. && let Ok(object) = object.cast::<ID3D12Object>()
  1366. {
  1367. // SAFETY: a plain call on a live object.
  1368. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
  1369. }
  1370. return;
  1371. }
  1372. if dred_any()
  1373. && let Ok(object) = object.cast::<ID3D12Object>()
  1374. {
  1375. // SAFETY: a plain call on a live object.
  1376. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  1377. }
  1378. }
  1379. /// One in [`ALIVE`]`[0]` while it lives (a host list), and one in
  1380. /// [`LISTS`]`[3]` until it is first reset.
  1381. struct Counted {
  1382. /// Not reset since it was made.
  1383. fresh: std::sync::atomic::AtomicBool,
  1384. }
  1385. impl Counted {
  1386. fn new() -> Counted {
  1387. ALIVE[0].fetch_add(1, Ordering::Relaxed);
  1388. LISTS[3].fetch_add(1, Ordering::Relaxed);
  1389. Counted {
  1390. fresh: std::sync::atomic::AtomicBool::new(true),
  1391. }
  1392. }
  1393. /// The list is reset: it is in use.
  1394. fn used(&self) {
  1395. if self.fresh.swap(false, Ordering::Relaxed) {
  1396. LISTS[3].fetch_sub(1, Ordering::Relaxed);
  1397. }
  1398. }
  1399. }
  1400. impl Drop for Counted {
  1401. fn drop(&mut self) {
  1402. ALIVE[0].fetch_sub(1, Ordering::Relaxed);
  1403. self.used();
  1404. }
  1405. }
  1406. /// A chunk of upload memory for lists' scratch data: the buffer, its
  1407. /// mapping.
  1408. struct Chunk {
  1409. buffer: ID3D12Resource,
  1410. data: usize,
  1411. }
  1412. // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
  1413. // written only by the list that holds the chunk.
  1414. unsafe impl Send for Chunk {}
  1415. /// Upload chunks handed out front to back: the chunks (each with its
  1416. /// bytes), the one in use and the bytes used in it.
  1417. #[derive(Default)]
  1418. struct Scratch {
  1419. chunks: Vec<(Chunk, u64)>,
  1420. current: usize,
  1421. used: u64,
  1422. }
  1423. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  1424. unsafe impl Send for Scratch {}
  1425. impl Drop for Scratch {
  1426. fn drop(&mut self) {
  1427. give_chunks(std::mem::take(&mut self.chunks));
  1428. }
  1429. }
  1430. const SCRATCH_CHUNK: u64 = 4 << 20;
  1431. /// A list's first chunk when the chunks are shared ([`scratch_pool`]): most
  1432. /// lists put a few constants or a rectangle's corners there, and every
  1433. /// list that did took 4 MiB of the PC's memory for it.
  1434. const SCRATCH_FIRST: u64 = 256 << 10;
  1435. /// The most bytes of chunks kept while no list holds them.
  1436. const SPARE_MOST: u64 = 128 << 20;
  1437. /// Whether lists share their scratch chunks: a list takes a chunk when it
  1438. /// first needs one, a small one first, and gives all of them back when it
  1439. /// is reset or dropped, for the next list. Before, a list kept every chunk
  1440. /// it ever took (4 MiB each) for as long as it lived, used or not, and the
  1441. /// host lists of held submissions, which live for one submission, each
  1442. /// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and
  1443. /// freed per frame of gameplay (run 60).
  1444. /// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before.
  1445. fn scratch_pool() -> bool {
  1446. static ON: OnceLock<bool> = OnceLock::new();
  1447. *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0"))
  1448. }
  1449. /// Things of some sizes that nothing holds now, kept for whoever next asks
  1450. /// for one of the same size.
  1451. struct Spare<T> {
  1452. kept: Vec<(T, u64)>,
  1453. bytes: u64,
  1454. }
  1455. impl<T> Spare<T> {
  1456. const fn new() -> Self {
  1457. Spare { kept: Vec::new(), bytes: 0 }
  1458. }
  1459. /// A kept thing of `size` bytes, the one given last.
  1460. fn take(&mut self, size: u64) -> Option<T> {
  1461. let at = self.kept.iter().rposition(|(_, s)| *s == size)?;
  1462. self.bytes -= size;
  1463. Some(self.kept.remove(at).0)
  1464. }
  1465. /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past
  1466. /// `most`: then it comes back.
  1467. fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> {
  1468. if self.bytes + size > most {
  1469. return Some(thing);
  1470. }
  1471. self.bytes += size;
  1472. self.kept.push((thing, size));
  1473. None
  1474. }
  1475. }
  1476. /// Scratch chunks no list holds.
  1477. static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new());
  1478. /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one.
  1479. fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
  1480. if scratch_pool()
  1481. && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size)
  1482. {
  1483. ALIVE[3].fetch_sub(1, Ordering::Relaxed);
  1484. ALIVE[4].fetch_sub(size, Ordering::Relaxed);
  1485. ALIVE[5].fetch_add(1, Ordering::Relaxed);
  1486. return Some(chunk);
  1487. }
  1488. let (buffer, data) = host.upload_buffer(size)?;
  1489. name(&buffer, || "list scratch".into());
  1490. ALIVE[1].fetch_add(1, Ordering::Relaxed);
  1491. ALIVE[2].fetch_add(size, Ordering::Relaxed);
  1492. Some(Chunk {
  1493. buffer,
  1494. data: data as usize,
  1495. })
  1496. }
  1497. /// A list is done with `chunks` (it was reset after its submissions ran,
  1498. /// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and
  1499. /// without the pool.
  1500. fn give_chunks(chunks: Vec<(Chunk, u64)>) {
  1501. if chunks.is_empty() {
  1502. return;
  1503. }
  1504. let mut freed = Vec::new();
  1505. {
  1506. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  1507. for (chunk, size) in chunks {
  1508. let back = if scratch_pool() {
  1509. spare.give(chunk, size, SPARE_MOST)
  1510. } else {
  1511. Some(chunk)
  1512. };
  1513. match back {
  1514. None => {
  1515. ALIVE[3].fetch_add(1, Ordering::Relaxed);
  1516. ALIVE[4].fetch_add(size, Ordering::Relaxed);
  1517. }
  1518. Some(chunk) => {
  1519. ALIVE[1].fetch_sub(1, Ordering::Relaxed);
  1520. ALIVE[2].fetch_sub(size, Ordering::Relaxed);
  1521. freed.push(chunk);
  1522. }
  1523. }
  1524. }
  1525. }
  1526. // Freed outside the lock.
  1527. drop(freed);
  1528. }
  1529. /// What the host keeps for copies in the card's own memory
  1530. /// ([`crate::shadow::cards`]): three lists of ours and the compare.
  1531. struct CardWork {
  1532. /// Before a submission's lists: what changed on the copies' CPU side
  1533. /// goes to their card side. Those not in use: a plan takes one and
  1534. /// gives it back when its submission has run (`Host::card_done`), so
  1535. /// that submissions sent ahead ([`late`]) each have their own.
  1536. sync: Vec<Prelude>,
  1537. /// After them, in the same submission: the compare of the declared
  1538. /// ranges with their bytes from before. As `sync`.
  1539. check: Vec<Prelude>,
  1540. /// After it ran: the pieces that differ come down.
  1541. fetch: Prelude,
  1542. root: ID3D12RootSignature,
  1543. pso: ID3D12PipelineState,
  1544. /// One dword per piece compared, odd where the piece differs: PC
  1545. /// memory, mapped (buffer, mapping, bytes).
  1546. differs: (ID3D12Resource, usize, u64),
  1547. /// Where the pieces that differ are fetched to: PC memory, mapped.
  1548. fetched: Option<(ID3D12Resource, usize, u64)>,
  1549. /// The dwords of `differs` taken by plans whose results were not read
  1550. /// yet.
  1551. taken: u32,
  1552. /// Plans made and not done with (`Host::card_done`).
  1553. out: u32,
  1554. }
  1555. // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only
  1556. // under the submission lock.
  1557. unsafe impl Send for CardWork {}
  1558. static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
  1559. /// The compare of a declared range of a copy in the card's memory with
  1560. /// its bytes from before, one group per 64 KiB piece (cut at multiples of
  1561. /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
  1562. /// gets a dword per piece, odd where a byte differs. The offsets are widened
  1563. /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
  1564. /// byte just outside the range costs a fetch that finds nothing.
  1565. ///
  1566. /// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and
  1567. /// one of them hashes their 64 hashes: 64 steps after one another. One thread
  1568. /// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's
  1569. /// 82 on the card (capture replay1, 405 of them), most of it waiting for
  1570. /// those steps.
  1571. pub(crate) const CARD_COMPARE: &str = r#"
  1572. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)"
  1573. cbuffer Span : register(b0) {
  1574. uint first; // the first piece
  1575. uint skew; // where the copy starts in its piece 0
  1576. uint size; // the copy's buffer, in bytes (a multiple of 64 KiB)
  1577. uint pieces;
  1578. uint out_at; // the first piece's dword in `differs`, in bytes
  1579. uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored)
  1580. };
  1581. ByteAddressBuffer now : register(t0);
  1582. // 16 bytes per piece of the copy: the hash of its bytes when they were
  1583. // last sent up (or hashed whole, the first time).
  1584. RWByteAddressBuffer hashes : register(u0);
  1585. RWByteAddressBuffer differs : register(u1);
  1586. groupshared uint4 parts[64];
  1587. [RootSignature(RS)]
  1588. [numthreads(64, 1, 1)]
  1589. void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
  1590. uint piece = first + id.x;
  1591. uint lo = piece * 65536u;
  1592. lo = lo > skew ? lo - skew : 0u;
  1593. uint hi = min((piece + 1u) * 65536u - skew, size);
  1594. lo = lo & ~15u;
  1595. hi = (hi + 15u) & ~15u;
  1596. uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread;
  1597. [loop]
  1598. for (uint at = lo + thread * 16u; at < hi; at += 1024u) {
  1599. h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1600. h = h.yzwx ^ (h >> 15);
  1601. }
  1602. parts[thread] = h;
  1603. GroupMemoryBarrierWithGroupSync();
  1604. if (thread != 0u) return;
  1605. h = parts[0];
  1606. [loop]
  1607. for (uint i = 1u; i < 64u; ++i) {
  1608. h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du);
  1609. h = h.yzwx ^ (h >> 15);
  1610. }
  1611. if (compare != 0u) {
  1612. // The flag, and above it 31 bits of the hash (`torn`).
  1613. uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
  1614. differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
  1615. // With the copy-back on its own thread: the next compare of the
  1616. // piece finds what is written from here on.
  1617. if (compare == 2u) hashes.Store4(piece * 16u, h);
  1618. } else {
  1619. hashes.Store4(piece * 16u, h);
  1620. }
  1621. }
  1622. "#;
  1623. /// The hash [`CARD_COMPARE`] gives of a piece with its flag.
  1624. #[cfg(test)]
  1625. pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
  1626. torn::hash(bytes)
  1627. }
  1628. /// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
  1629. /// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
  1630. /// parts a dispatch can hold.
  1631. ///
  1632. /// # Safety
  1633. /// The list is open with the compare's root signature, pipeline and buffers
  1634. /// set, and the pieces lie in the buffer.
  1635. unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) {
  1636. const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  1637. let mut done = 0;
  1638. while done < span.pieces {
  1639. let n = (span.pieces - done).min(MOST);
  1640. let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode];
  1641. // SAFETY: the caller's.
  1642. unsafe {
  1643. list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1644. list.Dispatch(n, 1, 1);
  1645. }
  1646. done += n;
  1647. }
  1648. }
  1649. /// Whether the pieces hashed again after ranges were sent up to a copy in
  1650. /// the card's memory are hashed in runs of pieces that touch, each piece
  1651. /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass
  1652. /// per range sent up.
  1653. ///
  1654. /// These passes are ours, they run on the card before every submission's
  1655. /// lists: a pass takes the time of one piece however few its pieces are.
  1656. /// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way;
  1657. /// a piece hashed when it need not be, or not hashed when it should, costs
  1658. /// a fetch that finds nothing and loses no shader write.
  1659. fn rehash_runs() -> bool {
  1660. static ON: OnceLock<bool> = OnceLock::new();
  1661. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_REHASH_RUNS").is_some_and(|v| v == "1"))
  1662. }
  1663. /// Since the last frame-rate line, of our own passes over copies in the
  1664. /// card's memory: hash passes after ranges were sent up, the pieces they
  1665. /// hashed, and compare passes after the lists.
  1666. static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1667. /// Whether what shaders wrote to copies in the card's memory is merged
  1668. /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by
  1669. /// default). The pieces the card's compare found differing come down in
  1670. /// one fetch and were then merged one after the other on the thread that
  1671. /// settles: about 630 pieces and 40 MB a frame (run 104), each compared
  1672. /// with the copy's CPU side byte by byte and put into title memory through
  1673. /// the kernel. A piece is its own bytes of its copy and of title memory,
  1674. /// so eight threads take an eighth of them each. (Not with [`relay`], whose
  1675. /// landings do not come here: `crate::land` has threads of its own.)
  1676. fn wide_merge() -> bool {
  1677. static ON: OnceLock<bool> = OnceLock::new();
  1678. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
  1679. }
  1680. /// One declared range of a copy in the card's memory, in a submission.
  1681. struct CardRange {
  1682. shadow: std::sync::Arc<crate::shadow::Shadow>,
  1683. /// As declared (title addresses), for the statistics.
  1684. declared: (usize, usize),
  1685. span: crate::shadow::CardSpan,
  1686. /// Its first piece's dword in the compare's results.
  1687. at: u32,
  1688. /// Whether the card compares it; else every piece is fetched.
  1689. compared: bool,
  1690. /// Looked at by `crate::picked`, and not declared: what is found changed
  1691. /// there was written through a view nobody declared. Not landed.
  1692. picked: bool,
  1693. }
  1694. impl CardPlan {
  1695. /// `crate::picked` is told where what it looked at changed, by the
  1696. /// compare's results.
  1697. fn picked_found(&self, differs: &[u32]) {
  1698. for r in self.ranges.iter().filter(|r| r.picked) {
  1699. let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
  1700. if let Some(p) = changed {
  1701. crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
  1702. }
  1703. }
  1704. }
  1705. }
  1706. /// What a submission does for copies in the card's memory.
  1707. struct CardPlan {
  1708. ranges: Vec<CardRange>,
  1709. /// The compare, run after the submission's lists.
  1710. check: Option<ID3D12CommandList>,
  1711. /// The copies whose card side was brought up to date, alive until the
  1712. /// submission has run.
  1713. _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>,
  1714. /// The lists of ours the plan recorded (whether the compare, the
  1715. /// list), given back by `Host::card_done`.
  1716. lists: Vec<(bool, Prelude)>,
  1717. /// With [`relay`]: the number of the send to copies in the card's memory
  1718. /// that the submission ran behind ([`QUEUE_ORDER`]).
  1719. sent_as: u64,
  1720. /// With [`upcheck`]: the look at what it sent up.
  1721. looks: Option<upcheck::Looks>,
  1722. /// With [`send`]: the memory its sends come from.
  1723. sends: Option<send::Memory>,
  1724. }
  1725. /// One piece of submission-time work, in recorded order.
  1726. enum Step {
  1727. /// A copy into title memory (destination, source, bytes): the title's
  1728. /// buffer copies, which later refreshes must see.
  1729. Copy(usize, usize, usize),
  1730. /// A copy of title memory into the list's own upload memory, and how
  1731. /// the card could bring the bytes instead.
  1732. Fill(usize, usize, usize, Option<card_steps::FillTo>),
  1733. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  1734. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  1735. /// intervenes.
  1736. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1737. /// Work that may write title memory.
  1738. Run(Box<dyn Fn() + Send>),
  1739. /// Work that writes host memory only, and the title memory it reads
  1740. /// (from, to; empty for none).
  1741. Host(Box<dyn Fn() + Send>, (usize, usize)),
  1742. /// Shaders write a range (address, bytes) of a buffer's host copy.
  1743. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  1744. /// Brings a texture's staging buffer up to date: once per submission,
  1745. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  1746. Texture(std::sync::Arc<crate::texture::Staging>),
  1747. /// A title buffer copy that the list does on the card ([`place`]): what
  1748. /// is done on the CPU for it.
  1749. Placed(place::Placed),
  1750. }
  1751. /// What a list does on the CPU when it is submitted: copies between host
  1752. /// memory regions (title buffers, upload buffers and buffer copies), and
  1753. /// the upload buffers its GPU commands read, kept until the list is reset.
  1754. #[derive(Default)]
  1755. struct Deferred {
  1756. /// Destination, source, bytes.
  1757. copies: Vec<Step>,
  1758. uploads: Vec<ID3D12Resource>,
  1759. /// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
  1760. upload_bytes: u64,
  1761. /// Host objects the list's commands name (pipelines, root signatures,
  1762. /// descriptor heaps): the title may release its objects before it
  1763. /// submits the list.
  1764. kept: Vec<windows::core::IUnknown>,
  1765. /// Buffer ranges refreshed since the last title copy (host copy,
  1766. /// address, bytes): refreshing them again would find the same bytes.
  1767. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  1768. /// Textures whose contents the list brings up to date.
  1769. textures: std::collections::HashSet<usize>,
  1770. /// Bottom-of-pipe writes, done once the list has run: address, what,
  1771. /// bytes.
  1772. writes: Vec<(usize, crate::queue::Written, usize)>,
  1773. /// Textures read back (texture to buffer copies), done once the list
  1774. /// has run: the host buffer the list copies the texels into, the title
  1775. /// memory they go to, the bytes of a row, the rows, the title's row
  1776. /// pitch.
  1777. backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
  1778. /// Whether the indirect-work budget is zeroed for this recording (a
  1779. /// step on the CPU, or in the list for the card's copy).
  1780. budget_zeroed: bool,
  1781. /// The indirect scratch buffer (`HostList::indirect_args`, by its
  1782. /// interface pointer) that a clamp in this recording left readable as
  1783. /// indirect arguments; 0 if none. It stays readable until the next
  1784. /// clamp into it ([`HostList::indirect_state`]).
  1785. indirect_readable: usize,
  1786. }
  1787. impl Deferred {
  1788. /// Holds `buffer` (`size` bytes of upload memory) until the list is
  1789. /// reset.
  1790. fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) {
  1791. ALIVE[6].fetch_add(1, Ordering::Relaxed);
  1792. ALIVE[7].fetch_add(size, Ordering::Relaxed);
  1793. self.upload_bytes += size;
  1794. self.uploads.push(buffer);
  1795. }
  1796. }
  1797. impl Drop for Deferred {
  1798. fn drop(&mut self) {
  1799. ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
  1800. ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
  1801. }
  1802. }
  1803. /// Whether a queue's submissions go to the card without a wait for each
  1804. /// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which
  1805. /// waits for every list on its own).
  1806. ///
  1807. /// Every submission was prepared, sent, waited for and copied back before
  1808. /// the next one was looked at, so the card stood idle while we prepared
  1809. /// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of
  1810. /// preparing, 194 ms of waiting and 78 ms of copying back, one after the
  1811. /// other, on the one thread that submits.
  1812. ///
  1813. /// With the switch a queue's submission is sent and joins a line of
  1814. /// "flights" ([`Flight`]); the thread goes on to the next one while the
  1815. /// card runs. The flights are settled together ([`Host::settle`]: one wait
  1816. /// for the card, what their shaders wrote copied back once per byte, then
  1817. /// their bottom-of-pipe writes and the fence signals behind them, in
  1818. /// order) at the next point where the title, or our own preparing, can
  1819. /// observe what they do. Those points, exactly:
  1820. ///
  1821. /// 1. a synchronous submission of ours ([`Host::execute`]): a present, a
  1822. /// read-back or map of a texture, a clear or upload run at once;
  1823. /// 2. the next submission reads title memory that a flight's shaders may
  1824. /// write: a title buffer copy, a fill of upload memory, a texture's
  1825. /// memory, any step that runs code of ours on title memory
  1826. /// ([`late_blocked`]);
  1827. /// 3. the next submission refreshes a range of a host copy that a flight's
  1828. /// shaders may write, and the title wrote a page of it since it was last
  1829. /// copied ([`stale_under_flights`]): the refresh leaves such a range
  1830. /// alone until the flight's writes are back, as it always did within a
  1831. /// submission;
  1832. /// 4. a queue stands at a wait for a memory value that no flight's
  1833. /// bottom-of-pipe write is known to satisfy, at an address a flight may
  1834. /// write ([`late_met`]);
  1835. /// 5. the title blocks on a fence without an event;
  1836. /// 6. the card has run every flight (a thread of ours waits for that:
  1837. /// [`late_helper`]), or the flights hold [`late_most`] host lists.
  1838. ///
  1839. /// What the title is told (bottom-of-pipe writes, fence values) is told
  1840. /// when the card has really run the work, later than before and never
  1841. /// earlier; a fence signalled on a queue while flights are in the air is
  1842. /// set behind them. A wait for a memory value that a flight's
  1843. /// bottom-of-pipe write satisfies counts as met: the waiting part goes to
  1844. /// the card behind that flight, which is the order the wait asks for.
  1845. ///
  1846. /// What it assumes beyond today: memory the title rewrites between two of
  1847. /// its submissions, without waiting for the first, may be seen by the
  1848. /// first's shaders (as on the console, where the card reads title memory
  1849. /// when it runs, not when the list is submitted).
  1850. pub(crate) fn late() -> bool {
  1851. late_stage() > 0
  1852. }
  1853. /// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]).
  1854. fn late_stage() -> u8 {
  1855. static STAGE: OnceLock<u8> = OnceLock::new();
  1856. *STAGE.get_or_init(|| {
  1857. if std::env::var_os("VICTORY_GPU_TIMING").is_some() {
  1858. return 0;
  1859. }
  1860. match std::env::var("VICTORY_LATE_WAIT").as_deref() {
  1861. Ok("1") => 1,
  1862. Ok("2") => 2,
  1863. Ok("3") => 3,
  1864. // The relay alone: on top of stage 3.
  1865. Err(_) if crate::shadow::relay() => 3,
  1866. _ => 0,
  1867. }
  1868. })
  1869. }
  1870. /// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no
  1871. /// longer a point. Where the title wrote a page that lies in a range a
  1872. /// flight's shaders may write, the bytes the title changed are found (the
  1873. /// page as it is now against what the copy held when the flight was
  1874. /// prepared) and put into the copy, and only those: what the flight's
  1875. /// shaders write beside them stays (`Shadow::merge_under_writes`). The
  1876. /// flights are settled for it only where that cannot be done: memory that
  1877. /// is not write-watched, or a copy in the card's memory with more changed
  1878. /// runs than a submission should send up one by one.
  1879. ///
  1880. /// In run 92 (stage 1) this point settled the flights five times a frame
  1881. /// of twelve, each time with the card's work still to wait for: 172 ms a
  1882. /// frame of waiting were left of 200.
  1883. ///
  1884. /// What differs from settling first: a byte both the title and a flight's
  1885. /// shader wrote is the title's if the shader wrote it first, the shader's
  1886. /// if it wrote it afterwards; settled first it was always the shader's.
  1887. /// The title writing a byte a shader of its own is writing is a race on
  1888. /// the console too.
  1889. fn late_exact() -> bool {
  1890. late_stage() > 1
  1891. }
  1892. /// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is
  1893. /// no longer a point where flights are settled). The copy to the back
  1894. /// buffer is sent as a flight of its own (`Host::execute_own`, a list of
  1895. /// its own for each present in the air) and the swap chain is told to
  1896. /// present behind it; the queue's call returns, and the card finishes the
  1897. /// frame while the title records the next one. What the title is told
  1898. /// about the frame (bottom-of-pipe writes, fences) is told when the card
  1899. /// has run it, by the settling thread.
  1900. ///
  1901. /// What is left out with it: the look whether the presented frame is black
  1902. /// (diagnostics; it reads the frame back at once). A frame that is saved
  1903. /// or listed is presented the old way. Once every second and a half a
  1904. /// submission settles the flights all the same, for the sweep that lets
  1905. /// idle host objects go (it needs nothing in the air).
  1906. pub(crate) fn late_free_present() -> bool {
  1907. late_stage() > 2
  1908. }
  1909. /// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns
  1910. /// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage,
  1911. /// and is off with it, in the timing run and with kept snapshots).
  1912. ///
  1913. /// With [`late`] alone every settle does three things on the thread that
  1914. /// holds the submission lock: it waits for everything in the air, copies
  1915. /// back with the card standing, and only then goes on preparing. The frame
  1916. /// stays a relay: the card works about 242 ms of it and one thread
  1917. /// prepares, waits and copies back for about 220.
  1918. ///
  1919. /// With the switch a thread of its own ([`relay_worker`]) lands flights as
  1920. /// soon as the card has run them, in the order they were sent and without
  1921. /// the submission lock: it fetches and merges what their shaders wrote to
  1922. /// copies in the card's memory, compares and merges the other copies,
  1923. /// frees the flights' ranges, and then does their read-backs, their
  1924. /// bottom-of-pipe writes and the fence signals behind them, in the line's
  1925. /// order. The submitting thread meanwhile prepares and sends the next
  1926. /// submissions. [`Host::settle`] no longer settles anything: it waits until
  1927. /// that thread has landed everything in the air, at the same points as
  1928. /// before (the list in [`late`]), so whoever can observe title memory, a
  1929. /// fence or a present still does so only after the flights before it are
  1930. /// merged.
  1931. ///
  1932. /// What makes that safe is in `crate::shadow::relay` (ranges counted per
  1933. /// flight; a merge that never stores into memory the card may be writing;
  1934. /// sends to card copies numbered) and here: flights land in the order of
  1935. /// [`LINE`] by one thread, so a later flight's results never reach title
  1936. /// memory before an earlier flight's; the compare on the card stores the
  1937. /// hash it made, so each flight's compare flags exactly what changed since
  1938. /// the compare before it, however late the pieces are fetched; the fetch
  1939. /// goes to the queue under [`QUEUE_ORDER`], which says which sends of
  1940. /// title bytes the card had received when it ran.
  1941. pub(crate) fn relay() -> bool {
  1942. static ON: OnceLock<bool> = OnceLock::new();
  1943. *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay())
  1944. }
  1945. /// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads
  1946. /// title memory a flight's shaders may write (a title buffer copy, a fill
  1947. /// of upload memory, a texture) waits only until the flights that declared
  1948. /// that memory have landed, not for everything in the air; and at
  1949. /// [`late_most`] lists in the air it waits until there are fewer. At `1`
  1950. /// both wait for everything.
  1951. fn relay_exact() -> bool {
  1952. static ON: OnceLock<bool> = OnceLock::new();
  1953. // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default
  1954. // since the walls of the first room were found drawn in every run with
  1955. // this set and in fewer than half without it).
  1956. *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2"))
  1957. }
  1958. /// Whether the pieces the relay fetches from the card's memory come over the
  1959. /// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
  1960. /// draws.
  1961. ///
  1962. /// On the drawing queue a fetch runs behind whatever was sent meanwhile,
  1963. /// and with the relay that is most of a frame: the thread that lands flights
  1964. /// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
  1965. /// a few milliseconds of copying, and everything that waits for a landing
  1966. /// (the title's fences, reads of memory flights may write) waited with it.
  1967. ///
  1968. /// What changes: the fetch runs when its flights are done and beside later
  1969. /// submissions, so of the sends of title bytes it is only known to have run
  1970. /// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
  1971. /// later are left out of the merge (`Shadow::card_merge_relay`): they are
  1972. /// the title's, newer than what the flights wrote. A later flight's bytes
  1973. /// may be in what is fetched, as before.
  1974. fn relay_copy() -> bool {
  1975. static ON: OnceLock<bool> = OnceLock::new();
  1976. *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
  1977. }
  1978. /// Told when something joins [`LINE`], for the thread that lands flights
  1979. /// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
  1980. /// what queues hold.
  1981. static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  1982. /// Told when flights have landed ([`relay`]): who waits for that looks
  1983. /// again.
  1984. static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new();
  1985. /// With [`relay`], the order of what we put on the queue: the number of
  1986. /// sends of changed ranges to copies in the card's memory so far
  1987. /// (`Host::card_before`). Held from the taking of the ranges until their
  1988. /// list is on the queue, and while a fetch of pieces goes to the queue: a
  1989. /// fetch sent with the count at N ran behind sends 1..N and ahead of every
  1990. /// later one.
  1991. static QUEUE_ORDER: Mutex<u64> = Mutex::new(0);
  1992. /// Since the last frame-rate line, of the thread that lands flights
  1993. /// ([`relay`]): landings, flights landed, microseconds it waited for the
  1994. /// card with nothing to land, microseconds it waited for fetches of card
  1995. /// copies' pieces, microseconds of landing in all.
  1996. static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  1997. /// Of the line's things in order (a flight: the value signalled on the
  1998. /// host's fence behind it; a write or a signal behind a flight: `None`):
  1999. /// how many, from the front, can be landed when the card has reached
  2000. /// `completed`: everything ahead of the first flight it has not run. A
  2001. /// later flight never lands before an earlier one, and what follows a
  2002. /// flight (its bottom-of-pipe writes, signals) never before the flight.
  2003. fn landable(line: &[Option<u64>], completed: u64) -> usize {
  2004. line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len())
  2005. }
  2006. /// For one plan of copies in the card's memory, with [`relay`]: `flags`
  2007. /// holds, for every piece of every range of the plan, the copy, the
  2008. /// piece's number in the copy and whether the compare flagged it there (or
  2009. /// did not run). The pieces to fetch, under whichever range, in order: all
  2010. /// of them flagged under any. Two ranges of a plan may hold parts of the same
  2011. /// 64 KiB piece; the compare hashes the whole piece for each and stores
  2012. /// the hash, so the second of them may find it stored already and not
  2013. /// flag it.
  2014. fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
  2015. let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
  2016. pieces.sort_unstable();
  2017. pieces.dedup();
  2018. pieces
  2019. }
  2020. #[cfg(test)]
  2021. mod relay_tests {
  2022. use super::{flagged_pieces, landable};
  2023. /// Two flights and what follows each: nothing of the second lands
  2024. /// before the card has run it, and nothing behind a flight lands
  2025. /// before the flight.
  2026. #[test]
  2027. fn flights_land_in_the_order_they_were_sent() {
  2028. // Flight (fence 5), its write, a signal, flight (fence 6), its write.
  2029. let line = [Some(5), None, None, Some(6), None];
  2030. assert_eq!(landable(&line, 4), 0);
  2031. assert_eq!(landable(&line, 5), 3);
  2032. assert_eq!(landable(&line, 6), 5);
  2033. assert_eq!(landable(&line, u64::MAX), 5);
  2034. // Signals with no flight ahead land at once; behind one they wait.
  2035. assert_eq!(landable(&[None, None], 0), 2);
  2036. assert_eq!(landable(&[None, Some(9), None], 8), 1);
  2037. assert_eq!(landable(&[], 3), 0);
  2038. // After the first three landed, the rest when its turn comes.
  2039. assert_eq!(landable(&line[3..], 5), 0);
  2040. assert_eq!(landable(&line[3..], 6), 2);
  2041. }
  2042. /// A piece flagged under one range of a plan is fetched under every
  2043. /// range that holds a part of it; pieces of other copies are not.
  2044. #[test]
  2045. fn a_piece_flagged_under_one_range_is_fetched_under_all() {
  2046. let (a, b) = (0x1000usize, 0x2000usize);
  2047. // Copy a: piece 3 under two ranges, flagged under the first only;
  2048. // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged.
  2049. let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)];
  2050. let fetch = flagged_pieces(&flags);
  2051. assert!(fetch.contains(&(a, 3)));
  2052. assert!(!fetch.contains(&(a, 4)));
  2053. assert!(!fetch.contains(&(b, 3)));
  2054. assert!(fetch.contains(&(b, 9)));
  2055. assert_eq!(fetch.len(), 2);
  2056. }
  2057. }
  2058. /// The most host lists in the air before the flights are settled
  2059. /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the
  2060. /// relay it stopped the submitting thread twice a frame for 92-103 ms in
  2061. /// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162;
  2062. /// 32 settled the flights three times a
  2063. /// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables
  2064. /// asked and none refused; watch "tables asked, N refused"): their dynamic
  2065. /// descriptor slots, upload
  2066. /// memory and scratch chunks are held until then, and a frame's lists held
  2067. /// all at once ran the slots out before (run 45).
  2068. fn late_most() -> usize {
  2069. static MOST: OnceLock<usize> = OnceLock::new();
  2070. *MOST.get_or_init(|| {
  2071. std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1)
  2072. })
  2073. }
  2074. /// Whether a submission with bottom-of-pipe writes may fly
  2075. /// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so
  2076. /// the title is told at once, as before; for telling a title that polls
  2077. /// such a value from one that does not).
  2078. fn late_writes() -> bool {
  2079. static ON: OnceLock<bool> = OnceLock::new();
  2080. *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0"))
  2081. }
  2082. /// Per host copy, the ranges a submission's shaders may write, as declared
  2083. /// (address, end).
  2084. type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>);
  2085. /// What [`Host::submit`] hands back for a submission it sent and did not
  2086. /// wait for.
  2087. struct Sent {
  2088. /// Its number among the submissions started.
  2089. number: u64,
  2090. card: Option<CardPlan>,
  2091. back: Vec<Declared>,
  2092. /// What was taken off it to be done on the card.
  2093. own: Option<card_steps::Taken>,
  2094. /// Its bottom-of-pipe writes.
  2095. writes: Vec<(usize, crate::queue::Written, usize)>,
  2096. }
  2097. /// A submission on the card that has not been waited for ([`late`]): its
  2098. /// host lists, taken from the title's (which it may reset meanwhile), and
  2099. /// what is to be done once it has run.
  2100. struct Flight {
  2101. number: u64,
  2102. /// The value signalled on the host's fence behind it.
  2103. fence: u64,
  2104. lists: Vec<crate::list::Detached>,
  2105. order: Vec<usize>,
  2106. card: Option<CardPlan>,
  2107. back: Vec<Declared>,
  2108. /// The list of ours that ran ahead of them ([`card_steps`]).
  2109. own: Option<card_steps::Taken>,
  2110. }
  2111. /// One thing in the line of what waits for the card, in order.
  2112. enum Late {
  2113. Run(Flight),
  2114. /// A bottom-of-pipe write of the flight before it: address, what, bytes.
  2115. Write(usize, crate::queue::Written, usize),
  2116. /// A fence (its address) signalled behind the flights before it.
  2117. Signal(usize, u64),
  2118. }
  2119. struct Line {
  2120. line: Vec<Late>,
  2121. /// The title memory the flights' shaders may write (address, end), in
  2122. /// order and joined.
  2123. written: Vec<(usize, usize)>,
  2124. /// Host lists in the flights.
  2125. lists: usize,
  2126. /// The value signalled on the host's fence behind the last flight.
  2127. target: u64,
  2128. /// A settle has taken the line and is not done: a signal still goes
  2129. /// behind it.
  2130. settling: bool,
  2131. /// Something was settled away from a queue's own calls: the helper
  2132. /// thread looks at what queues hold.
  2133. poke: bool,
  2134. /// Host lists of settled flights, reset and given back outside the
  2135. /// submission lock ([`land`]: a settle may run under a caller's own
  2136. /// locks).
  2137. landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>,
  2138. /// With [`relay`]: the bottom-of-pipe writes of the flights being
  2139. /// landed (taken out of `line`, not done yet), for [`late_met`].
  2140. in_hand: Vec<(usize, crate::queue::Written, usize)>,
  2141. /// With [`card_steps`]: what the flights being landed write.
  2142. landing: Vec<card_steps::Writer>,
  2143. }
  2144. // SAFETY: D3D12 objects (free-threaded) and host lists nothing records
  2145. // into; touched under the lock.
  2146. unsafe impl Send for Line {}
  2147. static LINE: Mutex<Line> = Mutex::new(Line {
  2148. line: Vec::new(),
  2149. written: Vec::new(),
  2150. lists: 0,
  2151. target: 0,
  2152. settling: false,
  2153. poke: false,
  2154. landed: Vec::new(),
  2155. in_hand: Vec::new(),
  2156. landing: Vec::new(),
  2157. });
  2158. /// Told when a flight joins [`LINE`] or it is poked.
  2159. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new();
  2160. fn line() -> std::sync::MutexGuard<'static, Line> {
  2161. LINE.lock().unwrap_or_else(|e| e.into_inner())
  2162. }
  2163. /// Why flights were settled ([`LATE_STATS`]' places from 2 on).
  2164. const WHY_SYNC: usize = 2;
  2165. const WHY_CARD_DONE: usize = 3;
  2166. const WHY_VALUE: usize = 4;
  2167. const WHY_STALE: usize = 5;
  2168. const WHY_READ: usize = 6;
  2169. const WHY_RUN: usize = 7;
  2170. const WHY_MOST: usize = 8;
  2171. const WHY_WRITES: usize = 9;
  2172. const WHY_FENCE: usize = 10;
  2173. /// Since the last frame-rate line: submissions sent without a wait;
  2174. /// settles; settles by reason ([`WHY_SYNC`]..); flights settled;
  2175. /// microseconds settles waited for the card; value waits met by a flight's
  2176. /// bottom-of-pipe write; fence signals set behind flights.
  2177. /// Then: the settles for title memory read, by what read it (a buffer
  2178. /// copy, a fill of upload memory, a texture).
  2179. static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
  2180. /// Since the last frame-rate line: the microseconds settles waited for the
  2181. /// card, by why they settled (the `WHY_` places).
  2182. static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  2183. /// Whether `[from, to)` touches one of `ranges` (in order, joined).
  2184. fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool {
  2185. if from >= to {
  2186. return false;
  2187. }
  2188. let at = ranges.partition_point(|r| r.1 <= from);
  2189. ranges.get(at).is_some_and(|r| r.0 < to)
  2190. }
  2191. /// `ranges` with `more`, in order, joined where they overlap or touch.
  2192. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) {
  2193. ranges.extend(more.into_iter().filter(|r| r.0 < r.1));
  2194. ranges.sort_unstable();
  2195. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  2196. for &(from, to) in ranges.iter() {
  2197. match out.last_mut() {
  2198. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  2199. _ => out.push((from, to)),
  2200. }
  2201. }
  2202. *ranges = out;
  2203. }
  2204. /// Whether anything is in the air.
  2205. fn flying() -> bool {
  2206. if !late() {
  2207. return false;
  2208. }
  2209. let line = line();
  2210. // (With the relay: also while flights are being landed.)
  2211. line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_)))
  2212. }
  2213. /// With flights in the air ([`late`]): why `runs` cannot be prepared
  2214. /// before they are settled, if so. Preparing reads title memory on the
  2215. /// CPU (the title's buffer copies, fills of upload memory, textures) and
  2216. /// runs steps of ours that may read or write it anywhere; what the
  2217. /// flights' shaders write is not there yet.
  2218. fn late_blocked(runs: &[&HostList]) -> Option<usize> {
  2219. let (written, copies) = {
  2220. let line = line();
  2221. if line.written.is_empty() {
  2222. return None;
  2223. }
  2224. (line.written.clone(), card_steps::copies(&line))
  2225. };
  2226. blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ))
  2227. }
  2228. /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
  2229. /// flights when the title itself wrote the memory since they were given it
  2230. /// (`VICTORY_FILL_TITLE=1`; off by default).
  2231. ///
  2232. /// The title's 174 MB heap is declared written as a whole (a root view has
  2233. /// no size), and the title keeps a ring of constants in it: one fill of 480
  2234. /// bytes a frame, at a new place each time, waited for every flight's
  2235. /// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
  2236. /// named). The title writes those bytes just before the draw that reads
  2237. /// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
  2238. ///
  2239. /// Or no shader's write went into that page in the last 600 frames
  2240. /// ([`crate::watch::landed_lately`]): the first alone left two thirds of
  2241. /// the wait, for constants at the end of a 64 KiB page that the title wrote
  2242. /// before the page was taken.
  2243. ///
  2244. /// What can go wrong: a constant a flight's shader really writes, in a
  2245. /// block that the title (or an earlier flight's copy-back) also wrote, or
  2246. /// for the first time, is read as it was before that flight.
  2247. fn fill_is_titles(src: usize, len: usize) -> bool {
  2248. const SMALL: usize = 64 << 10;
  2249. static ON: OnceLock<bool> = OnceLock::new();
  2250. let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
  2251. on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
  2252. }
  2253. /// Diagnostics: the waits for flights, by what waited, why it was not done
  2254. /// on the card ([`card_steps`]), its bytes, and the declared write it lies
  2255. /// in (start, bytes).
  2256. #[cfg(feature = "diagnostics")]
  2257. type Blamed = (&'static str, &'static str, usize, usize, usize);
  2258. /// How often and how long, and the address the last one read.
  2259. #[cfg(feature = "diagnostics")]
  2260. static BLAME: Mutex<Option<std::collections::HashMap<Blamed, (u64, u64, usize)>>> = Mutex::new(None);
  2261. /// What the wait that comes next is for, and why not on the card.
  2262. #[cfg(feature = "diagnostics")]
  2263. static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, ""));
  2264. /// Diagnostics: shader writes declared over a megabyte or more: the range
  2265. /// (from, to) and what declares it ([`wide_write`]): how often, and its
  2266. /// shaders.
  2267. #[cfg(feature = "diagnostics")]
  2268. static WIDE_WRITES: Mutex<Option<std::collections::HashMap<(usize, usize, usize), (u64, String)>>> = Mutex::new(None);
  2269. /// Diagnostics: a draw or dispatch declares that it writes `len` bytes at
  2270. /// `address`, through a root view of `pipeline`, a view in a table (0) or a
  2271. /// raw address (1).
  2272. #[cfg(feature = "diagnostics")]
  2273. pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) {
  2274. if len < 1 << 20 {
  2275. return;
  2276. }
  2277. let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner());
  2278. let e = all
  2279. .get_or_insert_with(Default::default)
  2280. .entry((address as usize, (address + len) as usize, pipeline))
  2281. .or_insert_with(|| {
  2282. let shaders = match pipeline {
  2283. 0 => "a view in a table".into(),
  2284. 1 => "a raw address".into(),
  2285. p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| {
  2286. p.stages.iter().map(|s| s.shader.hash.to_string()).collect::<Vec<_>>().join("+")
  2287. }),
  2288. };
  2289. (0, shaders)
  2290. });
  2291. e.0 += 1;
  2292. }
  2293. #[cfg(feature = "diagnostics")]
  2294. fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
  2295. let i = written.partition_point(|r| r.1 <= at);
  2296. let (from, to) = written.get(i).copied().unwrap_or((0, 0));
  2297. let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner());
  2298. let why = blamed.1;
  2299. blamed.0 = Some(((kind, why, len, from, to - from), at));
  2300. }
  2301. /// Why [`card_steps`] left the submission to the wait that comes next.
  2302. #[cfg(feature = "diagnostics")]
  2303. fn refused(why: &'static str) {
  2304. *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
  2305. }
  2306. /// The wait that comes next is for these ranges ([`stale_under_flights`]).
  2307. #[cfg(feature = "diagnostics")]
  2308. fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
  2309. if let Some((shadow, from, _)) = stale.first() {
  2310. let (start, len) = shadow.span();
  2311. let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
  2312. BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
  2313. }
  2314. }
  2315. /// The wait for what [`blame`] last named, or a wait of another reason than
  2316. /// title memory read, took `us`.
  2317. #[cfg(feature = "diagnostics")]
  2318. fn blamed(why: usize, us: u64) {
  2319. let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
  2320. let (key, at) = match (why, named) {
  2321. (WHY_READ | WHY_STALE, Some(named)) => named,
  2322. (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
  2323. _ => {
  2324. let kind = match why {
  2325. WHY_SYNC => "a synchronous submission, a present or the sweep",
  2326. WHY_VALUE => "a memory value",
  2327. WHY_STALE => "title memory changed under shader writes",
  2328. WHY_RUN => "a step of ours",
  2329. WHY_MOST => "lists in the air",
  2330. WHY_FENCE => "a blocking fence wait",
  2331. _ => "another reason",
  2332. };
  2333. ((kind, "", 0, 0, 0), 0)
  2334. }
  2335. };
  2336. let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
  2337. let e = all.get_or_insert_with(Default::default).entry(key).or_default();
  2338. *e = (e.0 + 1, e.1 + us, at);
  2339. }
  2340. /// For the frame-rate line: the five that waited longest.
  2341. #[cfg(feature = "diagnostics")]
  2342. fn log_blame(frames: f64) {
  2343. let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2344. let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  2345. let mut all: Vec<_> = all.into_iter().collect();
  2346. all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us));
  2347. for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) {
  2348. // The passes that declare it written, the ones that do so most.
  2349. let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new();
  2350. for ((a, b, _), (n, shaders)) in &wide {
  2351. if *a < at + len && at < *b {
  2352. *passes.entry(shaders).or_default() += n;
  2353. }
  2354. }
  2355. let mut passes: Vec<(&str, u64)> = passes.into_iter().collect();
  2356. passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1));
  2357. let passes: Vec<String> =
  2358. passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect();
  2359. tracing::info!(
  2360. "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \
  2361. over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}",
  2362. us as f64 / 1e3 / frames,
  2363. n as f64 / frames,
  2364. passes.join(", "),
  2365. match (why.is_empty(), kind) {
  2366. (true, _) => "",
  2367. (_, "title memory changed under shader writes") => "; not put in under them: ",
  2368. _ => "; not done on the card: ",
  2369. },
  2370. );
  2371. }
  2372. }
  2373. /// Whether flights that write `written` stop a read of `len` bytes at `src`.
  2374. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool {
  2375. touches(written, src, src + len) && !fill_is_titles(src, len)
  2376. }
  2377. /// Whether they stop a title buffer copy, and if so whether by its source.
  2378. fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option<bool> {
  2379. let read = read_blocked(written, src, len);
  2380. (read || touches(written, dst, dst + len)).then_some(read)
  2381. }
  2382. /// [`late_blocked`] against `written`, the title memory flights' shaders
  2383. /// may write (in order, joined); `count` whether the kind of read is
  2384. /// counted for the frame line.
  2385. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> {
  2386. if written.is_empty() {
  2387. return None;
  2388. }
  2389. // Destinations of copies at their place, if a step reads them.
  2390. let mut placed: Vec<(usize, usize)> = Vec::new();
  2391. for list in runs {
  2392. for step in &list.deferred().copies {
  2393. match step {
  2394. &Step::Copy(dst, src, len) => {
  2395. if let Some(_read) = copy_blocked(written, dst, src, len) {
  2396. if count {
  2397. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2398. #[cfg(feature = "diagnostics")]
  2399. if _read {
  2400. blame("a buffer copy's source", written, src, len);
  2401. } else {
  2402. blame("a buffer copy's destination", written, dst, len);
  2403. }
  2404. }
  2405. return Some(WHY_READ);
  2406. }
  2407. }
  2408. &Step::Fill(_, src, len, _) => {
  2409. if read_blocked(written, src, len) {
  2410. if count {
  2411. LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
  2412. #[cfg(feature = "diagnostics")]
  2413. blame("a fill of upload memory", written, src, len);
  2414. }
  2415. return Some(WHY_READ);
  2416. }
  2417. }
  2418. Step::Texture(staging) => {
  2419. let (at, len) = staging.memory();
  2420. if touches(written, at, at + len) {
  2421. if count {
  2422. LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
  2423. #[cfg(feature = "diagnostics")]
  2424. blame("a texture", written, at, len);
  2425. }
  2426. return Some(WHY_READ);
  2427. }
  2428. }
  2429. Step::Run(_) => return Some(WHY_RUN),
  2430. Step::Placed(p) => match p.waits(written) {
  2431. place::Waits::No => {}
  2432. place::Waits::ForReaders => placed.push((p.dst, p.dst + p.len)),
  2433. place::Waits::Yes => {
  2434. if count {
  2435. LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
  2436. #[cfg(feature = "diagnostics")]
  2437. blame("a buffer copy at its place", written, p.src, p.len);
  2438. }
  2439. return Some(WHY_READ);
  2440. }
  2441. },
  2442. Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
  2443. }
  2444. }
  2445. }
  2446. (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ)
  2447. }
  2448. /// With flights in the air, after the submission's write-watch asking:
  2449. /// whether `runs` refresh a range of a host copy that a flight's shaders
  2450. /// may write and that the title wrote since it was last copied. The
  2451. /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
  2452. /// the title's bytes there would reach the card a submission late.
  2453. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
  2454. use std::sync::Arc;
  2455. // Per copy, the span of what is refreshed (a flush brings that much
  2456. // up to date at most).
  2457. let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2458. // Where each copy is in it, if shaders may be writing it (none begins to
  2459. // while this runs): a frame has 20,000 refreshes of some 4,500 copies.
  2460. let mut places: ByCopy<Option<usize>> = ByCopy::default();
  2461. for list in runs {
  2462. for step in &list.deferred().copies {
  2463. if let Step::Refresh(shadow, address, len) = step {
  2464. let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
  2465. shadow.writes_pending().then(|| {
  2466. spans.push((shadow.clone(), *address, *address + *len));
  2467. spans.len() - 1
  2468. })
  2469. });
  2470. if let Some(i) = *place {
  2471. let s = &mut spans[i];
  2472. (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
  2473. }
  2474. }
  2475. }
  2476. }
  2477. if late_exact() {
  2478. // The title's bytes are put in beside the flights' writes; a
  2479. // settle is still due where that could not be done. At most this
  2480. // many changed runs go up to copies in the card's memory, each a
  2481. // copy of its own there. With [`card_steps`] the pages of the
  2482. // title's ring of constants come here too, which were waited for
  2483. // before: hundreds of short runs each, at about 1.5 us a run.
  2484. let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
  2485. spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
  2486. return spans;
  2487. }
  2488. spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
  2489. spans
  2490. }
  2491. /// A fence signal on a queue ([`late`]): goes behind the flights in the
  2492. /// air, if there are any, and is set when they are settled. Whether it
  2493. /// did; if not the caller sets the fence now.
  2494. pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
  2495. if !late() {
  2496. return false;
  2497. }
  2498. let mut line = line();
  2499. if line.line.is_empty() && !line.settling {
  2500. return false;
  2501. }
  2502. line.line.push(Late::Signal(fence, value));
  2503. LATE_STATS[14].fetch_add(1, Ordering::Relaxed);
  2504. drop(line);
  2505. // A signal alone (behind a settle under way) has no flight to wake
  2506. // the helper thread for it.
  2507. LINE_MOVED.notify_one();
  2508. RELAY_MOVED.notify_one();
  2509. true
  2510. }
  2511. /// A queue stands at `wait`, which memory does not meet now ([`late`]):
  2512. /// whether it is met once the flights in the air have run. A flight's
  2513. /// bottom-of-pipe write of a value that meets it says yes without a wait
  2514. /// for the card: the part behind the wait goes to the card behind that
  2515. /// flight, which is the order the wait asks for. If the flights may write
  2516. /// the value in a way not known here (shaders, a timestamp, another
  2517. /// width), they are settled and memory is asked again.
  2518. pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
  2519. let (address, bytes) = wait.place();
  2520. {
  2521. let line = line();
  2522. if line.line.is_empty() && line.in_hand.is_empty() {
  2523. return false;
  2524. }
  2525. let mut unsure = touches(&line.written, address, address + bytes);
  2526. // (With the relay: first the writes of flights being landed.)
  2527. let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item {
  2528. Late::Write(at, what, n) => Some((at, what, n)),
  2529. _ => None,
  2530. }));
  2531. for (at, what, n) in writes {
  2532. if *at >= address + bytes || address >= *at + *n {
  2533. continue;
  2534. }
  2535. match what {
  2536. crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
  2537. if wait.holds_for(*v) {
  2538. LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
  2539. return true;
  2540. }
  2541. }
  2542. _ => unsure = true,
  2543. }
  2544. }
  2545. if !unsure {
  2546. return false;
  2547. }
  2548. }
  2549. settle_now(WHY_VALUE);
  2550. wait.met()
  2551. }
  2552. /// Settles the flights in the air, if any ([`Host::settle`]), for reason
  2553. /// `why` (one of the `WHY_` places). Not from inside a submission.
  2554. pub(crate) fn settle_now(why: usize) {
  2555. if !late() {
  2556. return;
  2557. }
  2558. let Some(host) = host() else {
  2559. return;
  2560. };
  2561. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2562. host.settle(&mut submitted, why);
  2563. }
  2564. /// [`settle_now`] at a present, and for a fence the title blocks on.
  2565. pub(crate) fn settle_for_present() {
  2566. settle_now(WHY_SYNC);
  2567. }
  2568. pub(crate) fn settle_for_fence() {
  2569. settle_now(WHY_FENCE);
  2570. }
  2571. /// Resets the host lists of settled flights and keeps them for reuse, as
  2572. /// a queue does for the lists it ran (`crate::list::recycle`).
  2573. fn land() {
  2574. let landed = std::mem::take(&mut line().landed);
  2575. for (lists, order) in landed {
  2576. crate::list::recycle(lists, &order);
  2577. }
  2578. }
  2579. /// The thread that settles the flights once the card has run them all
  2580. /// ([`late`]): without it a bottom-of-pipe write would reach the title only
  2581. /// at the next call that settles, and a title thread that polls such a
  2582. /// value while the submitting thread waits for that thread would never
  2583. /// see it.
  2584. fn late_helper() {
  2585. let Some(host) = host() else {
  2586. return;
  2587. };
  2588. // SAFETY: a plain event of our own.
  2589. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2590. tracing::warn!("no event for the thread that settles submissions sent ahead");
  2591. return;
  2592. };
  2593. loop {
  2594. let target = {
  2595. let mut line = line();
  2596. loop {
  2597. if line.poke {
  2598. line.poke = false;
  2599. break None;
  2600. }
  2601. // (With the relay the flights are another thread's.)
  2602. if !relay() && !line.line.is_empty() && !line.settling {
  2603. break Some(line.target);
  2604. }
  2605. line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2606. }
  2607. };
  2608. let Some(target) = target else {
  2609. land();
  2610. crate::queue::release_held(false);
  2611. continue;
  2612. };
  2613. // The card first, without the submission lock: the submitting
  2614. // thread prepares and sends meanwhile.
  2615. // SAFETY: our fence and event.
  2616. unsafe {
  2617. if host.fence.SetEventOnCompletion(target, event).is_ok() {
  2618. WaitForSingleObject(event, INFINITE);
  2619. }
  2620. }
  2621. {
  2622. let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
  2623. // Something newer went up meanwhile: the card is waited for
  2624. // again, the submitting thread is not held up for it.
  2625. if line().target != target {
  2626. continue;
  2627. }
  2628. host.settle(&mut submitted, WHY_CARD_DONE);
  2629. }
  2630. land();
  2631. crate::queue::release_held(false);
  2632. }
  2633. }
  2634. /// Starts the threads of [`late`], once: the one that settles flights when
  2635. /// the card has run them and looks at what queues hold, and with [`relay`]
  2636. /// the one that lands flights.
  2637. fn late_threads() {
  2638. static HELPER: std::sync::Once = std::sync::Once::new();
  2639. HELPER.call_once(|| {
  2640. if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) {
  2641. tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow");
  2642. }
  2643. tracing::info!(
  2644. most = late_most(),
  2645. writes = late_writes(),
  2646. "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)"
  2647. );
  2648. if relay() {
  2649. // Without it nothing would ever land.
  2650. if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) {
  2651. fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}"));
  2652. }
  2653. tracing::info!(
  2654. exact = relay_exact(),
  2655. "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)"
  2656. );
  2657. }
  2658. });
  2659. }
  2660. /// With [`relay`]: waits until `done` says so of the line, looked at each
  2661. /// time flights have landed. Counted as a settle for `why`, and its time
  2662. /// as waiting for the card. The caller may hold the submission lock: the
  2663. /// thread that lands flights never takes it.
  2664. fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
  2665. let mut line = line();
  2666. if done(&line) {
  2667. return;
  2668. }
  2669. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  2670. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  2671. let was_working = working(false);
  2672. let waiting = std::time::Instant::now();
  2673. while !done(&line) {
  2674. line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
  2675. }
  2676. drop(line);
  2677. stood(waiting);
  2678. working(was_working);
  2679. let us = waiting.elapsed().as_micros() as u64;
  2680. LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
  2681. LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
  2682. SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
  2683. #[cfg(feature = "diagnostics")]
  2684. blamed(why, us);
  2685. }
  2686. /// What the thread that lands flights fetches card copies' pieces with
  2687. /// ([`relay`]): a list, a fence and an event of its own (the host's are
  2688. /// behind the submission lock), and the memory the pieces come down to.
  2689. struct RelayFetch {
  2690. list: Prelude,
  2691. /// With [`relay_copy`]: the card's copy queue, which `list` is for.
  2692. queue: Option<ID3D12CommandQueue>,
  2693. fence: ID3D12Fence,
  2694. event: HANDLE,
  2695. /// The last value signalled on `fence`.
  2696. sent: u64,
  2697. /// Buffer, mapping, bytes.
  2698. buffer: Option<(ID3D12Resource, usize, u64)>,
  2699. /// Pieces caught while a later flight was writing them.
  2700. suspects: torn::Suspects,
  2701. /// What earlier fetches brought of flights not landed yet.
  2702. had: crate::land::Had,
  2703. }
  2704. /// The thread that lands flights ([`relay`]): as soon as the card has run
  2705. /// the first flights of the line it takes them, with what follows them,
  2706. /// and does what they left to do ([`Host::relay_land`]); else it waits for
  2707. /// the card, or for a flight. It takes neither the submission lock nor
  2708. /// anything a caller of [`Host::settle`] may hold: resetting the landed
  2709. /// lists and looking at what queues hold are left to [`late_helper`].
  2710. fn relay_worker() {
  2711. let Some(host) = host() else {
  2712. return;
  2713. };
  2714. // SAFETY: a plain event of our own.
  2715. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
  2716. fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)"));
  2717. };
  2718. let mut fetch: Option<RelayFetch> = None;
  2719. loop {
  2720. let next = {
  2721. let mut line = line();
  2722. loop {
  2723. if line.line.is_empty() {
  2724. line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
  2725. continue;
  2726. }
  2727. let fences: Vec<Option<u64>> = line
  2728. .line
  2729. .iter()
  2730. .map(|l| match l {
  2731. Late::Run(flight) => Some(flight.fence),
  2732. _ => None,
  2733. })
  2734. .collect();
  2735. // SAFETY: a plain query.
  2736. let completed = unsafe { host.fence.GetCompletedValue() };
  2737. let n = landable(&fences, completed);
  2738. if n == 0 {
  2739. // The first thing is a flight the card has not run.
  2740. break Err(fences[0].unwrap_or(0));
  2741. }
  2742. line.settling = true;
  2743. let items: Vec<Late> = line.line.drain(..n).collect();
  2744. line.in_hand = items
  2745. .iter()
  2746. .filter_map(|l| match l {
  2747. Late::Write(at, what, bytes) => Some((*at, *what, *bytes)),
  2748. _ => None,
  2749. })
  2750. .collect();
  2751. if card_steps::stage() > 0 {
  2752. line.landing = card_steps::writers(&items);
  2753. }
  2754. break Ok(items);
  2755. }
  2756. };
  2757. match next {
  2758. Ok(items) => host.relay_land(items, &mut fetch),
  2759. Err(target) => {
  2760. let waiting = std::time::Instant::now();
  2761. // SAFETY: the host's fence and this thread's event.
  2762. let waited = unsafe {
  2763. host.fence.SetEventOnCompletion(target, event).map(|()| {
  2764. WaitForSingleObject(event, INFINITE);
  2765. })
  2766. };
  2767. if waited.is_err() {
  2768. std::thread::sleep(std::time::Duration::from_millis(1));
  2769. }
  2770. RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  2771. }
  2772. }
  2773. }
  2774. }
  2775. /// [`relay`]: what shaders wrote to the declared ranges `back` of copies
  2776. /// in the PC's memory goes into title memory. As [`hand_back`], each byte
  2777. /// once, the pieces that differ found on several threads; but the merge is
  2778. /// `Shadow::relay_merge`, which does not write the copy, and the ranges
  2779. /// are not done with here (each flight's are, afterwards). In two steps:
  2780. /// what is to be looked through and what of it differs ([`RelayBack::look`],
  2781. /// which needs nothing that the fetch from the card's memory brings), and
  2782. /// the merge.
  2783. struct RelayBack {
  2784. work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  2785. found: Option<Vec<Vec<(usize, usize)>>>,
  2786. }
  2787. fn relay_hand_back(back: &[Declared]) -> RelayBack {
  2788. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  2789. for (shadow, declared) in back {
  2790. if shadow.carded() {
  2791. continue;
  2792. }
  2793. let mut spans: Vec<(usize, usize)> = Vec::new();
  2794. join_ranges(&mut spans, declared.iter().copied());
  2795. for &(from, to) in &spans {
  2796. shadow.relay_compared(from, to - from);
  2797. }
  2798. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  2799. }
  2800. RelayBack { work, found: None }
  2801. }
  2802. impl RelayBack {
  2803. /// Looks the ranges through, once; its time counts as `stat`.
  2804. fn look(&mut self, stat: usize) {
  2805. if self.work.is_empty() || self.found.is_some() {
  2806. return;
  2807. }
  2808. let scanning = std::time::Instant::now();
  2809. // Looked through without a lock: a piece that changes meanwhile (a
  2810. // later flight writing, the title's bytes going in) is found now or
  2811. // by that flight's landing, and the merge looks again under the
  2812. // lock.
  2813. self.found = Some(crate::shadow::find_all(&self.work));
  2814. crate::land::spent(stat, scanning);
  2815. #[cfg(feature = "diagnostics")]
  2816. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2817. }
  2818. /// What differs goes into title memory.
  2819. fn merge(mut self) {
  2820. use crate::land;
  2821. self.look(land::stat::SCAN);
  2822. let Some(found) = self.found else {
  2823. return;
  2824. };
  2825. let merging = std::time::Instant::now();
  2826. let mut written: Vec<u64> = Vec::new();
  2827. if land::on() {
  2828. // Pieces in the same block of title memory in one job, in order.
  2829. let pieces: Vec<(usize, usize, usize)> =
  2830. found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
  2831. let start = |i: usize| self.work[i].0.span().0 as usize;
  2832. let mut order: Vec<usize> = (0..pieces.len()).collect();
  2833. order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
  2834. let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
  2835. let jobs = land::jobs(&cut);
  2836. let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
  2837. land::each(jobs.len(), &|j| {
  2838. let working = std::time::Instant::now();
  2839. let mut notes = land::Notes::default();
  2840. for &p in &order[jobs[j].clone()] {
  2841. let (i, at, n) = pieces[p];
  2842. put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
  2843. }
  2844. notes.flush();
  2845. land::spent(land::stat::BACK_ALL, working);
  2846. });
  2847. land::count(land::stat::JOBS, jobs.len() as u64);
  2848. written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
  2849. } else {
  2850. let (mut now, mut title) = (Vec::new(), Vec::new());
  2851. for ((shadow, ..), found) in self.work.iter().zip(found) {
  2852. let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
  2853. written.push(found.into_iter().map(merge).sum());
  2854. }
  2855. }
  2856. land::spent(land::stat::BACK, merging);
  2857. for ((_, from, to), written) in self.work.iter().zip(written) {
  2858. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  2859. #[cfg(feature = "diagnostics")]
  2860. crate::copystat::compared(*from, to - from, written as usize);
  2861. let _ = (from, to);
  2862. }
  2863. }
  2864. }
  2865. /// For the frame-rate line, with [`late`]: what the line of flights did
  2866. /// per frame since the last one.
  2867. fn late_line(frames: f64) {
  2868. if !late() {
  2869. return;
  2870. }
  2871. let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2872. tracing::info!(
  2873. "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
  2874. settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \
  2875. title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \
  2876. a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \
  2877. bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \
  2878. {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights",
  2879. s[0],
  2880. s[1],
  2881. if s[1] > 0.0 { s[11] / s[1] } else { 0.0 },
  2882. s[12] / 1000.0,
  2883. s[WHY_SYNC],
  2884. s[WHY_CARD_DONE],
  2885. s[WHY_VALUE],
  2886. s[WHY_STALE],
  2887. s[WHY_READ],
  2888. s[15],
  2889. s[16],
  2890. s[17],
  2891. s[WHY_RUN],
  2892. late_most(),
  2893. s[WHY_MOST],
  2894. s[WHY_WRITES],
  2895. s[WHY_FENCE],
  2896. s[13],
  2897. s[14],
  2898. );
  2899. {
  2900. let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect();
  2901. tracing::info!(
  2902. "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \
  2903. the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \
  2904. title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}",
  2905. w[WHY_SYNC],
  2906. w[WHY_CARD_DONE],
  2907. w[WHY_VALUE],
  2908. w[WHY_STALE],
  2909. w[WHY_READ],
  2910. w[WHY_RUN],
  2911. w[WHY_MOST],
  2912. w[WHY_WRITES],
  2913. w[WHY_FENCE],
  2914. );
  2915. }
  2916. if relay() {
  2917. let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2918. tracing::info!(
  2919. "the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
  2920. beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \
  2921. fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \
  2922. \"settles\" above are waits of other threads for it)",
  2923. r[1],
  2924. r[0],
  2925. r[2] / 1000.0,
  2926. r[3] / 1000.0,
  2927. r[4] / 1000.0,
  2928. );
  2929. if send::own() {
  2930. let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2931. tracing::info!(
  2932. "bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
  2933. taking them out of the CPU sides",
  2934. t[0] / (1 << 20) as f64,
  2935. t[1],
  2936. t[2],
  2937. t[3] / 1000.0,
  2938. );
  2939. }
  2940. let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2941. if t[0] > 0.0 {
  2942. tracing::info!(
  2943. "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",
  2944. t[0],
  2945. t[1],
  2946. t[2],
  2947. );
  2948. }
  2949. }
  2950. crate::land::log(frames);
  2951. if place::on() {
  2952. let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  2953. tracing::info!(
  2954. "title buffer copies at their place in the lists, per frame (VICTORY_COPIES_IN_PLACE): {:.1} of {:.1} KB, {:.1} of them out of what shaders wrote; {:.2} copies into textures out of what shaders wrote",
  2955. t[0],
  2956. t[1] / 1024.0,
  2957. t[2],
  2958. t[3],
  2959. );
  2960. }
  2961. card_steps::log(frames);
  2962. crate::picked::log(frames);
  2963. #[cfg(feature = "diagnostics")]
  2964. log_blame(frames);
  2965. if late_exact() {
  2966. let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames);
  2967. tracing::info!(
  2968. "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \
  2969. {runs:.0} changed runs, {:.2} MB",
  2970. bytes / (1 << 20) as f64
  2971. );
  2972. }
  2973. }
  2974. pub(crate) mod awake;
  2975. mod card_steps;
  2976. mod place;
  2977. mod send;
  2978. #[cfg(feature = "diagnostics")]
  2979. pub(crate) mod spans;
  2980. mod torn;
  2981. pub(crate) mod upcheck;
  2982. #[cfg(test)]
  2983. mod late_tests {
  2984. use super::{continues, join_ranges, touches};
  2985. /// Copies join only when both ends continue and the whole does not
  2986. /// overlap itself.
  2987. #[test]
  2988. fn copies_join_only_end_to_end_and_apart() {
  2989. // (destination, source, bytes)
  2990. assert!(continues((1000, 5000, 16), (1016, 5016, 32)));
  2991. assert!(continues((5000, 1000, 16), (5016, 1016, 32)));
  2992. // A gap, or only one side continues.
  2993. assert!(!continues((1000, 5000, 16), (1020, 5016, 32)));
  2994. assert!(!continues((1000, 5000, 16), (1016, 5020, 32)));
  2995. assert!(!continues((1000, 5000, 16), (1000, 5000, 16)));
  2996. // Together they would overlap: the second reads what the first wrote.
  2997. assert!(!continues((1000, 1016, 16), (1016, 1032, 16)));
  2998. assert!(!continues((1016, 1000, 16), (1032, 1016, 16)));
  2999. // They touch without overlapping.
  3000. assert!(continues((1000, 1032, 16), (1016, 1048, 16)));
  3001. assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8)));
  3002. }
  3003. /// Ranges are found by what they hold, not by where they start, and a
  3004. /// range that only touches another's end does not touch it.
  3005. #[test]
  3006. fn ranges_touch_where_they_overlap() {
  3007. let mut ranges = Vec::new();
  3008. join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]);
  3009. assert_eq!(ranges, [(10, 25), (40, 60)]);
  3010. join_ranges(&mut ranges, [(25, 40)]);
  3011. assert_eq!(ranges, [(10, 60)]);
  3012. let ranges = [(10usize, 25usize), (40, 60), (100, 101)];
  3013. for (from, to, hit) in [
  3014. (0, 10, false),
  3015. (0, 11, true),
  3016. (24, 25, true),
  3017. (25, 40, false),
  3018. (25, 41, true),
  3019. (59, 200, true),
  3020. (60, 100, false),
  3021. (100, 101, true),
  3022. (101, 500, false),
  3023. (30, 30, false),
  3024. (50, 50, false),
  3025. ] {
  3026. assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}");
  3027. }
  3028. assert!(!touches(&[], 0, usize::MAX));
  3029. }
  3030. }
  3031. /// Whether a title buffer copy that continues the one recorded before it
  3032. /// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by
  3033. /// default).
  3034. ///
  3035. /// Each copy is done at submission through the kernel, which reports a
  3036. /// page that is not there instead of faulting (`copy_mapped`), tells the
  3037. /// write watch and the guards, and ends the refreshes gathered so far: a
  3038. /// call into the kernel for some 480 bytes, 14,042 times a frame in run 86
  3039. /// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them
  3040. /// continue the one before is counted either way and said on its own line
  3041. /// with the frame rate; the switch is worth that many kernel calls.
  3042. ///
  3043. /// Joined, the same bytes move: [`continues`] joins only copies whose
  3044. /// ranges, taken together, do not overlap, and nothing is recorded between
  3045. /// two steps that follow each other. What differs: a page that is not
  3046. /// mapped now fails the joined copy as a whole (it then goes page by page,
  3047. /// zeros for what cannot be read, as a single copy does), where before
  3048. /// only the copy that held it did.
  3049. fn join_copies() -> bool {
  3050. static ON: OnceLock<bool> = OnceLock::new();
  3051. *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1"))
  3052. }
  3053. /// Since the last frame-rate line: title buffer copies recorded, and those
  3054. /// that continue the one before ([`join_copies`]).
  3055. static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  3056. /// Whether the copy `next` (destination, source, bytes) goes on exactly
  3057. /// where `last` ended, source and destination both, and the two as one do
  3058. /// not overlap (source over destination): then one copy of both moves the
  3059. /// bytes the two would move in turn.
  3060. fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
  3061. let ((d, s, n), (dst, src, len)) = (last, next);
  3062. let Some(all) = n.checked_add(len) else {
  3063. return false;
  3064. };
  3065. d.checked_add(n) == Some(dst)
  3066. && s.checked_add(n) == Some(src)
  3067. && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d))
  3068. }
  3069. /// The ranges the shaders of `runs` may write, per host copy, as declared.
  3070. /// One list's lock at a time: a submission may name a list twice.
  3071. fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
  3072. let mut back: Vec<Declared> = Vec::new();
  3073. // Where each copy is in it, and the ranges seen: dispatches declare the
  3074. // same ranges thousands of times a frame.
  3075. let mut places: ByCopy<usize> = ByCopy::default();
  3076. let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
  3077. for list in runs {
  3078. for step in &list.deferred().copies {
  3079. if let Step::GpuWrite(shadow, address, len) = step {
  3080. let key = std::sync::Arc::as_ptr(shadow) as usize;
  3081. if !seen.insert((key, *address, *len)) {
  3082. continue;
  3083. }
  3084. let i = *places.entry(key).or_insert_with(|| {
  3085. back.push((shadow.clone(), Vec::new()));
  3086. back.len() - 1
  3087. });
  3088. back[i].1.push((*address, *address + *len));
  3089. }
  3090. }
  3091. }
  3092. back
  3093. }
  3094. /// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
  3095. /// lines that say what the title's CPU was given while it decided whether
  3096. /// the camera is in a room. The values of the small read-backs
  3097. /// ([`read_backs`]), the frame's main pass by scissor rectangle with its
  3098. /// culling dispatches (`draw.rs`, `walls_census`), the shader-written
  3099. /// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
  3100. /// copies found stale after their refresh (`shadow.rs`; only with
  3101. /// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the
  3102. /// runtime, the read requests that fail (with 2: every request).
  3103. pub(crate) fn walls_trace() -> bool {
  3104. static ON: OnceLock<bool> = OnceLock::new();
  3105. *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
  3106. }
  3107. /// After `list` has run: the texels its read-backs copied into host
  3108. /// buffers of ours go to the title's memory (`HostList::defer_read_back`).
  3109. ///
  3110. /// A submission that is waited for did this itself. One sent ahead
  3111. /// ([`late`]) did not, at any stage: the flights' lists were settled
  3112. /// without it, so the title read a buffer nobody wrote, as before read-backs
  3113. /// were made (the exposure metering's two small float targets, every frame).
  3114. fn read_backs(list: &HostList) {
  3115. for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
  3116. let mut data = std::ptr::null_mut();
  3117. // SAFETY: a read-back buffer of ours, written by the list that has
  3118. // run; the title's destination holds every row (checked when the
  3119. // copy was recorded).
  3120. unsafe {
  3121. if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() {
  3122. let from = data.cast::<u8>().cast_const();
  3123. for line in 0..*rows {
  3124. std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
  3125. }
  3126. // The walls trace: what the title is handed (one row of at
  3127. // most 24 values: its 5x1 and 1x1 float targets).
  3128. if walls_trace() && *rows == 1 && *row <= 96 {
  3129. let mut values = [0f32; 24];
  3130. std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
  3131. tracing::info!(
  3132. frame = crate::frame::current(),
  3133. to = format_args!("{:#x}", *at),
  3134. bytes = *row,
  3135. values = ?&values[..*row / 4],
  3136. "walls trace: a read-back lands in title memory"
  3137. );
  3138. }
  3139. buffer.Unmap(0, None);
  3140. }
  3141. }
  3142. }
  3143. }
  3144. /// After the card ran what declared `back`: what shaders wrote there goes
  3145. /// into title memory, and the ranges are done with.
  3146. fn hand_back(back: &[Declared]) {
  3147. if crate::shadow::wide_back() {
  3148. // Every range first (the pieces that differ, found on several
  3149. // threads), then the merges, in order, as below.
  3150. let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  3151. for (shadow, declared) in back {
  3152. if shadow.carded() {
  3153. continue;
  3154. }
  3155. let mut sorted = declared.clone();
  3156. sorted.sort_unstable();
  3157. let mut spans: Vec<(usize, usize)> = Vec::new();
  3158. for (from, to) in sorted {
  3159. match spans.last_mut() {
  3160. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3161. _ => spans.push((from, to)),
  3162. }
  3163. }
  3164. work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
  3165. }
  3166. #[cfg(feature = "diagnostics")]
  3167. let scanning = std::time::Instant::now();
  3168. let found = crate::shadow::find_all(&work);
  3169. #[cfg(feature = "diagnostics")]
  3170. crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
  3171. for ((shadow, from, to), found) in work.iter().zip(found) {
  3172. let written = shadow.copy_back_with(*from, to - from, Some(found));
  3173. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3174. #[cfg(feature = "diagnostics")]
  3175. crate::copystat::compared(*from, to - from, written);
  3176. }
  3177. for (shadow, declared) in back {
  3178. shadow.copy_back_done(declared);
  3179. }
  3180. return;
  3181. }
  3182. for (shadow, declared) in back {
  3183. if shadow.carded() {
  3184. // Done before (`Host::card_back`).
  3185. shadow.copy_back_done(declared);
  3186. continue;
  3187. }
  3188. // Each byte compared once: the world declares dozens of views
  3189. // of its 174 MB heap that overlap almost entirely, and comparing
  3190. // every one whole was gigabytes a frame (0.3-0.5 s) for the few
  3191. // MB shaders wrote. Only ranges that overlap or touch are
  3192. // joined: what lies between two was not given to shaders (the
  3193. // snapshot does not hold it).
  3194. let mut sorted = declared.clone();
  3195. sorted.sort_unstable();
  3196. let mut spans: Vec<(usize, usize)> = Vec::new();
  3197. for (from, to) in sorted {
  3198. match spans.last_mut() {
  3199. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3200. _ => spans.push((from, to)),
  3201. }
  3202. }
  3203. for (from, to) in spans {
  3204. let written = shadow.copy_back(from, to - from);
  3205. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  3206. #[cfg(feature = "diagnostics")]
  3207. crate::copystat::compared(from, to - from, written);
  3208. }
  3209. shadow.copy_back_done(declared);
  3210. }
  3211. }
  3212. impl Host {
  3213. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  3214. /// mesh shaders need both); logged once.
  3215. pub(crate) fn mesh_shaders(&self) -> bool {
  3216. static MESH: OnceLock<bool> = OnceLock::new();
  3217. *MESH.get_or_init(|| {
  3218. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  3219. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  3220. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  3221. };
  3222. // SAFETY: each query writes its own structure of the given size.
  3223. let ok = unsafe {
  3224. self.device
  3225. .CheckFeatureSupport(
  3226. D3D12_FEATURE_D3D12_OPTIONS7,
  3227. (&raw mut options).cast(),
  3228. size_of_val(&options) as u32,
  3229. )
  3230. .is_ok()
  3231. && self
  3232. .device
  3233. .CheckFeatureSupport(
  3234. D3D12_FEATURE_SHADER_MODEL,
  3235. (&raw mut model).cast(),
  3236. size_of_val(&model) as u32,
  3237. )
  3238. .is_ok()
  3239. };
  3240. let mesh = ok
  3241. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  3242. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  3243. tracing::info!(mesh, "host mesh shader support");
  3244. mesh
  3245. })
  3246. }
  3247. /// Whether the host GPU supports the depth bounds test; logged once.
  3248. pub(crate) fn depth_bounds(&self) -> bool {
  3249. static BOUNDS: OnceLock<bool> = OnceLock::new();
  3250. *BOUNDS.get_or_init(|| {
  3251. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default();
  3252. // SAFETY: writes `options` of the given size.
  3253. let ok = unsafe {
  3254. self.device
  3255. .CheckFeatureSupport(
  3256. D3D12_FEATURE_D3D12_OPTIONS2,
  3257. (&raw mut options).cast(),
  3258. size_of_val(&options) as u32,
  3259. )
  3260. .is_ok()
  3261. };
  3262. let supported = ok && options.DepthBoundsTestSupported.as_bool();
  3263. tracing::info!(supported, "host depth bounds support");
  3264. supported
  3265. })
  3266. }
  3267. /// A new list, open for recording.
  3268. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  3269. #[cfg(feature = "diagnostics")]
  3270. let started = std::time::Instant::now();
  3271. #[cfg(feature = "diagnostics")]
  3272. let before = private_bytes();
  3273. let list = self.make_list();
  3274. LISTS[0].fetch_add(1, Ordering::Relaxed);
  3275. // (May shrink while a list is made, on another thread's account:
  3276. // added as it is, the sum is what counts.)
  3277. #[cfg(feature = "diagnostics")]
  3278. LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed);
  3279. #[cfg(feature = "diagnostics")]
  3280. {
  3281. use crate::copystat::{C, add};
  3282. add(C::HostLists, 1);
  3283. add(C::HostListNs, started.elapsed().as_nanos() as u64);
  3284. }
  3285. list
  3286. }
  3287. /// An allocator and a closed list for a prelude.
  3288. fn make_prelude(&self) -> Option<Prelude> {
  3289. // SAFETY: plain object creation.
  3290. let made: windows::core::Result<Prelude> = unsafe {
  3291. (|| {
  3292. let allocator: ID3D12CommandAllocator =
  3293. self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3294. let list: ID3D12GraphicsCommandList =
  3295. self.device
  3296. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
  3297. list.Close()?;
  3298. Ok((allocator, list))
  3299. })()
  3300. };
  3301. LISTS[1].fetch_add(1, Ordering::Relaxed);
  3302. match made {
  3303. Ok(prelude) => Some(prelude),
  3304. Err(e) => {
  3305. tracing::warn!(error = %e, "no host list for a prelude");
  3306. None
  3307. }
  3308. }
  3309. }
  3310. fn make_list(&self) -> windows::core::Result<HostList> {
  3311. // SAFETY: plain object creation.
  3312. unsafe {
  3313. let allocator: ID3D12CommandAllocator = self
  3314. .device
  3315. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  3316. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  3317. 0,
  3318. D3D12_COMMAND_LIST_TYPE_DIRECT,
  3319. &allocator,
  3320. None,
  3321. )?;
  3322. let prelude = OnceLock::new();
  3323. if !lazy_prelude() {
  3324. let _ = prelude.set(self.make_prelude());
  3325. }
  3326. #[cfg(feature = "diagnostics")]
  3327. let notes = std::sync::Arc::<Mutex<Vec<Note>>>::default();
  3328. let pipelines = std::sync::Arc::<Mutex<std::collections::BTreeSet<String>>>::default();
  3329. #[cfg(feature = "diagnostics")]
  3330. if dred_on() || dred_light() {
  3331. static NUMBER: AtomicU32 = AtomicU32::new(0);
  3332. let number = NUMBER.fetch_add(1, Ordering::Relaxed);
  3333. name(&list, || format!("victory host list {number}"));
  3334. let mut all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  3335. if number.is_multiple_of(256) {
  3336. all.retain(|_, l| l.0.strong_count() > 0);
  3337. }
  3338. all.insert(number, (std::sync::Arc::downgrade(&notes), std::sync::Arc::downgrade(&pipelines)));
  3339. }
  3340. Ok(HostList {
  3341. allocator,
  3342. list,
  3343. deferred: Mutex::default(),
  3344. scratch: Mutex::default(),
  3345. states: Mutex::default(),
  3346. twins: Mutex::default(),
  3347. prelude,
  3348. pipelines,
  3349. budget: OnceLock::new(),
  3350. card_budget: OnceLock::new(),
  3351. indirect_args: Mutex::default(),
  3352. batch_args: Mutex::default(),
  3353. _alive: Counted::new(),
  3354. #[cfg(feature = "diagnostics")]
  3355. notes,
  3356. #[cfg(feature = "diagnostics")]
  3357. stamps: OnceLock::new(),
  3358. })
  3359. }
  3360. }
  3361. /// The card's clock ([`CARD_CLOCK_US`]), made at the first send.
  3362. fn card_clock(&self) -> Option<&'static CardClock> {
  3363. static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new();
  3364. static WATCH: std::sync::Once = std::sync::Once::new();
  3365. let clock = CLOCK
  3366. .get_or_init(|| {
  3367. // SAFETY: a plain fence on our device.
  3368. let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?;
  3369. Some(CardClock {
  3370. fence,
  3371. state: Mutex::new((0, None)),
  3372. sent: std::sync::Condvar::new(),
  3373. })
  3374. })
  3375. .as_ref()?;
  3376. WATCH.call_once(|| {
  3377. if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) {
  3378. tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0");
  3379. }
  3380. });
  3381. Some(clock)
  3382. }
  3383. /// Lists of ours just went to the queue: the clock's signal goes
  3384. /// behind them, and an idle stretch of the card, if one was under way,
  3385. /// ends here ([`CARD_CLOCK_US`]).
  3386. fn card_sent(&self) {
  3387. let Some(clock) = self.card_clock() else {
  3388. return;
  3389. };
  3390. let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
  3391. state.0 += 1;
  3392. // SAFETY: our queue and the clock's fence.
  3393. let _ = unsafe { self.queue.Signal(&clock.fence, state.0) };
  3394. if let Some((since, worked_then)) = state.1.take() {
  3395. CARD_CLOCK_US[0].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
  3396. CARD_CLOCK_US[1].fetch_add(worked().saturating_sub(worked_then), Ordering::Relaxed);
  3397. }
  3398. drop(state);
  3399. clock.sent.notify_one();
  3400. }
  3401. /// Whether the host has what copies in the card's memory need (three
  3402. /// lists and the compare); made at the first ask. A copy goes to the
  3403. /// card's memory only if it has.
  3404. pub(crate) fn card_ready(&self) -> bool {
  3405. static READY: OnceLock<bool> = OnceLock::new();
  3406. *READY.get_or_init(|| match self.make_card_work() {
  3407. Ok(work) => {
  3408. *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work);
  3409. true
  3410. }
  3411. Err(e) => {
  3412. tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made");
  3413. false
  3414. }
  3415. })
  3416. }
  3417. fn make_card_work(&self) -> windows::core::Result<CardWork> {
  3418. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  3419. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  3420. let mut code: Option<ID3DBlob> = None;
  3421. // SAFETY: the source and names live through the call; the out
  3422. // pointer is ours.
  3423. unsafe {
  3424. D3DCompile(
  3425. CARD_COMPARE.as_ptr().cast(),
  3426. CARD_COMPARE.len(),
  3427. windows::core::s!("card compare"),
  3428. None,
  3429. None,
  3430. windows::core::s!("main"),
  3431. windows::core::s!("cs_5_1"),
  3432. 0,
  3433. 0,
  3434. &mut code,
  3435. None,
  3436. )?;
  3437. }
  3438. let code = code.ok_or_else(windows::core::Error::empty)?;
  3439. let list = || self.make_prelude().ok_or_else(windows::core::Error::empty);
  3440. // A megabyte of results: 262,144 pieces, 16 GB of declared ranges
  3441. // in one submission.
  3442. const RESULTS: u64 = 1 << 20;
  3443. let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?;
  3444. name(&differs, || "card compare results".into());
  3445. // SAFETY: the blob's own bytes; the root signature is inside the
  3446. // shader.
  3447. unsafe {
  3448. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  3449. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  3450. let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  3451. pRootSignature: std::mem::transmute_copy(&root),
  3452. CS: D3D12_SHADER_BYTECODE {
  3453. pShaderBytecode: bytes.as_ptr().cast(),
  3454. BytecodeLength: bytes.len(),
  3455. },
  3456. ..Default::default()
  3457. })?;
  3458. #[cfg(feature = "diagnostics")]
  3459. name(&pso, || crate::replay::play::COMPARE.into());
  3460. Ok(CardWork {
  3461. sync: vec![list()?],
  3462. check: vec![list()?],
  3463. fetch: list()?,
  3464. root,
  3465. pso,
  3466. differs: (differs, data as usize, RESULTS),
  3467. fetched: None,
  3468. taken: 0,
  3469. out: 0,
  3470. })
  3471. }
  3472. }
  3473. /// Before a submission's lists run, for copies in the card's memory
  3474. /// ([`crate::shadow::cards`]): what changed on their CPU side since
  3475. /// the last submission goes to their card side (a list of ours, run
  3476. /// now; the submission's lists follow it on the queue), and the ranges
  3477. /// this submission's shaders may write get a compare to run after its
  3478. /// lists. `None` if there is nothing to do.
  3479. ///
  3480. /// `flown`: the submission is sent ahead with [`relay`]. Its compare
  3481. /// then stores the hashes it makes (see [`flagged_pieces`] and
  3482. /// `relay`).
  3483. /// `picked`: ranges that may be written too, and ranges to look at
  3484. /// (`crate::picked`).
  3485. fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
  3486. use std::sync::Arc;
  3487. if !crate::shadow::cards() {
  3488. return None;
  3489. }
  3490. // The ranges this submission's shaders may write, per copy.
  3491. let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
  3492. for list in runs {
  3493. for step in &list.deferred().copies {
  3494. if let Step::GpuWrite(shadow, address, len) = step
  3495. && shadow.carded()
  3496. {
  3497. let range = (*address, *address + *len);
  3498. match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3499. Some((_, ranges)) => {
  3500. if !ranges.contains(&range) {
  3501. ranges.push(range);
  3502. }
  3503. }
  3504. None => declared.push((shadow.clone(), vec![range])),
  3505. }
  3506. }
  3507. }
  3508. }
  3509. let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
  3510. // (Of a copy with a declared range here, that says it.)
  3511. let looked: Vec<&crate::picked::Range> =
  3512. picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
  3513. // With the relay: the order of the queue is held from here until
  3514. // what is taken is on the queue, and the taking is numbered.
  3515. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  3516. let sent_as = match order.as_mut() {
  3517. Some(order) => {
  3518. **order += 1;
  3519. **order
  3520. }
  3521. None => 0,
  3522. };
  3523. let mut dirty = crate::shadow::card_dirty(sent_as);
  3524. if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
  3525. return None;
  3526. }
  3527. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3528. let work = work.as_mut()?;
  3529. // A copy whose shader writes are declared for the first time gets
  3530. // its bytes from before, whole.
  3531. let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
  3532. for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
  3533. if shadow.card_make_before(|size| {
  3534. let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
  3535. name(&before, || "title buffer on the card, hashes of its pieces".into());
  3536. Some(before)
  3537. }) {
  3538. whole.push(shadow.clone());
  3539. if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) {
  3540. dirty.push((shadow.clone(), Vec::new()));
  3541. }
  3542. }
  3543. }
  3544. let mut used: Vec<(bool, Prelude)> = Vec::new();
  3545. let mut looks = None;
  3546. // The bytes as they are now, whatever later submissions put there.
  3547. let own = if send::own() { send::take(self, &dirty) } else { None };
  3548. if !dirty.is_empty() {
  3549. let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
  3550. fail(format_args!("no host list to bring host copies in the card's memory up to date"));
  3551. };
  3552. let (allocator, list) = &sync;
  3553. // SAFETY: the list's last run finished (it ran ahead of a
  3554. // submission that was waited for, and came back after that);
  3555. // live buffers, and the ranges lie in them.
  3556. let recorded = unsafe {
  3557. (|| -> windows::core::Result<()> {
  3558. allocator.Reset()?;
  3559. list.Reset(allocator, None)?;
  3560. if upcheck::on() {
  3561. looks = upcheck::record(self, list, &dirty);
  3562. }
  3563. // Every copy first, then one barrier call, then every
  3564. // pass: a wait between each copy and its pass had the
  3565. // card do them one after the other.
  3566. let mut sent = Vec::new();
  3567. if let Some(own) = &own {
  3568. own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
  3569. }
  3570. for (shadow, ranges) in &dirty {
  3571. let Some((staging, before, _)) = shadow.card_sides() else {
  3572. continue;
  3573. };
  3574. for &(a, b) in ranges {
  3575. if own.is_none() {
  3576. list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
  3577. }
  3578. crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
  3579. }
  3580. crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
  3581. if own.is_none() && before.is_some() && !ranges.is_empty() {
  3582. sent.push(transition(
  3583. &shadow.buffer,
  3584. D3D12_RESOURCE_STATE_COPY_DEST,
  3585. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  3586. ));
  3587. }
  3588. }
  3589. if !sent.is_empty() {
  3590. list.ResourceBarrier(&sent);
  3591. }
  3592. list.SetComputeRootSignature(&work.root);
  3593. list.SetPipelineState(&work.pso);
  3594. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3595. for (shadow, ranges) in &dirty {
  3596. let Some((_, Some(before), size)) = shadow.card_sides() else {
  3597. continue;
  3598. };
  3599. // No twin (it cost the card the copy's size again,
  3600. // 399 MB in run 75): `before` holds a 128-bit hash
  3601. // of each 64 KiB piece. The pieces just sent up are
  3602. // hashed again, all of them the first time; the
  3603. // compare after the lists hashes the declared
  3604. // pieces and flags those whose hash is another.
  3605. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  3606. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3607. let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
  3608. vec![shadow.card_run(0, usize::MAX)]
  3609. } else {
  3610. ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
  3611. };
  3612. // The same pieces in fewer passes (`rehash_runs`).
  3613. let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
  3614. CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3615. CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
  3616. for run in runs {
  3617. card_pass(list, &run, size as u32, 0, 0);
  3618. }
  3619. }
  3620. list.Close()?;
  3621. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  3622. Ok(())
  3623. })()
  3624. };
  3625. if let Err(e) = recorded {
  3626. fail(format_args!("host copies in the card's memory could not be brought up to date ({e})"));
  3627. }
  3628. used.push((false, sync));
  3629. }
  3630. drop(order);
  3631. let mut plan = CardPlan {
  3632. ranges: Vec::new(),
  3633. check: None,
  3634. _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
  3635. lists: used,
  3636. sent_as,
  3637. looks,
  3638. sends: own.map(send::Own::memory),
  3639. };
  3640. // Each byte once, as the copy-back joins the declared ranges. The
  3641. // results go behind those of plans still in the air.
  3642. let mut at = work.taken;
  3643. for (shadow, ranges) in &declared {
  3644. let mut sorted = ranges.clone();
  3645. sorted.sort_unstable();
  3646. let mut spans: Vec<(usize, usize)> = Vec::new();
  3647. for (from, to) in sorted {
  3648. match spans.last_mut() {
  3649. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  3650. _ => spans.push((from, to)),
  3651. }
  3652. }
  3653. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3654. for (from, to) in spans {
  3655. let Some(span) = shadow.card_span(from, to) else {
  3656. continue;
  3657. };
  3658. let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2;
  3659. plan.ranges.push(CardRange {
  3660. shadow: shadow.clone(),
  3661. declared: (from, to),
  3662. span,
  3663. at,
  3664. compared,
  3665. picked: false,
  3666. });
  3667. if compared {
  3668. at += span.pieces;
  3669. }
  3670. }
  3671. }
  3672. for (shadow, from, len) in looked {
  3673. let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  3674. if let Some(span) = shadow.card_span(*from, from + len)
  3675. && twin
  3676. && u64::from(at + span.pieces) * 4 <= work.differs.2
  3677. {
  3678. plan.ranges.push(CardRange {
  3679. shadow: shadow.clone(),
  3680. declared: (*from, from + len),
  3681. span,
  3682. at,
  3683. compared: true,
  3684. picked: true,
  3685. });
  3686. at += span.pieces;
  3687. }
  3688. }
  3689. work.taken = at;
  3690. if plan.ranges.iter().any(|r| r.compared) {
  3691. let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
  3692. fail(format_args!("no host list for the compare of host copies in the card's memory"));
  3693. };
  3694. let (allocator, list) = &check;
  3695. // SAFETY: the list's last run finished (its submission was
  3696. // waited for, and it came back after that); live buffers; the
  3697. // compare's own root signature.
  3698. let recorded = unsafe {
  3699. (|| -> windows::core::Result<ID3D12CommandList> {
  3700. allocator.Reset()?;
  3701. list.Reset(allocator, None)?;
  3702. // What the submission's shaders wrote, first.
  3703. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  3704. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3705. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3706. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3707. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3708. pResource: std::mem::ManuallyDrop::new(None),
  3709. }),
  3710. },
  3711. }]);
  3712. list.SetComputeRootSignature(&work.root);
  3713. list.SetPipelineState(&work.pso);
  3714. list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress());
  3715. for r in plan.ranges.iter().filter(|r| r.compared) {
  3716. let Some((_, Some(before), size)) = r.shadow.card_sides() else {
  3717. continue;
  3718. };
  3719. list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
  3720. list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
  3721. // (What is only looked at keeps its hashes: what
  3722. // changed there is the next declared range's to land.)
  3723. card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
  3724. CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
  3725. }
  3726. list.Close()?;
  3727. list.cast()
  3728. })()
  3729. };
  3730. match recorded {
  3731. Ok(list) => plan.check = Some(list),
  3732. Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")),
  3733. }
  3734. plan.lists.push((true, check));
  3735. }
  3736. work.out += 1;
  3737. Some(plan)
  3738. }
  3739. /// With [`relay`]: whether the compare's result area is half taken by
  3740. /// plans in the air. It starts from the beginning only when no plan is
  3741. /// out, so the caller lets the flights land first.
  3742. fn card_results_low(&self) -> bool {
  3743. CARD_WORK
  3744. .lock()
  3745. .unwrap_or_else(|e| e.into_inner())
  3746. .as_ref()
  3747. .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2)
  3748. }
  3749. /// The plan's submission has run and its results were read
  3750. /// ([`Host::card_back`]): its lists are free for the next plan. Called
  3751. /// when nothing of ours is on the card, so the compare's results start
  3752. /// from the beginning again.
  3753. fn card_done(&self, plan: CardPlan) {
  3754. if let Some(looks) = plan.looks {
  3755. looks.read();
  3756. }
  3757. if let Some(memory) = plan.sends {
  3758. send::give_back(memory);
  3759. }
  3760. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3761. let Some(work) = work.as_mut() else {
  3762. return;
  3763. };
  3764. for (check, list) in plan.lists {
  3765. if check { work.check.push(list) } else { work.sync.push(list) }
  3766. }
  3767. work.out = work.out.saturating_sub(1);
  3768. // With the relay other plans may be on the card, their results
  3769. // not read yet: the area starts again only when none is out.
  3770. if !relay() || work.out == 0 {
  3771. work.taken = 0;
  3772. }
  3773. }
  3774. /// The relay's own list, fence, event for [`Host::relay_card_back`].
  3775. fn make_relay_fetch(&self) -> Option<RelayFetch> {
  3776. // SAFETY: plain object creation.
  3777. let copying = relay_copy().then(|| unsafe {
  3778. (|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
  3779. let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
  3780. let list: ID3D12GraphicsCommandList =
  3781. self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
  3782. list.Close()?;
  3783. let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  3784. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  3785. Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
  3786. ..Default::default()
  3787. })?;
  3788. Ok(((allocator, list), queue))
  3789. })()
  3790. });
  3791. let (list, queue) = match copying {
  3792. Some(Ok((list, queue))) => (list, Some(queue)),
  3793. Some(Err(e)) => {
  3794. tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
  3795. (self.make_prelude()?, None)
  3796. }
  3797. None => (self.make_prelude()?, None),
  3798. };
  3799. // SAFETY: plain objects of our own.
  3800. unsafe {
  3801. let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  3802. let event = CreateEventW(None, false, false, None).ok()?;
  3803. Some(RelayFetch {
  3804. list,
  3805. queue,
  3806. fence,
  3807. event,
  3808. sent: 0,
  3809. buffer: None,
  3810. suspects: torn::Suspects::default(),
  3811. had: crate::land::Had::default(),
  3812. })
  3813. }
  3814. }
  3815. /// [`relay`], on the thread that lands flights: for the plans of the
  3816. /// flights being landed (the card has run them), the pieces their
  3817. /// compares flagged are fetched, once each, with a list and a wait of
  3818. /// this thread's own, and what shaders wrote in them goes into title
  3819. /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but:
  3820. /// no submission lock; a piece flagged under one range of a plan is
  3821. /// fetched under all ([`flagged_pieces`]); the fetch runs behind
  3822. /// whatever was sent meanwhile, so it may bring a later flight's
  3823. /// bytes, which that flight's landing then finds merged already; and
  3824. /// nothing is sent back up. `plans` come with the value signalled behind
  3825. /// their flight. `meanwhile` is called while the fetch is on its way, if
  3826. /// there is one.
  3827. fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
  3828. use crate::land;
  3829. let gathering = std::time::Instant::now();
  3830. let differs = {
  3831. let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  3832. work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
  3833. };
  3834. let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
  3835. let mut total = 0u64;
  3836. if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
  3837. fetch.had.landing(first);
  3838. }
  3839. // SAFETY: the mapping of the results. The compares of these plans
  3840. // have run, and their dwords are given to no other plan before these
  3841. // are done with (`card_done`).
  3842. let differs = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
  3843. if let Some(differs) = differs {
  3844. // Pieces caught while a later flight was at them (`torn`).
  3845. let suspects = fetch.as_ref().map(|f| &f.suspects);
  3846. let mut seen = std::collections::HashSet::new();
  3847. for &(plan, behind) in plans {
  3848. plan.picked_found(differs);
  3849. let flags: Vec<(usize, u32, bool)> = plan
  3850. .ranges
  3851. .iter()
  3852. .filter(|r| !r.picked)
  3853. .flat_map(|r| {
  3854. (0..r.span.pieces).map(move |p| {
  3855. let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
  3856. let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
  3857. (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
  3858. })
  3859. })
  3860. .collect();
  3861. let fetched = flagged_pieces(&flags);
  3862. for r in plan.ranges.iter().filter(|r| !r.picked) {
  3863. let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
  3864. if upcheck::on() {
  3865. upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
  3866. }
  3867. for p in 0..r.span.pieces {
  3868. if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
  3869. continue;
  3870. }
  3871. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  3872. if lo < hi && !seen.contains(&(copy, lo, hi)) {
  3873. let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
  3874. if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
  3875. land::count(land::stat::HAD, 1);
  3876. land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
  3877. if land::skip_on() {
  3878. continue;
  3879. }
  3880. }
  3881. if upcheck::on() {
  3882. upcheck::fetched(r.shadow.id(), lo);
  3883. }
  3884. seen.insert((copy, lo, hi));
  3885. pieces.push((r.shadow.clone(), lo, hi, total));
  3886. total += (hi - lo) as u64;
  3887. }
  3888. }
  3889. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  3890. }
  3891. }
  3892. }
  3893. if land::on() {
  3894. // In the order they are landed, each byte of a copy once.
  3895. let keys: Vec<land::Piece> =
  3896. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
  3897. total = 0;
  3898. pieces = land::ordered(&keys)
  3899. .into_iter()
  3900. .map(|(i, title, len)| {
  3901. let shadow = &pieces[i].0;
  3902. let lo = title - shadow.span().0 as usize;
  3903. let at = total;
  3904. total += len as u64;
  3905. (shadow.clone(), lo, lo + len, at)
  3906. })
  3907. .collect();
  3908. }
  3909. land::spent(land::stat::GATHER, gathering);
  3910. if fetch.is_none() {
  3911. *fetch = self.make_relay_fetch();
  3912. }
  3913. // On the copy queue a later flight may be at a piece while it is
  3914. // fetched: the pieces come down whole, to be hashed.
  3915. let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
  3916. .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
  3917. if let Some(check) = &check {
  3918. total = check.total;
  3919. }
  3920. // The sends these flights ran behind, all a fetch on the copy queue
  3921. // is known to have run behind.
  3922. let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
  3923. if pieces.is_empty() {
  3924. // Nothing to fetch: every send so far is older than the next
  3925. // fetch, if that goes to the queue the sends went to.
  3926. let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
  3927. true => behind,
  3928. false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
  3929. };
  3930. crate::shadow::relay_fetched(after);
  3931. return;
  3932. }
  3933. let Some(f) = fetch.as_mut() else {
  3934. fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
  3935. };
  3936. if f.buffer.as_ref().is_none_or(|b| b.2 < total) {
  3937. let size = total.next_multiple_of(16 << 20);
  3938. f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  3939. }
  3940. let Some((buffer, data, _)) = f.buffer.clone() else {
  3941. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)"));
  3942. };
  3943. f.sent += 1;
  3944. let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
  3945. let copy_queue = f.queue.clone();
  3946. let waiting = std::time::Instant::now();
  3947. // The flights the fetch runs behind: those in the line by now have
  3948. // been given to the queue. On the copy queue, those landed here.
  3949. let ahead = match copy_queue {
  3950. Some(_) => 0,
  3951. None => line().target,
  3952. };
  3953. // SAFETY: the list's last run was waited for by this thread; live
  3954. // buffers (the copies are held by the plans); the fence and the
  3955. // event are this thread's.
  3956. let ran = unsafe {
  3957. (|| -> windows::core::Result<u64> {
  3958. allocator.Reset()?;
  3959. list.Reset(&allocator, None)?;
  3960. for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
  3961. list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
  3962. }
  3963. list.Close()?;
  3964. let lists = [Some(list.cast::<ID3D12CommandList>()?)];
  3965. if let Some(queue) = &copy_queue {
  3966. queue.ExecuteCommandLists(&lists);
  3967. queue.Signal(&fence, sent)?;
  3968. meanwhile();
  3969. fence.SetEventOnCompletion(sent, event)?;
  3970. WaitForSingleObject(event, INFINITE);
  3971. return Ok(behind);
  3972. }
  3973. // In the order of the queue: the sends of title bytes so
  3974. // far are ahead of this fetch, every later one behind it.
  3975. let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
  3976. self.queue.ExecuteCommandLists(&lists);
  3977. let after = *order;
  3978. drop(order);
  3979. self.card_sent();
  3980. self.queue.Signal(&fence, sent)?;
  3981. meanwhile();
  3982. fence.SetEventOnCompletion(sent, event)?;
  3983. WaitForSingleObject(event, INFINITE);
  3984. Ok(after)
  3985. })()
  3986. };
  3987. let after = match ran {
  3988. Ok(after) => after,
  3989. Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
  3990. };
  3991. let us = waiting.elapsed().as_micros() as u64;
  3992. RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
  3993. {
  3994. use crate::shadow::CARD_STATS;
  3995. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  3996. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  3997. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  3998. CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
  3999. }
  4000. let merging = std::time::Instant::now();
  4001. let mut written = 0;
  4002. if land::on() {
  4003. let titles: Vec<(usize, usize)> =
  4004. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
  4005. let jobs = land::jobs(&titles);
  4006. let put = std::sync::atomic::AtomicU64::new(0);
  4007. land::each(jobs.len(), &|j| {
  4008. let working = std::time::Instant::now();
  4009. if let Some(check) = &check {
  4010. for i in jobs[j].clone() {
  4011. // SAFETY: as below.
  4012. unsafe { check.look(i, data) };
  4013. }
  4014. }
  4015. let mut notes = land::Notes::default();
  4016. for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
  4017. let addressed: Vec<(usize, usize, usize)> =
  4018. run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
  4019. // SAFETY: the mapping of the fetched bytes, `total` of
  4020. // them; the copy into it has run, and the next waits
  4021. // for this call.
  4022. put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
  4023. }
  4024. notes.flush();
  4025. land::spent(land::stat::CARD_ALL, working);
  4026. });
  4027. land::count(land::stat::JOBS, jobs.len() as u64);
  4028. written = put.into_inner();
  4029. } else {
  4030. let mut title = Vec::new();
  4031. for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
  4032. if let Some(check) = &check {
  4033. // SAFETY: as below.
  4034. unsafe { check.look(i, data) };
  4035. }
  4036. // SAFETY: the mapping of the fetched bytes, `total` of them;
  4037. // the copy into it has run.
  4038. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
  4039. let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
  4040. shadow.walls_merged(gpu.len(), merged);
  4041. written += merged as u64;
  4042. }
  4043. }
  4044. land::spent(land::stat::CARD, merging);
  4045. COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
  4046. if let Some(f) = fetch.as_mut() {
  4047. if let Some(check) = &check {
  4048. check.done(&mut f.suspects);
  4049. }
  4050. f.had.fetched(
  4051. ahead,
  4052. pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
  4053. );
  4054. }
  4055. // Sends up to `after` are of no use to any later merge.
  4056. crate::shadow::relay_fetched(after);
  4057. }
  4058. /// [`relay`], on the thread that lands flights: `items` are the first
  4059. /// things of the line, flights the card has run and what follows them.
  4060. /// What their shaders wrote goes into title memory (copies in the
  4061. /// card's memory first, then the others, each byte once whichever
  4062. /// flights declared it); then every flight's ranges are done with;
  4063. /// then, in the line's order, each flight's read-backs, its
  4064. /// bottom-of-pipe writes and the fence signals behind it. Title memory
  4065. /// is complete before the title is told anything.
  4066. fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
  4067. let landing = std::time::Instant::now();
  4068. {
  4069. let flights: Vec<&Flight> = items
  4070. .iter()
  4071. .filter_map(|l| match l {
  4072. Late::Run(flight) => Some(flight),
  4073. _ => None,
  4074. })
  4075. .collect();
  4076. if !flights.is_empty() {
  4077. // SAFETY: a plain query.
  4078. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4079. let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect();
  4080. fail(format_args!(
  4081. "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}",
  4082. flights.len(),
  4083. runs.len(),
  4084. self.removal_data(&runs),
  4085. last_notes(&runs)
  4086. ));
  4087. }
  4088. let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
  4089. // (Each byte once: the ranges are joined.)
  4090. let mut back: Vec<Declared> = Vec::new();
  4091. for flight in &flights {
  4092. for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
  4093. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4094. Some((_, all)) => all.extend_from_slice(ranges),
  4095. None => back.push((shadow.clone(), ranges.clone())),
  4096. }
  4097. }
  4098. }
  4099. let mut hand_back = relay_hand_back(&back);
  4100. self.relay_card_back(&plans, fetch, &mut || {
  4101. if crate::land::on() {
  4102. hand_back.look(crate::land::stat::SCAN_BESIDE);
  4103. }
  4104. });
  4105. hand_back.merge();
  4106. let finishing = std::time::Instant::now();
  4107. // Only now, and flight by flight: a range another flight
  4108. // in the air declared too stays closed to refreshes.
  4109. for flight in &flights {
  4110. for (shadow, ranges) in &flight.back {
  4111. shadow.copy_back_done(ranges);
  4112. }
  4113. }
  4114. crate::land::spent(crate::land::stat::DONE, finishing);
  4115. COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4116. RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
  4117. RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
  4118. }
  4119. }
  4120. // In the order given: what tells the title the card is done.
  4121. let mut last = 0;
  4122. let mut landed = Vec::new();
  4123. let mut telling = std::time::Instant::now();
  4124. for item in items {
  4125. telling = match item {
  4126. Late::Run(flight) => {
  4127. last = flight.number;
  4128. for &i in &flight.order {
  4129. read_backs(flight.lists[i].host());
  4130. }
  4131. if let Some(card) = flight.card {
  4132. self.card_done(card);
  4133. }
  4134. if let Some(own) = flight.own {
  4135. own.landed();
  4136. }
  4137. landed.push((flight.lists, flight.order));
  4138. crate::land::spent(crate::land::stat::READ_BACKS, telling)
  4139. }
  4140. Late::Write(at, what, bytes) => {
  4141. what.write(at as *mut u8, bytes);
  4142. crate::land::spent(crate::land::stat::TOLD, telling)
  4143. }
  4144. Late::Signal(fence, value) => {
  4145. crate::fence::set(fence as crate::object::This, value);
  4146. crate::land::spent(crate::land::stat::TOLD, telling)
  4147. }
  4148. };
  4149. }
  4150. if last > 0 {
  4151. FINISHED.store(last, Ordering::Release);
  4152. bury(last);
  4153. }
  4154. self.log_messages();
  4155. crate::land::spent(crate::land::stat::REST, telling);
  4156. RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
  4157. {
  4158. let mut line = line();
  4159. let Line {
  4160. line: items,
  4161. written,
  4162. lists,
  4163. settling,
  4164. poke,
  4165. landed: kept,
  4166. in_hand,
  4167. landing,
  4168. ..
  4169. } = &mut *line;
  4170. kept.extend(landed);
  4171. in_hand.clear();
  4172. landing.clear();
  4173. // What is still in the air, from the flights that are.
  4174. written.clear();
  4175. *lists = 0;
  4176. let mut ranges = Vec::new();
  4177. for item in items.iter() {
  4178. if let Late::Run(flight) = item {
  4179. *lists += flight.order.len().max(1);
  4180. ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied()));
  4181. }
  4182. }
  4183. join_ranges(written, ranges);
  4184. *settling = false;
  4185. // The landed lists are reset, and what queues hold looked at,
  4186. // by the helper thread (they take locks a waiter may hold).
  4187. *poke = true;
  4188. }
  4189. LINE_MOVED.notify_all();
  4190. LINE_LANDED.notify_all();
  4191. }
  4192. /// After a submission ran, for copies in the card's memory: the pieces
  4193. /// of the declared ranges that the compare found differing (all of a
  4194. /// range it did not compare) are fetched, with one more wait for the
  4195. /// card, and what shaders wrote in them goes into title memory.
  4196. /// `submitted` is the last value signalled on the fence. `seen` holds
  4197. /// the pieces fetched already since the card was last waited for
  4198. /// (several submissions settled together name the same ones).
  4199. fn card_back(
  4200. &self,
  4201. plan: &CardPlan,
  4202. submitted: &mut u64,
  4203. seen: &mut std::collections::HashSet<(usize, usize, usize)>,
  4204. ) {
  4205. if plan.ranges.is_empty() {
  4206. return;
  4207. }
  4208. let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
  4209. let Some(work) = work.as_mut() else {
  4210. return;
  4211. };
  4212. // SAFETY: the mapping of the results, which the compare (it has
  4213. // run) wrote.
  4214. let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) };
  4215. // The pieces to fetch: the range, the offsets in its copy, and
  4216. // where the bytes come down.
  4217. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
  4218. let mut total = 0u64;
  4219. plan.picked_found(differs);
  4220. for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
  4221. for p in 0..r.span.pieces {
  4222. if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
  4223. continue;
  4224. }
  4225. let (lo, hi) = r.shadow.card_piece(&r.span, p);
  4226. if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) {
  4227. pieces.push((i, lo, hi, total));
  4228. total += (hi - lo) as u64;
  4229. }
  4230. }
  4231. crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
  4232. }
  4233. let mut written = vec![0usize; plan.ranges.len()];
  4234. if !pieces.is_empty() {
  4235. if work.fetched.as_ref().is_none_or(|f| f.2 < total) {
  4236. let size = total.next_multiple_of(16 << 20);
  4237. work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size));
  4238. }
  4239. let Some((fetched, data, _)) = &work.fetched else {
  4240. fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)"));
  4241. };
  4242. let waiting = std::time::Instant::now();
  4243. let (allocator, list) = &work.fetch;
  4244. // SAFETY: the list's last run was waited for; live buffers; the
  4245. // fence and event are ours, under the submission lock.
  4246. let ran = unsafe {
  4247. (|| -> windows::core::Result<()> {
  4248. allocator.Reset()?;
  4249. list.Reset(allocator, None)?;
  4250. for &(i, lo, hi, at) in &pieces {
  4251. list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64);
  4252. }
  4253. list.Close()?;
  4254. self.queue.ExecuteCommandLists(&[Some(list.cast()?)]);
  4255. self.card_sent();
  4256. *submitted += 1;
  4257. self.queue.Signal(&self.fence, *submitted)?;
  4258. self.fence.SetEventOnCompletion(*submitted, self.event)?;
  4259. let was_working = working(false);
  4260. WaitForSingleObject(self.event, INFINITE);
  4261. stood(waiting);
  4262. working(was_working);
  4263. Ok(())
  4264. })()
  4265. };
  4266. if let Err(e) = ran {
  4267. fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})"));
  4268. }
  4269. {
  4270. use crate::shadow::CARD_STATS;
  4271. CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed);
  4272. CARD_STATS[4].fetch_add(total, Ordering::Relaxed);
  4273. CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
  4274. CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed);
  4275. }
  4276. if wide_merge() && pieces.len() >= 8 {
  4277. // The pieces are apart from one another (each its own bytes
  4278. // of its copy and of title memory): several at a time.
  4279. let fetched = *data;
  4280. let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> =
  4281. std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect());
  4282. let each = pieces.len().div_ceil(8);
  4283. let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces
  4284. .chunks(each)
  4285. .map(|chunk| {
  4286. let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> =
  4287. chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect();
  4288. let counts = counts.clone();
  4289. Box::new(move || {
  4290. let mut title = Vec::new();
  4291. for (shadow, i, lo, hi, at) in chunk {
  4292. // SAFETY: the mapping of the fetched bytes;
  4293. // the copy into it has run, and the caller
  4294. // waits for this job.
  4295. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
  4296. let merged = shadow.card_merge(lo, gpu, &mut title);
  4297. shadow.walls_merged(gpu.len(), merged);
  4298. counts[i].fetch_add(merged, Ordering::Relaxed);
  4299. }
  4300. }) as Box<dyn FnOnce() + Send>
  4301. })
  4302. .collect();
  4303. crate::shadow::wide_run(jobs);
  4304. for (written, count) in written.iter_mut().zip(counts.iter()) {
  4305. *written += count.load(Ordering::Relaxed);
  4306. }
  4307. } else {
  4308. let mut title = Vec::new();
  4309. for &(i, lo, hi, at) in &pieces {
  4310. // SAFETY: the mapping of the fetched bytes, `total` of
  4311. // them; the copy into it has run.
  4312. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
  4313. let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
  4314. plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
  4315. written[i] += merged;
  4316. }
  4317. }
  4318. }
  4319. for (r, written) in plan.ranges.iter().zip(written) {
  4320. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  4321. let (from, to) = r.declared;
  4322. #[cfg(feature = "diagnostics")]
  4323. crate::copystat::compared(from, to - from, written);
  4324. let _ = (from, to);
  4325. }
  4326. }
  4327. /// Runs closed lists and waits for them, and with [`late`] for
  4328. /// everything sent to the card before them, which is settled first.
  4329. pub(crate) fn execute(&self, runs: &[&HostList]) {
  4330. let _ = self.submit(runs, false);
  4331. }
  4332. /// A queue's submission with [`late`]: the host lists `lists`, taken
  4333. /// from the title's, go to the card in `order` and are not waited for.
  4334. /// They join the line of flights and are settled, with the others in
  4335. /// the air, at the next point where what they do can be observed
  4336. /// ([`late`] lists those points); their host lists are reset and kept
  4337. /// for reuse then, as a queue does for the lists it ran.
  4338. pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
  4339. if order.is_empty() {
  4340. crate::list::recycle(lists, &order);
  4341. return;
  4342. }
  4343. late_threads();
  4344. let sent = {
  4345. let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
  4346. self.submit(&runs, true)
  4347. };
  4348. let Some((mut submitted, sent)) = sent else {
  4349. // (Not reached: a submission sent ahead always comes back.)
  4350. crate::list::recycle(lists, &order);
  4351. return;
  4352. };
  4353. let told = !sent.writes.is_empty();
  4354. let most = {
  4355. let mut line = line();
  4356. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4357. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4358. *flying += order.len();
  4359. *target = *submitted;
  4360. items.push(Late::Run(Flight {
  4361. number: sent.number,
  4362. fence: *target,
  4363. lists,
  4364. order,
  4365. card: sent.card,
  4366. back: sent.back,
  4367. own: sent.own,
  4368. }));
  4369. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4370. *flying >= late_most()
  4371. };
  4372. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4373. RELAY_MOVED.notify_one();
  4374. if told && !late_writes() {
  4375. self.settle(&mut submitted, WHY_WRITES);
  4376. } else if most && relay_exact() {
  4377. // Until there are fewer, not until there are none.
  4378. relay_wait(WHY_MOST, |line| line.lists < late_most());
  4379. } else if most {
  4380. self.settle(&mut submitted, WHY_MOST);
  4381. } else {
  4382. LINE_MOVED.notify_one();
  4383. }
  4384. drop(submitted);
  4385. land();
  4386. }
  4387. /// Sends `list`, a closed list of ours (the present's copy), as a
  4388. /// flight ([`late_free_present`]): not waited for, settled with the
  4389. /// others. The caller keeps the list and does not reset it before the
  4390. /// submission whose number comes back has finished ([`FINISHED`]); 0 if
  4391. /// it ran and was waited for after all.
  4392. fn execute_own(&self, list: &HostList) -> u64 {
  4393. late_threads();
  4394. let Some((submitted, sent)) = self.submit(&[list], true) else {
  4395. return 0;
  4396. };
  4397. let number = sent.number;
  4398. {
  4399. let mut line = line();
  4400. let Line { line: items, written, lists: flying, target, .. } = &mut *line;
  4401. join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
  4402. *flying += 1;
  4403. *target = *submitted;
  4404. items.push(Late::Run(Flight {
  4405. number,
  4406. fence: *target,
  4407. lists: Vec::new(),
  4408. order: Vec::new(),
  4409. card: sent.card,
  4410. back: sent.back,
  4411. own: sent.own,
  4412. }));
  4413. items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
  4414. }
  4415. LATE_STATS[0].fetch_add(1, Ordering::Relaxed);
  4416. LINE_MOVED.notify_one();
  4417. RELAY_MOVED.notify_one();
  4418. drop(submitted);
  4419. number
  4420. }
  4421. /// Waits for the card to run every flight in the air ([`late`]) and
  4422. /// does what they left to do, as [`Host::execute`] does for one
  4423. /// submission after its wait: the pieces their shaders wrote in copies
  4424. /// in the card's memory are fetched and merged (each once), the ranges
  4425. /// they declared in the other copies are compared and copied back
  4426. /// (each byte once, whichever flights declared it), and then, in the
  4427. /// order they were given: their bottom-of-pipe writes and the fence
  4428. /// signals behind them. `submitted` is the submission lock's value;
  4429. /// `why` one of the `WHY_` places. Nothing happens if nothing flies.
  4430. ///
  4431. /// Everything in the air is settled, never the first flights alone:
  4432. /// the merge writes the copies' CPU side, which a flight still on the
  4433. /// card may be writing too.
  4434. fn settle(&self, submitted: &mut u64, why: usize) {
  4435. if !late() {
  4436. return;
  4437. }
  4438. if relay() {
  4439. // Nothing is settled here: the thread that lands flights does
  4440. // it, in order, and this waits until nothing is in the air and
  4441. // nothing is being landed. Every point that settled before
  4442. // comes here, so each still sees title memory, fences and
  4443. // bottom-of-pipe values as after a settle.
  4444. relay_wait(why, |line| line.line.is_empty() && !line.settling);
  4445. return;
  4446. }
  4447. let was_working = working(true);
  4448. let mut counted = false;
  4449. loop {
  4450. let items = {
  4451. let mut line = line();
  4452. if line.line.is_empty() {
  4453. line.settling = false;
  4454. break;
  4455. }
  4456. line.settling = true;
  4457. line.written.clear();
  4458. line.lists = 0;
  4459. std::mem::take(&mut line.line)
  4460. };
  4461. let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count();
  4462. if !counted {
  4463. counted = true;
  4464. LATE_STATS[1].fetch_add(1, Ordering::Relaxed);
  4465. LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
  4466. }
  4467. LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed);
  4468. if flights > 0 {
  4469. submitting(2, flights);
  4470. let waiting = std::time::Instant::now();
  4471. // SAFETY: the fence and event are ours, under the
  4472. // submission lock; `submitted` is the last value signalled.
  4473. unsafe {
  4474. match self.fence.SetEventOnCompletion(*submitted, self.event) {
  4475. Ok(()) => {
  4476. working(false);
  4477. WaitForSingleObject(self.event, INFINITE);
  4478. stood(waiting);
  4479. working(true);
  4480. }
  4481. Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"),
  4482. }
  4483. }
  4484. let gpu = waiting.elapsed();
  4485. LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4486. LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4487. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4488. #[cfg(feature = "diagnostics")]
  4489. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4490. format!("{flights} submissions sent ahead, settled together")
  4491. });
  4492. // SAFETY: a plain query.
  4493. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4494. let runs: Vec<&HostList> = items
  4495. .iter()
  4496. .filter_map(|i| match i {
  4497. Late::Run(f) => Some(f),
  4498. _ => None,
  4499. })
  4500. .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host()))
  4501. .collect();
  4502. fail(format_args!(
  4503. "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}",
  4504. runs.len(),
  4505. self.removal_data(&runs),
  4506. last_notes(&runs)
  4507. ));
  4508. }
  4509. submitting(3, flights);
  4510. let copying = std::time::Instant::now();
  4511. let mut seen = std::collections::HashSet::new();
  4512. let mut back: Vec<Declared> = Vec::new();
  4513. for item in &items {
  4514. let Late::Run(flight) = item else {
  4515. continue;
  4516. };
  4517. if let Some(card) = &flight.card {
  4518. self.card_back(card, submitted, &mut seen);
  4519. }
  4520. for (shadow, ranges) in &flight.back {
  4521. match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
  4522. Some((_, all)) => {
  4523. for range in ranges {
  4524. if !all.contains(range) {
  4525. all.push(*range);
  4526. }
  4527. }
  4528. }
  4529. None => back.push((shadow.clone(), ranges.clone())),
  4530. }
  4531. }
  4532. }
  4533. hand_back(&back);
  4534. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4535. }
  4536. // In the order given: what tells the title the card is done.
  4537. let mut last = 0;
  4538. let mut landed = Vec::new();
  4539. for item in items {
  4540. match item {
  4541. Late::Run(flight) => {
  4542. last = flight.number;
  4543. for &i in &flight.order {
  4544. read_backs(flight.lists[i].host());
  4545. }
  4546. if let Some(card) = flight.card {
  4547. self.card_done(card);
  4548. }
  4549. landed.push((flight.lists, flight.order));
  4550. }
  4551. Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
  4552. Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
  4553. }
  4554. }
  4555. if last > 0 {
  4556. FINISHED.store(last, Ordering::Release);
  4557. bury(last);
  4558. }
  4559. line().landed.extend(landed);
  4560. }
  4561. if counted {
  4562. self.log_messages();
  4563. submitting(0, 0);
  4564. // What was settled may be what a queue stands at, and the
  4565. // caller may not be one that looks (a read-back, a present).
  4566. if why != WHY_CARD_DONE {
  4567. line().poke = true;
  4568. LINE_MOVED.notify_one();
  4569. }
  4570. }
  4571. working(was_working);
  4572. }
  4573. /// For a submission of `runs` that refreshes the ranges `stale` of host
  4574. /// copies, which flights may be writing and the title wrote too
  4575. /// ([`stale_under_flights`]): the flights land first. `ranges` are
  4576. /// those of the submission's one asking, which is made again.
  4577. ///
  4578. /// With [`card_steps`] only the flights that declared them: a range of
  4579. /// a copy nobody declared any more is refreshed like any other. What
  4580. /// they landed is title memory written, so everything is asked and
  4581. /// looked at again; what is left after three times waits as before.
  4582. fn settle_stale(
  4583. &self,
  4584. submitted: &mut u64,
  4585. runs: &[&HostList],
  4586. mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  4587. ranges: &[(usize, usize)],
  4588. ) {
  4589. if relay_exact() && card_steps::stage() > 0 {
  4590. for _ in 0..3 {
  4591. #[cfg(feature = "diagnostics")]
  4592. blame_stale(&stale);
  4593. relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
  4594. crate::watch::ask_once(ranges);
  4595. stale = stale_under_flights(runs);
  4596. if stale.is_empty() {
  4597. return;
  4598. }
  4599. }
  4600. }
  4601. #[cfg(feature = "diagnostics")]
  4602. blame_stale(&stale);
  4603. self.settle(submitted, WHY_STALE);
  4604. crate::watch::ask_once(ranges);
  4605. }
  4606. /// [`Host::execute`], or with `late` the first half of
  4607. /// [`Host::execute_late`]: the lists are prepared and sent, and what is
  4608. /// to be done once they have run comes back with the submission lock
  4609. /// still held.
  4610. fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
  4611. #[cfg(feature = "diagnostics")]
  4612. let called = std::time::Instant::now();
  4613. #[cfg(feature = "diagnostics")]
  4614. crate::copystat::submission_begins();
  4615. // One submission at a time from preparation to copy-back: snapshots
  4616. // and the ranges shaders write are per host copy, not per submission.
  4617. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  4618. let was_working = working(true);
  4619. submitting(1, runs.len());
  4620. // Flights in the air ([`late`]): a submission that is waited for
  4621. // settles them first, one sent ahead only if preparing it reads
  4622. // what they write.
  4623. // Or the reads are done on the card, behind the flights.
  4624. let own = if late { self.card_steps(runs) } else { None };
  4625. if !late {
  4626. self.settle(&mut submitted, WHY_SYNC);
  4627. } else if own.is_none()
  4628. && let Some(why) = late_blocked(runs)
  4629. {
  4630. if relay_exact() && why == WHY_READ {
  4631. // Only until the flights that may write what is read have
  4632. // landed: their copy-back's end, not the card's other work.
  4633. relay_wait(why, |line| {
  4634. blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs)
  4635. });
  4636. } else {
  4637. self.settle(&mut submitted, why);
  4638. }
  4639. }
  4640. // Descriptors the title copied into placed heaps directly, before
  4641. // command lists that index those slots are submitted.
  4642. crate::descriptor::sync_heaps();
  4643. // That list runs first, and is one of the submission's from here on.
  4644. let with: Vec<&HostList>;
  4645. let runs = match &own {
  4646. Some(own) => {
  4647. with = std::iter::once(own.list()).chain(runs.iter().copied()).collect();
  4648. &with[..]
  4649. }
  4650. None => runs,
  4651. };
  4652. let behind = late && flying();
  4653. // Before this submission counts as started: what the sweep lets go
  4654. // of is named by no list, and nothing runs now (behind flights the
  4655. // sweep waits for a submission that finds none in the air: there is
  4656. // one at every present).
  4657. static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  4658. if !behind {
  4659. if upcheck::on() {
  4660. upcheck::at_rest(self);
  4661. }
  4662. sweep();
  4663. SWEPT.store(now_ms(), Ordering::Relaxed);
  4664. } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
  4665. // With the present sent ahead nothing else brings a moment
  4666. // with nothing in the air: one is made for the sweep.
  4667. self.settle(&mut submitted, WHY_SYNC);
  4668. if upcheck::on() {
  4669. upcheck::at_rest(self);
  4670. }
  4671. sweep();
  4672. SWEPT.store(now_ms(), Ordering::Relaxed);
  4673. }
  4674. let behind = late && flying();
  4675. // The slots that waited for a texture's host copy, before the
  4676. // lists that may read them run.
  4677. crate::descriptor::make_waiting();
  4678. let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
  4679. // The ranges shaders write are counted for it (with the relay).
  4680. crate::shadow::preparing(this_submission);
  4681. let started = std::time::Instant::now();
  4682. #[cfg(feature = "diagnostics")]
  4683. let lock = (started - called).as_micros() as u64;
  4684. #[cfg(feature = "diagnostics")]
  4685. crate::copystat::add(crate::copystat::C::Submissions, 1);
  4686. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  4687. // Where each run's lists start in `lists`.
  4688. let mut firsts = Vec::with_capacity(runs.len());
  4689. let mut batch = Batch::default();
  4690. #[cfg(feature = "diagnostics")]
  4691. let split = Split::begin();
  4692. // The time a settle of flights takes inside this preparing: the
  4693. // wait for the card and the copy-back have their own places on the
  4694. // frame line (run 92 showed them twice, "preparing" 250 ms for 135).
  4695. let mut settled = std::time::Duration::ZERO;
  4696. // One write-watch asking for everything the submission refreshes
  4697. // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges.
  4698. if crate::watch::once() {
  4699. let mut spans: ByCopy<(usize, usize)> = ByCopy::default();
  4700. for list in runs {
  4701. for step in &list.deferred().copies {
  4702. if let Step::Refresh(shadow, address, len) = step
  4703. && shadow.asked_ahead()
  4704. {
  4705. let span = spans
  4706. .entry(std::sync::Arc::as_ptr(shadow) as usize)
  4707. .or_insert((*address, *address + *len));
  4708. *span = (span.0.min(*address), span.1.max(*address + *len));
  4709. }
  4710. }
  4711. }
  4712. let ranges: Vec<(usize, usize)> = spans.into_values().collect();
  4713. #[cfg(feature = "diagnostics")]
  4714. SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
  4715. crate::watch::ask_once(&ranges);
  4716. #[cfg(feature = "diagnostics")]
  4717. split.part(0);
  4718. // Behind flights: the title wrote memory that a flight's shaders
  4719. // may write too, and this submission refreshes it. The flights
  4720. // are settled, and the asking made again: the copy-back wrote
  4721. // title memory, which other copies of it must see.
  4722. if upcheck::on() {
  4723. upcheck::order(runs);
  4724. if behind {
  4725. upcheck::reads(runs);
  4726. }
  4727. }
  4728. let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
  4729. if !stale.is_empty() {
  4730. let settling = std::time::Instant::now();
  4731. self.settle_stale(&mut submitted, runs, stale, &ranges);
  4732. settled += settling.elapsed();
  4733. }
  4734. } else if behind && !stale_under_flights(runs).is_empty() {
  4735. let settling = std::time::Instant::now();
  4736. self.settle(&mut submitted, WHY_STALE);
  4737. settled += settling.elapsed();
  4738. }
  4739. #[cfg(feature = "diagnostics")]
  4740. split.part(1);
  4741. // What flights in the air may write.
  4742. let air = line().written.clone();
  4743. for list in runs {
  4744. list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
  4745. firsts.push(lists.len());
  4746. if let Some(prelude) = list.prelude() {
  4747. lists.push(Some(prelude));
  4748. }
  4749. lists.push(list.list.cast().ok());
  4750. }
  4751. batch.flush();
  4752. crate::watch::ask_once_end();
  4753. #[cfg(feature = "diagnostics")]
  4754. split.part(2);
  4755. // The snapshots of the ranges shaders may write, if they were left
  4756. // for now (`crate::shadow::wide_back`): the refreshes are done, the
  4757. // lists have not gone to the card.
  4758. {
  4759. #[cfg(feature = "diagnostics")]
  4760. let snapshots = std::time::Instant::now();
  4761. crate::shadow::take_snapshots();
  4762. #[cfg(feature = "diagnostics")]
  4763. crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64);
  4764. }
  4765. #[cfg(feature = "diagnostics")]
  4766. split.part(3);
  4767. // Copies in the card's memory: what changed on their CPU side goes
  4768. // up ahead of the lists, and a compare of what the shaders may
  4769. // write follows them in the same submission.
  4770. let flown = late && relay();
  4771. if flown && self.card_results_low() {
  4772. let settling = std::time::Instant::now();
  4773. self.settle(&mut submitted, WHY_MOST);
  4774. settled += settling.elapsed();
  4775. }
  4776. // What shaders may write through views they pick: last, so that no
  4777. // refresh of this submission leaves it alone.
  4778. let picked = crate::picked::declare(runs);
  4779. for (shadow, at, len) in &picked.written {
  4780. shadow.writing(*at, *len);
  4781. }
  4782. let card = self.card_before(runs, &picked, flown);
  4783. // The sends are taken: from here on the references hold what the
  4784. // copies in the lists put.
  4785. for (shadow, at, bytes) in batch.placed.drain(..) {
  4786. shadow.placed_copy(at, &bytes);
  4787. }
  4788. if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
  4789. lists.push(Some(check));
  4790. }
  4791. #[cfg(feature = "diagnostics")]
  4792. split.part(4);
  4793. let prepared = std::time::Instant::now();
  4794. if late {
  4795. *submitted += 1;
  4796. #[cfg(feature = "diagnostics")]
  4797. if let Some([front, behind]) = self.span_lists() {
  4798. lists.insert(0, Some(front));
  4799. lists.push(Some(behind));
  4800. }
  4801. // SAFETY: closed lists; the fence is ours.
  4802. let signalled = unsafe {
  4803. self.queue.ExecuteCommandLists(&lists);
  4804. self.queue.Signal(&self.fence, *submitted)
  4805. };
  4806. awake::sent(&self.device);
  4807. self.card_sent();
  4808. if let Err(e) = signalled {
  4809. fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
  4810. }
  4811. #[cfg(feature = "diagnostics")]
  4812. split.part(5);
  4813. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4814. let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
  4815. SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
  4816. submitting(0, 0);
  4817. #[cfg(feature = "diagnostics")]
  4818. crate::copystat::submission_ends(lock);
  4819. let sent = Sent {
  4820. number: this_submission,
  4821. card,
  4822. back,
  4823. own,
  4824. writes,
  4825. };
  4826. working(was_working);
  4827. return Some((submitted, sent));
  4828. }
  4829. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  4830. #[cfg(feature = "diagnostics")]
  4831. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  4832. firsts
  4833. .iter()
  4834. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  4835. .map(|(&a, &b)| &lists[a..b])
  4836. .collect()
  4837. } else {
  4838. vec![&lists[..]]
  4839. };
  4840. #[cfg(not(feature = "diagnostics"))]
  4841. let groups = [&lists[..]];
  4842. submitting(2, runs.len());
  4843. for (i, group) in groups.iter().enumerate() {
  4844. *submitted += 1;
  4845. let started = std::time::Instant::now();
  4846. // SAFETY: closed lists; the fence and event are ours.
  4847. unsafe {
  4848. self.queue.ExecuteCommandLists(group);
  4849. self.card_sent();
  4850. let waited = self
  4851. .queue
  4852. .Signal(&self.fence, *submitted)
  4853. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  4854. match waited {
  4855. Ok(()) => {
  4856. working(false);
  4857. WaitForSingleObject(self.event, INFINITE);
  4858. stood(started);
  4859. working(true);
  4860. }
  4861. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  4862. }
  4863. }
  4864. // With timing on each group is one of `runs` (and the compare
  4865. // of copies in the card's memory, with the last): every
  4866. // command's time on the card goes to the sums by pipeline.
  4867. #[cfg(feature = "diagnostics")]
  4868. if timing() {
  4869. // SAFETY: a plain query.
  4870. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4871. for (ms, op) in runs[i].slowest(frequency, usize::MAX) {
  4872. crate::copystat::command_took(&op, ms);
  4873. }
  4874. }
  4875. // A submission of one list was never named here (`groups.len()
  4876. // > 1` was the test): the two 50 ms lists of the gameplay
  4877. // frame, each a submission of its own, printed nothing.
  4878. #[cfg(feature = "diagnostics")]
  4879. if timing() && started.elapsed() > std::time::Duration::from_millis(50) {
  4880. // SAFETY: a plain query.
  4881. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  4882. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  4883. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  4884. for (ms, op) in runs[i].slowest(frequency, 6) {
  4885. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  4886. }
  4887. }
  4888. let _ = (i, started);
  4889. }
  4890. let _ = &firsts;
  4891. FINISHED.store(this_submission, Ordering::Release);
  4892. bury(this_submission);
  4893. let gpu = prepared.elapsed();
  4894. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  4895. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  4896. #[cfg(feature = "diagnostics")]
  4897. crate::copystat::card_waited(gpu.as_micros() as u64, || {
  4898. let pipelines: std::collections::BTreeSet<String> = runs
  4899. .iter()
  4900. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4901. .collect();
  4902. let text = format!("{} lists, pipelines {pipelines:?}", runs.len());
  4903. text.chars().take(1200).collect()
  4904. });
  4905. // The host resets a device whose submission runs for about 2 s.
  4906. if gpu > std::time::Duration::from_millis(250) {
  4907. let pipelines: std::collections::BTreeSet<String> = runs
  4908. .iter()
  4909. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  4910. .collect();
  4911. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  4912. }
  4913. // SAFETY: a plain query.
  4914. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  4915. fail(format_args!(
  4916. "host GPU device removed after a submission of {} lists{}{}",
  4917. runs.len(),
  4918. self.removal_data(runs),
  4919. last_notes(runs)
  4920. ));
  4921. }
  4922. submitting(3, runs.len());
  4923. // What shaders wrote goes back before the bottom-of-pipe writes,
  4924. // which tell the title the GPU is done; each range once per
  4925. // submission, however many dispatches declared it (the world's
  4926. // passes declare the same big ranges dozens of times).
  4927. let copying = std::time::Instant::now();
  4928. // For copies in the card's memory the compare has run there: the
  4929. // pieces that differ are fetched and merged.
  4930. if let Some(card) = &card {
  4931. self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
  4932. }
  4933. let back = crate::picked::with(declared_writes(runs), &picked.written);
  4934. hand_back(&back);
  4935. if let Some(card) = card {
  4936. self.card_done(card);
  4937. }
  4938. #[cfg(feature = "diagnostics")]
  4939. if !back.is_empty() {
  4940. crate::copystat::add(crate::copystat::C::BackSubmissions, 1);
  4941. }
  4942. // Nothing of this submission goes back to the title: no range of
  4943. // shader writes, no value written when it is done. The wait for
  4944. // such a one is only for order and for what the card still holds.
  4945. #[cfg(feature = "diagnostics")]
  4946. if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) {
  4947. use crate::copystat::{C, add};
  4948. add(C::NothingBack, 1);
  4949. add(C::NothingBackUs, gpu.as_micros() as u64);
  4950. }
  4951. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  4952. for list in runs {
  4953. // Read backs first: a value written at the bottom of the pipe
  4954. // may be what tells the title that they are there.
  4955. read_backs(list);
  4956. for &(at, what, bytes) in &list.deferred().writes {
  4957. what.write(at as *mut u8, bytes);
  4958. }
  4959. }
  4960. self.log_messages();
  4961. submitting(0, 0);
  4962. #[cfg(feature = "diagnostics")]
  4963. crate::copystat::submission_ends(lock);
  4964. // With the relay: nothing is in the air now, so no fetch still to
  4965. // be merged is older than the sends to card copies so far, and
  4966. // their notes can go.
  4967. if relay() {
  4968. crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
  4969. }
  4970. working(was_working);
  4971. None
  4972. }
  4973. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  4974. /// it lies in (by the names we give them) or the title memory copy just
  4975. /// below it; for each list that did not finish, the command it stopped
  4976. /// at and what the draws and dispatches in flight there run (or, in
  4977. /// lists that never started, the pipelines they bind).
  4978. fn removal_data(&self, runs: &[&HostList]) -> String {
  4979. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  4980. return String::new();
  4981. };
  4982. let mut text = String::new();
  4983. let mut fault_va = None;
  4984. // SAFETY: the outputs are the runtime's, valid while the device
  4985. // lives; nodes are walked as linked, histories have their counts.
  4986. unsafe {
  4987. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  4988. && fault.PageFaultVA != 0
  4989. {
  4990. let va = fault.PageFaultVA;
  4991. fault_va = Some(va);
  4992. text.push_str(&format!("; page fault at {va:#x}"));
  4993. for (what, head) in [
  4994. ("inside", fault.pHeadExistingAllocationNode),
  4995. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  4996. ] {
  4997. let mut names = Vec::new();
  4998. let mut node = head;
  4999. while let Some(n) = node.as_ref()
  5000. && names.len() < 8
  5001. {
  5002. let name = if n.ObjectNameW.is_null() {
  5003. "unnamed".to_owned()
  5004. } else {
  5005. n.ObjectNameW.to_string().unwrap_or_default()
  5006. };
  5007. names.push(format!("{name} (type {})", n.AllocationType.0));
  5008. node = n.pNext;
  5009. }
  5010. if !names.is_empty() {
  5011. text.push_str(&format!("; {what} {names:?}"));
  5012. }
  5013. }
  5014. text.push_str(&crate::shadow::near(va));
  5015. text.push_str(&crate::descriptor::host::near_heaps(va));
  5016. }
  5017. // The plain output: the extended one (with marker texts) came
  5018. // back without stopped lists on this host.
  5019. if dred_faults() {
  5020. return text;
  5021. }
  5022. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  5023. Ok(crumbs) => crumbs,
  5024. Err(e) => {
  5025. text.push_str(&format!("; no breadcrumbs ({e})"));
  5026. return text;
  5027. }
  5028. };
  5029. // Every list's progress (done/count), in the runtime's order.
  5030. let mut progress = Vec::new();
  5031. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  5032. while let Some(p) = node.as_ref() {
  5033. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5034. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  5035. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  5036. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  5037. node = p.pNext;
  5038. }
  5039. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  5040. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  5041. while let Some(p) = plain.as_ref() {
  5042. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  5043. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  5044. let history =
  5045. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  5046. text.push_str(&format!(
  5047. "; a list stopped at command {done} of {} (op {})",
  5048. p.BreadcrumbCount, history[done as usize].0
  5049. ));
  5050. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  5051. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  5052. let named = [
  5053. (!p.pCommandListDebugNameW.is_null()).then(|| p.pCommandListDebugNameW.to_string().unwrap_or_default()),
  5054. (!p.pCommandListDebugNameA.is_null()).then(|| {
  5055. std::ffi::CStr::from_ptr(p.pCommandListDebugNameA.cast()).to_string_lossy().into_owned()
  5056. }),
  5057. ]
  5058. .into_iter()
  5059. .flatten()
  5060. .next()
  5061. .unwrap_or_default();
  5062. text.push_str(&format!(" of \"{named}\""));
  5063. // Not one of the caller's: by the name.
  5064. #[cfg(feature = "diagnostics")]
  5065. let by_name = list_number(&named).and_then(|n| {
  5066. let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
  5067. all.get(&n).map(|(notes, pipelines)| (notes.upgrade(), pipelines.upgrade()))
  5068. });
  5069. #[cfg(not(feature = "diagnostics"))]
  5070. #[allow(clippy::type_complexity)]
  5071. let by_name: Option<(Option<()>, Option<std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>>)> = None;
  5072. #[cfg(feature = "diagnostics")]
  5073. let noted = run.map(|r| r.notes.clone()).or_else(|| by_name.as_ref().and_then(|b| b.0.clone()));
  5074. let bound = run.map(|r| r.pipelines.clone()).or_else(|| by_name.as_ref().and_then(|b| b.1.clone()));
  5075. // The k-th marker command is the k-th note.
  5076. #[cfg(feature = "diagnostics")]
  5077. let markers: Vec<(u32, String)> = noted.map_or_else(Vec::new, |notes| {
  5078. let notes = notes.lock().unwrap_or_else(|e| e.into_inner());
  5079. history
  5080. .iter()
  5081. .enumerate()
  5082. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  5083. .zip(notes.iter())
  5084. .map(|((at, _), (note, range))| {
  5085. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  5086. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  5087. })
  5088. .collect()
  5089. });
  5090. #[cfg(not(feature = "diagnostics"))]
  5091. let markers: Vec<(u32, String)> = Vec::new();
  5092. #[cfg(not(feature = "diagnostics"))]
  5093. let _ = fault_va;
  5094. if done > 0 {
  5095. text.push_str(&in_flight(history, &markers, done as usize));
  5096. }
  5097. // (Without markers a list that stopped midway says what
  5098. // it may have been at only by what it binds.)
  5099. if (done == 0 || markers.is_empty())
  5100. && let Some(bound) = bound
  5101. {
  5102. let pipelines = bound.lock().unwrap_or_else(|e| e.into_inner());
  5103. text.push_str(&format!(", its pipelines {pipelines:?}"));
  5104. }
  5105. }
  5106. plain = p.pNext;
  5107. }
  5108. }
  5109. text
  5110. }
  5111. /// Moves the debug layer's messages into our log; returns the first
  5112. /// error among them.
  5113. pub(crate) fn log_messages(&self) -> Option<String> {
  5114. let Some(queue) = &self.messages else {
  5115. return None;
  5116. };
  5117. let mut first_error = None;
  5118. // SAFETY: each message is read into a buffer of the size the queue
  5119. // reports, then the queue is emptied.
  5120. unsafe {
  5121. for i in 0..queue.GetNumStoredMessages() {
  5122. let mut size = 0;
  5123. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  5124. continue;
  5125. }
  5126. let mut buffer = vec![0u64; size.div_ceil(8)];
  5127. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  5128. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  5129. let m = &*message;
  5130. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  5131. let text = String::from_utf8_lossy(text);
  5132. let text = text.trim_end_matches('\0');
  5133. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  5134. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  5135. first_error = Some(text.to_owned());
  5136. }
  5137. }
  5138. }
  5139. queue.ClearStoredMessages();
  5140. }
  5141. first_error
  5142. }
  5143. /// A host render target view of `resource`, valid until it is recorded.
  5144. pub(crate) fn rtv(
  5145. &self,
  5146. resource: Option<&ID3D12Resource>,
  5147. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  5148. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5149. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5150. // SAFETY: a slot of our heap and a live resource, or none with a
  5151. // description (a typed null view).
  5152. unsafe {
  5153. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  5154. handle.ptr += (slot * self.rtv_size) as usize;
  5155. self.device
  5156. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  5157. handle
  5158. }
  5159. }
  5160. /// A host depth view of `resource`, valid until it is recorded.
  5161. pub(crate) fn dsv(
  5162. &self,
  5163. resource: &ID3D12Resource,
  5164. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  5165. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  5166. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  5167. // SAFETY: a slot of our heap and a live resource.
  5168. unsafe {
  5169. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  5170. handle.ptr += (slot * self.dsv_size) as usize;
  5171. self.device
  5172. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  5173. handle
  5174. }
  5175. }
  5176. }
  5177. impl HostList {
  5178. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  5179. #[cfg(feature = "diagnostics")]
  5180. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  5181. if !timing() {
  5182. return None;
  5183. }
  5184. self.stamps
  5185. .get_or_init(|| {
  5186. let device = &host()?.device;
  5187. let mut heap: Option<ID3D12QueryHeap> = None;
  5188. let mut back: Option<ID3D12Resource> = None;
  5189. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  5190. let desc = D3D12_RESOURCE_DESC {
  5191. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  5192. Width: u64::from(STAMPS) * 8,
  5193. Height: 1,
  5194. DepthOrArraySize: 1,
  5195. MipLevels: 1,
  5196. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  5197. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  5198. ..Default::default()
  5199. };
  5200. // SAFETY: plain object creation.
  5201. unsafe {
  5202. device
  5203. .CreateQueryHeap(
  5204. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  5205. &mut heap,
  5206. )
  5207. .ok()?;
  5208. device
  5209. .CreateCommittedResource(
  5210. &readback,
  5211. D3D12_HEAP_FLAG_NONE,
  5212. &desc,
  5213. D3D12_RESOURCE_STATE_COPY_DEST,
  5214. None,
  5215. &mut back,
  5216. )
  5217. .ok()?;
  5218. }
  5219. Some((heap?, back?))
  5220. })
  5221. .as_ref()
  5222. }
  5223. /// The noted commands that took longest on the GPU, longest first, as
  5224. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  5225. #[cfg(feature = "diagnostics")]
  5226. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  5227. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  5228. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  5229. return Vec::new();
  5230. };
  5231. let mut data = std::ptr::null_mut();
  5232. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  5233. // SAFETY: a read-back buffer the finished list resolved into.
  5234. let stamps: Vec<u64> = unsafe {
  5235. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  5236. return Vec::new();
  5237. }
  5238. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  5239. back.Unmap(0, None);
  5240. s
  5241. };
  5242. let mut times: Vec<(f64, String)> = (0..count)
  5243. .map(|i| {
  5244. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  5245. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  5246. })
  5247. .collect();
  5248. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  5249. times.truncate(n);
  5250. times
  5251. }
  5252. pub(crate) fn close(&self) {
  5253. self.twins_to_depth();
  5254. let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
  5255. if let Some((scratch, _)) = scratch {
  5256. self.indirect_common(&scratch);
  5257. }
  5258. self.batches_common();
  5259. self.card_budget_out();
  5260. #[cfg(feature = "diagnostics")]
  5261. if let Some((heap, back)) = self.stamps() {
  5262. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  5263. // SAFETY: an open list, our heap and read-back buffer.
  5264. unsafe {
  5265. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  5266. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  5267. }
  5268. }
  5269. // SAFETY: our list.
  5270. if let Err(e) = unsafe { self.list.Close() } {
  5271. fail(format_args!(
  5272. "a host command list did not close ({e}): a command recorded into it was invalid"
  5273. ));
  5274. }
  5275. }
  5276. /// Only after the list's last submission finished (every one is waited
  5277. /// for).
  5278. pub(crate) fn reset(&self) {
  5279. #[cfg(feature = "diagnostics")]
  5280. let started = std::time::Instant::now();
  5281. self._alive.used();
  5282. *self.deferred() = Deferred::default();
  5283. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5284. self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5285. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5286. #[cfg(feature = "diagnostics")]
  5287. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  5288. {
  5289. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5290. (scratch.current, scratch.used) = (0, 0);
  5291. // Every submission of the list has run: nothing reads its
  5292. // scratch memory any more, and the next list to ask takes it.
  5293. if scratch_pool() {
  5294. give_chunks(std::mem::take(&mut scratch.chunks));
  5295. }
  5296. }
  5297. // SAFETY: the list is not executing.
  5298. let reset = unsafe {
  5299. self.allocator
  5300. .Reset()
  5301. .and_then(|()| self.list.Reset(&self.allocator, None))
  5302. };
  5303. if let Err(e) = reset {
  5304. fail(format_args!("a host command list did not reset ({e})"));
  5305. }
  5306. #[cfg(feature = "diagnostics")]
  5307. crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64);
  5308. }
  5309. /// Moves a title texture's host copy to `wanted` (a host state) in this
  5310. /// list: the host texture and the state it leaves, if that is a change.
  5311. /// The list's first use of a texture records nothing: its prelude brings
  5312. /// the texture there at submission.
  5313. pub(crate) fn transition(
  5314. &self,
  5315. resource: crate::object::This,
  5316. wanted: u32,
  5317. ) -> Option<(&'static ID3D12Resource, u32)> {
  5318. let texture = crate::resource::host_resource(resource)?;
  5319. let copy = crate::resource::host_copy(resource)?;
  5320. let wanted = legal_state(texture, wanted);
  5321. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5322. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  5323. std::collections::hash_map::Entry::Vacant(v) => {
  5324. v.insert((wanted, wanted, copy));
  5325. None
  5326. }
  5327. std::collections::hash_map::Entry::Occupied(mut o) => {
  5328. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5329. (before != wanted).then_some((texture, before))
  5330. }
  5331. }
  5332. }
  5333. /// Moves host texture `copy` to `wanted` (a host state) in this list,
  5334. /// as [`HostList::transition`] does a title resource's host copy, and
  5335. /// records the barrier: for textures that are not a title resource's
  5336. /// host copy (colour twins) and for the copies between the two.
  5337. fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) {
  5338. let wanted = legal_state(&copy.texture, wanted);
  5339. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5340. let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) {
  5341. std::collections::hash_map::Entry::Vacant(v) => {
  5342. v.insert((wanted, wanted, copy.clone()));
  5343. None
  5344. }
  5345. std::collections::hash_map::Entry::Occupied(mut o) => {
  5346. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  5347. (before != wanted).then_some(before)
  5348. }
  5349. };
  5350. drop(states);
  5351. if let Some(before) = before {
  5352. let barrier = transition(
  5353. &copy.texture,
  5354. D3D12_RESOURCE_STATES(before as i32),
  5355. D3D12_RESOURCE_STATES(wanted as i32),
  5356. );
  5357. // SAFETY: an open list and a live texture.
  5358. unsafe { self.list.ResourceBarrier(&[barrier]) };
  5359. }
  5360. }
  5361. /// A use of title texture `resource` about to be recorded, if it is a
  5362. /// depth texture with a colour twin (false if it is not): of the twin
  5363. /// (`colour`: unordered access) or of the depth texture (depth target,
  5364. /// clear, shader read, copy, resolve), writing it or only reading. The
  5365. /// side used is first brought up to date: by a copy recorded here if
  5366. /// this list wrote the other side since, by the list's prelude if the
  5367. /// list uses the side as it finds it. The twin is left in the
  5368. /// unordered access state; the caller moves the depth texture to the
  5369. /// state its use needs, as for any texture. A twin still ahead when the
  5370. /// list closes is copied then (`twins_to_depth`).
  5371. /// shortcut: every depth target bound for a draw counts as written
  5372. /// (also when the draw only tests), and every unordered access view a
  5373. /// shader names as written; views a shader picks from the heap by a
  5374. /// computed index are not seen here at all.
  5375. pub(crate) fn twin_use(
  5376. &self,
  5377. resource: crate::object::This,
  5378. colour: bool,
  5379. write: bool,
  5380. ) -> bool {
  5381. const UNORDERED_ACCESS: u32 = 0x8;
  5382. // Asked for every texture a draw reads: most have no twin.
  5383. let Some(twin) = crate::resource::twin(resource) else {
  5384. return false;
  5385. };
  5386. let Some(depth) = crate::resource::host_copy(resource) else {
  5387. return false;
  5388. };
  5389. let side = usize::from(colour);
  5390. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5391. let u = twins
  5392. .entry(std::sync::Arc::as_ptr(&twin) as usize)
  5393. .or_insert_with(|| TwinUse {
  5394. depth: depth.clone(),
  5395. twin: twin.clone(),
  5396. needs: [false; 2],
  5397. behind: [None; 2],
  5398. writing: false,
  5399. late: false,
  5400. });
  5401. let copy = match u.behind[side] {
  5402. Some(behind) => behind,
  5403. None => {
  5404. u.needs[side] = true;
  5405. false
  5406. }
  5407. };
  5408. u.behind[side] = Some(false);
  5409. match (write, colour) {
  5410. // Shaders write the twin when the draw or dispatch runs: what
  5411. // the same one reads of the depth texture is prepared before
  5412. // (`twins_written`).
  5413. (true, true) => u.writing = true,
  5414. (true, false) => u.behind[1] = Some(true),
  5415. (false, _) => {}
  5416. }
  5417. // shortcut: the depth plane's twin is not drawn into the plane
  5418. // here: the pass sets a pipeline and a target of ours, which a list
  5419. // still recording the title's commands cannot take. This use sees
  5420. // the plane as it was; the pass runs when the list closes
  5421. // (`twins_to_depth`). Counted.
  5422. if copy && !colour && twin.plane.is_some() {
  5423. u.late = true;
  5424. crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed);
  5425. }
  5426. drop(twins);
  5427. if copy {
  5428. self.twin_copy(&depth, &twin, colour);
  5429. } else if colour {
  5430. self.settle(&twin.colour, UNORDERED_ACCESS);
  5431. }
  5432. // The depth plane's twin is written through unordered access too.
  5433. if colour && let Some(plane) = &twin.plane {
  5434. self.settle(plane, UNORDERED_ACCESS);
  5435. }
  5436. true
  5437. }
  5438. /// Records the pass that draws the twin of the depth plane of `depth`
  5439. /// into the plane, if `twin` has one, with the moves to the states the
  5440. /// pass needs; the twin is left in the unordered access state. Only
  5441. /// for a list that records nothing of the title's afterwards
  5442. /// (`record_plane_pass`).
  5443. fn pass_plane(
  5444. &self,
  5445. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5446. twin: &crate::resource::Twin,
  5447. ) {
  5448. const UNORDERED_ACCESS: u32 = 0x8;
  5449. const DEPTH_WRITE: u32 = 0x10;
  5450. const PIXEL_SHADER_RESOURCE: u32 = 0x80;
  5451. let Some(plane) = &twin.plane else { return };
  5452. self.settle(depth, DEPTH_WRITE);
  5453. self.settle(plane, PIXEL_SHADER_RESOURCE);
  5454. record_plane_pass(&self.list, &depth.texture, &plane.texture);
  5455. self.settle(plane, UNORDERED_ACCESS);
  5456. }
  5457. /// Records the copy of a depth texture into its colour twin (`colour`)
  5458. /// or of the twin into the depth texture, with the moves to the copy
  5459. /// states. The twin is left in the unordered access state.
  5460. fn twin_copy(
  5461. &self,
  5462. depth: &std::sync::Arc<crate::resource::HostTexture>,
  5463. twin: &crate::resource::Twin,
  5464. colour: bool,
  5465. ) {
  5466. const UNORDERED_ACCESS: u32 = 0x8;
  5467. const COPY_DEST: u32 = 0x400;
  5468. const COPY_SOURCE: u32 = 0x800;
  5469. let (from, to) = if colour {
  5470. (depth, &twin.colour)
  5471. } else {
  5472. (&twin.colour, depth)
  5473. };
  5474. self.settle(from, COPY_SOURCE);
  5475. self.settle(to, COPY_DEST);
  5476. record_twin_copy(&self.list, &depth.texture, twin, colour);
  5477. self.settle(&twin.colour, UNORDERED_ACCESS);
  5478. }
  5479. /// Before the list closes: the depth textures whose twins it wrote last
  5480. /// are given what was written, and left readable by shaders. Shaders
  5481. /// that pick a view from the heap by a computed index are not seen by
  5482. /// `twin_use` and read the depth texture in lists that never name it
  5483. /// (in a captured frame of the title no table names a shadow
  5484. /// map for reading but the pass that fills the next one).
  5485. fn twins_to_depth(&self) {
  5486. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  5487. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5488. let written: Vec<_> = twins
  5489. .values_mut()
  5490. .filter(|u| u.behind[0] == Some(true) || u.late)
  5491. .map(|u| {
  5492. // Not copied again if the list copied since the last write
  5493. // and only the depth plane's pass is left.
  5494. let copy = u.behind[0] == Some(true);
  5495. u.behind[0] = Some(false);
  5496. u.late = false;
  5497. (u.depth.clone(), u.twin.clone(), copy)
  5498. })
  5499. .collect();
  5500. drop(twins);
  5501. for (depth, twin, copy) in &written {
  5502. if *copy {
  5503. self.twin_copy(depth, twin, false);
  5504. }
  5505. // Nothing of the title's is recorded after this: the pass may
  5506. // leave its own pipeline and target set.
  5507. self.pass_plane(depth, twin);
  5508. self.settle(depth, SHADER_RESOURCE);
  5509. }
  5510. }
  5511. /// The draw or dispatch just prepared is recorded: the twins it writes
  5512. /// now hold what their depth textures lack.
  5513. pub(crate) fn twins_written(&self) {
  5514. let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5515. for u in twins.values_mut().filter(|u| u.writing) {
  5516. u.writing = false;
  5517. u.behind[0] = Some(true);
  5518. }
  5519. }
  5520. /// At submission: the list that moves each texture this list uses from
  5521. /// its real state to the one the list starts with; the textures' real
  5522. /// states become those the list ends with. For depth textures with a
  5523. /// colour twin it first copies the side the list uses as it finds it
  5524. /// from the other, if a list submitted earlier left it behind.
  5525. fn prelude(&self) -> Option<ID3D12CommandList> {
  5526. const COPY_DEST: u32 = 0x400;
  5527. const COPY_SOURCE: u32 = 0x800;
  5528. let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
  5529. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  5530. // The copies (depth texture, twin, whether into the twin); the
  5531. // sides are then as this list leaves them.
  5532. let mut syncs = Vec::new();
  5533. let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
  5534. for u in twins.values() {
  5535. let real = u.twin.behind.load(Ordering::Relaxed);
  5536. let mut behind = [real & 1 != 0, real & 2 != 0];
  5537. for side in [0, 1] {
  5538. if u.needs[side] && behind[side] {
  5539. syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
  5540. behind = [false; 2];
  5541. }
  5542. }
  5543. let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
  5544. let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
  5545. u.twin.behind.store(left, Ordering::Relaxed);
  5546. }
  5547. drop(twins);
  5548. // A copy runs with its textures in the copy states: each moves
  5549. // there from its real state, and from there to the state the list
  5550. // starts with (back to its real state if the list does not use it).
  5551. let mut to_copy = Vec::new();
  5552. let mut barriers = Vec::new();
  5553. let mut copying = std::collections::HashMap::new();
  5554. for (depth, twin, colour) in &syncs {
  5555. let (from, to) = if *colour {
  5556. (depth, &twin.colour)
  5557. } else {
  5558. (&twin.colour, depth)
  5559. };
  5560. for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
  5561. let key = std::sync::Arc::as_ptr(texture) as usize;
  5562. let real = texture.state.load(Ordering::Relaxed);
  5563. copying.insert(key, state);
  5564. if real != state {
  5565. to_copy.push(transition(
  5566. &texture.texture,
  5567. host_state(real),
  5568. host_state(state),
  5569. ));
  5570. if !states.contains_key(&key) {
  5571. barriers.push(transition(
  5572. &texture.texture,
  5573. host_state(state),
  5574. host_state(real),
  5575. ));
  5576. }
  5577. }
  5578. }
  5579. }
  5580. barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
  5581. let real = copy.state.swap(*last, Ordering::Relaxed);
  5582. let real = copying.get(key).copied().unwrap_or(real);
  5583. (real != *first)
  5584. .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
  5585. }));
  5586. if barriers.is_empty() && syncs.is_empty() {
  5587. return None;
  5588. }
  5589. let Some((allocator, list)) = self
  5590. .prelude
  5591. .get_or_init(|| host().and_then(|h| h.make_prelude()))
  5592. .as_ref()
  5593. else {
  5594. fail(format_args!("no host list for a state prelude"));
  5595. };
  5596. // SAFETY: the prelude is not executing (every submission is waited
  5597. // for); the textures are live.
  5598. let recorded = unsafe {
  5599. allocator.Reset().and_then(|()| {
  5600. list.Reset(allocator, None)?;
  5601. if !to_copy.is_empty() {
  5602. list.ResourceBarrier(&to_copy);
  5603. }
  5604. for (depth, twin, colour) in &syncs {
  5605. record_twin_copy(list, &depth.texture, twin, *colour);
  5606. }
  5607. if !barriers.is_empty() {
  5608. list.ResourceBarrier(&barriers);
  5609. }
  5610. list.Close()
  5611. })
  5612. };
  5613. if let Err(e) = recorded {
  5614. fail(format_args!("a host state prelude did not record ({e})"));
  5615. }
  5616. list.cast().ok()
  5617. }
  5618. /// Notes what the command about to be recorded does, as a marker
  5619. /// command whose text the list keeps (diagnostics, with device-removed
  5620. /// data on): the report pairs the breadcrumbs' marker commands with the
  5621. /// texts in order and names the commands a fault stopped among.
  5622. #[cfg(feature = "diagnostics")]
  5623. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  5624. self.note(what, None);
  5625. }
  5626. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  5627. /// `(address, bytes)`: the report places the faulting address in it.
  5628. #[cfg(feature = "diagnostics")]
  5629. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  5630. self.note(what, Some(range));
  5631. }
  5632. #[cfg(feature = "diagnostics")]
  5633. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  5634. if !dred_on() {
  5635. crate::capture::op(std::ptr::from_ref(self) as usize, what);
  5636. return;
  5637. }
  5638. {
  5639. let started = std::time::Instant::now();
  5640. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  5641. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  5642. // SAFETY: an open list and our query heap.
  5643. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  5644. }
  5645. let what = what();
  5646. crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone());
  5647. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  5648. const UNICODE: u32 = 0;
  5649. // SAFETY: an open list; the marker is copied when recorded.
  5650. unsafe {
  5651. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  5652. };
  5653. self.notes
  5654. .lock()
  5655. .unwrap_or_else(|e| e.into_inner())
  5656. .push((what, range));
  5657. crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64);
  5658. }
  5659. }
  5660. /// Whether nothing recorded since the list was opened does any work:
  5661. /// no draw or dispatch (the first keeps its pipeline), no copy, clear,
  5662. /// upload or resolve (they defer a step or move a texture's state), no
  5663. /// bottom-of-pipe write. State set on the list does not count.
  5664. pub(crate) fn untouched(&self) -> bool {
  5665. {
  5666. let deferred = self.deferred();
  5667. if !(deferred.copies.is_empty()
  5668. && deferred.uploads.is_empty()
  5669. && deferred.kept.is_empty()
  5670. && deferred.textures.is_empty()
  5671. && deferred.writes.is_empty()
  5672. && deferred.backs.is_empty())
  5673. {
  5674. return false;
  5675. }
  5676. }
  5677. self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5678. && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  5679. }
  5680. /// Notes a pipeline the list binds.
  5681. pub(crate) fn used_pipeline(&self, name: &str) {
  5682. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  5683. if !pipelines.contains(name) {
  5684. pipelines.insert(name.to_owned());
  5685. }
  5686. }
  5687. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  5688. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  5689. }
  5690. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  5691. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  5692. let mut deferred = self.deferred();
  5693. COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed);
  5694. // A copy that goes on where the one recorded just before it ended,
  5695. // source and destination both: with `join_copies` the two are one
  5696. // step.
  5697. if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut()
  5698. && continues((*d, *s, *n), (dst as usize, src as usize, len))
  5699. {
  5700. COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed);
  5701. if join_copies() {
  5702. *n += len;
  5703. return;
  5704. }
  5705. }
  5706. deferred
  5707. .copies
  5708. .push(Step::Copy(dst as usize, src as usize, len));
  5709. deferred.refreshed.clear();
  5710. }
  5711. /// Copies `len` bytes of title memory at `src` into the list's upload
  5712. /// memory at `dst` when the list is submitted.
  5713. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  5714. self.deferred()
  5715. .copies
  5716. .push(Step::Fill(dst as usize, src as usize, len, None));
  5717. }
  5718. /// As [`HostList::defer_fill`], for upload memory that only `slot` (a
  5719. /// title heap's address, and the slot) shows.
  5720. pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
  5721. self.deferred()
  5722. .copies
  5723. .push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
  5724. }
  5725. /// As [`HostList::defer_fill`], for the beginning of a buffer
  5726. /// [`HostList::upload`] made.
  5727. pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
  5728. let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
  5729. self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
  5730. }
  5731. /// Brings `[address, address + len)` of a buffer's host copy up to date
  5732. /// when the list is submitted (once per range until a title copy
  5733. /// intervenes), keeping the copy alive until the list is reset.
  5734. pub(crate) fn defer_refresh(
  5735. &self,
  5736. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5737. address: usize,
  5738. len: usize,
  5739. ) {
  5740. let mut deferred = self.deferred();
  5741. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  5742. if deferred.refreshed.insert(key) {
  5743. deferred
  5744. .copies
  5745. .push(Step::Refresh(shadow.clone(), address, len));
  5746. }
  5747. }
  5748. /// Shaders of the list write `[address, address + len)` of a buffer's
  5749. /// host copy: copied back into title memory once the list has run.
  5750. pub(crate) fn defer_gpu_write(
  5751. &self,
  5752. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  5753. address: usize,
  5754. len: usize,
  5755. ) {
  5756. self.deferred()
  5757. .copies
  5758. .push(Step::GpuWrite(shadow.clone(), address, len));
  5759. }
  5760. /// A read back: once the list has run, `rows` rows of `row` bytes go
  5761. /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`)
  5762. /// to title memory at `dst`, pitched `pitch`. The buffer lives until
  5763. /// the list is reset.
  5764. pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) {
  5765. self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch]));
  5766. }
  5767. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  5768. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  5769. self.deferred().writes.push((dst as usize, what, bytes));
  5770. }
  5771. /// A mapped upload buffer of `size` bytes, alive until the list is
  5772. /// reset.
  5773. ///
  5774. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  5775. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  5776. // With [`card_steps`] the card may be the one that fills it.
  5777. let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
  5778. name(&buffer, || format!("list upload {size:#x}"));
  5779. self.deferred().hold_upload(buffer.clone(), size);
  5780. Some((buffer, data))
  5781. }
  5782. /// `len` bytes of upload memory (256-byte aligned) until the list is
  5783. /// reset: the host GPU address and the CPU pointer.
  5784. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  5785. let (buffer, at, data) = self.scratch_at(len)?;
  5786. // SAFETY: a live buffer.
  5787. Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data))
  5788. }
  5789. /// [`HostList::scratch`]: the buffer, the offset in it and the CPU
  5790. /// pointer.
  5791. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
  5792. let host = host()?;
  5793. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5794. let len = len.max(1).next_multiple_of(256);
  5795. if len > SCRATCH_CHUNK {
  5796. let (buffer, data) = host.upload_buffer(len)?;
  5797. name(&buffer, || format!("list scratch {len:#x}"));
  5798. self.deferred().hold_upload(buffer.clone(), len);
  5799. return Some((buffer, 0, data));
  5800. }
  5801. // The chunk in use while `len` fits in what is left of it, else the
  5802. // next one (a list's first chunk may be a small one).
  5803. while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 {
  5804. (s.current, s.used) = (s.current + 1, 0);
  5805. }
  5806. if s.current == s.chunks.len() {
  5807. let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST {
  5808. SCRATCH_FIRST
  5809. } else {
  5810. SCRATCH_CHUNK
  5811. };
  5812. let chunk = take_chunk(host, size)?;
  5813. s.chunks.push((chunk, size));
  5814. s.used = 0;
  5815. }
  5816. let (data, buffer) = (s.chunks[s.current].0.data, s.chunks[s.current].0.buffer.clone());
  5817. let at = s.used;
  5818. s.used += len;
  5819. Some((buffer, at, (data + at as usize) as *mut u8))
  5820. }
  5821. /// The bytes of scratch chunks the list holds now (after a reset:
  5822. /// none while lists share their chunks).
  5823. pub(crate) fn scratch_kept(&self) -> u64 {
  5824. let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  5825. scratch.chunks.iter().map(|c| c.1).sum()
  5826. }
  5827. /// The host address of the list's indirect-work budget, zeroed at each
  5828. /// submission of the list from the first use after a reset on.
  5829. pub(crate) fn budget(&self) -> Option<u64> {
  5830. let (buffer, data) = self
  5831. .budget
  5832. .get_or_init(|| {
  5833. let (b, d) = host()?.shared_buffer(256)?;
  5834. Some((b, d as usize))
  5835. })
  5836. .as_ref()?;
  5837. let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref();
  5838. let mut deferred = self.deferred();
  5839. if !deferred.budget_zeroed {
  5840. deferred.budget_zeroed = true;
  5841. let at = *data;
  5842. // SAFETY: the list's own mapped words, written before it runs.
  5843. // The words after the budget hold what the clamp noted about the
  5844. // list's last run (mesh dispatches: the largest group count
  5845. // asked for, the groups asked in all; with the card's copy, as
  5846. // the list's end copied them here): taken, then zeroed.
  5847. let notes = Box::new(move || unsafe {
  5848. let words = at as *mut u32;
  5849. let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
  5850. MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
  5851. MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
  5852. for k in 0..3 {
  5853. words.add(k).write_volatile(0);
  5854. }
  5855. });
  5856. deferred.copies.push(Step::Host(notes, (0, 0)));
  5857. drop(deferred);
  5858. if let Some(card) = card {
  5859. self.zero_card_budget(card);
  5860. }
  5861. }
  5862. // SAFETY: a live buffer.
  5863. Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() })
  5864. }
  5865. /// The budget's words in the card's own memory ([`card_budget`]), if
  5866. /// the list can zero them itself (`WriteBufferImmediate`).
  5867. fn make_card_budget(&self) -> Option<ID3D12Resource> {
  5868. if !card_budget() {
  5869. return None;
  5870. }
  5871. self.list.cast::<ID3D12GraphicsCommandList2>().ok()?;
  5872. let buffer = host()?.uav_buffer(256)?;
  5873. name(&buffer, || "indirect budget".to_owned());
  5874. Some(buffer)
  5875. }
  5876. /// Records, before the list's first clamp, the zeroing of the card's
  5877. /// copy of the budget: common, written as a copy, then left for
  5878. /// unordered access until the list closes ([`HostList::card_budget_out`]).
  5879. fn zero_card_budget(&self, card: &ID3D12Resource) {
  5880. let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else {
  5881. return;
  5882. };
  5883. // SAFETY: a live buffer.
  5884. let at = unsafe { card.GetGPUVirtualAddress() };
  5885. let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  5886. Dest: at + offset,
  5887. Value: 0,
  5888. });
  5889. // SAFETY: an open list; the buffer is the list's own and in the
  5890. // common state at the start of every recording.
  5891. unsafe {
  5892. self.list.ResourceBarrier(&[transition(
  5893. card,
  5894. D3D12_RESOURCE_STATE_COMMON,
  5895. D3D12_RESOURCE_STATE_COPY_DEST,
  5896. )]);
  5897. list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None);
  5898. self.list.ResourceBarrier(&[transition(
  5899. card,
  5900. D3D12_RESOURCE_STATE_COPY_DEST,
  5901. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5902. )]);
  5903. }
  5904. }
  5905. /// Before the list closes, if this recording charged the card's copy
  5906. /// of the budget: its notes on mesh records go to the mapped words
  5907. /// (read at the next submission), and it goes back to common.
  5908. fn card_budget_out(&self) {
  5909. if !self.deferred().budget_zeroed {
  5910. return;
  5911. }
  5912. let (Some(Some(card)), Some(Some((mapped, _)))) =
  5913. (self.card_budget.get(), self.budget.get())
  5914. else {
  5915. return;
  5916. };
  5917. // SAFETY: an open list; both buffers are the list's own. The
  5918. // mapped one is promoted from common to the copy destination.
  5919. unsafe {
  5920. self.list.ResourceBarrier(&[transition(
  5921. card,
  5922. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  5923. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5924. )]);
  5925. self.list.CopyBufferRegion(mapped, 4, card, 4, 8);
  5926. self.list.ResourceBarrier(&[transition(
  5927. card,
  5928. D3D12_RESOURCE_STATE_COPY_SOURCE,
  5929. D3D12_RESOURCE_STATE_COMMON,
  5930. )]);
  5931. }
  5932. }
  5933. /// A device-local unordered-access buffer of at least `size` bytes for
  5934. /// clamped indirect arguments, reused across executions and resets of the
  5935. /// list. Smaller buffers replaced mid-list stay alive until
  5936. /// [`HostList::reset`].
  5937. pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> {
  5938. let needed = size.max(64 << 10);
  5939. let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner());
  5940. if let Some((buffer, cap)) = &*slot
  5941. && *cap >= needed
  5942. {
  5943. return Some(buffer.clone());
  5944. }
  5945. let prev = slot.as_ref().map_or(0, |(_, cap)| *cap);
  5946. let alloc = prev
  5947. .saturating_mul(2)
  5948. .max(needed)
  5949. .next_multiple_of(64 << 10);
  5950. let buffer = host()?.uav_buffer(alloc)?;
  5951. name(&buffer, || format!("indirect arguments {alloc:#x}"));
  5952. let old = slot.replace((buffer.clone(), alloc));
  5953. drop(slot);
  5954. if let Some((old_buf, _)) = old {
  5955. // It ends the list common, as every scratch buffer does.
  5956. self.indirect_common(&old_buf);
  5957. self.keep(&old_buf);
  5958. }
  5959. Some(buffer)
  5960. }
  5961. /// Where the next batch of clamped records goes: a device-local buffer
  5962. /// the list keeps from recording to recording, the batch's place in it
  5963. /// and the state the buffer is in. Every batch of a recording has a place
  5964. /// of its own: the executions before it may still read theirs.
  5965. pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
  5966. use crate::indirect::batch::{JOBS, SLOT};
  5967. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5968. let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
  5969. if buffer == args.0.len() {
  5970. let size = u64::from(BATCHES * JOBS * SLOT);
  5971. let made = host()?.uav_buffer(size)?;
  5972. name(&made, || format!("indirect batches {size:#x}"));
  5973. args.0.push(made);
  5974. }
  5975. args.1 += 1;
  5976. // (Its first batch finds it as the recording before left it:
  5977. // `batches_common`.)
  5978. let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
  5979. Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
  5980. }
  5981. /// Before the list closes: the scratch buffers of the batched clamps go
  5982. /// back to the common state, where the next recording expects them.
  5983. fn batches_common(&self) {
  5984. let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
  5985. let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
  5986. let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
  5987. .iter()
  5988. .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
  5989. .collect();
  5990. if !barriers.is_empty() {
  5991. // SAFETY: an open list and live buffers this recording left in
  5992. // `INDIRECT_ARGUMENT`.
  5993. unsafe { self.list.ResourceBarrier(&barriers) };
  5994. }
  5995. }
  5996. /// Moves `scratch` back to the common state if a clamp left it readable
  5997. /// as indirect arguments ([`HostList::indirect_readable`]): where the
  5998. /// list's first clamp expects it. Done before the list closes and before
  5999. /// a bigger scratch buffer replaces it: one barrier per list (where
  6000. /// there was one per indirect execution), and the list ends as it
  6001. /// begins however it is submitted.
  6002. fn indirect_common(&self, scratch: &ID3D12Resource) {
  6003. {
  6004. let mut deferred = self.deferred();
  6005. if deferred.indirect_readable != scratch.as_raw() as usize {
  6006. return;
  6007. }
  6008. deferred.indirect_readable = 0;
  6009. }
  6010. let barrier = transition(
  6011. scratch,
  6012. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  6013. D3D12_RESOURCE_STATE_COMMON,
  6014. );
  6015. // SAFETY: an open list and a live buffer this recording left in
  6016. // `INDIRECT_ARGUMENT`.
  6017. unsafe { self.list.ResourceBarrier(&[barrier]) };
  6018. }
  6019. /// The state the list's indirect scratch buffer `scratch` is in at this
  6020. /// point of the recording: indirect arguments if a clamp in this
  6021. /// recording left it so ([`HostList::indirect_readable`]), otherwise
  6022. /// common: the state a buffer is made in, and the one a recording
  6023. /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]).
  6024. pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES {
  6025. if self.deferred().indirect_readable == scratch.as_raw() as usize {
  6026. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT
  6027. } else {
  6028. D3D12_RESOURCE_STATE_COMMON
  6029. }
  6030. }
  6031. /// A clamp recorded in this list left `scratch` readable as indirect
  6032. /// arguments. It stays so for every execution that reads it, until the
  6033. /// next clamp moves it back to unordered access.
  6034. pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) {
  6035. self.deferred().indirect_readable = scratch.as_raw() as usize;
  6036. }
  6037. /// Keeps `object` alive until the list is reset.
  6038. pub(crate) fn keep(&self, object: &impl Interface) {
  6039. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  6040. self.deferred().kept.push(object);
  6041. }
  6042. }
  6043. /// Whether this is the first time since the reset that the list asks
  6044. /// about `key` (a texture to bring up to date).
  6045. pub(crate) fn first_use(&self, key: usize) -> bool {
  6046. self.deferred().textures.insert(key)
  6047. }
  6048. /// Whether `key` was asked about ([`HostList::first_use`]) since the
  6049. /// reset.
  6050. pub(crate) fn used(&self, key: usize) -> bool {
  6051. self.deferred().textures.contains(&key)
  6052. }
  6053. /// Runs `work` when the list is submitted, in order with its copies.
  6054. /// `work` may write title memory (refreshes after it copy again).
  6055. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  6056. self.deferred().copies.push(Step::Run(Box::new(work)));
  6057. self.deferred().refreshed.clear();
  6058. }
  6059. /// As [`HostList::defer`], for work that writes only host memory.
  6060. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  6061. self.deferred().copies.push(Step::Host(Box::new(work), (0, 0)));
  6062. }
  6063. /// As [`HostList::defer_host`], for work that reads `len` bytes of title
  6064. /// memory at `from`.
  6065. pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) {
  6066. self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len)));
  6067. }
  6068. /// Brings a texture's staging buffer up to date when the list is
  6069. /// submitted, keeping it alive until the list is reset.
  6070. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  6071. self.deferred().copies.push(Step::Texture(staging));
  6072. }
  6073. /// Runs the list's submission-time steps; refreshes go into `batch`
  6074. /// (the title's big buffers, a 174 MB one among them, are read by most
  6075. /// lists of a submission, through many ranges). Copies and fills that
  6076. /// `taken` names (by their place) are left out: they are done on the
  6077. /// card ([`card_steps`]).
  6078. fn run_deferred(&self, batch: &mut Batch, air: &[(usize, usize)], taken: impl Fn(usize) -> bool) {
  6079. #[cfg(feature = "diagnostics")]
  6080. use crate::copystat::{C, add};
  6081. // The time and the bytes of the copies and fills, some 13,000 a
  6082. // frame between 20,000 refreshes: summed here and added once.
  6083. let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64);
  6084. #[cfg(feature = "diagnostics")]
  6085. let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64);
  6086. for (i, step) in self.deferred().copies.iter().enumerate() {
  6087. if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) {
  6088. continue;
  6089. }
  6090. let (started, copied) = match step {
  6091. &Step::Copy(dst, src, len) => {
  6092. let started = std::time::Instant::now();
  6093. #[cfg(feature = "diagnostics")]
  6094. {
  6095. copies += 1;
  6096. }
  6097. batch.title_written();
  6098. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  6099. // With the submission's one asking: the journal learns it.
  6100. crate::watch::wrote(dst, len);
  6101. // What the card holds there may be another value although
  6102. // ours did not change.
  6103. if send::own() {
  6104. crate::shadow::send_copied(dst, len);
  6105. }
  6106. (started, len)
  6107. }
  6108. &Step::Fill(dst, src, len, _) => {
  6109. let started = std::time::Instant::now();
  6110. #[cfg(feature = "diagnostics")]
  6111. {
  6112. copies += 1;
  6113. }
  6114. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  6115. (started, len)
  6116. }
  6117. Step::Placed(p) => {
  6118. let started = std::time::Instant::now();
  6119. let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len);
  6120. if free {
  6121. batch.title_written();
  6122. }
  6123. if let Some(bytes) = p.prepare(free) {
  6124. batch.placed.push((p.shadow.clone(), p.dst, bytes));
  6125. }
  6126. (started, p.len)
  6127. }
  6128. Step::Refresh(shadow, address, len) => {
  6129. #[cfg(feature = "diagnostics")]
  6130. {
  6131. refreshes += 1;
  6132. refreshed += *len as u64;
  6133. }
  6134. batch.add(shadow, *address, *len);
  6135. continue;
  6136. }
  6137. Step::Run(work) | Step::Host(work, _) => {
  6138. #[cfg(feature = "diagnostics")]
  6139. let started = std::time::Instant::now();
  6140. if matches!(step, Step::Run(_)) {
  6141. batch.title_written();
  6142. }
  6143. work();
  6144. // It wrote title memory, where is not known here: the
  6145. // submission's one asking ends, later refreshes ask anew.
  6146. if matches!(step, Step::Run(_)) {
  6147. crate::watch::ask_once_end();
  6148. }
  6149. #[cfg(feature = "diagnostics")]
  6150. {
  6151. add(C::Runs, 1);
  6152. add(C::RunUs, started.elapsed().as_micros() as u64);
  6153. }
  6154. continue;
  6155. }
  6156. Step::GpuWrite(shadow, address, len) => {
  6157. // The shaders start from the title's data: this copy's
  6158. // pending refresh first. The other copies' wait for
  6159. // the next flush of all (flushing all of them at every
  6160. // range a dispatch writes made thousands of write-watch
  6161. // askings a frame).
  6162. batch.flush_one(shadow);
  6163. #[cfg(feature = "diagnostics")]
  6164. let snapshot = std::time::Instant::now();
  6165. shadow.writing(*address, *len);
  6166. #[cfg(feature = "diagnostics")]
  6167. {
  6168. add(C::GpuWrites, 1);
  6169. add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64);
  6170. }
  6171. continue;
  6172. }
  6173. Step::Texture(staging) => {
  6174. if batch.texture_due(staging) {
  6175. batch.due.push(staging.clone());
  6176. if !wide_textures() {
  6177. batch.refresh_textures();
  6178. }
  6179. }
  6180. continue;
  6181. }
  6182. };
  6183. us += started.elapsed();
  6184. bytes += copied as u64;
  6185. }
  6186. PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed);
  6187. PREPARING[1].fetch_add(bytes, Ordering::Relaxed);
  6188. #[cfg(feature = "diagnostics")]
  6189. {
  6190. add(C::Copies, copies);
  6191. add(C::CopyBytes, bytes);
  6192. add(C::Refreshes, refreshes);
  6193. add(C::RefreshBytes, refreshed);
  6194. SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed);
  6195. }
  6196. }
  6197. }
  6198. /// A table by a copy's address.
  6199. pub(crate) type ByCopy<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHash>>;
  6200. /// A hash for addresses of ours: the bits that tell them apart, spread. The
  6201. /// tables it serves are asked 40,000 times a frame, and hold no one's keys
  6202. /// but our own.
  6203. #[derive(Default)]
  6204. pub(crate) struct AddressHash(u64);
  6205. impl std::hash::Hasher for AddressHash {
  6206. fn finish(&self) -> u64 {
  6207. self.0
  6208. }
  6209. fn write(&mut self, bytes: &[u8]) {
  6210. for &b in bytes {
  6211. self.write_usize(usize::from(b));
  6212. }
  6213. }
  6214. fn write_usize(&mut self, n: usize) {
  6215. let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  6216. self.0 = h ^ (h >> 32);
  6217. }
  6218. }
  6219. /// Since the last frame-rate line, nanoseconds of the submitting thread's
  6220. /// preparing: the write-watch asking for a submission; the title's bytes put
  6221. /// in under flights' writes; the lists' steps, the refreshes among them; the
  6222. /// snapshots; what goes to copies in the card's memory; the lists sent; and
  6223. /// of the steps: the refreshes, and the copies and fills (those with the
  6224. /// refreshes a copy of title memory flushes). Of the asking, which ranges it
  6225. /// is of. Of the refreshes, those before ranges are given to shaders, one
  6226. /// copy at a time: nanoseconds, and how many.
  6227. #[cfg(feature = "diagnostics")]
  6228. static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
  6229. /// Since the last frame-rate line: flushes of refreshes, their refreshes,
  6230. /// those known to copy nothing, and those done on several threads.
  6231. #[cfg(feature = "diagnostics")]
  6232. static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  6233. /// Counts into [`SPLIT`].
  6234. #[cfg(feature = "diagnostics")]
  6235. struct Split(std::cell::Cell<std::time::Instant>);
  6236. #[cfg(feature = "diagnostics")]
  6237. impl Split {
  6238. fn begin() -> Split {
  6239. Split(std::cell::Cell::new(std::time::Instant::now()))
  6240. }
  6241. /// Nanoseconds since the last part.
  6242. fn so_far(&self) -> u64 {
  6243. self.0.get().elapsed().as_nanos() as u64
  6244. }
  6245. /// What came since the last part was part `i`.
  6246. fn part(&self, i: usize) {
  6247. let now = std::time::Instant::now();
  6248. SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed);
  6249. }
  6250. }
  6251. /// The split of the preparing, per frame, for the frame-rate line.
  6252. #[cfg(feature = "diagnostics")]
  6253. fn split_line(frames: f64) {
  6254. let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6255. let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  6256. let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
  6257. let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
  6258. let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
  6259. tracing::info!(
  6260. "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' \
  6261. writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
  6262. 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 \
  6263. card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
  6264. ms[0],
  6265. ms[8],
  6266. ms[1],
  6267. ms[2],
  6268. ms[6],
  6269. f[0],
  6270. f[1],
  6271. f[2],
  6272. f[3],
  6273. ms[9],
  6274. ms[10] * 1e6,
  6275. ms[7],
  6276. ms[3],
  6277. ms[4],
  6278. ms[5],
  6279. if crate::watch::light() { "on" } else { "off" },
  6280. );
  6281. tracing::info!(
  6282. "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
  6283. written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
  6284. bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
  6285. waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
  6286. as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
  6287. a[0],
  6288. a[1] / 1024.0,
  6289. a[11] / 1e6,
  6290. a[12],
  6291. a[10],
  6292. a[9],
  6293. a[2],
  6294. a[3],
  6295. a[4],
  6296. a[5],
  6297. a[6],
  6298. a[7] / 1e6,
  6299. a[8] / 1e6,
  6300. s[0] / 1048576.0,
  6301. s[1] / 1048576.0,
  6302. s[2] / 1048576.0,
  6303. s[3],
  6304. );
  6305. tracing::info!(
  6306. "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures",
  6307. h[0],
  6308. h[1],
  6309. h[2],
  6310. );
  6311. }
  6312. /// Whether a submission's refreshes of host copies run on several threads,
  6313. /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it).
  6314. ///
  6315. /// A submission brings some sixty copies up to date, one after the other
  6316. /// on the submitting thread: for each, the pages the title wrote are asked
  6317. /// for and read through the kernel into the copy. That is the frame line's
  6318. /// "copies", 45-50 ms a frame, and the copies have nothing to do with one
  6319. /// another: each refresh writes its own copy and its own notes, and reads
  6320. /// title memory. With the switch the copies of a flush (four or more) are
  6321. /// spread over the threads kept for the snapshots (`crate::shadow::wide`).
  6322. /// The write-watch journal and the guards are behind their own locks, as
  6323. /// they are for the title's threads.
  6324. fn wide_refresh() -> bool {
  6325. static ON: OnceLock<bool> = OnceLock::new();
  6326. *ON.get_or_init(|| {
  6327. wide_refresh_enabled(
  6328. std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(),
  6329. std::thread::available_parallelism().ok().map(|n| n.get()),
  6330. )
  6331. })
  6332. }
  6333. fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool {
  6334. match setting {
  6335. Some("1") => true,
  6336. Some("0") => false,
  6337. _ => logical_cpus.is_some_and(|n| n >= 4),
  6338. }
  6339. }
  6340. #[cfg(test)]
  6341. mod wide_refresh_tests {
  6342. use super::wide_refresh_enabled;
  6343. #[test]
  6344. fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() {
  6345. assert!(wide_refresh_enabled(None, Some(4)));
  6346. assert!(wide_refresh_enabled(None, Some(16)));
  6347. assert!(!wide_refresh_enabled(None, Some(2)));
  6348. assert!(!wide_refresh_enabled(None, None));
  6349. assert!(wide_refresh_enabled(Some("1"), Some(1)));
  6350. assert!(!wide_refresh_enabled(Some("0"), Some(16)));
  6351. assert!(wide_refresh_enabled(Some("auto"), Some(4)));
  6352. }
  6353. }
  6354. /// A submission's refreshes not done yet, merged per buffer copy into the
  6355. /// range that covers them: done before a step that writes title memory or
  6356. /// gives a range to shaders, and before the lists run.
  6357. ///
  6358. /// Also the textures brought up to date in the submission so far: most
  6359. /// lists of a world submission sample the same textures, and a texture in
  6360. /// physical-page memory is hashed whole each time it is checked. Checked
  6361. /// once, it is checked again only after a step that writes title memory.
  6362. #[derive(Default)]
  6363. struct Batch {
  6364. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  6365. /// Where each copy (by address) is in `refreshes`: the list that makes
  6366. /// the heap's buffers ready adds some 4,100 copies, and searching them
  6367. /// for every refresh of a submission was tens of millions of
  6368. /// comparisons a frame.
  6369. index: ByCopy<usize>,
  6370. /// Staging buffers (by address) refreshed since the last title write,
  6371. /// or due to be.
  6372. textures: std::collections::HashSet<usize>,
  6373. /// Those due ([`Batch::refresh_textures`]).
  6374. due: Vec<std::sync::Arc<crate::texture::Staging>>,
  6375. /// What copies at their place in the submission's lists put into title
  6376. /// memory ([`place`]): the host copy, the title address, the bytes.
  6377. placed: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, Vec<u8>)>,
  6378. }
  6379. /// Whether a submission's textures are brought up to date on several
  6380. /// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
  6381. /// name them, as before).
  6382. ///
  6383. /// They are read, hashed and, if they changed, detiled into their staging
  6384. /// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
  6385. /// its own buffer, notes and lock, and is refreshed by the title's own
  6386. /// threads as it is. They are done before the next step that writes title
  6387. /// memory, as the copies' refreshes are, and before the lists go to the
  6388. /// card. What is new: the note of a list that its upload takes what the
  6389. /// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
  6390. /// an earlier list of the submission asked for, not behind it. The texture
  6391. /// is then uploaded by a later list too, once more than needed.
  6392. fn wide_textures() -> bool {
  6393. static ON: OnceLock<bool> = OnceLock::new();
  6394. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
  6395. }
  6396. impl Batch {
  6397. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  6398. let end = address + len;
  6399. let key = std::sync::Arc::as_ptr(shadow) as usize;
  6400. match self.index.get(&key) {
  6401. Some(&at) => {
  6402. let r = &mut self.refreshes[at];
  6403. (r.1, r.2) = (r.1.min(address), r.2.max(end));
  6404. }
  6405. None => {
  6406. self.index.insert(key, self.refreshes.len());
  6407. self.refreshes.push((shadow.clone(), address, end));
  6408. }
  6409. }
  6410. }
  6411. /// Before shaders are given a range of `shadow`'s copy: its pending
  6412. /// refresh is done, the others stay pending.
  6413. fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
  6414. let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
  6415. return;
  6416. };
  6417. let (shadow, from, to) = self.refreshes.swap_remove(at);
  6418. // The last entry took its place.
  6419. if let Some(moved) = self.refreshes.get(at) {
  6420. self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at);
  6421. }
  6422. #[cfg(feature = "diagnostics")]
  6423. let started = std::time::Instant::now();
  6424. if !(crate::watch::light() && shadow.nothing_new(from, to - from)) {
  6425. Self::update(&shadow, from, to);
  6426. }
  6427. #[cfg(feature = "diagnostics")]
  6428. {
  6429. let ns = started.elapsed().as_nanos() as u64;
  6430. SPLIT[6].fetch_add(ns, Ordering::Relaxed);
  6431. SPLIT[9].fetch_add(ns, Ordering::Relaxed);
  6432. SPLIT[10].fetch_add(1, Ordering::Relaxed);
  6433. }
  6434. }
  6435. /// Brings `[from, to)` of a copy up to date, timed.
  6436. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
  6437. let started = std::time::Instant::now();
  6438. let copied = shadow.update(from, to - from);
  6439. let us = started.elapsed().as_micros() as u64;
  6440. #[cfg(feature = "diagnostics")]
  6441. crate::copystat::range(from, to - from, us, 0);
  6442. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  6443. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  6444. }
  6445. /// Whether `staging` is still to be refreshed in this submission (and
  6446. /// notes it refreshed).
  6447. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  6448. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  6449. }
  6450. /// Before a step that writes title memory: pending refreshes are done
  6451. /// first, and textures are checked again after it.
  6452. fn title_written(&mut self) {
  6453. self.flush();
  6454. self.textures.clear();
  6455. }
  6456. /// The textures due are brought up to date.
  6457. fn refresh_textures(&mut self) {
  6458. if self.due.len() < 2 || !wide_textures() {
  6459. self.due.drain(..).for_each(|staging| staging.refresh());
  6460. return;
  6461. }
  6462. // The time counted is the time it took, not the threads' sum.
  6463. let started = std::time::Instant::now();
  6464. let before = PREPARING[2].load(Ordering::Relaxed);
  6465. let due = std::mem::take(&mut self.due);
  6466. crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
  6467. let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
  6468. PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6469. }
  6470. fn flush(&mut self) {
  6471. self.refresh_textures();
  6472. self.index.clear();
  6473. if self.refreshes.is_empty() {
  6474. return;
  6475. }
  6476. #[cfg(feature = "diagnostics")]
  6477. let (began, all) = (std::time::Instant::now(), self.refreshes.len());
  6478. self.flush_all();
  6479. #[cfg(feature = "diagnostics")]
  6480. {
  6481. SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed);
  6482. FLUSHES[0].fetch_add(1, Ordering::Relaxed);
  6483. FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed);
  6484. }
  6485. }
  6486. fn flush_all(&mut self) {
  6487. // Most of a flush's copies are as they were: they are told so here,
  6488. // from what the submission's asking found, before anything is asked
  6489. // and any thread woken. (Thousands of them, the heap's buffer views
  6490. // once a frame: on the threads, below.)
  6491. const FEW: usize = 256;
  6492. let light = crate::watch::light();
  6493. if light && self.refreshes.len() <= FEW {
  6494. let started = std::time::Instant::now();
  6495. #[cfg(feature = "diagnostics")]
  6496. let all = self.refreshes.len();
  6497. self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
  6498. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6499. #[cfg(feature = "diagnostics")]
  6500. FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed);
  6501. }
  6502. // One write-watch asking for the copies that lie close together,
  6503. // not one per copy.
  6504. let ahead = self.refreshes.len() > 1;
  6505. if ahead {
  6506. let started = std::time::Instant::now();
  6507. let ranges: Vec<(usize, usize)> = self
  6508. .refreshes
  6509. .iter()
  6510. .filter(|r| r.0.asked_ahead())
  6511. .map(|r| (r.1, r.2))
  6512. .collect();
  6513. crate::watch::ask_ahead(&ranges);
  6514. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  6515. }
  6516. if wide_refresh() && self.refreshes.len() >= 4 {
  6517. // Each copy on its own, several at a time: a copy's refresh
  6518. // writes that copy and reads title memory, nothing of another's.
  6519. // The time counted is the time it took, not the threads' sum.
  6520. let started = std::time::Instant::now();
  6521. let before = PREPARING[0].load(Ordering::Relaxed);
  6522. #[cfg(feature = "diagnostics")]
  6523. FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
  6524. if light {
  6525. // A number to a free thread, not a job to each copy.
  6526. let refreshes = std::mem::take(&mut self.refreshes);
  6527. crate::shadow::wide_each(refreshes.len(), move |i| {
  6528. let (shadow, from, to) = &refreshes[i];
  6529. if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) {
  6530. #[cfg(feature = "diagnostics")]
  6531. FLUSHES[2].fetch_add(1, Ordering::Relaxed);
  6532. return;
  6533. }
  6534. Self::update(shadow, *from, *to);
  6535. });
  6536. } else {
  6537. let jobs: Vec<Box<dyn FnOnce() + Send>> = self
  6538. .refreshes
  6539. .drain(..)
  6540. .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>)
  6541. .collect();
  6542. crate::shadow::wide_run(jobs);
  6543. }
  6544. let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before);
  6545. PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
  6546. } else {
  6547. for (shadow, from, to) in self.refreshes.drain(..) {
  6548. Self::update(&shadow, from, to);
  6549. }
  6550. }
  6551. if ahead {
  6552. crate::watch::ask_ahead_done();
  6553. }
  6554. }
  6555. }
  6556. /// Copies title memory at submission. The ranges were checked against their
  6557. /// resources when recorded, but the title may since have unmapped pages of
  6558. /// them (tiled memory, page mappings), which read as zeros here; a title
  6559. /// destination (`title_dst`) that is not all mapped is left alone.
  6560. ///
  6561. /// The source is read through the kernel (`ReadProcessMemory`), which
  6562. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  6563. /// cost about 2 ms per copy in the title's big pools (it walks the page
  6564. /// tables to the region's end), which made copies run at 100-200 MB/s.
  6565. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  6566. #[cfg(feature = "diagnostics")]
  6567. match crate::copystat::mode() {
  6568. 1 => {
  6569. // SAFETY: timing only: the caller vouches for the source.
  6570. unsafe { std::ptr::copy(src, dst, len) };
  6571. return;
  6572. }
  6573. 2 => return,
  6574. _ => {}
  6575. }
  6576. if len == 0 {
  6577. return;
  6578. }
  6579. // A title destination that is not all mapped is left alone. Asking
  6580. // Windows first (`VirtualQuery`) walks the page tables to the end of
  6581. // the destination's region: in the title's big blocks that is
  6582. // milliseconds a copy, and it was a seventh of the submitting thread's
  6583. // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below
  6584. // says the same when it fails, so the question is only asked then.
  6585. // `VICTORY_COPY_ASK=1` asks first, as before.
  6586. static ASK: OnceLock<bool> = OnceLock::new();
  6587. let ask_first = title_dst
  6588. && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1"));
  6589. if ask_first && !crate::texture::committed(dst, len) {
  6590. return;
  6591. }
  6592. if title_dst {
  6593. // The kernel writes the destination: it must not be guarded.
  6594. crate::watch::writing(dst as usize, len);
  6595. }
  6596. #[cfg(feature = "diagnostics")]
  6597. let moved = std::time::Instant::now();
  6598. let since = crate::watch::changes();
  6599. // (A title destination that is away only while the runtime changes a
  6600. // mapping beside it is written when that is done.)
  6601. let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
  6602. #[cfg(feature = "diagnostics")]
  6603. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  6604. if whole {
  6605. return;
  6606. }
  6607. // The copy failed: a source page is not there, or the destination is
  6608. // not all mapped. Then the destination stays as it is (the kernel may
  6609. // have written its first pages).
  6610. if title_dst && !ask_first && !crate::texture::committed(dst, len) {
  6611. crate::watch::lost("a copy of the title's", dst as usize, len);
  6612. return;
  6613. }
  6614. #[cfg(feature = "diagnostics")]
  6615. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  6616. #[cfg(feature = "diagnostics")]
  6617. let sparse = std::time::Instant::now();
  6618. if !title_dst && len >= 64 << 10 {
  6619. read_sparse(src, dst, len);
  6620. } else {
  6621. read_pieces(src, dst, len);
  6622. }
  6623. #[cfg(feature = "diagnostics")]
  6624. crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64);
  6625. }
  6626. /// After a failed bulk read into host memory, skip contiguous holes. Never
  6627. /// cache the query across copies: the title may remap the same address.
  6628. fn read_sparse(src: *const u8, dst: *mut u8, len: usize) {
  6629. use windows_sys::Win32::System::Memory::{
  6630. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery,
  6631. };
  6632. let mut offset = 0;
  6633. while offset < len {
  6634. let at = src.wrapping_add(offset);
  6635. let to = dst.wrapping_add(offset);
  6636. let remaining = len - offset;
  6637. // SAFETY: the query inspects an address and fills a local structure.
  6638. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  6639. let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) };
  6640. let n = (info.BaseAddress as usize).saturating_add(info.RegionSize)
  6641. .saturating_sub(at as usize).min(remaining);
  6642. if size != size_of_val(&info) || n == 0 {
  6643. read_pieces(at, to, remaining);
  6644. break;
  6645. }
  6646. if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS {
  6647. #[cfg(feature = "diagnostics")]
  6648. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6649. // SAFETY: this path is only used with a writable host destination.
  6650. unsafe { to.write_bytes(0, n) };
  6651. } else if !read(at, to, n) {
  6652. // A mapping may change between query and read.
  6653. read_pieces(at, to, n);
  6654. }
  6655. offset += n;
  6656. }
  6657. }
  6658. fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
  6659. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  6660. // that fails), zeros for what cannot be read.
  6661. for_pieces(src as usize, len, 64 << 10, |at, n| {
  6662. let to = dst.wrapping_add(at - src as usize);
  6663. if !read(at as *const u8, to, n) {
  6664. for_pieces(at, n, 4 << 10, |at, n| {
  6665. let to = dst.wrapping_add(at - src as usize);
  6666. if !read(at as *const u8, to, n) {
  6667. #[cfg(feature = "diagnostics")]
  6668. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  6669. zero(to, n);
  6670. }
  6671. });
  6672. }
  6673. });
  6674. }
  6675. /// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
  6676. /// destination of a title's copy), which can go between the question whether
  6677. /// it is there and this.
  6678. fn zero(to: *mut u8, n: usize) {
  6679. static ZEROS: [u8; 4096] = [0; 4096];
  6680. if n <= ZEROS.len() && crate::safecopy::on() {
  6681. // SAFETY: a destination that is not there fails the copy.
  6682. if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
  6683. crate::watch::lost("zeros", to as usize, n);
  6684. }
  6685. return;
  6686. }
  6687. // SAFETY: inside the destination, which is mapped.
  6688. unsafe { to.write_bytes(0, n) };
  6689. }
  6690. /// Reads title memory at `src` into `dst`; false if a page of it is not
  6691. /// readable.
  6692. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  6693. read(src, dst.as_mut_ptr(), dst.len())
  6694. }
  6695. /// Reads what is there of the `dst.len()` bytes of title memory at `src`,
  6696. /// zeros for the rest; returns how many bytes were there. Safe while the
  6697. /// runtime remaps title memory (the kernel, or a copy that takes the fault,
  6698. /// reads). What the runtime's record says is mapped is read in one go each,
  6699. /// and by pieces where that fails; memory it has no record of by pieces.
  6700. pub(crate) fn read_there(src: *const u8, dst: &mut [u8]) -> usize {
  6701. dst.fill(0);
  6702. let (start, len) = (src as usize, dst.len());
  6703. let mut got = 0;
  6704. let mut runs = crate::inplace::shown_runs(start, len);
  6705. if runs.is_empty() {
  6706. runs.push((start, len));
  6707. }
  6708. for (at, n) in runs {
  6709. let piece = &mut dst[at - start..at - start + n];
  6710. if read_into(at as *const u8, piece) {
  6711. got += n;
  6712. continue;
  6713. }
  6714. // (What failed may have written its first pages.)
  6715. piece.fill(0);
  6716. for_pieces(at, n, 64 << 10, |from, n| {
  6717. let piece = &mut dst[from - start..from - start + n];
  6718. if read_into(from as *const u8, piece) {
  6719. got += n;
  6720. return;
  6721. }
  6722. piece.fill(0);
  6723. for_pieces(from, n, 4 << 10, |from, n| {
  6724. let piece = &mut dst[from - start..from - start + n];
  6725. if read_into(from as *const u8, piece) {
  6726. got += n;
  6727. } else {
  6728. piece.fill(0);
  6729. }
  6730. });
  6731. });
  6732. }
  6733. got
  6734. }
  6735. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  6736. /// readable.
  6737. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  6738. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  6739. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6740. if crate::safecopy::on() {
  6741. // SAFETY: the destination is mapped writable memory of `len` bytes;
  6742. // a source page that is not there fails the copy.
  6743. return unsafe { crate::safecopy::copy(dst, src, len) };
  6744. }
  6745. let mut done = 0;
  6746. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  6747. // kernel checks the source.
  6748. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  6749. }
  6750. #[link(name = "ntdll", kind = "raw-dylib")]
  6751. unsafe extern "system" {
  6752. /// The kernel's write into a process's memory, `(process, address,
  6753. /// bytes, length, written out)`: an NTSTATUS, negative when a page of
  6754. /// the range is not there or not writable. It changes no protection.
  6755. fn NtWriteVirtualMemory(
  6756. process: *mut std::ffi::c_void,
  6757. base: *mut std::ffi::c_void,
  6758. buffer: *const std::ffi::c_void,
  6759. size: usize,
  6760. written: *mut usize,
  6761. ) -> i32;
  6762. }
  6763. /// Whether title memory is written with the kernel's own call
  6764. /// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks
  6765. /// what the pages are (as `VirtualQuery` does: about 2 ms a call in the
  6766. /// title's big pools, see [`copy_mapped`]): putting back what shaders wrote
  6767. /// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size
  6768. /// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before.
  6769. fn direct_writes() -> bool {
  6770. static ON: OnceLock<bool> = OnceLock::new();
  6771. *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0"))
  6772. }
  6773. /// Copies host memory into title memory after a submission (what shaders
  6774. /// wrote), leaving pages that are not mapped alone.
  6775. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  6776. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  6777. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  6778. let direct = direct_writes();
  6779. let since = crate::watch::changes();
  6780. let write = |at: usize, n: usize| {
  6781. let from = src.wrapping_add(at - dst as usize);
  6782. if crate::safecopy::on() {
  6783. // SAFETY: the source is ours; a destination page that is not
  6784. // there, or not writable, fails the copy.
  6785. return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
  6786. }
  6787. let mut done = 0;
  6788. if direct {
  6789. // SAFETY: as below; the kernel checks the destination and
  6790. // writes nothing it cannot (the caller opened its guards:
  6791. // `crate::watch::writing`).
  6792. return unsafe {
  6793. NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0
  6794. };
  6795. }
  6796. // SAFETY: the source is our mapped host copy; the kernel checks the
  6797. // destination.
  6798. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  6799. };
  6800. if len == 0 || write(dst as usize, len) {
  6801. return;
  6802. }
  6803. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  6804. if !write(at, n) {
  6805. for_pieces(at, n, 4 << 10, |at, n| {
  6806. if write(at, n) {
  6807. return;
  6808. }
  6809. // The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
  6810. // refresh guarded the block again since the caller opened
  6811. // it; and any where the runtime was changing a mapping.
  6812. crate::watch::writing(at, n);
  6813. if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
  6814. crate::watch::lost("a host copy's bytes", at, n);
  6815. }
  6816. });
  6817. }
  6818. });
  6819. }
  6820. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  6821. /// `step`.
  6822. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  6823. let end = start + len;
  6824. let mut at = start;
  6825. while at < end {
  6826. let next = ((at / step + 1) * step).min(end);
  6827. f(at, next - at);
  6828. at = next;
  6829. }
  6830. }
  6831. impl Host {
  6832. /// The queue everything of ours runs on, for a call that must go to it
  6833. /// in order with the lists (`crate::tiles`: a texture's levels are
  6834. /// given memory ahead of the list that uploads them).
  6835. pub(crate) fn queue(&self) -> &ID3D12CommandQueue {
  6836. &self.queue
  6837. }
  6838. /// A buffer in the upload heap, mapped for writing.
  6839. /// A buffer of `size` bytes the card writes and we read (a read back),
  6840. /// in the state copies into it need.
  6841. pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  6842. let heap = D3D12_HEAP_PROPERTIES {
  6843. Type: D3D12_HEAP_TYPE_READBACK,
  6844. ..Default::default()
  6845. };
  6846. let desc = D3D12_RESOURCE_DESC {
  6847. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6848. Width: size.max(1),
  6849. Height: 1,
  6850. DepthOrArraySize: 1,
  6851. MipLevels: 1,
  6852. SampleDesc: DXGI_SAMPLE_DESC {
  6853. Count: 1,
  6854. Quality: 0,
  6855. },
  6856. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6857. ..Default::default()
  6858. };
  6859. let mut buffer: Option<ID3D12Resource> = None;
  6860. // SAFETY: plain creation of a read-back buffer.
  6861. let made = unsafe {
  6862. self.device.CreateCommittedResource(
  6863. &heap,
  6864. D3D12_HEAP_FLAG_NONE,
  6865. &desc,
  6866. D3D12_RESOURCE_STATE_COPY_DEST,
  6867. None,
  6868. &mut buffer,
  6869. )
  6870. };
  6871. match made {
  6872. Ok(()) => buffer,
  6873. Err(e) => {
  6874. tracing::warn!(error = %e, size, "no read-back buffer");
  6875. None
  6876. }
  6877. }
  6878. }
  6879. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  6880. MADE[0].fetch_add(1, Ordering::Relaxed);
  6881. MADE[1].fetch_add(size, Ordering::Relaxed);
  6882. let heap = D3D12_HEAP_PROPERTIES {
  6883. Type: D3D12_HEAP_TYPE_UPLOAD,
  6884. ..Default::default()
  6885. };
  6886. let desc = D3D12_RESOURCE_DESC {
  6887. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  6888. Width: size.max(1),
  6889. Height: 1,
  6890. DepthOrArraySize: 1,
  6891. MipLevels: 1,
  6892. SampleDesc: DXGI_SAMPLE_DESC {
  6893. Count: 1,
  6894. Quality: 0,
  6895. },
  6896. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  6897. ..Default::default()
  6898. };
  6899. let mut buffer: Option<ID3D12Resource> = None;
  6900. let mut data = std::ptr::null_mut();
  6901. // SAFETY: plain creation and mapping of an upload buffer.
  6902. let made = unsafe {
  6903. self.device
  6904. .CreateCommittedResource(
  6905. &heap,
  6906. D3D12_HEAP_FLAG_NONE,
  6907. &desc,
  6908. D3D12_RESOURCE_STATE_GENERIC_READ,
  6909. None,
  6910. &mut buffer,
  6911. )
  6912. .and_then(|()| {
  6913. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  6914. b.Map(0, None, Some(&mut data))
  6915. })
  6916. };
  6917. match made {
  6918. Ok(()) => Some((buffer?, data.cast())),
  6919. Err(e) => {
  6920. tracing::warn!(error = %e, size, "no upload buffer");
  6921. None
  6922. }
  6923. }
  6924. }
  6925. }
  6926. /// The swap chain formats a presented texture can be copied into: its own
  6927. /// family's.
  6928. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  6929. Some(match format.0 {
  6930. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  6931. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  6932. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  6933. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  6934. _ => return None,
  6935. })
  6936. }
  6937. const BUFFERS: u32 = 2;
  6938. struct Presenter {
  6939. swap_chain: IDXGISwapChain3,
  6940. width: u32,
  6941. height: u32,
  6942. format: DXGI_FORMAT,
  6943. copy: HostList,
  6944. /// With presents sent ahead ([`late_free_present`]): a list for each
  6945. /// present in the air, and the submission it last flew as (it is used
  6946. /// again once that one has finished).
  6947. ahead: Vec<(HostList, u64)>,
  6948. hwnd: HWND,
  6949. meter: Meter,
  6950. }
  6951. /// The frame rate, shown in the window's caption every second and logged
  6952. /// every few seconds.
  6953. struct Meter {
  6954. since: std::time::Instant,
  6955. frames: u32,
  6956. #[cfg(feature = "diagnostics")]
  6957. copy_stats_frames: u64,
  6958. drawn: u64,
  6959. logged: std::time::Instant,
  6960. /// The caption the window had, once read.
  6961. caption: Option<Vec<u16>>,
  6962. }
  6963. impl Meter {
  6964. fn new() -> Self {
  6965. let now = std::time::Instant::now();
  6966. Meter {
  6967. since: now,
  6968. frames: 0,
  6969. #[cfg(feature = "diagnostics")]
  6970. copy_stats_frames: 0,
  6971. drawn: crate::draw::drawn(),
  6972. logged: now,
  6973. caption: None,
  6974. }
  6975. }
  6976. /// Counts a presented frame.
  6977. fn frame(&mut self, hwnd: HWND) {
  6978. #[cfg(feature = "diagnostics")]
  6979. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  6980. #[cfg(feature = "diagnostics")]
  6981. crate::copystat::presented();
  6982. self.frames += 1;
  6983. #[cfg(feature = "diagnostics")]
  6984. {
  6985. self.copy_stats_frames += 1;
  6986. }
  6987. let elapsed = self.since.elapsed();
  6988. if elapsed < std::time::Duration::from_secs(1) {
  6989. return;
  6990. }
  6991. let drawn = crate::draw::drawn();
  6992. let frames = f64::from(self.frames);
  6993. let fps = frames / elapsed.as_secs_f64();
  6994. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  6995. let draws = (drawn - self.drawn) as f64 / frames;
  6996. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  6997. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  6998. let [cpu, gpu] = [0, 1].map(|i| {
  6999. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  7000. });
  7001. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  7002. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  7003. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  7004. });
  7005. let [back_ms, back_mb] = [0, 1].map(|i| {
  7006. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  7007. });
  7008. let dropped = crate::draw::take_dropped() as f64 / frames;
  7009. let indirect = crate::list::take_indirect() as f64 / frames;
  7010. let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
  7011. let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
  7012. tracing::info!(
  7013. "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
  7014. );
  7015. crate::shadow::exact_line(frames);
  7016. crate::descriptor::sync_line(frames);
  7017. late_line(frames);
  7018. card_clock_line(frames, ms);
  7019. #[cfg(feature = "diagnostics")]
  7020. spans::line(frames);
  7021. crate::shadow::back_line(frames);
  7022. #[cfg(feature = "diagnostics")]
  7023. split_line(frames);
  7024. {
  7025. let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7026. if passes + compares > 0.0 {
  7027. tracing::info!(
  7028. "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
  7029. ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
  7030. if rehash_runs() { "on" } else { "off" }
  7031. );
  7032. }
  7033. }
  7034. {
  7035. let [own, asking, still, all] =
  7036. [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
  7037. if all >= 1.0 {
  7038. tracing::info!(
  7039. "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \
  7040. is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \
  7041. hold still (the runtime remapping it); the rest is reading, hashing and detiling"
  7042. );
  7043. }
  7044. let [through, left, filled, short] =
  7045. [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7046. if through + left + filled > 0.0 {
  7047. tracing::info!(
  7048. "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \
  7049. {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \
  7050. {filled:.1} first fillings from the pages there (VICTORY_TEXTURE_FILL=0: left empty), {short:.1} of them \
  7051. with less than was mapped (looked at again)"
  7052. );
  7053. }
  7054. }
  7055. {
  7056. let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7057. if copies > 0.0 {
  7058. tracing::info!(
  7059. "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \
  7060. (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {})",
  7061. if join_copies() { "on" } else { "off" }
  7062. );
  7063. }
  7064. }
  7065. // Passes over the heap's buffer views for shaders that pick them by index.
  7066. let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames;
  7067. let picked_ms =
  7068. crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames;
  7069. // Copies between depth textures and their colour twins, each way.
  7070. let [twin_to_depth, twin_to_colour] =
  7071. [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7072. // Depth planes drawn from their twins.
  7073. let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames;
  7074. // Copies in the card's memory (`crate::shadow::cards`).
  7075. let card = crate::shadow::card_stats();
  7076. #[cfg(feature = "diagnostics")]
  7077. let slow = crate::watch::slow_asks();
  7078. // Over the same frames as the counts above.
  7079. #[cfg(feature = "diagnostics")]
  7080. let drops = crate::pipeline::take_drops();
  7081. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  7082. self.logged = std::time::Instant::now();
  7083. tracing::info!(
  7084. "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)",
  7085. crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed)
  7086. );
  7087. crate::tiles::status();
  7088. {
  7089. let [queued, due, away, partly, oldest] =
  7090. [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed));
  7091. let [same, parts, tails] =
  7092. [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed));
  7093. tracing::info!(
  7094. "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \
  7095. {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \
  7096. the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \
  7097. as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \
  7098. {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \
  7099. {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \
  7100. {} made slots found unmapped and made null",
  7101. crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed),
  7102. crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed),
  7103. crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed),
  7104. crate::descriptor::host::STALE[0].load(Ordering::Relaxed),
  7105. crate::descriptor::host::STALE[1].load(Ordering::Relaxed),
  7106. crate::descriptor::host::STALE[2].load(Ordering::Relaxed),
  7107. crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
  7108. crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
  7109. );
  7110. }
  7111. {
  7112. let mode = crate::watch::page_writes();
  7113. let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
  7114. let [kept, dropped, slots, uploaded] =
  7115. [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
  7116. tracing::info!(
  7117. "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)",
  7118. bytes >> 20,
  7119. if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
  7120. if mode & 4 != 0 { "told as well" } else { "counted only" },
  7121. if mode & 2 != 0 { "made due again" } else { "left as they were" }
  7122. );
  7123. }
  7124. #[cfg(feature = "diagnostics")]
  7125. tracing::info!(
  7126. "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms",
  7127. slow[0] as f64 / frames,
  7128. slow[1] as f64 / 1e3 / frames,
  7129. slow[2] as f64 / 1e3
  7130. );
  7131. if crate::shadow::cards() {
  7132. let per_frame = |i: usize| card[i] as f64 / frames;
  7133. tracing::info!(
  7134. "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \
  7135. {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \
  7136. ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)",
  7137. card[7],
  7138. card[8] >> 20,
  7139. card[9] >> 20,
  7140. per_frame(0) / 1e6,
  7141. per_frame(1),
  7142. per_frame(2),
  7143. per_frame(3),
  7144. per_frame(4) / 1e6,
  7145. per_frame(5),
  7146. per_frame(6) / 1e3
  7147. );
  7148. }
  7149. tracing::info!(
  7150. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  7151. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  7152. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  7153. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  7154. {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
  7155. textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
  7156. {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}",
  7157. picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
  7158. picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20,
  7159. picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed),
  7160. picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed),
  7161. du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed),
  7162. du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed),
  7163. du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed),
  7164. du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed),
  7165. refused = format!(
  7166. "{} ({} 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",
  7167. crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed),
  7168. crate::shadow::OWN_MADE.load(Ordering::Relaxed),
  7169. crate::resource::TWINS[0].load(Ordering::Relaxed),
  7170. crate::resource::TWINS[1].load(Ordering::Relaxed),
  7171. crate::resource::PLANES[1].load(Ordering::Relaxed),
  7172. crate::resource::PLANES[2].load(Ordering::Relaxed)
  7173. ),
  7174. making = crate::pipeline::making(),
  7175. placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed),
  7176. objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed)
  7177. );
  7178. #[cfg(feature = "diagnostics")]
  7179. {
  7180. let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
  7181. tracing::info!(
  7182. "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
  7183. put[0],
  7184. put[1],
  7185. put[2] / 1e6,
  7186. put[3]
  7187. );
  7188. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  7189. for (why, n) in drops.iter().take(40) {
  7190. tracing::info!(
  7191. "dropped {:.1}/frame without a host pipeline: {why}",
  7192. *n as f64 / frames
  7193. );
  7194. }
  7195. }
  7196. }
  7197. if self.caption.is_none() {
  7198. // The window's own text, read without a message.
  7199. let mut buffer = vec![0u16; 512];
  7200. // SAFETY: a window handle and a buffer of that length.
  7201. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  7202. buffer.truncate(n.max(0) as usize);
  7203. self.caption = Some(buffer);
  7204. }
  7205. let Some(caption) = &self.caption else { return };
  7206. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  7207. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  7208. text.push(0);
  7209. // Setting the text waits for the window's thread (a title thread,
  7210. // which may not pump for a while), so a thread of ours does it and
  7211. // presenting never waits; it takes the newest text when free.
  7212. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  7213. static SETTER: std::sync::Once = std::sync::Once::new();
  7214. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  7215. SETTER.call_once(|| {
  7216. let _ = std::thread::Builder::new()
  7217. .name("victory-caption".into())
  7218. .spawn(|| {
  7219. loop {
  7220. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  7221. match next {
  7222. // SAFETY: a window handle and a NUL-terminated text.
  7223. Some((hwnd, text)) => unsafe {
  7224. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  7225. },
  7226. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  7227. }
  7228. }
  7229. });
  7230. });
  7231. }
  7232. }
  7233. impl Host {
  7234. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  7235. /// as frame `frame` (saved if captures are on). `None` if nothing was
  7236. /// shown; else, in diagnostics builds, whether the frame was black.
  7237. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  7238. // SAFETY: a live resource.
  7239. let desc = unsafe { texture.GetDesc() };
  7240. let Some(format) = swap_format(desc.Format) else {
  7241. tracing::warn!(format = desc.Format.0, "cannot present this format");
  7242. return None;
  7243. };
  7244. let (width, height) = (desc.Width as u32, desc.Height);
  7245. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  7246. if presenter.is_none() {
  7247. *presenter = match self.presenter(width, height, format) {
  7248. Ok(p) => Some(p),
  7249. Err(e) => {
  7250. tracing::warn!(error = %e, "no swap chain");
  7251. return None;
  7252. }
  7253. };
  7254. }
  7255. let p = presenter.as_mut()?;
  7256. if (p.width, p.height, p.format) != (width, height, format) {
  7257. // Presents sent ahead hold back buffers until they have run.
  7258. settle_now(WHY_SYNC);
  7259. // SAFETY: no back buffer is held; every submission was waited for.
  7260. let resized = unsafe {
  7261. p.swap_chain
  7262. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  7263. };
  7264. match resized {
  7265. Ok(()) => {
  7266. (p.width, p.height, p.format) = (width, height, format);
  7267. tracing::info!(
  7268. width,
  7269. height,
  7270. format = format.0,
  7271. frame,
  7272. "the swap chain's buffers were made again for another size or format"
  7273. );
  7274. self.log_video_memory("right after the swap chain's buffers were made again");
  7275. }
  7276. Err(e) => {
  7277. tracing::warn!(error = %e, width, height, "swap chain not resized");
  7278. return None;
  7279. }
  7280. }
  7281. }
  7282. let state = D3D12_RESOURCE_STATES(state as i32);
  7283. // SAFETY: our swap chain, list and a live source texture.
  7284. unsafe {
  7285. let index = p.swap_chain.GetCurrentBackBufferIndex();
  7286. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  7287. return None;
  7288. };
  7289. // Sent ahead ([`late_free_present`]) unless the frame is to be
  7290. // read back at once (a saved or listed frame): then a list of
  7291. // its own, one whose last flight has finished or a new one.
  7292. #[cfg(feature = "diagnostics")]
  7293. let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame);
  7294. #[cfg(not(feature = "diagnostics"))]
  7295. let read_now = false;
  7296. let slot = if late_free_present() && !read_now {
  7297. let finished = FINISHED.load(Ordering::Acquire);
  7298. p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| {
  7299. let list = self.new_list().ok()?;
  7300. list.close();
  7301. p.ahead.push((list, 0));
  7302. Some(p.ahead.len() - 1)
  7303. })
  7304. } else {
  7305. None
  7306. };
  7307. let copy = match slot {
  7308. Some(i) => &p.ahead[i].0,
  7309. None => &p.copy,
  7310. };
  7311. copy.reset();
  7312. let list = &copy.list;
  7313. list.ResourceBarrier(&[
  7314. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  7315. transition(
  7316. &back,
  7317. D3D12_RESOURCE_STATE_PRESENT,
  7318. D3D12_RESOURCE_STATE_COPY_DEST,
  7319. ),
  7320. ]);
  7321. list.CopyResource(&back, texture);
  7322. #[cfg(feature = "diagnostics")]
  7323. let capture = crate::capture::wanted(frame)
  7324. .then(|| crate::capture::read_back(&self.device, list, texture))
  7325. .flatten();
  7326. #[cfg(feature = "diagnostics")]
  7327. let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
  7328. #[cfg(not(feature = "diagnostics"))]
  7329. let _ = frame;
  7330. list.ResourceBarrier(&[
  7331. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  7332. transition(
  7333. &back,
  7334. D3D12_RESOURCE_STATE_COPY_DEST,
  7335. D3D12_RESOURCE_STATE_PRESENT,
  7336. ),
  7337. ]);
  7338. copy.close();
  7339. match slot {
  7340. Some(i) => {
  7341. let flown = self.execute_own(copy);
  7342. p.ahead[i].1 = flown;
  7343. }
  7344. None => self.execute(&[copy]),
  7345. }
  7346. #[cfg(feature = "diagnostics")]
  7347. if let Some((buffer, footprint)) = capture {
  7348. crate::capture::save_read_back(frame, &buffer, &footprint);
  7349. }
  7350. #[cfg(feature = "diagnostics")]
  7351. crate::replay::record::present(texture, state);
  7352. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  7353. p.meter.frame(p.hwnd);
  7354. #[cfg(feature = "diagnostics")]
  7355. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  7356. #[cfg(not(feature = "diagnostics"))]
  7357. Some(false)
  7358. }
  7359. }
  7360. fn presenter(
  7361. &self,
  7362. width: u32,
  7363. height: u32,
  7364. format: DXGI_FORMAT,
  7365. ) -> windows::core::Result<Presenter> {
  7366. let hwnd = match title_window() {
  7367. Some(hwnd) => hwnd,
  7368. None => window(width, height)?,
  7369. };
  7370. self.log_video_memory("right before the swap chain is made");
  7371. // SAFETY: plain object creation for our window.
  7372. unsafe {
  7373. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  7374. let desc = DXGI_SWAP_CHAIN_DESC1 {
  7375. Width: width,
  7376. Height: height,
  7377. Format: format,
  7378. SampleDesc: DXGI_SAMPLE_DESC {
  7379. Count: 1,
  7380. Quality: 0,
  7381. },
  7382. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  7383. BufferCount: BUFFERS,
  7384. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  7385. ..Default::default()
  7386. };
  7387. let swap_chain = factory
  7388. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  7389. .cast::<IDXGISwapChain3>()?;
  7390. let copy = self.new_list()?;
  7391. copy.close();
  7392. tracing::info!(width, height, format = format.0, "presenting to a window");
  7393. self.log_video_memory("right after the swap chain is made");
  7394. Ok(Presenter {
  7395. swap_chain,
  7396. width,
  7397. height,
  7398. format,
  7399. copy,
  7400. ahead: Vec::new(),
  7401. hwnd,
  7402. meter: Meter::new(),
  7403. })
  7404. }
  7405. }
  7406. }
  7407. /// A visible top-level window of this process: the one the title made, if
  7408. /// it made one.
  7409. fn title_window() -> Option<HWND> {
  7410. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  7411. let mut process = 0;
  7412. // SAFETY: a window handle from the enumeration; `found` is ours.
  7413. unsafe {
  7414. GetWindowThreadProcessId(hwnd, Some(&mut process));
  7415. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  7416. && IsWindowVisible(hwnd).as_bool()
  7417. {
  7418. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  7419. return false.into();
  7420. }
  7421. }
  7422. true.into()
  7423. }
  7424. let mut found: Option<HWND> = None;
  7425. // SAFETY: the callback only writes `found`, which outlives the call.
  7426. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  7427. found
  7428. }
  7429. /// `state` without the bits the host texture's flags forbid: the console
  7430. /// lets the title name states its own resources allow (unordered access on
  7431. /// a depth target, whose host copy cannot have both).
  7432. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  7433. // SAFETY: a plain query.
  7434. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  7435. }
  7436. /// [`legal_state`] for a texture with resource flags `flags`.
  7437. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  7438. // (flag, set or clear forbids, state bits): render target, unordered
  7439. // access, depth, denied shader resource.
  7440. const FORBIDDEN: [(u32, bool, u32); 4] = [
  7441. (0x1, false, 0x4),
  7442. (0x4, false, 0x8),
  7443. (0x2, false, 0x10 | 0x20),
  7444. (0x8, true, 0x40 | 0x80),
  7445. ];
  7446. FORBIDDEN
  7447. .iter()
  7448. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  7449. .fold(state, |s, &(_, _, bits)| s & !bits)
  7450. }
  7451. impl Host {
  7452. /// The card's memory as the system accounts it to this process, in
  7453. /// bytes: the budget and the use of the card's own memory, then of the
  7454. /// PC's memory shared with the card (where the system moves what does
  7455. /// not fit on the card).
  7456. pub(crate) fn video_memory(&self) -> Option<[u64; 4]> {
  7457. let adapter = self.adapter.as_ref()?;
  7458. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7459. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7460. // SAFETY: plain queries that fill our structures.
  7461. unsafe {
  7462. adapter
  7463. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7464. .ok()?;
  7465. adapter
  7466. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7467. .ok()?;
  7468. }
  7469. // The card's budget moved by 256 MB or more since the last look:
  7470. // said at once, with what was in use at the last look, so the log
  7471. // has the moment. (It fell from 11,242 MB to some 10,300 MB with
  7472. // the first world frame in runs 179 to 185, and the memory line,
  7473. // seconds later, was the first to show it. We reserve nothing
  7474. // and make the swap chain once, at the start.)
  7475. static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  7476. let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
  7477. let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
  7478. if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
  7479. tracing::info!(
  7480. "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",
  7481. last[0] >> 20,
  7482. own.Budget >> 20,
  7483. crate::frame::current(),
  7484. last[1] >> 20,
  7485. last[2] >> 20
  7486. );
  7487. self.log_video_memory("right after that change");
  7488. }
  7489. Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
  7490. }
  7491. /// Both of the system's memory groups for this process, in bytes: for
  7492. /// the card's own memory and then for the PC's memory shared with the
  7493. /// card, the budget, the use, what could still be reserved and what
  7494. /// is reserved (the layer reserves none).
  7495. pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
  7496. let adapter = self.adapter.as_ref()?;
  7497. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7498. let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  7499. // SAFETY: plain queries that fill our structures.
  7500. unsafe {
  7501. adapter
  7502. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  7503. .ok()?;
  7504. adapter
  7505. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
  7506. .ok()?;
  7507. }
  7508. let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
  7509. [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
  7510. };
  7511. Some([all(&own), all(&shared)])
  7512. }
  7513. /// Logs [`Self::video_memory_groups`], with `when` it is said.
  7514. pub(crate) fn log_video_memory(&self, when: &str) {
  7515. let Some([own, shared]) = self.video_memory_groups() else {
  7516. return;
  7517. };
  7518. tracing::info!(
  7519. "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)",
  7520. when,
  7521. own[0] >> 20,
  7522. own[1] >> 20,
  7523. own[2] >> 20,
  7524. own[3] >> 20,
  7525. shared[0] >> 20,
  7526. shared[1] >> 20,
  7527. shared[2] >> 20,
  7528. shared[3] >> 20
  7529. );
  7530. }
  7531. /// A buffer in system memory that the CPU maps (write-back, so reading
  7532. /// it is fast too) and shaders read and write: for host copies of title
  7533. /// memory that shaders write, which upload memory cannot be. Starts in
  7534. /// the common state (buffers move out of it implicitly).
  7535. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  7536. MADE[2].fetch_add(1, Ordering::Relaxed);
  7537. MADE[3].fetch_add(size, Ordering::Relaxed);
  7538. let heap = D3D12_HEAP_PROPERTIES {
  7539. Type: D3D12_HEAP_TYPE_CUSTOM,
  7540. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  7541. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  7542. ..Default::default()
  7543. };
  7544. let desc = D3D12_RESOURCE_DESC {
  7545. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7546. Width: size.max(1),
  7547. Height: 1,
  7548. DepthOrArraySize: 1,
  7549. MipLevels: 1,
  7550. SampleDesc: DXGI_SAMPLE_DESC {
  7551. Count: 1,
  7552. Quality: 0,
  7553. },
  7554. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7555. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7556. ..Default::default()
  7557. };
  7558. let mut buffer: Option<ID3D12Resource> = None;
  7559. let mut data = std::ptr::null_mut();
  7560. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7561. let made = unsafe {
  7562. self.device
  7563. .CreateCommittedResource(
  7564. &heap,
  7565. D3D12_HEAP_FLAG_NONE,
  7566. &desc,
  7567. D3D12_RESOURCE_STATE_COMMON,
  7568. None,
  7569. &mut buffer,
  7570. )
  7571. .and_then(|()| {
  7572. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7573. b.Map(0, None, Some(&mut data))
  7574. })
  7575. };
  7576. match made {
  7577. Ok(()) => Some((buffer?, data.cast())),
  7578. Err(e) => {
  7579. tracing::warn!(error = %e, size, "no shared buffer");
  7580. None
  7581. }
  7582. }
  7583. }
  7584. /// Whether buffers can lie in the card's memory and be mapped by the CPU
  7585. /// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver
  7586. /// that offer it); logged once.
  7587. pub(crate) fn mapped_card_memory(&self) -> bool {
  7588. static THERE: OnceLock<bool> = OnceLock::new();
  7589. *THERE.get_or_init(|| {
  7590. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default();
  7591. // SAFETY: writes `options` of the given size.
  7592. let ok = unsafe {
  7593. self.device
  7594. .CheckFeatureSupport(
  7595. D3D12_FEATURE_D3D12_OPTIONS16,
  7596. (&raw mut options).cast(),
  7597. size_of_val(&options) as u32,
  7598. )
  7599. .is_ok()
  7600. };
  7601. let supported = ok && options.GPUUploadHeapSupported.as_bool();
  7602. tracing::info!(supported, "card memory the CPU maps");
  7603. supported
  7604. })
  7605. }
  7606. /// A buffer in the card's own memory that the CPU maps, shaders read and
  7607. /// (with `written`) may write. The CPU should only write it: a read of the
  7608. /// mapping crosses the bus a few bytes at a time.
  7609. pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> {
  7610. if !self.mapped_card_memory() {
  7611. return None;
  7612. }
  7613. MADE[4].fetch_add(1, Ordering::Relaxed);
  7614. MADE[5].fetch_add(size, Ordering::Relaxed);
  7615. let heap = D3D12_HEAP_PROPERTIES {
  7616. Type: D3D12_HEAP_TYPE_GPU_UPLOAD,
  7617. ..Default::default()
  7618. };
  7619. let desc = D3D12_RESOURCE_DESC {
  7620. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7621. Width: size.max(1),
  7622. Height: 1,
  7623. DepthOrArraySize: 1,
  7624. MipLevels: 1,
  7625. SampleDesc: DXGI_SAMPLE_DESC {
  7626. Count: 1,
  7627. Quality: 0,
  7628. },
  7629. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7630. Flags: if written {
  7631. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
  7632. } else {
  7633. D3D12_RESOURCE_FLAG_NONE
  7634. },
  7635. ..Default::default()
  7636. };
  7637. let mut buffer: Option<ID3D12Resource> = None;
  7638. let mut data = std::ptr::null_mut();
  7639. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  7640. let made = unsafe {
  7641. self.device
  7642. .CreateCommittedResource(
  7643. &heap,
  7644. D3D12_HEAP_FLAG_NONE,
  7645. &desc,
  7646. D3D12_RESOURCE_STATE_COMMON,
  7647. None,
  7648. &mut buffer,
  7649. )
  7650. .and_then(|()| {
  7651. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  7652. b.Map(0, None, Some(&mut data))
  7653. })
  7654. };
  7655. match made {
  7656. Ok(()) => Some((buffer?, data.cast())),
  7657. Err(e) => {
  7658. tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps");
  7659. None
  7660. }
  7661. }
  7662. }
  7663. /// A device-local buffer shaders may write (unordered access) and indirect
  7664. /// execution may read, starting in the common state.
  7665. pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
  7666. MADE[4].fetch_add(1, Ordering::Relaxed);
  7667. MADE[5].fetch_add(size, Ordering::Relaxed);
  7668. let heap = D3D12_HEAP_PROPERTIES {
  7669. Type: D3D12_HEAP_TYPE_DEFAULT,
  7670. ..Default::default()
  7671. };
  7672. let desc = D3D12_RESOURCE_DESC {
  7673. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  7674. Width: size.max(1),
  7675. Height: 1,
  7676. DepthOrArraySize: 1,
  7677. MipLevels: 1,
  7678. SampleDesc: DXGI_SAMPLE_DESC {
  7679. Count: 1,
  7680. Quality: 0,
  7681. },
  7682. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  7683. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  7684. ..Default::default()
  7685. };
  7686. let mut buffer: Option<ID3D12Resource> = None;
  7687. // SAFETY: plain creation of a device-local buffer.
  7688. let made = unsafe {
  7689. self.device.CreateCommittedResource(
  7690. &heap,
  7691. D3D12_HEAP_FLAG_NONE,
  7692. &desc,
  7693. D3D12_RESOURCE_STATE_COMMON,
  7694. None,
  7695. &mut buffer,
  7696. )
  7697. };
  7698. match made {
  7699. Ok(()) => buffer,
  7700. Err(e) => {
  7701. tracing::warn!(error = %e, size, "no unordered-access buffer");
  7702. None
  7703. }
  7704. }
  7705. }
  7706. }
  7707. /// For adapters without device-removed data (the software one): the last
  7708. /// commands each list of the failed submission noted (diagnostics, with
  7709. /// `VICTORY_D3D12_DRED`).
  7710. fn last_notes(runs: &[&HostList]) -> String {
  7711. #[cfg(feature = "diagnostics")]
  7712. {
  7713. let mut text = String::new();
  7714. for (i, r) in runs.iter().enumerate() {
  7715. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  7716. for (n, _) in notes.iter().rev().take(6).rev() {
  7717. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  7718. }
  7719. }
  7720. text
  7721. }
  7722. #[cfg(not(feature = "diagnostics"))]
  7723. {
  7724. let _ = runs;
  7725. String::new()
  7726. }
  7727. }
  7728. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  7729. /// command reads (diagnostics).
  7730. #[cfg(feature = "diagnostics")]
  7731. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  7732. let end = start + bytes;
  7733. if va < start {
  7734. format!(" (fault {:#x} below its source)", start - va)
  7735. } else if va < end {
  7736. format!(" (fault at source +{:#x})", va - start)
  7737. } else {
  7738. format!(" (fault {:#x} past its source's end)", va - end)
  7739. }
  7740. }
  7741. /// The commands that may have been running where a list stopped at
  7742. /// command `done`: those between the barriers around it (work between
  7743. /// barriers overlaps on the GPU), by kind, and what the markers just
  7744. /// before them say (`HostList::note_op`: diagnostics builds with
  7745. /// device-removed data on).
  7746. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  7747. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  7748. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  7749. let to = history[done..]
  7750. .iter()
  7751. .position(barrier)
  7752. .map_or(history.len(), |b| (done + b).max(done + 1));
  7753. let mut text = format!(", commands {from}..{to} between its barriers:");
  7754. let mut shown = 0;
  7755. // From just before the command the GPU had not finished: the first
  7756. // twelve after the barrier named draws long done when a list of 79
  7757. // mesh draws stopped at its 45th (run 41).
  7758. for i in from.max(done.saturating_sub(4))..to {
  7759. let op = history[i];
  7760. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  7761. continue;
  7762. }
  7763. shown += 1;
  7764. let marker = i
  7765. .checked_sub(1)
  7766. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  7767. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  7768. .map_or("no marker", |(_, s)| s.as_str());
  7769. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  7770. }
  7771. text
  7772. }
  7773. pub(crate) fn transition(
  7774. resource: &ID3D12Resource,
  7775. before: D3D12_RESOURCE_STATES,
  7776. after: D3D12_RESOURCE_STATES,
  7777. ) -> D3D12_RESOURCE_BARRIER {
  7778. D3D12_RESOURCE_BARRIER {
  7779. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  7780. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  7781. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  7782. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  7783. // SAFETY: a borrowed pointer; the barrier never releases it.
  7784. pResource: unsafe { std::mem::transmute_copy(resource) },
  7785. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  7786. StateBefore: before,
  7787. StateAfter: after,
  7788. }),
  7789. },
  7790. }
  7791. }
  7792. /// A window of the given client size, owned by its own message thread.
  7793. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7794. let (sender, receiver) = std::sync::mpsc::channel();
  7795. std::thread::Builder::new()
  7796. .name("victory-window".into())
  7797. .spawn(move || {
  7798. let made = make_window(width, height);
  7799. let ok = made.is_ok();
  7800. let _ = sender.send(made.map(|h| h.0 as usize));
  7801. if ok {
  7802. pump();
  7803. }
  7804. })
  7805. .map_err(|_| windows::core::Error::empty())?;
  7806. let hwnd = receiver
  7807. .recv()
  7808. .map_err(|_| windows::core::Error::empty())??;
  7809. Ok(HWND(hwnd as *mut _))
  7810. }
  7811. extern "system" fn window_proc(
  7812. hwnd: HWND,
  7813. message: u32,
  7814. wparam: WPARAM,
  7815. lparam: LPARAM,
  7816. ) -> LRESULT {
  7817. // SAFETY: the default handling for our window.
  7818. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  7819. }
  7820. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  7821. const CLASS: PCWSTR = w!("VIctory");
  7822. // SAFETY: registers our class once and creates a window of it.
  7823. unsafe {
  7824. let instance = GetModuleHandleW(None)?;
  7825. let class = WNDCLASSEXW {
  7826. cbSize: size_of::<WNDCLASSEXW>() as u32,
  7827. lpfnWndProc: Some(window_proc),
  7828. hInstance: instance.into(),
  7829. lpszClassName: CLASS,
  7830. hCursor: LoadCursorW(None, IDC_ARROW)?,
  7831. ..Default::default()
  7832. };
  7833. RegisterClassExW(&class);
  7834. let mut rect = RECT {
  7835. left: 0,
  7836. top: 0,
  7837. right: width as i32,
  7838. bottom: height as i32,
  7839. };
  7840. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  7841. CreateWindowExW(
  7842. WINDOW_EX_STYLE(0),
  7843. CLASS,
  7844. w!("VIctory"),
  7845. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  7846. CW_USEDEFAULT,
  7847. CW_USEDEFAULT,
  7848. rect.right - rect.left,
  7849. rect.bottom - rect.top,
  7850. None,
  7851. None,
  7852. Some(instance.into()),
  7853. None,
  7854. )
  7855. }
  7856. }
  7857. fn pump() {
  7858. let mut message = MSG::default();
  7859. // SAFETY: the standard message loop of this thread's window.
  7860. unsafe {
  7861. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  7862. let _ = TranslateMessage(&message);
  7863. DispatchMessageW(&message);
  7864. }
  7865. }
  7866. }
  7867. #[cfg(test)]
  7868. mod trail {
  7869. /// The trail keeps the newest things, and the report made when the
  7870. /// host device is removed says them and the pipeline library's state
  7871. /// (no card is asked for any of it).
  7872. #[test]
  7873. fn the_removal_report_says_the_newest_things_done() {
  7874. for n in 0..super::TRAIL_MOST + 5 {
  7875. super::trail(|| format!("thing {n} done"));
  7876. }
  7877. let text = super::removal_context();
  7878. assert!(text.contains("the submitting thread was"));
  7879. assert!(text.contains("pipeline library: no call running"));
  7880. assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4)));
  7881. assert!(!text.contains("thing 4 done"), "the oldest entries are dropped");
  7882. }
  7883. }
  7884. #[cfg(test)]
  7885. mod spare {
  7886. use super::Spare;
  7887. /// Kept things come back by size, the last given first, and nothing is
  7888. /// kept past the limit.
  7889. #[test]
  7890. fn kept_things_come_back_by_size_within_the_limit() {
  7891. let mut spare: Spare<u32> = Spare::new();
  7892. assert_eq!(spare.take(4), None);
  7893. assert_eq!(spare.give(1, 4, 10), None);
  7894. assert_eq!(spare.give(2, 1, 10), None);
  7895. assert_eq!(spare.give(3, 4, 10), None);
  7896. assert_eq!(spare.bytes, 9);
  7897. // Past the limit: handed back, nothing changes.
  7898. assert_eq!(spare.give(4, 4, 10), Some(4));
  7899. assert_eq!(spare.bytes, 9);
  7900. assert_eq!(spare.take(2), None, "no thing of that size");
  7901. assert_eq!(spare.take(4), Some(3));
  7902. assert_eq!(spare.take(4), Some(1));
  7903. assert_eq!(spare.take(4), None);
  7904. assert_eq!(spare.take(1), Some(2));
  7905. assert_eq!(spare.bytes, 0);
  7906. assert!(spare.kept.is_empty());
  7907. }
  7908. }
  7909. #[cfg(test)]
  7910. mod refresh_tests {
  7911. use super::Batch;
  7912. use crate::shadow::Shadow;
  7913. use std::sync::Arc;
  7914. use windows_sys::Win32::System::Memory::{
  7915. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
  7916. VirtualAlloc,
  7917. };
  7918. const PAGE: usize = 64 << 10;
  7919. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  7920. /// Title memory for the tests (never given back: copies of it stay in
  7921. /// the guards): write-watched, or a view of a section.
  7922. fn title(len: usize, view: bool) -> usize {
  7923. // SAFETY: plain allocations.
  7924. let at = unsafe {
  7925. if view {
  7926. let section =
  7927. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  7928. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  7929. // As the runtime tells of it.
  7930. crate::title_memory_section(section as usize, len as u64, true);
  7931. crate::title_memory_remapped(at, len);
  7932. crate::title_memory_view(at, len, section as usize, 0);
  7933. at
  7934. } else {
  7935. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize
  7936. }
  7937. };
  7938. assert_ne!(at, 0);
  7939. at
  7940. }
  7941. /// Title memory of `blocks` pages in a placeholder, one view to a page,
  7942. /// and every fourth page not there: as a title that streams has it.
  7943. fn with_holes(blocks: usize) -> usize {
  7944. use windows_sys::Win32::System::Memory::{
  7945. MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
  7946. VirtualAlloc2, VirtualFree,
  7947. };
  7948. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  7949. // SAFETY: a placeholder and a section of our own.
  7950. unsafe {
  7951. let at = VirtualAlloc2(
  7952. GetCurrentProcess(),
  7953. std::ptr::null(),
  7954. blocks * PAGE,
  7955. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  7956. PAGE_NOACCESS,
  7957. std::ptr::null_mut(),
  7958. 0,
  7959. ) as usize;
  7960. assert_ne!(at, 0);
  7961. let len = blocks * PAGE;
  7962. let section =
  7963. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
  7964. for block in (0..blocks).filter(|b| b % 4 != 3) {
  7965. let to = at + block * PAGE;
  7966. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  7967. let view = MapViewOfFile3(
  7968. section,
  7969. GetCurrentProcess(),
  7970. to as *const _,
  7971. (block * PAGE) as u64,
  7972. PAGE,
  7973. MEM_REPLACE_PLACEHOLDER,
  7974. PAGE_READWRITE,
  7975. std::ptr::null_mut(),
  7976. 0,
  7977. );
  7978. assert_eq!(view.Value as usize, to);
  7979. crate::title_memory_remapped(to, PAGE);
  7980. }
  7981. at
  7982. }
  7983. }
  7984. fn memory(len: usize) -> *mut u8 {
  7985. // SAFETY: a plain allocation.
  7986. unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
  7987. }
  7988. struct Random(u64);
  7989. impl Random {
  7990. fn below(&mut self, n: usize) -> usize {
  7991. self.0 ^= self.0 << 13;
  7992. self.0 ^= self.0 >> 7;
  7993. self.0 ^= self.0 << 17;
  7994. (self.0 >> 11) as usize % n
  7995. }
  7996. }
  7997. /// Prepares as a submission does: one asking for all the ranges, the
  7998. /// refreshes in several flushes, the asking's end.
  7999. fn submission(ranges: &[(Arc<Shadow>, usize, usize)], flushes: usize) {
  8000. // One at a time, as submissions are.
  8001. static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
  8002. let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
  8003. let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect();
  8004. crate::watch::ask_once(&asked);
  8005. let mut batch = Batch::default();
  8006. for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) {
  8007. for (shadow, at, len) in part {
  8008. batch.add(shadow, *at, *len);
  8009. }
  8010. batch.flush();
  8011. }
  8012. crate::watch::ask_once_end();
  8013. }
  8014. /// Whatever is written where, by the title or by us, and whichever
  8015. /// copies (of both kinds of memory, over one another, none on a page
  8016. /// line) are refreshed in which ranges: a refreshed range holds what
  8017. /// title memory holds.
  8018. #[test]
  8019. fn refreshed_ranges_hold_title_memory() {
  8020. // SAFETY (all blocks): title memory and copies of the test's own,
  8021. // written by this thread and, in `Batch::flush`, by the threads that
  8022. // refresh, which are done when it returns.
  8023. let mut random = Random(0x1234_5678_9ABC_DEF1);
  8024. const LEN: usize = 24 * PAGE;
  8025. let regions = [title(LEN, false), title(LEN, true)];
  8026. let mut copies = Vec::new();
  8027. for &region in &regions {
  8028. for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] {
  8029. let data = memory(to - from);
  8030. copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data));
  8031. }
  8032. }
  8033. let byte = |at: usize| unsafe { (at as *const u8).read_volatile() };
  8034. for round in 0..600 {
  8035. for _ in 0..random.below(4) {
  8036. let at = regions[random.below(2)] + random.below(LEN - 64);
  8037. let n = 1 + random.below(60);
  8038. if random.below(3) == 0 {
  8039. // What shaders wrote.
  8040. let was: Vec<u8> = (0..n).map(|i| byte(at + i)).collect();
  8041. let now: Vec<u8> = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect();
  8042. Shadow::put(at, &was, &now);
  8043. assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put");
  8044. continue;
  8045. }
  8046. for i in 0..n {
  8047. unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) };
  8048. }
  8049. }
  8050. let mut ranges = Vec::new();
  8051. for (shadow, _) in &copies {
  8052. if random.below(3) == 0 {
  8053. continue;
  8054. }
  8055. let (start, len) = shadow.span();
  8056. let (start, len) = (start as usize, len as usize);
  8057. // Often the range of the time before, as a list's is.
  8058. let from = if random.below(2) == 0 { 0 } else { random.below(len) };
  8059. let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) };
  8060. ranges.push((shadow.clone(), start + from, n));
  8061. }
  8062. if ranges.is_empty() {
  8063. continue;
  8064. }
  8065. let flushes = 1 + random.below(3);
  8066. submission(&ranges, flushes);
  8067. for (shadow, at, n) in &ranges {
  8068. let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1;
  8069. let start = shadow.span().0 as usize;
  8070. let same = unsafe {
  8071. std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n)
  8072. };
  8073. assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at));
  8074. }
  8075. }
  8076. }
  8077. /// A copy in the card's memory, with the card's side and the sends to it
  8078. /// played by the test.
  8079. struct Carded {
  8080. shadow: Arc<Shadow>,
  8081. data: usize,
  8082. start: usize,
  8083. len: usize,
  8084. /// The last send, the last send every fetch to come is behind, and
  8085. /// the card's bytes: the queue's order is the order it is locked in.
  8086. card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
  8087. /// Whether a flight that writes it has not landed.
  8088. flying: std::sync::atomic::AtomicBool,
  8089. /// The dword of each eight its shaders write.
  8090. class: usize,
  8091. }
  8092. impl Carded {
  8093. fn new(start: usize, len: usize, class: usize) -> Carded {
  8094. let data = memory(len);
  8095. Carded {
  8096. shadow: Shadow::unbacked(start as u64, data, len as u64, true),
  8097. data: data as usize,
  8098. start,
  8099. len,
  8100. card: std::sync::Mutex::new((0, 0, vec![0; len])),
  8101. flying: std::sync::atomic::AtomicBool::new(false),
  8102. class,
  8103. }
  8104. }
  8105. /// What changed on the CPU's side goes up.
  8106. fn send(&self) {
  8107. let mut card = self.card.lock().unwrap();
  8108. card.0 += 1;
  8109. let (number, merged) = (card.0, card.1);
  8110. for (a, b) in self.shadow.send_up(number, merged) {
  8111. // SAFETY: the copy's bytes; nothing writes those that are to
  8112. // go up.
  8113. unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
  8114. }
  8115. }
  8116. }
  8117. /// Everything at once: the title writes its memory on two threads, the
  8118. /// submitting thread puts its bytes in under shader writes
  8119. /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
  8120. /// the card's memory, one not), sends up what changed and declares what
  8121. /// the next flight's shaders write, and what flights wrote is landed
  8122. /// meanwhile (`crate::land`, beside the guards). When all of it stands
  8123. /// still and the copies are refreshed once more, each of them, and the
  8124. /// card's side of those that have one, hold what title memory holds, and
  8125. /// title memory what was written last.
  8126. ///
  8127. /// Into the first copy shaders write besides through a view nobody
  8128. /// declared, words the title does not write: nothing that goes up ever
  8129. /// puts an older value over those.
  8130. ///
  8131. /// (It fails in the first rounds if `landed_beside` notes nothing, or
  8132. /// only takes the block out of the guards' clean ones and leaves its bit,
  8133. /// or if a fault leaves the bit; in some thousand rounds,
  8134. /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
  8135. #[test]
  8136. fn landings_title_writes_and_light_refreshes_at_once() {
  8137. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  8138. assert!(crate::safecopy::on());
  8139. const LEN: usize = 24 * PAGE;
  8140. let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
  8141. let region = title(LEN, true);
  8142. let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
  8143. let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
  8144. let plain = {
  8145. let (start, len) = (region + 700, LEN - 9000);
  8146. let data = memory(len);
  8147. (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
  8148. };
  8149. // What was last written so, by offset.
  8150. let mut undeclared = std::collections::HashMap::new();
  8151. let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0");
  8152. let stop = AtomicBool::new(false);
  8153. // Also when an assertion fails on one of the threads.
  8154. struct Stop<'a>(&'a AtomicBool);
  8155. impl Drop for Stop<'_> {
  8156. fn drop(&mut self) {
  8157. self.0.store(true, Ordering::Relaxed);
  8158. }
  8159. }
  8160. // Held shared by who writes title memory, alone while it is looked at.
  8161. let still = std::sync::RwLock::new(());
  8162. let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
  8163. std::thread::scope(|s| {
  8164. for t in 0..2usize {
  8165. let (stop, still) = (&stop, &still);
  8166. s.spawn(move || {
  8167. let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
  8168. let mut value = 0u32;
  8169. while !stop.load(Ordering::Relaxed) {
  8170. {
  8171. let _moving = still.read().unwrap();
  8172. for _ in 0..3 {
  8173. value += 1;
  8174. // Of each eight dwords, one a thread.
  8175. let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
  8176. dword(at).store(value, Ordering::Relaxed);
  8177. }
  8178. }
  8179. std::thread::sleep(std::time::Duration::from_micros(20));
  8180. }
  8181. });
  8182. }
  8183. // Lands flights.
  8184. {
  8185. let (carded, stop) = (&carded, &stop);
  8186. s.spawn(move || {
  8187. let _stop = Stop(stop);
  8188. while let Ok((which, ranges, value)) = flights.recv() {
  8189. let c = &carded[which];
  8190. // Fetched: the card's bytes, behind every send so far.
  8191. let (after, now) = {
  8192. let card = c.card.lock().unwrap();
  8193. (card.0, card.2.clone())
  8194. };
  8195. // By piece: 64 KiB of title memory.
  8196. let mut pieces = Vec::new();
  8197. for &(from, to) in &ranges {
  8198. let mut at = from;
  8199. while at < to {
  8200. let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
  8201. pieces.push((at, next, now.as_ptr() as usize + at));
  8202. at = next;
  8203. }
  8204. }
  8205. let parts: Vec<_> = pieces.chunks(3).collect();
  8206. crate::land::each(parts.len(), &|i| {
  8207. let mut notes = crate::land::Notes::default();
  8208. // SAFETY: the bytes of `now`; each piece once.
  8209. unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
  8210. notes.flush();
  8211. });
  8212. for &(from, to) in &ranges {
  8213. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8214. // (The next fetch may have brought more.)
  8215. assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
  8216. }
  8217. }
  8218. let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
  8219. c.shadow.copy_back_done(&done);
  8220. c.card.lock().unwrap().1 = after;
  8221. c.flying.store(false, Ordering::Release);
  8222. }
  8223. });
  8224. }
  8225. let _stop = Stop(&stop);
  8226. let mut random = Random(0xABCD_EF01_2345_6789);
  8227. let check = |round: usize, random: &mut Random, quiet: bool| {
  8228. for c in &carded {
  8229. if c.shadow.writes_pending() {
  8230. let mut runs = usize::MAX;
  8231. assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
  8232. }
  8233. }
  8234. let mut ranges = Vec::new();
  8235. for (shadow, start, len) in
  8236. carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
  8237. {
  8238. // All of it, or a part; often the same part.
  8239. let (from, n) = match random.below(3) {
  8240. _ if quiet => (0, len),
  8241. 0 => (0, len),
  8242. 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
  8243. _ => {
  8244. let from = random.below(len / 4) * 4;
  8245. (from, (4 + random.below((len - from) / 4) * 4).min(len - from))
  8246. }
  8247. };
  8248. ranges.push((shadow.clone(), start + from, n));
  8249. }
  8250. submission(&ranges, 1 + random.below(3));
  8251. carded.iter().for_each(Carded::send);
  8252. };
  8253. let mut value = 1u32;
  8254. for round in 0..rounds {
  8255. check(round, &mut random, false);
  8256. if exact {
  8257. let c = &carded[0];
  8258. let mut card = c.card.lock().unwrap();
  8259. for _ in 0..40 {
  8260. value += 1;
  8261. let at = random.below(LEN / 32) * 32 + 4 * 6;
  8262. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8263. undeclared.insert(at, value);
  8264. }
  8265. }
  8266. // The flight of this submission: its shaders' writes.
  8267. for (which, c) in carded.iter().enumerate() {
  8268. if c.flying.swap(true, Ordering::Acquire) {
  8269. continue;
  8270. }
  8271. value += 1;
  8272. let mut ranges: Vec<(usize, usize)> = Vec::new();
  8273. let first = random.below(6) * PAGE / 2;
  8274. for k in 0..2 {
  8275. let from = first + k * 9 * PAGE + 4 * random.below(9000);
  8276. let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
  8277. if from < to {
  8278. ranges.push((from, to));
  8279. }
  8280. }
  8281. for &(from, to) in &ranges {
  8282. c.shadow.writing(c.start + from, to - from);
  8283. }
  8284. {
  8285. let mut card = c.card.lock().unwrap();
  8286. for &(from, to) in &ranges {
  8287. for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
  8288. card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
  8289. }
  8290. }
  8291. }
  8292. fly.send((which, ranges, value)).unwrap();
  8293. }
  8294. if round % 20 != 19 {
  8295. continue;
  8296. }
  8297. // Still: no flight in the air, no title write.
  8298. let _still = still.write().unwrap();
  8299. while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
  8300. assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
  8301. std::thread::yield_now();
  8302. }
  8303. check(round, &mut random, true);
  8304. // SAFETY: the test's own memory, written by nobody now.
  8305. let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
  8306. let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
  8307. for c in &carded {
  8308. let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
  8309. assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
  8310. let card = c.card.lock().unwrap();
  8311. let mut side = card.2.clone();
  8312. if c.class == carded[0].class {
  8313. // (They may have been landed meanwhile, by a flight
  8314. // that declared their range, and may not.)
  8315. for (&at, &value) in &undeclared {
  8316. let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
  8317. assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
  8318. side[at..at + 4].copy_from_slice(&there[at..at + 4]);
  8319. }
  8320. }
  8321. assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
  8322. }
  8323. assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
  8324. }
  8325. drop(fly);
  8326. });
  8327. }
  8328. /// The title's bytes put in under shader writes, for a copy of 174 MB
  8329. /// whose shader writes were declared as 40 ranges that overlap, with 12
  8330. /// pages written since. Run with `--ignored --nocapture`, and with
  8331. /// `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8332. #[test]
  8333. #[ignore]
  8334. fn bytes_under_overlapping_ranges() {
  8335. const BIG: usize = 174 << 20;
  8336. let big = title(BIG, true);
  8337. // SAFETY (both): the test's own memory.
  8338. unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
  8339. let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8340. copy.update(big, BIG);
  8341. copy.take_dirty();
  8342. for i in 0..40 {
  8343. copy.writing(big + i * 5920, BIG - i * 5920);
  8344. }
  8345. let mut best = f64::MAX;
  8346. for round in 0..30 {
  8347. for i in 0..12 {
  8348. unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
  8349. }
  8350. let started = std::time::Instant::now();
  8351. let mut runs = usize::MAX;
  8352. assert!(!copy.merge_under_writes(big, BIG, &mut runs));
  8353. best = best.min(started.elapsed().as_secs_f64() * 1e3);
  8354. copy.take_dirty();
  8355. }
  8356. println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
  8357. }
  8358. /// A range nothing wrote is known to be as it was, at its ends too, and
  8359. /// is so no more once something wrote it.
  8360. #[test]
  8361. fn unchanged_ranges_are_known() {
  8362. for view in [false, true] {
  8363. let region = title(8 * PAGE, view);
  8364. // (A page read for the first time counts as written.)
  8365. // SAFETY: the test's own memory.
  8366. unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) };
  8367. let data = memory(8 * PAGE);
  8368. let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false);
  8369. // Ends in the middle of pages.
  8370. let (at, len) = (region + 500, 5 * PAGE);
  8371. let look = |expected: bool, what: &str| {
  8372. // The submission's one asking, which takes two ranges. (Again
  8373. // if a submission of another test ended it.)
  8374. let mut known = false;
  8375. for _ in 0..100 {
  8376. crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]);
  8377. known = copy.nothing_new(at, len);
  8378. if known || !expected {
  8379. break;
  8380. }
  8381. }
  8382. assert_eq!(known, expected, "view {view}: {what}");
  8383. let copied = copy.update(at, len);
  8384. crate::watch::ask_once_end();
  8385. copied
  8386. };
  8387. assert_eq!(look(false, "never taken"), len);
  8388. assert_eq!(look(true, "taken"), 0);
  8389. assert_eq!(look(true, "taken"), 0);
  8390. // SAFETY: the test's own memory.
  8391. unsafe { ((region + 600) as *mut u8).write_volatile(1) };
  8392. assert_eq!(look(false, "written at its end"), PAGE - 500);
  8393. assert_eq!(look(true, "taken again"), 0);
  8394. // Outside the range, on its last page.
  8395. // SAFETY: as above.
  8396. unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) };
  8397. assert_eq!(look(false, "written on its last page"), 500);
  8398. // A longer range was never taken whole.
  8399. assert!(!copy.nothing_new(region, 6 * PAGE));
  8400. }
  8401. }
  8402. /// Of a copy in the card's memory only the dwords title memory changed go
  8403. /// up, and none beside them, not even between two in 64 bytes; a page
  8404. /// never taken goes up whole.
  8405. #[test]
  8406. fn only_what_differs_goes_up() {
  8407. let region = title(4 * PAGE, true);
  8408. let data = memory(4 * PAGE);
  8409. let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true);
  8410. copy.update(region, 4 * PAGE);
  8411. assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change");
  8412. // What the relay does: shader writes into title memory, and into the
  8413. // CPU's side.
  8414. crate::watch::landing(region + PAGE + 640, 64);
  8415. // SAFETY: the test's own memory.
  8416. unsafe {
  8417. std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64);
  8418. std::ptr::write_bytes(data.add(PAGE + 640), 7, 64);
  8419. }
  8420. copy.update(region, 4 * PAGE);
  8421. let again = copy.take_dirty();
  8422. // SAFETY: as above.
  8423. unsafe {
  8424. ((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
  8425. ((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
  8426. ((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
  8427. // The value that was there.
  8428. ((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
  8429. }
  8430. copy.update(region, 4 * PAGE);
  8431. let written = copy.take_dirty();
  8432. if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0") {
  8433. assert_eq!(again, []);
  8434. assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
  8435. } else {
  8436. assert_eq!(again, [(PAGE, 2 * PAGE)]);
  8437. assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
  8438. }
  8439. // SAFETY: as above.
  8440. assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
  8441. }
  8442. /// The refreshes of a frame as run record-1 had them: 30 submissions, the
  8443. /// first with a copy for each of 4,400 ranges, the others with 60 and a
  8444. /// big copy that 55 landed pieces and 9 title writes opened, while a
  8445. /// thread lands what shaders wrote. Run with `--ignored --nocapture`,
  8446. /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was.
  8447. #[test]
  8448. #[ignore]
  8449. fn frame_of_refreshes() {
  8450. let mut random = Random(0x9876_5432_1234_5671);
  8451. const EACH: usize = 224 << 10;
  8452. const BIG: usize = 174 << 20;
  8453. let watched = title(3000 * EACH, false);
  8454. // `VICTORY_BENCH_HOLES=0`: views without holes.
  8455. let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
  8456. let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
  8457. let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
  8458. let big = title(BIG, true);
  8459. // SAFETY: the test's own memory.
  8460. unsafe {
  8461. std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
  8462. for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
  8463. std::ptr::write_bytes(at as *mut u8, 1, PAGE);
  8464. }
  8465. std::ptr::write_bytes(big as *mut u8, 1, BIG);
  8466. }
  8467. let mut small = Vec::new();
  8468. for i in 0..4400 {
  8469. let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) };
  8470. let data = memory(EACH);
  8471. // The range views read, not all of the copy.
  8472. small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
  8473. }
  8474. let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
  8475. // The same memory, as another copy: what is landed is landed through
  8476. // it, and the refreshes are of the first.
  8477. let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
  8478. let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
  8479. let (mut sum, mut landing) = (0.0, 0.0);
  8480. const FRAMES: usize = 12;
  8481. for frame in 0..FRAMES {
  8482. let mut took = [0f64; 2];
  8483. for i in 0..30 {
  8484. // The title's writes, and the relay's beside the submission.
  8485. for _ in 0..9 {
  8486. let at = views + random.below(1400 * EACH / 8) * 8;
  8487. if there(at) {
  8488. // SAFETY: the test's own memory.
  8489. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8490. }
  8491. }
  8492. for _ in 0..60 {
  8493. let at = watched + random.below(3000 * EACH / 8) * 8;
  8494. // SAFETY: the test's own memory.
  8495. unsafe { (at as *mut u64).write_volatile(frame as u64) };
  8496. }
  8497. let first = random.below(BIG / PAGE - 60);
  8498. let lands = lands.clone();
  8499. let land = std::thread::spawn(move || {
  8500. let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
  8501. let started = std::time::Instant::now();
  8502. for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
  8503. let pieces: Vec<_> =
  8504. pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
  8505. let mut notes = crate::land::Notes::default();
  8506. // SAFETY: the bytes of `now`; nothing else lands here.
  8507. unsafe { lands.land_card(&pieces, 0, &mut notes) };
  8508. notes.flush();
  8509. }
  8510. started.elapsed().as_secs_f64() * 1e3
  8511. });
  8512. let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
  8513. small.iter().cloned().chain([heap.clone()]).collect()
  8514. } else {
  8515. (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect()
  8516. };
  8517. let started = std::time::Instant::now();
  8518. submission(&ranges, 3);
  8519. took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3;
  8520. let put = land.join().unwrap();
  8521. if frame >= 2 {
  8522. landing += put;
  8523. }
  8524. heap.0.take_dirty();
  8525. }
  8526. if frame >= 2 {
  8527. sum += took[0] + took[1];
  8528. for k in 0..2 {
  8529. best[k] = best[k].min(took[k]);
  8530. asking[k] += took[k];
  8531. }
  8532. }
  8533. }
  8534. println!(
  8535. "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \
  8536. others {:.2} (best {:.2}); the landing thread's puts {:.2}",
  8537. crate::watch::light(),
  8538. sum / (FRAMES - 2) as f64,
  8539. asking[0] / (FRAMES - 2) as f64,
  8540. best[0],
  8541. asking[1] / (FRAMES - 2) as f64,
  8542. best[1],
  8543. landing / (FRAMES - 2) as f64,
  8544. );
  8545. #[cfg(feature = "diagnostics")]
  8546. println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64));
  8547. }
  8548. }
  8549. #[cfg(test)]
  8550. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  8551. use super::Batch;
  8552. use std::sync::Arc;
  8553. #[test]
  8554. fn a_texture_is_checked_once_per_submission() {
  8555. let mut batch = Batch::default();
  8556. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  8557. // The first list sampling each texture checks it ...
  8558. assert!(batch.texture_due(&a));
  8559. assert!(batch.texture_due(&b));
  8560. // ... later lists of the same submission do not.
  8561. assert!(!batch.texture_due(&a));
  8562. assert!(!batch.texture_due(&a.clone()));
  8563. assert!(!batch.texture_due(&b));
  8564. }
  8565. #[test]
  8566. fn title_writes_make_textures_due_again() {
  8567. let mut batch = Batch::default();
  8568. let a = Arc::new(1u32);
  8569. assert!(batch.texture_due(&a));
  8570. assert!(!batch.texture_due(&a));
  8571. // A copy into title memory or work that may write it may have
  8572. // changed the texture's memory.
  8573. batch.title_written();
  8574. assert!(batch.texture_due(&a));
  8575. assert!(!batch.texture_due(&a));
  8576. // A fresh submission starts over.
  8577. let mut next = Batch::default();
  8578. assert!(next.texture_due(&a));
  8579. }
  8580. /// The hashing a submission does for textures in physical-page memory,
  8581. /// with every list checking the textures it samples (before) and with
  8582. /// each checked once (after). Run with
  8583. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  8584. #[test]
  8585. #[ignore = "benchmark"]
  8586. fn texture_checks_per_submission() {
  8587. const TEXTURES: usize = 48;
  8588. const SIZE: usize = 4 << 20;
  8589. const LISTS: usize = 12;
  8590. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  8591. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  8592. .collect();
  8593. let submit = |dedupe: bool| {
  8594. let mut batch = Batch::default();
  8595. let mut hashed = 0usize;
  8596. let started = std::time::Instant::now();
  8597. for _ in 0..LISTS {
  8598. for t in &textures {
  8599. if !dedupe || batch.texture_due(t) {
  8600. std::hint::black_box(blake3::hash(t));
  8601. hashed += 1;
  8602. }
  8603. }
  8604. }
  8605. (started.elapsed(), hashed)
  8606. };
  8607. submit(false); // warm up
  8608. let (before, n_before) = submit(false);
  8609. let (after, n_after) = submit(true);
  8610. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  8611. println!(
  8612. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  8613. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  8614. SIZE >> 20,
  8615. before.as_secs_f64() / after.as_secs_f64()
  8616. );
  8617. }
  8618. #[test]
  8619. fn vram_idle_ms_scales_with_pressure() {
  8620. let vram_idle_ms = |memory| super::vram_idle_for(memory, false);
  8621. let keeps = |memory| super::vram_idle_for(memory, true);
  8622. let gib = 1024 * 1024 * 1024;
  8623. assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000);
  8624. assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000);
  8625. assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500);
  8626. assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000);
  8627. assert_eq!(keeps(None), 5_000);
  8628. // Normal (< 75%)
  8629. assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000);
  8630. assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000);
  8631. assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000);
  8632. // Moderate (75%..85%)
  8633. assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500);
  8634. assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500);
  8635. // High (>= 85%, including over-budget)
  8636. assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000);
  8637. assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000);
  8638. // Missing or zero budget falls back to normal
  8639. assert_eq!(vram_idle_ms(None), 5_000);
  8640. assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
  8641. }
  8642. #[test]
  8643. fn ram_idle_ms_scales_with_pressure() {
  8644. use super::ram_idle_ms;
  8645. let gib = 1024 * 1024 * 1024;
  8646. // Normal (>= 4 GiB)
  8647. assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
  8648. assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000);
  8649. // Moderate (2 GiB..4 GiB)
  8650. assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000);
  8651. assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000);
  8652. // High (< 2 GiB)
  8653. assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000);
  8654. assert_eq!(ram_idle_ms(Some(0)), 2_000);
  8655. // Missing falls back to normal
  8656. assert_eq!(ram_idle_ms(None), 10_000);
  8657. }
  8658. }