shadow.rs 230 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223
  1. //! Host copies of title buffers (decision 0007, step 3 and "Copies of title
  2. //! memory"). Title buffers are title memory, which the host GPU cannot
  3. //! read, so a buffer a draw uses gets a persistent host buffer of its size
  4. //! on first use (system memory shaders may also write), and the ranges each
  5. //! submission reads (vertex, index and constant data, buffer views) are
  6. //! brought up to date from title memory before it runs: the 64 KiB pages
  7. //! the title wrote since they were last copied ([`crate::watch`]: write
  8. //! watching, or read-only guards on physical-page views), all of it where
  9. //! neither works. A title GPU address inside the buffer is the same offset
  10. //! in its copy. Ranges shaders write go back to title memory after the
  11. //! submission ([`Shadow::gpu_writes`]).
  12. //!
  13. //! shortcut: only the ranges draws are known to read are brought up to
  14. //! date (vertex and index buffer views, constant buffers in tables, root
  15. //! descriptors, buffer views in tables); buffers read through directly
  16. //! indexed heaps keep what their first use copied.
  17. use std::collections::BTreeMap;
  18. use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
  19. use std::sync::{Arc, Mutex, RwLock};
  20. use windows::Win32::Graphics::Direct3D12::ID3D12Resource;
  21. use crate::host::{HostList, host};
  22. use crate::watch::PAGE;
  23. /// A title buffer's host copy.
  24. pub(crate) struct Shadow {
  25. /// The bytes of `buffer`, once asked.
  26. width: std::sync::OnceLock<u64>,
  27. pub(crate) buffer: ID3D12Resource,
  28. data: *mut u8,
  29. gpu: u64,
  30. /// Where the title buffer starts and how long it is.
  31. start: u64,
  32. len: u64,
  33. /// Per page of title memory from `start`'s on: the write-watch asking
  34. /// after which it was last copied (0: never).
  35. copied: Mutex<Vec<u64>>,
  36. /// Two ranges of title memory taken whole, the last one and the longest,
  37. /// and the asking after which each was ([`Shadow::copy_stale`]). A page
  38. /// a range holds in part cannot say so in `copied`. Locked inside
  39. /// `copied`'s lock.
  40. ranged: Mutex<[(usize, usize, u64); 2]>,
  41. /// Whether the memory is write-watched: unknown, yes, no.
  42. watched: AtomicU8,
  43. /// Ranges shaders of a submission not yet copied back may be writing:
  44. /// title memory there is older than the copy.
  45. pending: Mutex<Vec<(usize, usize)>>,
  46. /// With [`relay`]: how many submissions not yet copied back declared
  47. /// each range of `pending` ([`Flights`]). Locked inside `pending`'s
  48. /// lock.
  49. flights: Mutex<Flights>,
  50. /// The copy's bytes before the submission ran, for the ranges its
  51. /// shaders write (`pending`), each at its offset in the copy: what the
  52. /// GPU wrote differs. Room for the whole copy; only those ranges' bytes
  53. /// are set (and read).
  54. before: Mutex<Option<Vec<u8>>>,
  55. /// Held shared while pieces of the copy are landed (`crate::land`), each
  56. /// its own bytes of it on several threads, and alone while title bytes
  57. /// go in under shader writes ([`Shadow::merge_under_writes`]), which
  58. /// takes `before`'s lock too. Taken ahead of that one.
  59. merging: RwLock<()>,
  60. /// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot
  61. /// hold the copy's bytes as they are now, and whether the snapshot is
  62. /// counted in [`KEPT_BYTES`].
  63. kept: Mutex<(Vec<bool>, bool)>,
  64. /// When the copy was last asked for (`crate::host::moment`): a window
  65. /// outside buffers nothing asked for in a while, and nothing holds, is
  66. /// let go ([`let_go_idle`]).
  67. used: AtomicU64,
  68. /// The lowest and highest title address asked for in the copy (a
  69. /// window is 4 MiB whatever was asked: measured for the memory line).
  70. asked: [AtomicU64; 2],
  71. /// Asks for the copy that gave no length (root views: they read from
  72. /// their address to the copy's end, whatever lies there).
  73. unsized_asks: AtomicU64,
  74. /// Whether shaders were ever declared to write it.
  75. written: std::sync::atomic::AtomicBool,
  76. /// A number no other copy has had. Its address is no name for a copy:
  77. /// one let go and another made may share it.
  78. id: u64,
  79. /// With [`cards`], for a big title buffer: `buffer` is in the card's
  80. /// own memory, and this is the rest of the copy.
  81. card: Option<Card>,
  82. /// A window of title memory outside buffers, not a title buffer's copy.
  83. window: bool,
  84. /// Of a copy with two sides: only the dwords the title changed go up,
  85. /// as with [`send_changed`] ([`by_address`]).
  86. changes_only: std::sync::atomic::AtomicBool,
  87. /// A window in card memory the CPU maps ([`window_mapped_for`]).
  88. mapped: bool,
  89. /// With `crate::inplace`: not a copy at all. `buffer` is placed in a
  90. /// heap opened on the title memory itself, so shaders read and write
  91. /// the title's own bytes and nothing is copied either way. The heap,
  92. /// and the bytes from the buffer's first byte to `start` (the heap
  93. /// begins on a 64 KiB line; a title buffer need not).
  94. place: Option<(windows::Win32::Graphics::Direct3D12::ID3D12Heap, u64)>,
  95. }
  96. /// What a copy in the card's memory ([`cards`]) has beside the buffer
  97. /// shaders see.
  98. struct Card {
  99. /// The CPU's side, in the PC's memory: what `data` maps. Title memory
  100. /// is copied into it as into any copy, and what changed in it goes to
  101. /// the card's side before the next submission.
  102. staging: ID3D12Resource,
  103. /// The card side's bytes as they were when the submission's shaders
  104. /// started, in the card's memory too: made when shader writes are
  105. /// first declared for the copy, and compared with the card's side, on
  106. /// the card, after each submission that declares some.
  107. before: Mutex<Option<ID3D12Resource>>,
  108. /// Offsets of the copy whose bytes changed on the CPU's side and have
  109. /// not gone to the card's side yet.
  110. dirty: Mutex<Vec<(usize, usize)>>,
  111. /// With [`relay`]: the offsets that went from `dirty` to the card's
  112. /// side, each with the number of the send that took it
  113. /// ([`card_dirty`]), kept until a fetch sent after it has been merged.
  114. /// Locked inside `dirty`'s lock.
  115. sent: Mutex<SentRuns>,
  116. /// Whether something was put into `dirty` since it was last taken.
  117. touched: std::sync::atomic::AtomicBool,
  118. /// The buffers' bytes (the title buffer's, rounded up to 64 KiB).
  119. size: u64,
  120. }
  121. /// Whether the host copies of big title buffers are in the card's own
  122. /// memory (on by default since run 75 showed it holds: the BVH skinning
  123. /// list went from 50.5 to 4.5 ms on the card; `VICTORY_CARD_BUFFERS=0`
  124. /// keeps every copy in the PC's memory, as before. Read when a copy is
  125. /// made, so it takes a fresh start).
  126. ///
  127. /// Every host copy was a buffer in the PC's memory that the card reads
  128. /// and writes over the bus, so that our code can fill it and compare it.
  129. /// The title's shaders read almost all their buffer data from a few big
  130. /// title buffers (in the gameplay frame of run 69, 190-330 MB of distinct
  131. /// ranges of the 174 MB heap per list against 0-13 MB elsewhere), and a
  132. /// skinning dispatch of ONE group of 32 threads took 1.8 ms on the card
  133. /// (run 70): the time of some 170 loads one after the other, not of the
  134. /// arithmetic.
  135. ///
  136. /// With the switch, a title buffer of [`card_limits`]' size or more has two
  137. /// sides. Shaders see `Shadow::buffer`, in the card's memory. The CPU's
  138. /// side (`Card::staging`, what `Shadow::data` maps) takes title memory as
  139. /// before, and the ranges that changed in it are copied to the card's side
  140. /// before each submission (`Host::card_before`). What shaders wrote is
  141. /// found on the card: after the submission's lists a compute pass of ours
  142. /// compares each declared range, by 64 KiB piece, with the card side's
  143. /// bytes from before (`Card::before`), and only the pieces that differ are
  144. /// fetched and merged into title memory, byte by byte as
  145. /// [`Shadow::copy_back`] does (`Host::card_back`, [`Shadow::card_merge`]).
  146. /// No snapshot is taken and nothing is compared on the CPU for such a copy.
  147. ///
  148. /// What it assumes is what [`keeps`] assumes: shaders write a copy only in
  149. /// ranges declared as written. A write outside them is seen by later
  150. /// shaders, as before, and goes back to the title the next time a declared
  151. /// range holds its piece (before: never).
  152. pub(crate) fn cards() -> bool {
  153. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  154. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_BUFFERS").is_none_or(|v| v != "0"))
  155. }
  156. /// Default `(min_mb, max_mb)` for [`card_limits`] chosen from the adapter's
  157. /// local VRAM budget (`DXGI_QUERY_VIDEO_MEMORY_INFO.Budget`), in bytes.
  158. ///
  159. /// - Unknown (`None`, e.g. WARP) or `<= 12 GiB` (8–12 GB cards, whose WDDM
  160. /// budget is below 12 GiB): `(16, 512)` MiB, matching the 12 GB baseline.
  161. /// - `> 12 GiB` and `< 20 GiB` (16 GB cards, whose WDDM budget is typically
  162. /// ~13.5–15.2 GiB): `(4, 2048)` MiB.
  163. /// - `>= 20 GiB` (24–32+ GB cards): `(1, (budget_mb / 4).min(8192))` MiB,
  164. /// capping at 25% of local budget (at most 8 GiB) so "before" twins (up to 2x)
  165. /// still leave headroom for textures and render targets.
  166. fn default_card_limits_mb(local_vram_budget: Option<u64>) -> (u64, u64) {
  167. let Some(budget_bytes) = local_vram_budget else {
  168. return (16, 512);
  169. };
  170. let budget_mb = budget_bytes >> 20;
  171. const TWELVE_GIB_MB: u64 = 12 * 1024;
  172. const TWENTY_GIB_MB: u64 = 20 * 1024;
  173. if budget_mb <= TWELVE_GIB_MB {
  174. (16, 512)
  175. } else if budget_mb < TWENTY_GIB_MB {
  176. (4, 2048)
  177. } else {
  178. (1, (budget_mb / 4).min(8192))
  179. }
  180. }
  181. /// Resolve `(min_bytes, max_bytes)` from the adapter's local VRAM budget and
  182. /// optional explicit MiB overrides from `VICTORY_CARD_BUFFERS_MIN_MB` /
  183. /// `VICTORY_CARD_BUFFERS_MB`.
  184. fn resolve_card_limits(
  185. local_vram_budget: Option<u64>,
  186. min_mb_override: Option<u64>,
  187. max_mb_override: Option<u64>,
  188. ) -> (u64, u64) {
  189. const MIB: u64 = 1 << 20;
  190. let (default_min_mb, default_max_mb) = default_card_limits_mb(local_vram_budget);
  191. let min_bytes = min_mb_override.unwrap_or(default_min_mb).saturating_mul(MIB).max(MIB);
  192. let max_bytes = max_mb_override.unwrap_or(default_max_mb).saturating_mul(MIB);
  193. (min_bytes, max_bytes)
  194. }
  195. /// The smallest title buffer whose copy goes to the card's memory, and the
  196. /// most bytes of such copies (their "before" twins not counted: a copy
  197. /// shaders write takes its size twice), both in bytes:
  198. /// `VICTORY_CARD_BUFFERS_MIN_MB` and `VICTORY_CARD_BUFFERS_MB`.
  199. /// Defaults scale with the adapter's local VRAM budget (16 MiB / 512 MiB on
  200. /// `<= 12 GiB` budgets, 4 MiB / 2048 MiB on 16 GB cards, 1 MiB / up to 8192 MiB
  201. /// on `>= 20 GiB` budgets), and explicit env vars always override.
  202. fn card_limits() -> (u64, u64) {
  203. static LIMITS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new();
  204. *LIMITS.get_or_init(|| {
  205. let env_mb = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<u64>().ok());
  206. let vram_budget = crate::host::host().and_then(|h| h.video_memory()).map(|[budget, ..]| budget);
  207. let (mut min_bytes, max_bytes) = resolve_card_limits(
  208. vram_budget,
  209. env_mb("VICTORY_CARD_BUFFERS_MIN_MB"),
  210. env_mb("VICTORY_CARD_BUFFERS_MB"),
  211. );
  212. if card_all() {
  213. min_bytes = 0;
  214. }
  215. tracing::info!(
  216. vram_budget_mb = vram_budget.map(|b| b >> 20),
  217. card_buffers_min_mb = min_bytes >> 20,
  218. card_buffers_max_mb = max_bytes >> 20,
  219. "card buffer limits"
  220. );
  221. (min_bytes, max_bytes)
  222. })
  223. }
  224. /// Bytes alive of copies' card sides, and of their "before" twins.
  225. static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
  226. /// Whether the texture queue leaves room on the card for the card copies
  227. /// of title buffers that are not made yet
  228. /// (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`; off by default).
  229. ///
  230. /// The copies are made in one burst when the world loads (run 189: 94 of
  231. /// its 95 within two seconds, right before the first world frame), and
  232. /// [`card_for`] makes one only while the card is under eight tenths of its
  233. /// budget. That held as long as the textures picked by index filled the
  234. /// card after the burst. Since the texture queue keeps packed neighbours
  235. /// (52b8060) it fills the card while the world loads: 85% and more at the
  236. /// burst in runs 190 to 192, so one copy of 95 was made, the CPU looked
  237. /// for shader writes in 600 to 720 MB a frame where it had been 30, and
  238. /// the frame went from about 240 to 370-470 ms.
  239. ///
  240. /// With the switch, the texture queue's rule (`resource::room`) counts the
  241. /// part of [`card_limits`]' second number that no copy has taken yet as
  242. /// used, and a copy may be made up to nine tenths of the budget: the room
  243. /// it takes was kept for it. After the burst what is kept is what the
  244. /// burst left of the limit (87 MB of 1,024 in run 189).
  245. ///
  246. /// On by default from the build after run 199
  247. /// (`VICTORY_CARD_ROOM_FOR_BUFFERS=0`: off, as before). Run 193 had it on and still made 31 copies of 95: the copies
  248. /// and the world's render targets (+1,603 MB) arrive in the same first
  249. /// world frame and raced for the 448 MB left under the line, and a copy
  250. /// turned down is not asked for again (`lookup` asks once), while its room
  251. /// went on being kept (616 MB to the end of the run). So now: the texture
  252. /// queue also keeps room for the targets (`resource::targets_room_kept`),
  253. /// a copy is made up to 97 hundredths of the budget (its room was kept),
  254. /// and the room of a copy turned down is given up ([`CARD_REFUSED`]).
  255. fn card_room_kept_on() -> bool {
  256. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  257. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_none_or(|v| v != "0"))
  258. }
  259. /// Title buffers big enough for a copy in the card's memory that were
  260. /// turned down for want of room, since the start, and their bytes: their
  261. /// copies stay in the PC's memory for as long as the title keeps the
  262. /// buffers, so no room is kept for them any more.
  263. static CARD_REFUSED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
  264. /// The bytes of the card's memory the texture queue leaves free for card
  265. /// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with
  266. /// the switch off or without card copies.
  267. pub(crate) fn card_room_kept() -> u64 {
  268. if !card_room_kept_on() || !cards() {
  269. return 0;
  270. }
  271. // Not more than such copies came to in any session, whatever they may
  272. // come to: on a card of 24 GB a quarter of its budget was kept for them,
  273. // 5 GB that never came (941 MB in 97 copies after fifteen minutes), and
  274. // no texture was made any more with 5 GB of the card free (session
  275. // play-1125-0127: 1,453 passes refused, the ground and people black).
  276. const SEEN: u64 = 1 << 30;
  277. card_limits().1.min(SEEN).saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed))
  278. }
  279. /// The copies in the card's memory.
  280. static CARDED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new());
  281. /// Since the last frame line: bytes copied to card sides and the ranges
  282. /// they were; pieces compared on the card, pieces fetched and their
  283. /// bytes; the waits for the card the fetches added and their microseconds.
  284. pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7];
  285. /// [`CARD_STATS`], taken; then the copies in the card's memory, their
  286. /// bytes and their "before" twins' bytes.
  287. pub(crate) fn card_stats() -> [u64; 10] {
  288. let mut out = [0u64; 10];
  289. for (i, stat) in CARD_STATS.iter().enumerate() {
  290. out[i] = stat.swap(0, Ordering::Relaxed);
  291. }
  292. out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64;
  293. out[8] = CARD_BYTES[0].load(Ordering::Relaxed)
  294. + WINDOW_CARD_BYTES.load(Ordering::Relaxed)
  295. + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed);
  296. out[9] = CARD_BYTES[1].load(Ordering::Relaxed);
  297. out
  298. }
  299. /// The bytes of the hashes kept on the card for a copy of `size` bytes: 16
  300. /// for each 64 KiB piece (a copy that does not start on a piece boundary
  301. /// has one piece more).
  302. pub(crate) fn card_hash_bytes(size: u64) -> u64 {
  303. (size / PIECE as u64 + 2) * 16
  304. }
  305. /// A buffer of `size` bytes in the card's memory for a title buffer's
  306. /// copy, if the copy is to be there: [`cards`] is on, the size is within
  307. /// [`card_limits`] and below 1 GiB (the compare counts in 32 bits), and the
  308. /// host has what it takes (`Host::card_ready`).
  309. fn card_for(size: u64) -> Option<ID3D12Resource> {
  310. let there = card_room_for(size);
  311. if there.is_some() || !card_all() || size >= 1 << 30 {
  312. return there;
  313. }
  314. // Two sides all the same, the card's in the PC's memory.
  315. let host = host()?;
  316. if !cards() || !host.card_ready() {
  317. return None;
  318. }
  319. let (buffer, _) = host.shared_buffer(size)?;
  320. CARD_BYTES[0].fetch_add(size, Ordering::Relaxed);
  321. Some(buffer)
  322. }
  323. /// Whether every title buffer's copy has two sides, however small
  324. /// (`VICTORY_CARD_ALL=1`; off by default).
  325. ///
  326. /// A copy with one side, in the PC's memory, is what the card reads while
  327. /// our refreshes write it: a submission that is prepared changes it under
  328. /// the ones in the air ahead of it. The title's CPU does not write what they
  329. /// still read, but its own buffer copies are done by us at preparing
  330. /// (`crate::host::send` has the order of those right for copies with two
  331. /// sides), and so are the bytes put in beside shaders' writes.
  332. fn card_all() -> bool {
  333. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  334. *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ALL").is_some_and(|v| v == "1"))
  335. }
  336. /// [`card_for`] in the card's own memory.
  337. fn card_room_for(size: u64) -> Option<ID3D12Resource> {
  338. if !cards() {
  339. return None;
  340. }
  341. let (least, most) = card_limits();
  342. if size < least || size >= 1 << 30 {
  343. return None;
  344. }
  345. let host = host()?;
  346. if !host.card_ready() {
  347. return None;
  348. }
  349. // Only while the card has room: with this copy on it, a fifth of the
  350. // budget the system gives us must still be free. Copies are made when
  351. // the world loads, before the textures fill the card; the texture
  352. // queue's own rule (`resource::room`: nine tenths of the budget) counts
  353. // them, so the card's use stays where it was and the textures' share
  354. // shrinks by the copies' bytes, at most `card_limits`' second number.
  355. // (With `card_room_kept_on` the texture queue kept this copy's room
  356. // free, and the copy may go up to the queue's own line.)
  357. let hundredths = if card_room_kept_on() { 97 } else { 80 };
  358. if let Some([budget, used, ..]) = host.video_memory()
  359. && used + size > budget / 100 * hundredths
  360. {
  361. // Said, with the numbers it was decided by: run 193 made 31 copies
  362. // of 95 and no line named the others. The first 64, then every
  363. // 32nd.
  364. let n = CARD_REFUSED[0].fetch_add(1, Ordering::Relaxed) + 1;
  365. let bytes = CARD_REFUSED[1].fetch_add(size, Ordering::Relaxed) + size;
  366. if n <= 64 || n.is_multiple_of(32) {
  367. tracing::info!(
  368. "no card copy for a title buffer of {} KiB: the card has {} MB in use of a budget of {} MB and a copy is made up to \
  369. {} MB; the copies made hold {} MB of at most {} MB; {} buffers turned down so far ({} MB), frame {}",
  370. size >> 10,
  371. used >> 20,
  372. budget >> 20,
  373. (budget / 100 * hundredths) >> 20,
  374. CARD_BYTES[0].load(Ordering::Relaxed) >> 20,
  375. most >> 20,
  376. n,
  377. bytes >> 20,
  378. crate::frame::current()
  379. );
  380. }
  381. return None;
  382. }
  383. if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most {
  384. CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed);
  385. return None;
  386. }
  387. let buffer = host.uav_buffer(size);
  388. if buffer.is_none() {
  389. CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed);
  390. }
  391. buffer
  392. }
  393. /// The most bytes of windows outside buffers whose copies go to the card's
  394. /// memory (`VICTORY_CARD_WINDOWS_MB`; 0, the default, none).
  395. ///
  396. /// Windows are two thirds of the PC memory the card shares (run 104: 861
  397. /// windows, 3,552 MB of 5,400), and every draw that takes vertices, indices
  398. /// or constants from the title's own allocator reads them over the bus.
  399. /// Shaders write none of them (run 91: "0.0 MB compared in 0 ranges of
  400. /// windows"), so a window on the card needs only what a card copy has
  401. /// already: the CPU's side takes title memory as before, and what changed
  402. /// in it goes up before each submission. No hashes, no compare, no fetch,
  403. /// unless a shader does declare a write to it one day.
  404. ///
  405. /// A window goes to the card while there is room under this number and
  406. /// while a fifth of the card's budget is free, as title buffers do
  407. /// (`card_for`): textures keep their room, and once they have filled the
  408. /// card later windows stay where they are. The CPU's side stays in the PC's
  409. /// memory, so the memory shared with the card does not shrink by this
  410. /// alone; what moves is what shaders read.
  411. fn window_card_most() -> u64 {
  412. static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  413. *MOST.get_or_init(|| {
  414. std::env::var("VICTORY_CARD_WINDOWS_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0) << 20
  415. })
  416. }
  417. /// Bytes alive of windows' card sides ([`window_card_most`]).
  418. static WINDOW_CARD_BYTES: AtomicU64 = AtomicU64::new(0);
  419. /// A buffer in the card's memory for a window of `size` bytes, if it is to
  420. /// be there ([`window_card_most`]).
  421. fn window_card_for(size: u64) -> Option<ID3D12Resource> {
  422. let there = window_room_for(size);
  423. if there.is_some() || !windows_own() || !cards() {
  424. return there;
  425. }
  426. // Two sides all the same, the card's in the PC's memory.
  427. let host = host()?;
  428. if !host.card_ready() {
  429. return None;
  430. }
  431. let (buffer, _) = host.shared_buffer(size)?;
  432. WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed);
  433. Some(buffer)
  434. }
  435. /// The most bytes of windows outside buffers that lie in the card's memory
  436. /// and are filled by the CPU through the bus (`VICTORY_WINDOWS_BAR_MB`; 0, the
  437. /// default, none): one buffer (`D3D12_HEAP_TYPE_GPU_UPLOAD`), no CPU's side, no
  438. /// copy to send and no list of changes, unlike [`window_card_most`]. The CPU
  439. /// only writes them, as no shader is declared to write a window; if one were,
  440. /// its snapshot and compare would read through the bus, right but slow. In a
  441. /// captured frame the lists take 26 ms of the card instead of 29, the frame 32
  442. /// instead of 36; filling them costs the CPU what it did.
  443. ///
  444. /// Windows go there while a fifth of the card's budget is free, as with
  445. /// [`window_room_for`], which this comes before.
  446. fn window_mapped_most() -> u64 {
  447. static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  448. *MOST.get_or_init(|| {
  449. std::env::var("VICTORY_WINDOWS_BAR_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0) << 20
  450. })
  451. }
  452. /// Bytes alive of windows in card memory the CPU maps.
  453. static WINDOW_MAPPED_BYTES: AtomicU64 = AtomicU64::new(0);
  454. /// A buffer for a window of `size` bytes in card memory the CPU maps, if it is
  455. /// to be there ([`window_mapped_most`]).
  456. fn window_mapped_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  457. let most = window_mapped_most();
  458. if most == 0 {
  459. return None;
  460. }
  461. let host = host()?;
  462. if let Some([budget, used, ..]) = host.video_memory()
  463. && used + size > budget / 10 * 8
  464. {
  465. return None;
  466. }
  467. if WINDOW_MAPPED_BYTES.fetch_add(size, Ordering::Relaxed) + size > most {
  468. WINDOW_MAPPED_BYTES.fetch_sub(size, Ordering::Relaxed);
  469. return None;
  470. }
  471. let made = host.mapped_card_buffer(size, true);
  472. if made.is_none() {
  473. WINDOW_MAPPED_BYTES.fetch_sub(size, Ordering::Relaxed);
  474. }
  475. made
  476. }
  477. /// Whether windows outside buffers have two sides too, so that submissions
  478. /// in the air read the bytes they were prepared with (`VICTORY_WINDOWS_OWN=1`;
  479. /// off by default: it takes the windows' bytes again, 3.3 GB in capture
  480. /// replay2, and what changes in them under submissions in the air is what the
  481. /// title's CPU writes, which it does not while they read it).
  482. fn windows_own() -> bool {
  483. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  484. *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOWS_OWN").is_some_and(|v| v == "1"))
  485. }
  486. /// [`window_card_for`] in the card's own memory.
  487. fn window_room_for(size: u64) -> Option<ID3D12Resource> {
  488. let most = window_card_most();
  489. if most == 0 || !cards() {
  490. return None;
  491. }
  492. let host = host()?;
  493. if !host.card_ready() {
  494. return None;
  495. }
  496. if let Some([budget, used, ..]) = host.video_memory()
  497. && used + size > budget / 10 * 8
  498. {
  499. return None;
  500. }
  501. if WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed) + size > most {
  502. WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed);
  503. return None;
  504. }
  505. let buffer = host.uav_buffer(size);
  506. if buffer.is_none() {
  507. WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed);
  508. }
  509. buffer
  510. }
  511. /// What went up, by send: its number, and the offsets, in order and joined
  512. /// (a refresh sends thousands of runs of a few words).
  513. #[derive(Default)]
  514. struct SentRuns(Vec<(u64, Vec<(usize, usize)>)>);
  515. impl SentRuns {
  516. fn note(&mut self, number: u64, ranges: Vec<(usize, usize)>) {
  517. if ranges.is_empty() {
  518. return;
  519. }
  520. let ranges = joined(ranges);
  521. match self.0.iter_mut().find(|s| s.0 == number) {
  522. Some((_, all)) => *all = joined([std::mem::take(all), ranges].concat()),
  523. None => self.0.push((number, ranges)),
  524. }
  525. }
  526. /// Sends up to `number` are of no use any more.
  527. fn forget(&mut self, number: u64) {
  528. self.0.retain(|s| s.0 > number);
  529. }
  530. /// Adds to `out` what sends after `number` took of `[from, to)`.
  531. fn near(&self, number: u64, from: usize, to: usize, out: &mut Vec<(usize, usize)>) {
  532. for (_, ranges) in self.0.iter().filter(|s| s.0 > number) {
  533. let first = ranges.partition_point(|r| r.1 <= from);
  534. out.extend(ranges[first..].iter().take_while(|r| r.0 < to).copied());
  535. }
  536. }
  537. #[cfg(test)]
  538. fn of(all: &[(usize, usize, u64)]) -> SentRuns {
  539. let mut sent = SentRuns::default();
  540. for &(a, b, number) in all {
  541. sent.note(number, vec![(a, b)]);
  542. }
  543. sent
  544. }
  545. }
  546. /// The copies in the card's memory whose CPU side changed since they were
  547. /// last asked: each with the changed offsets, in order and joined where
  548. /// they touch. The ranges are taken: the caller copies them to the card's
  549. /// side (`Host::card_before`).
  550. ///
  551. /// With [`relay`], `sent_as` is the number of the send that takes them
  552. /// (`crate::host`'s order of the queue): each range is noted with it, in
  553. /// the same lock that took it, so that a merge of pieces fetched before
  554. /// that send knows the card did not hold these bytes yet
  555. /// ([`Shadow::card_merge_relay`]). Notes of sends that every fetch still to
  556. /// be merged came after are dropped.
  557. pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc<Shadow>, Vec<(usize, usize)>)> {
  558. let mut out = Vec::new();
  559. let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner());
  560. let fetched = RELAY_FETCHED.load(Ordering::Acquire);
  561. carded.retain(|weak| {
  562. let Some(shadow) = weak.upgrade() else {
  563. return false;
  564. };
  565. let ranges = shadow
  566. .card
  567. .as_ref()
  568. .filter(|c| c.touched.swap(false, Ordering::AcqRel))
  569. .map(|c| {
  570. let mut dirty = c.dirty.lock().unwrap_or_else(|e| e.into_inner());
  571. let ranges = std::mem::take(&mut *dirty);
  572. if relay() {
  573. let mut sent = c.sent.lock().unwrap_or_else(|e| e.into_inner());
  574. sent.forget(fetched);
  575. sent.note(sent_as, ranges.clone());
  576. }
  577. ranges
  578. })
  579. .unwrap_or_default();
  580. if !ranges.is_empty() {
  581. out.push((shadow, joined(ranges)));
  582. }
  583. true
  584. });
  585. out
  586. }
  587. /// Diagnostics (`crate::host::upcheck`, nothing in the air): copies whose
  588. /// pages the write watch and the guards hold for unchanged since they were
  589. /// taken, compared with title memory, `most` bytes a call in turn. `say` gets
  590. /// the copy, the title address of a page that is not the same, the words that
  591. /// differ and the first of them (its address, the copy's value, title
  592. /// memory's). Returns the bytes compared.
  593. pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize, (usize, u32, u32))) -> usize {
  594. static NEXT: AtomicU64 = AtomicU64::new(0);
  595. let mut all: Vec<Arc<Shadow>> = buffers_read().values().filter_map(|e| e.shadow.clone()).collect();
  596. all.extend(LOOSE.write().unwrap_or_else(|e| e.into_inner()).values().cloned());
  597. all.retain(|s| s.place.is_none() && s.watched.load(Ordering::Relaxed) == 1);
  598. all.sort_by_key(|s| s.id);
  599. let next = NEXT.load(Ordering::Relaxed);
  600. let turn = all.partition_point(|s| s.id < next);
  601. let mut done = 0;
  602. let mut title = vec![0u8; PAGE];
  603. for shadow in all[turn..].iter().chain(&all[..turn]) {
  604. if done >= most {
  605. NEXT.store(shadow.id, Ordering::Relaxed);
  606. break;
  607. }
  608. let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize);
  609. // (What it finds written stays noted for the next refresh.)
  610. let Some((_, written)) = crate::watch::writes(start, end, true) else {
  611. continue;
  612. };
  613. let written: std::collections::HashMap<usize, u64> = written.into_iter().collect();
  614. let copied = shadow.copied.lock().unwrap_or_else(|e| e.into_inner()).clone();
  615. for (i, &at) in copied.iter().enumerate() {
  616. let page = start / PAGE + i;
  617. if at == 0 || written.get(&page).is_some_and(|&w| w > at) {
  618. continue;
  619. }
  620. let (lo, hi) = ((page * PAGE).max(start), ((page + 1) * PAGE).min(end));
  621. let title = &mut title[..hi - lo];
  622. if !crate::host::read_into(lo as *const u8, title) {
  623. continue;
  624. }
  625. done += hi - lo;
  626. // SAFETY: inside the mapping; nothing is in the air and the
  627. // submission lock is held.
  628. let held = unsafe { std::slice::from_raw_parts(shadow.data.add(lo - start).cast_const(), hi - lo) };
  629. if held == title {
  630. continue;
  631. }
  632. let word = |b: &[u8], k: usize| u32::from_le_bytes([b[k], b[k + 1], b[k + 2], b[k + 3]]);
  633. let differ: Vec<usize> = (0..(hi - lo) & !3).step_by(4).filter(|&k| word(held, k) != word(title, k)).collect();
  634. // Written meanwhile: not stale, and the next refresh sees it.
  635. let again = crate::watch::writes(lo, hi, true).is_none_or(|(_, w)| w.iter().any(|&(p, w)| p == page && w > at));
  636. if let Some(&k) = differ.first()
  637. && !again
  638. {
  639. say(shadow, lo, differ.len(), (lo + k, word(held, k), word(title, k)));
  640. }
  641. }
  642. }
  643. done
  644. }
  645. /// Copies of memory (from, to, bytes: apart), on several threads if they are
  646. /// many.
  647. pub(crate) fn copy_all(copies: Vec<(usize, usize, usize)>) {
  648. let bytes: usize = copies.iter().map(|c| c.2).sum();
  649. if bytes > 4 << 20 {
  650. wide(copy_jobs(copies));
  651. return;
  652. }
  653. for (src, dst, len) in copies {
  654. // SAFETY: the caller's ranges.
  655. unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) };
  656. }
  657. }
  658. /// A title buffer copy was done on the CPU into `[dst, dst + len)`: all of it
  659. /// goes up to the copies in the card's memory that hold it, whether their
  660. /// CPU side held the same before or not. Left out is what shaders in the air
  661. /// may be writing (such a copy waits for them, or is done on the card).
  662. pub(crate) fn send_copied(dst: usize, len: usize) {
  663. for shadow in carded_copies() {
  664. let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize);
  665. let (from, to) = (dst.max(start), (dst + len).min(end));
  666. if from >= to {
  667. continue;
  668. }
  669. let busy: Vec<(usize, usize)> =
  670. shadow.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().copied().filter(|&(a, b)| a < to && b > from).collect();
  671. for (a, b) in outside(from, to, busy) {
  672. shadow.copy(a, b);
  673. }
  674. }
  675. }
  676. /// The copies in the card's memory (diagnostics: `crate::host::upcheck`).
  677. pub(crate) fn carded_copies() -> Vec<Arc<Shadow>> {
  678. CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(std::sync::Weak::upgrade).collect()
  679. }
  680. /// Ranges in order, those that overlap or touch as one.
  681. fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
  682. ranges.sort_unstable();
  683. let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
  684. for (from, to) in ranges {
  685. match out.last_mut() {
  686. Some(last) if from <= last.1 => last.1 = last.1.max(to),
  687. _ => out.push((from, to)),
  688. }
  689. }
  690. out
  691. }
  692. /// Runs of pieces to hash again (`Host::card_before`), those that overlap
  693. /// or touch as one, in order: every piece of `runs` is in the result once
  694. /// and no other piece is. Ranges sent up lie close together (514 a frame
  695. /// for 87 MB in run 102), and each had a pass of its own over its pieces,
  696. /// so a piece that held several ranges was hashed once for each.
  697. pub(crate) fn joined_piece_runs(mut runs: Vec<CardSpan>) -> Vec<CardSpan> {
  698. runs.sort_unstable_by_key(|r| r.first);
  699. let mut out: Vec<CardSpan> = Vec::with_capacity(runs.len());
  700. for run in runs {
  701. match out.last_mut() {
  702. Some(last) if run.first <= last.first + last.pieces => {
  703. last.pieces = last.pieces.max(run.first + run.pieces - last.first);
  704. last.to = last.to.max(run.to);
  705. }
  706. _ => out.push(run),
  707. }
  708. }
  709. out
  710. }
  711. /// A declared range of a copy in the card's memory, as the compare on the
  712. /// card takes it: its offsets in the copy, its first 64 KiB piece (pieces
  713. /// are cut at multiples of 64 KiB of title memory; piece 0 holds offset
  714. /// 0), how many pieces hold it, and where the copy starts in piece 0.
  715. #[derive(Clone, Copy, Debug, PartialEq, Eq)]
  716. pub(crate) struct CardSpan {
  717. pub(crate) from: u32,
  718. pub(crate) to: u32,
  719. pub(crate) first: u32,
  720. pub(crate) pieces: u32,
  721. pub(crate) skew: u32,
  722. }
  723. /// [`CardSpan`] for offsets `[from, to)` (`from < to`) of a copy of title
  724. /// memory from `start` on.
  725. fn card_span_of(start: usize, from: usize, to: usize) -> CardSpan {
  726. let pieces = pieces_of(start, from, to);
  727. CardSpan {
  728. from: from as u32,
  729. to: to as u32,
  730. first: pieces.start as u32,
  731. pieces: pieces.len() as u32,
  732. skew: (start % PIECE) as u32,
  733. }
  734. }
  735. /// The offsets of piece `i` of `span` that lie in the span, for a copy of
  736. /// `len` bytes of title memory from `start` on: what is fetched and merged
  737. /// of a piece the compare found differing.
  738. fn card_piece_of(start: usize, len: usize, span: &CardSpan, i: u32) -> (usize, usize) {
  739. let (lo, hi) = piece_at(start, len, (span.first + i) as usize);
  740. (lo.max(span.from as usize), hi.min(span.to as usize))
  741. }
  742. /// The offsets [`Shadow::card_hashed`] gives, for a card's buffer of `size`
  743. /// bytes for title memory from `start` on.
  744. fn card_hashed_of(start: usize, size: usize, piece: usize) -> (usize, usize) {
  745. let (lo, hi) = piece_at(start, size, piece);
  746. (lo & !15, hi.next_multiple_of(16))
  747. }
  748. #[cfg(test)]
  749. mod card_tests {
  750. use super::{CardSpan, PIECE, card_hashed_of, card_piece_of, card_span_of, joined, joined_piece_runs};
  751. /// Joined runs hold every piece of the runs given, once, and no other.
  752. #[test]
  753. fn piece_runs_join_without_losing_or_adding_pieces() {
  754. let run = |first: u32, pieces: u32| CardSpan {
  755. from: first * 65536,
  756. to: (first + pieces) * 65536,
  757. first,
  758. pieces,
  759. skew: 7,
  760. };
  761. let runs = vec![run(40, 1), run(3, 2), run(4, 1), run(5, 3), run(40, 1), run(9, 1), run(41, 2), run(100, 1)];
  762. let mut wanted: Vec<u32> = runs.iter().flat_map(|r| r.first..r.first + r.pieces).collect();
  763. wanted.sort_unstable();
  764. wanted.dedup();
  765. let joined = joined_piece_runs(runs);
  766. let got: Vec<u32> = joined.iter().flat_map(|r| r.first..r.first + r.pieces).collect();
  767. assert_eq!(got, wanted);
  768. assert_eq!(joined.iter().map(|r| (r.first, r.pieces)).collect::<Vec<_>>(), [(3, 5), (9, 1), (40, 3), (100, 1)]);
  769. assert!(joined.iter().all(|r| r.skew == 7));
  770. assert!(joined_piece_runs(Vec::new()).is_empty());
  771. }
  772. /// The offsets the compare's shader takes for a piece (`CARD_COMPARE`
  773. /// in host.rs), before it widens them to 16 bytes.
  774. fn shader_piece(span: &CardSpan, i: u32) -> (u32, u32) {
  775. let piece = span.first + i;
  776. let lo = piece * 65536;
  777. let lo = if lo > span.skew { lo - span.skew } else { 0 };
  778. let hi = (piece + 1) * 65536 - span.skew;
  779. (lo.max(span.from), hi.min(span.to))
  780. }
  781. /// The pieces of a span cover it without gaps, and the shader's
  782. /// arithmetic names the same bytes as ours.
  783. #[test]
  784. fn the_shader_and_the_merge_cut_the_same_pieces() {
  785. for start in [0usize, 4096, PIECE - 16, PIECE, 3 * PIECE + 0x1f00, 0xd_b790_df00] {
  786. let len = 5 * PIECE + 4096;
  787. for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] {
  788. let span = card_span_of(start, from, to);
  789. let mut at = from;
  790. for i in 0..span.pieces {
  791. let (lo, hi) = card_piece_of(start, len, &span, i);
  792. assert_eq!(lo, at, "{start:#x} {from} {to} piece {i}");
  793. assert!(hi > lo && hi - lo <= PIECE);
  794. assert_eq!(shader_piece(&span, i), (lo as u32, hi as u32), "{start:#x} {from} {to} piece {i}");
  795. at = hi;
  796. }
  797. assert_eq!(at, to, "{start:#x} {from} {to}");
  798. }
  799. }
  800. }
  801. /// Changed ranges are joined where they overlap or touch, and only there.
  802. /// What is fetched of a piece to hash it is what the shader hashes.
  803. #[test]
  804. fn a_piece_is_hashed_here_as_on_the_card() {
  805. for start in [0usize, 0x10_0000, 0xd_5edb_c780, 0x12_3456_7008] {
  806. for size in [1usize << 16, 5 << 16, 0x20_0000] {
  807. let span = card_span_of(start, 0, size);
  808. for i in 0..span.pieces {
  809. // As `CARD_COMPARE` has it.
  810. let (piece, skew, size) = (span.first + i, span.skew, size as u32);
  811. let lo = (piece * 65536).saturating_sub(skew);
  812. let hi = ((piece + 1) * 65536 - skew).min(size);
  813. let shader = (lo & !15, (hi + 15) & !15);
  814. let here = card_hashed_of(start, size as usize, piece as usize);
  815. assert_eq!((here.0 as u32, here.1 as u32), shader, "start {start:#x} size {size:#x} piece {piece}");
  816. }
  817. }
  818. }
  819. }
  820. #[test]
  821. fn ranges_join_where_they_touch() {
  822. assert_eq!(joined(vec![(8, 12), (0, 4), (4, 6), (10, 20), (30, 31)]), [(0, 6), (8, 20), (30, 31)]);
  823. assert!(joined(Vec::new()).is_empty());
  824. }
  825. }
  826. /// Whether the copy-back of what shaders wrote runs on a thread of its own,
  827. /// beside the submitting thread and outside the submission lock
  828. /// (`VICTORY_RELAY=1` or `2`; off by default; not with kept snapshots,
  829. /// [`keeps`]). `crate::host::relay` says what it does; here it changes
  830. /// what a copy keeps:
  831. ///
  832. /// - the ranges shaders may be writing are counted per submission
  833. /// ([`Flights`]): a range two flights declared stays closed to refreshes
  834. /// until both have been copied back;
  835. /// - the merge of what the card wrote never stores into memory the card
  836. /// may be writing ([`merge_piece`]): what it learns goes into title
  837. /// memory and into the copy's reference (the snapshot, or the CPU's side
  838. /// of a copy in the card's memory), under that reference's lock;
  839. /// - what goes up to a copy in the card's memory is numbered
  840. /// ([`card_dirty`]), so that a merge can tell the title's bytes the card
  841. /// had not received from bytes the card wrote.
  842. pub(crate) fn relay() -> bool {
  843. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  844. // On by default (stage 2, `crate::host::relay_exact`); `VICTORY_RELAY=0`
  845. // turns it off, `=1` asks for the first stage.
  846. // The crate's own tests run without it unless they ask: several of
  847. // them look at title memory right after a submission, which the
  848. // relay's landing thread may still be writing.
  849. *ON.get_or_init(|| std::env::var("VICTORY_RELAY").map_or(!cfg!(test), |v| v == "1" || v == "2") && !keeps())
  850. }
  851. /// The submission being prepared (its number among those started): what
  852. /// [`Shadow::writing`] counts a declared range for ([`Flights`]).
  853. static PREPARED: AtomicU64 = AtomicU64::new(0);
  854. /// A submission's preparing begins (`crate::host`, under the submission
  855. /// lock).
  856. pub(crate) fn preparing(number: u64) {
  857. PREPARED.store(number, Ordering::Relaxed);
  858. }
  859. /// With [`relay`]: the number of the last send of changed ranges to the
  860. /// card (`crate::host`'s order of the queue) that every fetch still to be
  861. /// merged came after. Notes of sends up to it are of no use any more.
  862. static RELAY_FETCHED: AtomicU64 = AtomicU64::new(0);
  863. /// A fetch sent after send `number` is the oldest one that may still be
  864. /// merged ([`RELAY_FETCHED`]).
  865. pub(crate) fn relay_fetched(number: u64) {
  866. RELAY_FETCHED.fetch_max(number, Ordering::AcqRel);
  867. }
  868. /// With [`relay`]: how many submissions that are not copied back yet
  869. /// declared each range shaders may be writing (range, count, the last
  870. /// submission that declared it).
  871. ///
  872. /// Without it a range declared by two flights was one entry, and the end
  873. /// of the first flight's copy-back removed it while the second was still
  874. /// writing: the next refresh would have put title bytes over what the
  875. /// second flight's shaders were writing.
  876. #[derive(Default)]
  877. struct Flights(std::collections::HashMap<(usize, usize), (u32, u64)>);
  878. impl Flights {
  879. /// Submission `number` declares `range`: counted once for it, however
  880. /// often it declares it.
  881. fn declare(&mut self, range: (usize, usize), number: u64) {
  882. let f = self.0.entry(range).or_insert((0, number));
  883. if f.0 == 0 || f.1 != number {
  884. *f = (f.0 + 1, number);
  885. }
  886. }
  887. /// One submission that declared `ranges` (each once) is copied back:
  888. /// the ranges no other submission still holds, in order.
  889. fn done(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> {
  890. let mut free = Vec::new();
  891. for range in ranges {
  892. match self.0.get_mut(range) {
  893. Some(f) if f.0 > 1 => f.0 -= 1,
  894. Some(_) => {
  895. self.0.remove(range);
  896. free.push(*range);
  897. }
  898. // Not counted (declared before anything counted): free.
  899. None => free.push(*range),
  900. }
  901. }
  902. free.sort_unstable();
  903. free
  904. }
  905. }
  906. /// The relay's merge of a stretch of a copy ([`relay`]). `now` is what the
  907. /// card's memory holds, read once; `held` is the copy's reference for the
  908. /// stretch (its snapshot, or the CPU's side of a copy in the card's
  909. /// memory): what the card's memory held when it was last looked at;
  910. /// `title` is title memory as just read. Every byte the card changed
  911. /// (`now` differs from `held`) goes into `title` and into `held`; every
  912. /// other byte of both stays as it is, so a byte the title wrote and the
  913. /// card did not keeps the title's value. Whether `title` changed.
  914. ///
  915. /// Nothing is stored into `now`'s source: the card may be writing it for a
  916. /// later flight at this moment, and a store there, even of the value just
  917. /// read, could undo that write. (The merge of a waited-for submission
  918. /// stores every byte of a differing stretch back into the copy.)
  919. fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool {
  920. let mut differs = 0u8;
  921. for ((n, h), t) in now.iter().zip(held.iter_mut()).zip(title.iter_mut()) {
  922. let wrote = if *n != *h { 0xffu8 } else { 0 };
  923. let merged = (*t & !wrote) | (*n & wrote);
  924. differs |= merged ^ *t;
  925. *t = merged;
  926. *h = (*h & !wrote) | (*n & wrote);
  927. }
  928. differs != 0
  929. }
  930. /// `[from, to)` without the ranges of `skip`, in order.
  931. fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
  932. skip.sort_unstable();
  933. let mut out = Vec::new();
  934. let mut at = from;
  935. for (a, b) in skip {
  936. if b <= at {
  937. continue;
  938. }
  939. if a >= to {
  940. break;
  941. }
  942. if a > at {
  943. out.push((at, a));
  944. }
  945. at = at.max(b);
  946. }
  947. if at < to {
  948. out.push((at, to));
  949. }
  950. out
  951. }
  952. #[cfg(test)]
  953. mod relay_tests {
  954. use super::{Flights, changed_runs, merge_piece, outside};
  955. /// A range two flights declared is free only when both are done, in
  956. /// either order; a submission that declares it many times counts once.
  957. #[test]
  958. fn a_range_stays_closed_until_every_flight_that_declared_it_is_done() {
  959. let (a, b) = ((0x1000, 0x2000), (0x1800, 0x3000));
  960. let mut flights = Flights::default();
  961. for _ in 0..3 {
  962. flights.declare(a, 7);
  963. }
  964. flights.declare(b, 7);
  965. flights.declare(a, 8);
  966. // Flight 7 lands: `a` is still flight 8's, `b` was only flight 7's.
  967. assert_eq!(flights.done(&[a, b]), vec![b]);
  968. // Declared again meanwhile by a third.
  969. flights.declare(a, 9);
  970. assert_eq!(flights.done(&[a]), vec![]);
  971. assert_eq!(flights.done(&[a]), vec![a]);
  972. assert!(flights.0.is_empty());
  973. // The later flight first: the same.
  974. flights.declare(a, 1);
  975. flights.declare(a, 2);
  976. assert_eq!(flights.done(&[a]), vec![]);
  977. assert_eq!(flights.done(&[a]), vec![a]);
  978. // A range never counted is free at once.
  979. assert_eq!(flights.done(&[b]), vec![b]);
  980. }
  981. /// The merge moves exactly the bytes the card changed, into title
  982. /// memory and into the reference, and stores nothing else.
  983. #[test]
  984. fn the_merge_stores_only_what_the_card_changed() {
  985. let held0: Vec<u8> = (0..200u32).map(|i| (i * 5 + 1) as u8).collect();
  986. let mut now = held0.clone();
  987. for at in [0usize, 3, 4, 5, 64, 199] {
  988. now[at] ^= 0x33;
  989. }
  990. // The title wrote other bytes meanwhile, and one the card wrote too.
  991. let mut title = held0.clone();
  992. for at in [1usize, 5, 100] {
  993. title[at] = 0xee;
  994. }
  995. let title0 = title.clone();
  996. let mut held = held0.clone();
  997. assert!(merge_piece(&now, &mut held, &mut title));
  998. for at in 0..200 {
  999. if now[at] != held0[at] {
  1000. assert_eq!((title[at], held[at]), (now[at], now[at]), "the card's byte at {at}");
  1001. } else {
  1002. assert_eq!((title[at], held[at]), (title0[at], held0[at]), "untouched at {at}");
  1003. }
  1004. }
  1005. // Again with nothing new: nothing changes and nothing is reported.
  1006. let (title1, held1) = (title.clone(), held.clone());
  1007. assert!(!merge_piece(&now, &mut held, &mut title));
  1008. assert_eq!((title, held), (title1, held1));
  1009. }
  1010. #[test]
  1011. fn ranges_are_cut_out() {
  1012. assert_eq!(outside(10, 50, vec![]), vec![(10, 50)]);
  1013. assert_eq!(outside(10, 50, vec![(0, 10), (50, 60)]), vec![(10, 50)]);
  1014. assert_eq!(outside(10, 50, vec![(30, 35), (0, 12), (34, 40), (48, 99)]), vec![(12, 30), (40, 48)]);
  1015. assert_eq!(outside(10, 50, vec![(0, 99)]), vec![]);
  1016. }
  1017. /// A model of a copy in the PC's memory under the relay: the card
  1018. /// writes `copy` directly; `snap` is the snapshot; `title` is title
  1019. /// memory. Flight A and flight B declare overlapping ranges and both
  1020. /// are in the air; the title's CPU writes in between and its bytes are
  1021. /// put in beside the flights' (`merge_under_writes`: into the copy and
  1022. /// the snapshot); A lands while B is still writing; then B lands.
  1023. #[test]
  1024. fn two_flights_overlapping_ranges_and_a_cpu_write_in_between() {
  1025. const N: usize = 64;
  1026. let base: Vec<u8> = (0..N as u32).map(|i| i as u8).collect();
  1027. let (mut copy, mut title) = (base.clone(), base.clone());
  1028. // A declares [0, 40), B declares [24, 64): each byte's snapshot is
  1029. // taken when the first range that holds it is declared.
  1030. let (a, b) = ((0usize, 40usize), (24usize, 64usize));
  1031. let mut snap = base.clone();
  1032. // The card runs A: writes 4..12 and 30..34.
  1033. for at in (4..12).chain(30..34) {
  1034. copy[at] = 0xa0;
  1035. }
  1036. // The title's CPU writes 8..10 (over A's bytes), 20 and 50, after
  1037. // A's refresh: the next submission's preparing finds them against
  1038. // the snapshot and puts them in, into the copy and the snapshot.
  1039. for at in [8usize, 9, 20, 50] {
  1040. title[at] = 0x77;
  1041. }
  1042. for (at, n) in changed_runs(&title, &snap) {
  1043. copy[at..at + n].copy_from_slice(&title[at..at + n]);
  1044. snap[at..at + n].copy_from_slice(&title[at..at + n]);
  1045. }
  1046. // The card starts B: it has written 32..36 so far, over A's 32..34.
  1047. for at in 32..36 {
  1048. copy[at] = 0xb0;
  1049. }
  1050. // A lands (B still on the card): its range is merged. The copy is
  1051. // read once and not written.
  1052. let seen = copy.clone();
  1053. {
  1054. let mut t = title[a.0..a.1].to_vec();
  1055. assert!(merge_piece(&seen[a.0..a.1], &mut snap[a.0..a.1], &mut t));
  1056. title[a.0..a.1].copy_from_slice(&t);
  1057. }
  1058. assert_eq!(copy, seen, "the merge stores nothing into the copy");
  1059. // A's bytes are in title memory, except where the title wrote
  1060. // after A's shaders did (8, 9: the title's); B's first bytes came
  1061. // along; nothing of B's range beyond A's was touched.
  1062. for at in (4..8).chain(10..12).chain(30..32) {
  1063. assert_eq!(title[at], 0xa0, "A's byte at {at}");
  1064. }
  1065. assert_eq!((title[8], title[9], title[20], title[50]), (0x77, 0x77, 0x77, 0x77));
  1066. for at in 32..36 {
  1067. assert_eq!(title[at], 0xb0, "B's byte so far at {at}");
  1068. }
  1069. // The card finishes B: 36..44.
  1070. for at in 36..44 {
  1071. copy[at] = 0xb1;
  1072. }
  1073. // The title's CPU writes 40 after B's shader did: found against
  1074. // the snapshot at the next preparing, which is before B lands.
  1075. title[40] = 0x55;
  1076. for (at, n) in changed_runs(&title[b.0..b.1], &snap[b.0..b.1]) {
  1077. let at = at + b.0;
  1078. copy[at..at + n].copy_from_slice(&title[at..at + n]);
  1079. snap[at..at + n].copy_from_slice(&title[at..at + n]);
  1080. }
  1081. // B lands.
  1082. let seen = copy.clone();
  1083. {
  1084. let mut t = title[b.0..b.1].to_vec();
  1085. assert!(merge_piece(&seen[b.0..b.1], &mut snap[b.0..b.1], &mut t));
  1086. title[b.0..b.1].copy_from_slice(&t);
  1087. }
  1088. // B's results are there, never replaced by A's older ones.
  1089. for at in 32..36 {
  1090. assert_eq!(title[at], 0xb0);
  1091. }
  1092. for at in (36..40).chain(41..44) {
  1093. assert_eq!(title[at], 0xb1, "B's byte at {at}");
  1094. }
  1095. assert_eq!(title[40], 0x55, "the title wrote it last");
  1096. // In the declared ranges the copy, the snapshot and title memory
  1097. // now agree byte for byte: nothing is left to hand back, and
  1098. // nothing was lost.
  1099. assert_eq!(copy[a.0..b.1], title[a.0..b.1]);
  1100. assert_eq!(snap[a.0..b.1], title[a.0..b.1]);
  1101. // A third merge finds nothing.
  1102. let mut t = title.clone();
  1103. assert!(!merge_piece(&copy, &mut snap, &mut t));
  1104. }
  1105. /// A model of a copy in the card's memory under the relay: `card` is
  1106. /// the card's side, `cpu` the CPU's side, `title` title memory. The
  1107. /// title's changed bytes go into the CPU's side at once and up to the
  1108. /// card with a later send; pieces fetched before that send must not
  1109. /// take the card's older bytes there for something the card wrote.
  1110. #[test]
  1111. fn title_bytes_not_yet_on_the_card_are_not_taken_for_shader_writes() {
  1112. const N: usize = 48;
  1113. let base: Vec<u8> = (0..N as u32).map(|i| (i + 100) as u8).collect();
  1114. let (mut card, mut cpu, mut title) = (base.clone(), base.clone(), base.clone());
  1115. // Flight A's shaders write 10..14 on the card.
  1116. for at in 10..14 {
  1117. card[at] = 0xa0;
  1118. }
  1119. // The title's CPU writes 12 (over A's) and 30; the preparing of
  1120. // the next submission puts both into the CPU's side and notes them
  1121. // to go up (send 5). They are not on the card yet.
  1122. title[12] = 0x77;
  1123. title[30] = 0x78;
  1124. let mut noted = Vec::new();
  1125. for (at, n) in changed_runs(&title, &cpu) {
  1126. cpu[at..at + n].copy_from_slice(&title[at..at + n]);
  1127. noted.push((at, at + n, 5u64));
  1128. }
  1129. // A's pieces are fetched after send 4, before send 5: the fetch
  1130. // holds A's bytes and the card's old bytes at 12 and 30.
  1131. let fetched = card.clone();
  1132. let fetched_after = 4u64;
  1133. // Send 5 goes up behind it.
  1134. for &(a, b, _) in &noted {
  1135. card[a..b].copy_from_slice(&cpu[a..b]);
  1136. }
  1137. // The merge leaves out what went up after the fetch.
  1138. let skip: Vec<(usize, usize)> = noted.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)).collect();
  1139. let mut changed = false;
  1140. for (a, b) in outside(0, N, skip) {
  1141. let mut t = title[a..b].to_vec();
  1142. changed |= merge_piece(&fetched[a..b], &mut cpu[a..b], &mut t);
  1143. title[a..b].copy_from_slice(&t);
  1144. }
  1145. assert!(changed);
  1146. // A's bytes arrived; the title's two writes stand, in title memory
  1147. // and on both sides of the copy.
  1148. for at in [10usize, 11, 13] {
  1149. assert_eq!((title[at], cpu[at]), (0xa0, 0xa0));
  1150. }
  1151. assert_eq!((title[12], cpu[12], card[12]), (0x77, 0x77, 0x77));
  1152. assert_eq!((title[30], cpu[30], card[30]), (0x78, 0x78, 0x78));
  1153. assert_eq!(card, cpu);
  1154. assert_eq!(card, title);
  1155. // Without the leaving out, the card's old byte at 30 would have
  1156. // been taken for a shader write and put over the title's.
  1157. let mut wrong_title = title.clone();
  1158. let mut wrong_cpu = cpu.clone();
  1159. merge_piece(&fetched, &mut wrong_cpu, &mut wrong_title);
  1160. assert_eq!(wrong_title[30], base[30]);
  1161. }
  1162. }
  1163. /// Snapshot memory kept for reuse (already touched, so no page faults).
  1164. static POOL: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new());
  1165. /// An empty buffer with room for `n` bytes, from the pool if it has one
  1166. /// of about that size: a small copy's snapshot took the 174 MB buffer kept
  1167. /// for the big heap's, which then got another, until eight of them were
  1168. /// reserved (1.4 GB in run 24).
  1169. fn pooled(n: usize) -> Vec<u8> {
  1170. let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
  1171. let most = n.saturating_mul(4).max(1 << 20);
  1172. let fit = pool
  1173. .iter()
  1174. .enumerate()
  1175. .filter(|(_, v)| v.capacity() >= n && v.capacity() <= most)
  1176. .min_by_key(|(_, v)| v.capacity())
  1177. .map(|(i, _)| i);
  1178. let mut v = match fit {
  1179. Some(i) => pool.swap_remove(i),
  1180. None => Vec::with_capacity(n),
  1181. };
  1182. v.clear();
  1183. v
  1184. }
  1185. /// How many snapshot buffers are kept (`VICTORY_SNAPSHOT_POOL`; `8`: as
  1186. /// before).
  1187. ///
  1188. /// A frame gives some 330 ranges of copies in the PC's memory to shaders, and
  1189. /// most are of copies of their own; with two or three frames in the air eight
  1190. /// buffers were the eight largest, and every other snapshot was memory fresh
  1191. /// from the kernel and given back to it: 11 % of the submitting thread in the
  1192. /// opening (profile cpu-1: `NtAllocateVirtualMemory` under
  1193. /// [`Shadow::writing`]), and the page faults of filling it.
  1194. fn snapshots_kept() -> usize {
  1195. static MOST: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
  1196. *MOST.get_or_init(|| std::env::var("VICTORY_SNAPSHOT_POOL").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1024))
  1197. }
  1198. /// Returns a snapshot buffer to the pool: at most [`snapshots_kept`] kept,
  1199. /// the largest, and of those the largest one and the next ones up to `KEPT`
  1200. /// bytes in all.
  1201. fn give_back(v: Vec<u8>) {
  1202. const KEPT: usize = 512 << 20;
  1203. let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
  1204. pool.push(v);
  1205. pool.sort_by_key(|v| std::cmp::Reverse(v.capacity()));
  1206. let (mut kept, mut total) = (0, 0usize);
  1207. for v in pool.iter().take(snapshots_kept()) {
  1208. total = total.saturating_add(v.capacity());
  1209. if kept > 0 && total > KEPT {
  1210. break;
  1211. }
  1212. kept += 1;
  1213. }
  1214. // (Given back to the kernel without the lock: milliseconds.)
  1215. let gone = pool.split_off(kept);
  1216. drop(pool);
  1217. drop(gone);
  1218. }
  1219. const NOT_WATCHED: u8 = 2;
  1220. /// Watched, not by the kernel but by the guards, when last asked about.
  1221. const GUARDED: u8 = 3;
  1222. // Fixed-size equality compiles to two SIMD comparisons on Windows x64.
  1223. // Only the first or last unequal chunk needs a byte-wise search.
  1224. const DIFF_CHUNK: usize = 32;
  1225. /// Where `a` and `b` first differ within their common length.
  1226. fn first_difference(a: &[u8], b: &[u8]) -> Option<usize> {
  1227. let len = a.len().min(b.len());
  1228. let (a_chunks, a_tail) = a[..len].as_chunks::<DIFF_CHUNK>();
  1229. let (b_chunks, b_tail) = b[..len].as_chunks::<DIFF_CHUNK>();
  1230. let (offset, a, b) = match a_chunks.iter().zip(b_chunks).position(|(x, y)| x != y) {
  1231. Some(i) => (i * DIFF_CHUNK, &a_chunks[i][..], &b_chunks[i][..]),
  1232. None => (len - a_tail.len(), a_tail, b_tail),
  1233. };
  1234. a.iter().zip(b).position(|(x, y)| x != y).map(|i| offset + i)
  1235. }
  1236. /// Where `a` and `b` last differ within their common length.
  1237. fn last_difference(a: &[u8], b: &[u8]) -> Option<usize> {
  1238. let len = a.len().min(b.len());
  1239. let (a_chunks, a_tail) = a[..len].as_chunks::<DIFF_CHUNK>();
  1240. let (b_chunks, b_tail) = b[..len].as_chunks::<DIFF_CHUNK>();
  1241. if let Some(i) = a_tail.iter().zip(b_tail).rposition(|(x, y)| x != y) {
  1242. return Some(len - a_tail.len() + i);
  1243. }
  1244. let chunk = a_chunks.iter().zip(b_chunks).rposition(|(x, y)| x != y)?;
  1245. a_chunks[chunk]
  1246. .iter()
  1247. .zip(&b_chunks[chunk])
  1248. .rposition(|(x, y)| x != y)
  1249. .map(|i| chunk * DIFF_CHUNK + i)
  1250. }
  1251. #[cfg(test)]
  1252. mod difference_tests {
  1253. use super::{first_difference, last_difference};
  1254. /// The chunk searches agree with a byte-wise scan across chunk boundaries.
  1255. #[test]
  1256. fn differences_are_found_as_byte_by_byte() {
  1257. let base: Vec<u8> = (0..98u32).map(|i| (i * 7 + 3) as u8).collect();
  1258. for len in [0, 1, 31, 32, 33, 63, 64, 65, 97] {
  1259. let a = &base[1..1 + len];
  1260. let same = a.to_vec();
  1261. assert_eq!(first_difference(&same, a), None);
  1262. assert_eq!(last_difference(&same, a), None);
  1263. for at in 0..len {
  1264. for other in at..len {
  1265. let mut b = a.to_vec();
  1266. b[at] ^= 0x80;
  1267. b[other] ^= 0x01;
  1268. let first = a.iter().zip(&b).position(|(x, y)| x != y);
  1269. let last = a.iter().zip(&b).rposition(|(x, y)| x != y);
  1270. assert_eq!(first_difference(a, &b), first, "{len} {at} {other}");
  1271. assert_eq!(last_difference(a, &b), last, "{len} {at} {other}");
  1272. }
  1273. }
  1274. }
  1275. }
  1276. #[test]
  1277. fn differences_ignore_bytes_past_the_shorter_slice() {
  1278. let a = [0; 65];
  1279. let mut b = [0; 67];
  1280. b[65] = 1;
  1281. assert_eq!(first_difference(&a, &b), None);
  1282. assert_eq!(last_difference(&b, &a), None);
  1283. b[32] = 1;
  1284. b[64] = 1;
  1285. assert_eq!(first_difference(&b, &a), Some(32));
  1286. assert_eq!(last_difference(&a, &b), Some(64));
  1287. }
  1288. }
  1289. /// The unit shader writes are looked for and put back in.
  1290. const PIECE: usize = 64 << 10;
  1291. /// Calls `f` with `[from, to)` cut at multiples of [`PIECE`].
  1292. fn for_pieces_of(from: usize, to: usize, mut f: impl FnMut(usize, usize)) {
  1293. let mut at = from;
  1294. while at < to {
  1295. let next = ((at / PIECE + 1) * PIECE).min(to);
  1296. f(at, next);
  1297. at = next;
  1298. }
  1299. }
  1300. /// Copies `len` bytes, on several threads if they are many: a snapshot of
  1301. /// the world's big heap is 100-170 MB per submission, 2-4 GB a frame, and
  1302. /// one thread copies some 8 GB/s.
  1303. ///
  1304. /// # Safety
  1305. /// Both ranges are valid for `len` bytes and do not overlap.
  1306. unsafe fn copy_wide(src: *const u8, dst: *mut u8, len: usize) {
  1307. const PER_THREAD: usize = 16 << 20;
  1308. let threads = (len / PER_THREAD).clamp(1, 6);
  1309. if threads == 1 {
  1310. // SAFETY: the caller's.
  1311. unsafe { std::ptr::copy_nonoverlapping(src, dst, len) };
  1312. return;
  1313. }
  1314. let (src, dst, each) = (src as usize, dst as usize, len.div_ceil(threads));
  1315. std::thread::scope(|s| {
  1316. for i in 0..threads {
  1317. let at = (i * each).min(len);
  1318. let n = each.min(len - at);
  1319. s.spawn(move || {
  1320. // SAFETY: a part of the caller's ranges.
  1321. unsafe { std::ptr::copy_nonoverlapping((src + at) as *const u8, (dst + at) as *mut u8, n) };
  1322. });
  1323. }
  1324. });
  1325. }
  1326. /// Whether the snapshots of a submission's shader-written ranges, and the
  1327. /// compare that finds what the shaders wrote, run on several threads
  1328. /// across ranges (`VICTORY_WIDE_BACK=1`; off by default).
  1329. ///
  1330. /// Both ran range by range on the submitting thread, a range on several
  1331. /// threads only if it was 16 MiB or more. The ranges left on the CPU's side
  1332. /// since the big buffers went to the card are small and many: in run 86,
  1333. /// 7,024 declared ranges a frame, 375 MB of them compared after the card
  1334. /// ran in 563 pieces of work, none of 16 MiB: 51 ms a frame of snapshots
  1335. /// and 35 ms of comparing, one thread, bound by one core's memory speed.
  1336. ///
  1337. /// With the switch a submission's snapshots are noted as it is prepared
  1338. /// and taken together when its refreshes are done, just before it goes to
  1339. /// the card ([`take_snapshots`]), and the compares of everything declared
  1340. /// run together after the card ([`find_all`]), both cut into pieces of
  1341. /// work of about 1 MiB for a few threads that are kept ([`wide`]). The
  1342. /// bytes taken and the bytes compared are the same ones: a range's bytes
  1343. /// cannot change between the moment it is declared and the end of the
  1344. /// preparing (a declared range is left alone by every refresh, the title's
  1345. /// own copies write title memory and not the copy, and the card runs the
  1346. /// lists only afterwards).
  1347. pub(crate) fn wide_back() -> bool {
  1348. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1349. // On by default; `VICTORY_WIDE_BACK=0` turns it off.
  1350. *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_BACK").is_none_or(|v| v != "0"))
  1351. }
  1352. type Job = Box<dyn FnOnce() + Send>;
  1353. /// Threads kept for [`wide`]: what they are to do, and the word that there
  1354. /// is something.
  1355. struct Workers {
  1356. jobs: Mutex<std::collections::VecDeque<Job>>,
  1357. more: std::sync::Condvar,
  1358. }
  1359. /// How many threads are kept for [`wide`].
  1360. fn wide_threads() -> usize {
  1361. std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6)
  1362. }
  1363. fn workers() -> &'static Workers {
  1364. static WORKERS: std::sync::OnceLock<Workers> = std::sync::OnceLock::new();
  1365. static STARTED: std::sync::Once = std::sync::Once::new();
  1366. let workers = WORKERS.get_or_init(|| Workers {
  1367. jobs: Mutex::new(std::collections::VecDeque::new()),
  1368. more: std::sync::Condvar::new(),
  1369. });
  1370. STARTED.call_once(|| {
  1371. for i in 0..wide_threads() {
  1372. let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || {
  1373. crate::cores::keep_helper_on_fast_cores("victory-wide");
  1374. let workers = WORKERS.get().expect("made above");
  1375. loop {
  1376. let job = {
  1377. let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
  1378. loop {
  1379. if let Some(job) = jobs.pop_front() {
  1380. break job;
  1381. }
  1382. jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner());
  1383. }
  1384. };
  1385. let _working = crate::timeline::span("a job for another thread");
  1386. job();
  1387. }
  1388. });
  1389. }
  1390. });
  1391. workers
  1392. }
  1393. /// Runs `jobs` on the kept threads and on this one, and returns when all
  1394. /// of them are done. The jobs copy and compare memory; they do not panic.
  1395. fn wide(jobs: Vec<Job>) {
  1396. if jobs.len() < 2 {
  1397. for job in jobs {
  1398. job();
  1399. }
  1400. return;
  1401. }
  1402. let workers = workers();
  1403. let _wide = crate::timeline::span("work spread over threads");
  1404. let left = Arc::new((Mutex::new(jobs.len()), std::sync::Condvar::new()));
  1405. {
  1406. let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
  1407. for job in jobs {
  1408. let left = left.clone();
  1409. queue.push_back(Box::new(move || {
  1410. job();
  1411. let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner());
  1412. *n -= 1;
  1413. if *n == 0 {
  1414. left.1.notify_all();
  1415. }
  1416. }));
  1417. }
  1418. }
  1419. workers.more.notify_all();
  1420. loop {
  1421. let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front();
  1422. match job {
  1423. Some(job) => job(),
  1424. None => break,
  1425. }
  1426. }
  1427. let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner());
  1428. while *n > 0 {
  1429. n = left.1.wait(n).unwrap_or_else(|e| e.into_inner());
  1430. }
  1431. }
  1432. /// [`wide`], for the host's own work on host copies (a submission's
  1433. /// refreshes, the merge of what shaders wrote to card copies).
  1434. pub(crate) fn wide_run(jobs: Vec<Box<dyn FnOnce() + Send>>) {
  1435. wide(jobs);
  1436. }
  1437. /// Calls `work` with every number under `n`, on the kept threads and on
  1438. /// this one, the next number to whichever is free: for thousands of small
  1439. /// pieces of work, where a job each ([`wide`]) is mostly the jobs' queue.
  1440. pub(crate) fn wide_each(n: usize, work: impl Fn(usize) + Send + Sync + 'static) {
  1441. let next = Arc::new(std::sync::atomic::AtomicUsize::new(0));
  1442. let work = Arc::new(work);
  1443. let threads = (wide_threads() + 1).min(n);
  1444. let jobs = (0..threads)
  1445. .map(|_| {
  1446. let (next, work) = (next.clone(), work.clone());
  1447. Box::new(move || {
  1448. loop {
  1449. let i = next.fetch_add(1, Ordering::Relaxed);
  1450. if i >= n {
  1451. break;
  1452. }
  1453. work(i);
  1454. }
  1455. }) as Job
  1456. })
  1457. .collect();
  1458. wide(jobs);
  1459. }
  1460. /// About this many bytes to a piece of work for [`wide`].
  1461. const WIDE_JOB: usize = 1 << 20;
  1462. /// With [`wide_back`]: the snapshots noted while a submission is prepared
  1463. /// (from, to, bytes), taken by [`take_snapshots`].
  1464. static SNAPS: Mutex<Vec<(usize, usize, usize)>> = Mutex::new(Vec::new());
  1465. /// With [`wide_back`], when a submission's refreshes are done and before
  1466. /// its lists go to the card: takes the snapshots [`Shadow::writing`] noted.
  1467. /// Nothing to do without the switch.
  1468. pub(crate) fn take_snapshots() {
  1469. let snaps = std::mem::take(&mut *SNAPS.lock().unwrap_or_else(|e| e.into_inner()));
  1470. if snaps.is_empty() {
  1471. return;
  1472. }
  1473. wide(copy_jobs(snaps));
  1474. }
  1475. /// `copies` (from, to, bytes) as pieces of work of about [`WIDE_JOB`]
  1476. /// bytes each: long ones cut, short ones together.
  1477. fn copy_jobs(copies: Vec<(usize, usize, usize)>) -> Vec<Job> {
  1478. let mut jobs: Vec<Job> = Vec::new();
  1479. let mut group: Vec<(usize, usize, usize)> = Vec::new();
  1480. let mut bytes = 0;
  1481. let flush = |group: &mut Vec<(usize, usize, usize)>, jobs: &mut Vec<Job>| {
  1482. let group = std::mem::take(group);
  1483. if !group.is_empty() {
  1484. jobs.push(Box::new(move || {
  1485. for (src, dst, len) in group {
  1486. // SAFETY: the caller's ranges: a host copy's mapping and
  1487. // its snapshot, which do not overlap.
  1488. unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) };
  1489. }
  1490. }));
  1491. }
  1492. };
  1493. for (src, dst, len) in copies {
  1494. let mut at = 0;
  1495. while at < len {
  1496. let n = (WIDE_JOB - bytes).min(len - at);
  1497. group.push((src + at, dst + at, n));
  1498. at += n;
  1499. bytes += n;
  1500. if bytes >= WIDE_JOB {
  1501. flush(&mut group, &mut jobs);
  1502. bytes = 0;
  1503. }
  1504. }
  1505. }
  1506. flush(&mut group, &mut jobs);
  1507. jobs
  1508. }
  1509. /// With [`wide_back`]: for each of `work` (a copy not in the card's memory
  1510. /// and a range `[address, end)` its shaders may have written, declared and
  1511. /// not yet done), the 64 KiB pieces that differ from the snapshot, as
  1512. /// [`Shadow::copy_back_with`] takes them; found on several threads.
  1513. pub(crate) fn find_all(work: &[(Arc<Shadow>, usize, usize)]) -> Vec<Vec<(usize, usize)>> {
  1514. let scans = work
  1515. .iter()
  1516. .map(|(shadow, address, end)| {
  1517. let (from, to) = shadow.inside(*address, end.saturating_sub(*address));
  1518. // The snapshot's memory stays until the range is done with
  1519. // (`copy_back_done`), which comes after this.
  1520. match shadow.before.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
  1521. Some(before) => (shadow.data as usize, before.as_ptr() as usize, shadow.start as usize, from, to),
  1522. None => (0, 0, 0, 0, 0),
  1523. }
  1524. })
  1525. .collect();
  1526. find_pieces(scans)
  1527. }
  1528. /// For each of `scans` (where a copy's bytes are, where its snapshot's
  1529. /// are, the title address the copy starts at, offsets from and to): the
  1530. /// 64 KiB pieces (cut at multiples of 64 KiB of title memory, as
  1531. /// [`Shadow::differing`] cuts them) of `[from, to)` whose bytes differ, as
  1532. /// (offset, bytes) in order. On several threads ([`wide`]), in pieces of
  1533. /// work of about [`WIDE_JOB`] bytes that hold whole pieces.
  1534. fn find_pieces(scans: Vec<(usize, usize, usize, usize, usize)>) -> Vec<Vec<(usize, usize)>> {
  1535. // What a job finds: (which scan, its place among that scan's jobs, the
  1536. // pieces).
  1537. type Found = Vec<(usize, usize, Vec<(usize, usize)>)>;
  1538. // A job's part of a scan: the scan, then which and place.
  1539. type Part = (usize, usize, usize, usize, usize, usize, usize);
  1540. let found: Arc<Mutex<Found>> = Arc::default();
  1541. let mut jobs: Vec<Job> = Vec::new();
  1542. let mut group: Vec<Part> = Vec::new();
  1543. let mut bytes = 0;
  1544. let flush = |group: &mut Vec<Part>, jobs: &mut Vec<Job>| {
  1545. let group = std::mem::take(group);
  1546. if group.is_empty() {
  1547. return;
  1548. }
  1549. let found = found.clone();
  1550. jobs.push(Box::new(move || {
  1551. let mut mine: Found = Vec::with_capacity(group.len());
  1552. for (data, before, start, from, to, which, place) in group {
  1553. let mut pieces = Vec::new();
  1554. let mut at = from;
  1555. while at < to {
  1556. let n = (PIECE - (start + at) % PIECE).min(to - at);
  1557. // SAFETY: inside the copy's mapping and its snapshot
  1558. // (which holds the copy's bytes at the copy's offsets);
  1559. // nothing writes either while a submission's results
  1560. // are compared.
  1561. let (now, old) = unsafe {
  1562. (
  1563. std::slice::from_raw_parts((data + at) as *const u8, n),
  1564. std::slice::from_raw_parts((before + at) as *const u8, n),
  1565. )
  1566. };
  1567. if now != old {
  1568. pieces.push((at, n));
  1569. }
  1570. at += n;
  1571. }
  1572. mine.push((which, place, pieces));
  1573. }
  1574. found.lock().unwrap_or_else(|e| e.into_inner()).extend(mine);
  1575. }));
  1576. };
  1577. let count = scans.len();
  1578. for (which, (data, before, start, from, to)) in scans.into_iter().enumerate() {
  1579. let (mut at, mut place) = (from, 0);
  1580. while at < to {
  1581. // Cut where pieces end, so that every job sees whole pieces.
  1582. let room = (WIDE_JOB - bytes).max(PIECE);
  1583. let mut next = (at + room).min(to);
  1584. if next < to {
  1585. next -= (start + next) % PIECE;
  1586. if next <= at {
  1587. next = (at + PIECE - (start + at) % PIECE).min(to);
  1588. }
  1589. }
  1590. group.push((data, before, start, at, next, which, place));
  1591. bytes += next - at;
  1592. place += 1;
  1593. at = next;
  1594. if bytes >= WIDE_JOB {
  1595. flush(&mut group, &mut jobs);
  1596. bytes = 0;
  1597. }
  1598. }
  1599. }
  1600. flush(&mut group, &mut jobs);
  1601. wide(jobs);
  1602. let mut found = std::mem::take(&mut *found.lock().unwrap_or_else(|e| e.into_inner()));
  1603. found.sort_unstable_by_key(|f| (f.0, f.1));
  1604. let mut out = vec![Vec::new(); count];
  1605. for (which, _, pieces) in found {
  1606. out[which].extend(pieces);
  1607. }
  1608. out
  1609. }
  1610. /// Since the last frame-rate line, of the shader-written ranges looked for
  1611. /// on the CPU (copies not in the card's memory): bytes snapshotted in
  1612. /// windows outside buffers and in title buffers' copies; bytes compared in
  1613. /// windows, in buffers' copies, and of those in copies of 1 MiB or more;
  1614. /// ranges compared in windows and in buffers' copies.
  1615. static BACK_CLASS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7];
  1616. /// For the frame-rate line: where the CPU's search for shader writes goes
  1617. /// (per frame). A copy of a title buffer can go to the card's memory,
  1618. /// where the card does the search (`VICTORY_CARD_BUFFERS_MIN_MB`); a
  1619. /// window outside buffers cannot as the code stands.
  1620. pub(crate) fn back_line(frames: f64) {
  1621. let c: Vec<f64> = BACK_CLASS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  1622. if c.iter().all(|&v| v == 0.0) {
  1623. return;
  1624. }
  1625. let mb = |v: f64| v / (1 << 20) as f64;
  1626. tracing::info!(
  1627. "shader writes looked for on the CPU per frame: {:.1} MB compared in {:.0} ranges of windows outside buffers ({:.1} MB \
  1628. snapshotted), {:.1} MB in {:.0} ranges of title buffers' copies ({:.1} MB snapshotted), of them {:.1} MB in copies \
  1629. of 1 MiB or more (VICTORY_CARD_BUFFERS_MIN_MB=1 would have the card look there)",
  1630. mb(c[2]),
  1631. c[5],
  1632. mb(c[0]),
  1633. mb(c[3]),
  1634. c[6],
  1635. mb(c[1]),
  1636. mb(c[4]),
  1637. );
  1638. }
  1639. #[cfg(test)]
  1640. mod wide_tests {
  1641. use super::{Job, PIECE, WIDE_JOB, copy_jobs, find_pieces, wide};
  1642. use std::sync::Arc;
  1643. use std::sync::atomic::{AtomicUsize, Ordering};
  1644. /// Every job runs once, however many there are, and `wide` returns
  1645. /// only when all have.
  1646. #[test]
  1647. fn all_jobs_run_before_wide_returns() {
  1648. for n in [0usize, 1, 2, 7, 300] {
  1649. let ran = Arc::new(AtomicUsize::new(0));
  1650. let jobs: Vec<Job> = (0..n)
  1651. .map(|i| {
  1652. let ran = ran.clone();
  1653. Box::new(move || {
  1654. ran.fetch_add(i + 1, Ordering::Relaxed);
  1655. }) as Job
  1656. })
  1657. .collect();
  1658. wide(jobs);
  1659. assert_eq!(ran.load(Ordering::Relaxed), n * (n + 1) / 2, "{n} jobs");
  1660. }
  1661. }
  1662. /// Copies cut into jobs copy every byte once: long ones, short ones
  1663. /// and empty ones.
  1664. #[test]
  1665. fn copies_cut_into_jobs_copy_the_same_bytes() {
  1666. let len = 3 * WIDE_JOB + 12345;
  1667. let src: Vec<u8> = (0..len).map(|i| (i * 31 + i / 977) as u8).collect();
  1668. let mut dst = vec![0u8; len];
  1669. let (s, d) = (src.as_ptr() as usize, dst.as_mut_ptr() as usize);
  1670. // Ranges of the buffer, each to the same offsets of the other.
  1671. let cuts = [0, 1, 1, 4096, 70_000, WIDE_JOB + 3, 2 * WIDE_JOB + 3, 2 * WIDE_JOB + 9, len];
  1672. let copies: Vec<(usize, usize, usize)> = cuts.windows(2).map(|w| (s + w[0], d + w[0], w[1] - w[0])).collect();
  1673. let jobs = copy_jobs(copies);
  1674. assert!(jobs.len() >= 3);
  1675. wide(jobs);
  1676. assert!(src == dst);
  1677. }
  1678. /// The pieces found on several threads are the ones a walk piece by
  1679. /// piece finds, for copies that start anywhere in a 64 KiB piece of
  1680. /// title memory and ranges that start and end anywhere.
  1681. #[test]
  1682. fn pieces_found_wide_are_those_found_one_by_one() {
  1683. let len = 5 * WIDE_JOB / 2 + 777;
  1684. let old: Vec<u8> = (0..len).map(|i| (i * 7 + i / 513) as u8).collect();
  1685. let mut now = old.clone();
  1686. // Changes: single bytes at piece edges, a run across two pieces,
  1687. // the last byte, and nothing in between.
  1688. for at in [0usize, 1, PIECE - 1, PIECE, 3 * PIECE + 5, WIDE_JOB - 1, WIDE_JOB, WIDE_JOB + PIECE / 2, 2 * WIDE_JOB + 9, len - 1] {
  1689. now[at] ^= 0x5a;
  1690. }
  1691. for byte in &mut now[9 * PIECE - 40..9 * PIECE + 40] {
  1692. *byte ^= 0x01;
  1693. }
  1694. let (data, before) = (now.as_ptr() as usize, old.as_ptr() as usize);
  1695. let mut scans = Vec::new();
  1696. let mut wanted = Vec::new();
  1697. for start in [0usize, 4096, PIECE - 16, 0xd_b790_df00] {
  1698. for (from, to) in [(0, len), (0, 1), (1, 2), (PIECE - 1, PIECE + 1), (3 * PIECE, 3 * PIECE), (12345, len - 1), (WIDE_JOB - 3, 2 * WIDE_JOB + 10)] {
  1699. scans.push((data, before, start, from, to));
  1700. let mut pieces = Vec::new();
  1701. let mut at = from;
  1702. while at < to {
  1703. let n = (PIECE - (start + at) % PIECE).min(to - at);
  1704. if now[at..at + n] != old[at..at + n] {
  1705. pieces.push((at, n));
  1706. }
  1707. at += n;
  1708. }
  1709. wanted.push(pieces);
  1710. }
  1711. }
  1712. // A scan of nothing (a range whose snapshot is gone).
  1713. scans.push((0, 0, 0, 0, 0));
  1714. wanted.push(Vec::new());
  1715. assert_eq!(find_pieces(scans), wanted);
  1716. }
  1717. }
  1718. /// What [`Shadow::copy_back`] does with a piece that differs from the
  1719. /// snapshot: `host` is the copy's bytes there, `old` the snapshot's. From
  1720. /// the first byte that differs to the last, title memory is read into
  1721. /// `title` (scratch, sized to that stretch) by `read` (the stretch's offset
  1722. /// in the piece, where to), the GPU's bytes are put in and `host` takes the
  1723. /// result. The stretch's offset in the piece and its length if that changed
  1724. /// title memory; none if nothing differs or title memory is not there.
  1725. /// `runs` takes the runs of the stretch (offsets into `title`, lengths)
  1726. /// whose bytes are the GPU's and differ from the title's as read: only
  1727. /// those are to be written, so a title write that lands between the read
  1728. /// and the write elsewhere in the stretch stays (upstream VIctory #2009).
  1729. /// `mask` is scratch.
  1730. fn back_piece(
  1731. host: &mut [u8],
  1732. old: &[u8],
  1733. title: &mut Vec<u8>,
  1734. mask: &mut Vec<u8>,
  1735. runs: &mut Vec<(usize, usize)>,
  1736. read: impl FnOnce(usize, &mut [u8]) -> bool,
  1737. ) -> Option<(usize, usize)> {
  1738. runs.clear();
  1739. // From the first byte that differs to the last: title memory is read
  1740. // and written there only (a shader that sets a few words of a piece
  1741. // cost a read, a walk and a write of all 64 KiB of it).
  1742. let first = first_difference(host, old)?;
  1743. let last = last_difference(host, old).unwrap_or(first);
  1744. let n = last + 1 - first;
  1745. let (host, old) = (&mut host[first..=last], &old[first..=last]);
  1746. title.clear();
  1747. title.resize(n, 0);
  1748. if !read(first, title) {
  1749. return None;
  1750. }
  1751. // Title memory with the GPU's bytes put in; the copy takes the title's
  1752. // bytes in turn.
  1753. // Without a branch, so the loop runs many bytes at a time: the GPU's
  1754. // byte where the copy's byte is not what it was before the submission
  1755. // and the title left its byte as it was, else the title's. (With the
  1756. // two searches above this was 44 ms a frame for 970 pieces.)
  1757. // Where the shader and the title both changed a byte while the GPU ran,
  1758. // the title's stays: the shader computed its byte from the copy's older
  1759. // data (one cleared a bit of a record the title had already replaced,
  1760. // and copying it back broke the title's object: an access violation
  1761. // through 0xffffffff00000000; PalmVIDev e0b70476, VIctory f39c6c2).
  1762. mask.clear();
  1763. mask.resize(n, 0);
  1764. let mut differs = 0u8;
  1765. for (((t, h), o), m) in title.iter_mut().zip(host.iter_mut()).zip(old).zip(mask.iter_mut()) {
  1766. let gpu = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 };
  1767. let merged = (*t & !gpu) | (*h & gpu);
  1768. *m = merged ^ *t;
  1769. differs |= *m;
  1770. *t = merged;
  1771. *h = merged;
  1772. }
  1773. if differs == 0 {
  1774. return None;
  1775. }
  1776. let mut i = 0;
  1777. while i < n {
  1778. while i < n && mask[i] == 0 {
  1779. i += 1;
  1780. }
  1781. let start = i;
  1782. while i < n && mask[i] != 0 {
  1783. i += 1;
  1784. }
  1785. if i > start {
  1786. runs.push((start, i - start));
  1787. }
  1788. }
  1789. Some((first, n))
  1790. }
  1791. /// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages
  1792. /// compared, changed runs put in, and their bytes.
  1793. static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
  1794. /// Why [`Shadow::merge_under_writes`] last left the caller to wait.
  1795. static STALE_WHY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
  1796. fn note_stale(why: usize) {
  1797. STALE_WHY.store(why, Ordering::Relaxed);
  1798. }
  1799. /// [`STALE_WHY`] in words (diagnostics).
  1800. #[cfg(feature = "diagnostics")]
  1801. pub(crate) fn stale_why() -> &'static str {
  1802. const WHY: [&str; 4] = [
  1803. "the memory is not watched",
  1804. "the journal does not say what was written",
  1805. "more changed runs than a submission sends up",
  1806. "no snapshot",
  1807. ];
  1808. WHY[STALE_WHY.load(Ordering::Relaxed).min(3)]
  1809. }
  1810. /// [`MERGED`], taken.
  1811. pub(crate) fn merged_stats() -> [u64; 3] {
  1812. [0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed))
  1813. }
  1814. /// The runs of bytes where `now` differs from `was` (of one length), as
  1815. /// (offset, bytes) in order: every differing byte is in a run and no equal
  1816. /// byte is.
  1817. fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> {
  1818. let n = now.len().min(was.len());
  1819. let mut runs = Vec::new();
  1820. let mut i = 0;
  1821. while i < n {
  1822. // Equal bytes, many at a time while they last (a page looked at
  1823. // under a flight's writes hardly ever differs at all).
  1824. while i + 512 <= n && now[i..i + 512] == was[i..i + 512] {
  1825. i += 512;
  1826. }
  1827. while i + 8 <= n && now[i..i + 8] == was[i..i + 8] {
  1828. i += 8;
  1829. }
  1830. while i < n && now[i] == was[i] {
  1831. i += 1;
  1832. }
  1833. if i >= n {
  1834. break;
  1835. }
  1836. let first = i;
  1837. while i < n && now[i] != was[i] {
  1838. i += 1;
  1839. }
  1840. runs.push((first, i - first));
  1841. }
  1842. runs
  1843. }
  1844. /// Whether a refresh of a copy in the card's memory takes, and sends up,
  1845. /// the dwords that title memory changed and no others
  1846. /// (`VICTORY_SEND_CHANGED=1`; off: the 64 KiB pages written since it last
  1847. /// took them, whole). Off since run tile1-0: the room lost its indirect light
  1848. /// and geometry exploded; run bis1-0, the same but for this, was right.
  1849. ///
  1850. /// A page that counts as written is mostly not the title's doing, or not all
  1851. /// of it: a word the title wrote, and around it what shaders wrote and the
  1852. /// title never touched; or only what the relay put into title memory, which
  1853. /// the card and the CPU's side hold already ([`Shadow::card_merge_relay`]).
  1854. /// Sent up whole, such a page goes over whatever the card holds there that
  1855. /// did not come back yet, or never will (a write through a view nobody
  1856. /// declared): what stood on the card, newer, was gone.
  1857. ///
  1858. /// What it rests on: the CPU's side is what the card's side was last known
  1859. /// to hold, for every range no shader may be writing (no refresh touches
  1860. /// the others). So a dword goes up only if title memory holds another value
  1861. /// of it than the CPU's side, which then holds it too; title memory is read
  1862. /// once, what is compared is what is stored and sent. Dwords, not bytes:
  1863. /// no shader writes less, and the title's bytes beside a changed one in its
  1864. /// dword are those the CPU's side holds.
  1865. ///
  1866. /// A page never taken goes up whole as long as no shader's write was ever
  1867. /// declared for the copy. After that it is compared as any other: the CPU's
  1868. /// side and the card's began as zeros, both.
  1869. ///
  1870. /// What it cannot know: that the title wrote a value over the same value.
  1871. /// Where a shader wrote in between, through a view nobody declared, the
  1872. /// shader's stays.
  1873. fn send_changed() -> bool {
  1874. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1875. *ON.get_or_init(|| {
  1876. #[cfg(feature = "diagnostics")]
  1877. if crate::copystat::mode() != 0 {
  1878. return false;
  1879. }
  1880. std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v != "0")
  1881. })
  1882. }
  1883. /// Since the last frame-rate line, of pages taken into copies in the
  1884. /// card's memory ([`send_changed`]): bytes compared, those of pages that
  1885. /// held the same, bytes to go up, and the runs they are.
  1886. static SEND: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
  1887. /// [`SEND`], taken.
  1888. #[cfg(feature = "diagnostics")]
  1889. pub(crate) fn send_stats() -> [u64; 4] {
  1890. [0, 1, 2, 3].map(|i| SEND[i].swap(0, Ordering::Relaxed))
  1891. }
  1892. /// Whether what shaders wrote goes into title memory run by run
  1893. /// ([`put_changed`]; on by default, `VICTORY_EXACT_BACK=0` writes the whole
  1894. /// stretch from the first changed byte to the last, as before).
  1895. pub(crate) fn exact_back() -> bool {
  1896. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1897. *ON.get_or_init(|| std::env::var_os("VICTORY_EXACT_BACK").is_none_or(|v| v != "0"))
  1898. }
  1899. /// Since the last frame-rate line: pieces put back by [`put_changed`], the
  1900. /// writes they took, the bytes written, and the pieces whose runs were
  1901. /// joined over bytes that had not changed.
  1902. pub(crate) static PUT: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
  1903. /// The dwords (of title memory from `at` on) where `merged` differs from
  1904. /// `title`, as (offset, bytes) in order, joined where at most `gap` bytes
  1905. /// lie between.
  1906. fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize, usize)> {
  1907. let mut runs: Vec<(usize, usize)> = Vec::new();
  1908. for (from, n) in changed_runs(merged, title) {
  1909. // Shaders write dwords: the whole of each.
  1910. let lo = ((at + from) & !3).max(at) - at;
  1911. let hi = ((at + from + n + 3) & !3).min(at + title.len()) - at;
  1912. match runs.last_mut() {
  1913. Some((a, len)) if lo <= *a + *len + gap => *len = (*len).max(hi - *a),
  1914. _ => runs.push((lo, hi - lo)),
  1915. }
  1916. }
  1917. runs
  1918. }
  1919. /// What shaders wrote goes into title memory from `at` on: `title` is what
  1920. /// was read there, `merged` the same with their bytes put in. Only the
  1921. /// dwords that differ are written. The whole stretch from the first changed
  1922. /// byte to the last was: between the read and the write the title's own
  1923. /// threads, or data streamed in, may have written the bytes between (a heap
  1924. /// holds what shaders write beside what the CPU does), and those writes were
  1925. /// undone. Beside running title threads (the relay) that is a piece of
  1926. /// memory going back in time now and then: runs pool1, blame1 and seriess2
  1927. /// ended in the title decoding garbage.
  1928. ///
  1929. /// shortcut: a piece with very many runs has them joined over small gaps,
  1930. /// where the old race is left.
  1931. fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize {
  1932. crate::watch::landing(at, title.len());
  1933. if !exact_back() {
  1934. crate::host::write_mapped(at as *mut u8, merged.as_ptr(), merged.len());
  1935. return merged.len();
  1936. }
  1937. if crate::safecopy::on() {
  1938. PUT[0].fetch_add(1, Ordering::Relaxed);
  1939. PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed);
  1940. let since = crate::watch::changes();
  1941. // SAFETY: title memory; a page of it that is not there fails the
  1942. // put, and the rest is put page by page.
  1943. if unsafe { crate::safecopy::put_changed(at as *mut u8, title, merged) } {
  1944. return merged.len();
  1945. }
  1946. let mut from = 0;
  1947. while from < merged.len() {
  1948. let n = (4096 - (at + from) % 4096).min(merged.len() - from);
  1949. let (was, now) = (&title[from..from + n], &merged[from..from + n]);
  1950. // SAFETY: as above.
  1951. let put = || unsafe { crate::safecopy::put_changed((at + from) as *mut u8, was, now) };
  1952. // A page that is away only while the runtime changes a mapping
  1953. // beside it gets its bytes when that is done.
  1954. if !put() && !crate::watch::again_after_change(since, put) {
  1955. crate::watch::lost("what shaders wrote", at + from, n);
  1956. }
  1957. from += n;
  1958. }
  1959. return merged.len();
  1960. }
  1961. let mut runs = dword_runs(at, title, merged, 0);
  1962. if runs.len() > 64 {
  1963. runs = dword_runs(at, title, merged, 32);
  1964. PUT[3].fetch_add(1, Ordering::Relaxed);
  1965. }
  1966. let mut written = 0;
  1967. for &(from, n) in &runs {
  1968. crate::host::write_mapped((at + from) as *mut u8, merged[from..].as_ptr(), n);
  1969. written += n;
  1970. }
  1971. PUT[0].fetch_add(1, Ordering::Relaxed);
  1972. PUT[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
  1973. PUT[2].fetch_add(written as u64, Ordering::Relaxed);
  1974. written
  1975. }
  1976. /// For `crate::land`'s measurement: a piece as [`Shadow::card_merge_relay`]
  1977. /// lands it without `VICTORY_LAND`: `n` bytes at `now`, `held` what the CPU's
  1978. /// side held, both the caller's alone.
  1979. #[cfg(test)]
  1980. pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, title: &mut Vec<u8>) {
  1981. // SAFETY: the caller's.
  1982. let (gpu, held) = unsafe { (std::slice::from_raw_parts(now as *const u8, n), std::slice::from_raw_parts_mut(held as *mut u8, n)) };
  1983. let Some(first) = first_difference(gpu, held) else {
  1984. return;
  1985. };
  1986. let last = last_difference(gpu, held).unwrap_or(first);
  1987. let n = last + 1 - first;
  1988. title.clear();
  1989. title.resize(n, 0);
  1990. assert!(crate::host::read_into((start + first) as *const u8, title));
  1991. let was = title.clone();
  1992. if merge_piece(&gpu[first..=last], &mut held[first..=last], title) {
  1993. put_changed(start + first, &was, title);
  1994. }
  1995. }
  1996. #[cfg(test)]
  1997. mod merge_tests {
  1998. use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed};
  1999. /// A piece put back takes the GPU's bytes where the copy changed and
  2000. /// the title's everywhere else, reads and writes title memory only from
  2001. /// the first change to the last, and its scratch holds that stretch and
  2002. /// no more: not the 64 KiB per range it once was.
  2003. #[test]
  2004. fn a_piece_put_back_reads_only_its_stretch() {
  2005. let old: Vec<u8> = (0..PIECE).map(|i| (i * 7 + i / 251) as u8).collect();
  2006. // The title wrote 7 and 40,000 since the snapshot; the GPU wrote 5,
  2007. // 9 and 40,000 (the GPU's byte wins where both wrote).
  2008. let mut title_memory = old.clone();
  2009. title_memory[7] ^= 0x11;
  2010. title_memory[40_000] ^= 0x22;
  2011. let mut host = old.clone();
  2012. for at in [5, 9] {
  2013. host[at] ^= 0x33;
  2014. }
  2015. let gpu = host.clone();
  2016. let mut scratch = Vec::new();
  2017. let (mut mask, mut runs) = (Vec::new(), Vec::new());
  2018. let mut asked = None;
  2019. let read = |first: usize, into: &mut [u8]| {
  2020. asked = Some((first, into.len()));
  2021. into.copy_from_slice(&title_memory[first..first + into.len()]);
  2022. true
  2023. };
  2024. assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((5, 5)));
  2025. assert_eq!(asked, Some((5, 5)));
  2026. let mut wanted = title_memory[5..10].to_vec();
  2027. wanted[0] = gpu[5];
  2028. wanted[4] = gpu[9];
  2029. assert_eq!(scratch, wanted);
  2030. assert_eq!(host[5..10], wanted);
  2031. // Only the GPU's two bytes are written back (upstream #2009).
  2032. assert_eq!(runs, [(0, 1), (4, 1)]);
  2033. // The copy outside the stretch is left as it was.
  2034. assert!(host[..5] == gpu[..5] && host[10..] == gpu[10..]);
  2035. assert!(scratch.capacity() < PIECE / 2, "scratch of {} bytes for a stretch of 5", scratch.capacity());
  2036. // Nothing differs: title memory is not read.
  2037. let mut same = old.clone();
  2038. assert_eq!(back_piece(&mut same, &old, &mut scratch, &mut mask, &mut runs, |_, _| unreachable!()), None);
  2039. // Title memory not there: nothing to write, the copy unchanged.
  2040. let mut host = gpu.clone();
  2041. assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, _| false), None);
  2042. assert!(host == gpu);
  2043. // The GPU wrote what the title holds already: nothing to write.
  2044. let mut title_memory = old.clone();
  2045. title_memory[5] = gpu[5];
  2046. title_memory[9] = gpu[9];
  2047. let mut host = gpu.clone();
  2048. let read = |first: usize, into: &mut [u8]| {
  2049. into.copy_from_slice(&title_memory[first..first + into.len()]);
  2050. true
  2051. };
  2052. assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), None);
  2053. // A whole piece changed: the scratch grows to it.
  2054. let mut host: Vec<u8> = old.iter().map(|b| !b).collect();
  2055. assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, into| into.len() == PIECE), Some((0, PIECE)));
  2056. assert_eq!(scratch.len(), PIECE);
  2057. }
  2058. /// A byte the shader and the title both changed while the GPU ran keeps
  2059. /// the title's (the shader computed it from the copy's older data); a
  2060. /// byte only the shader changed goes back, and only such bytes are in
  2061. /// the runs to write (PalmVIDev e0b70476, upstream #2009).
  2062. #[test]
  2063. fn a_byte_both_changed_keeps_the_titles_and_only_gpu_bytes_are_written() {
  2064. let old = vec![1u8, 2, 3, 4, 5, 6];
  2065. let mut host = old.clone();
  2066. host[1] = 20; // the GPU alone
  2067. host[3] = 40; // both
  2068. host[4] = 50; // the GPU alone
  2069. let mut title_memory = old.clone();
  2070. title_memory[3] = 44;
  2071. title_memory[5] = 66; // the title alone
  2072. let (mut scratch, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new());
  2073. let read = |first: usize, into: &mut [u8]| {
  2074. into.copy_from_slice(&title_memory[first..first + into.len()]);
  2075. true
  2076. };
  2077. assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((1, 4)));
  2078. assert_eq!(scratch, [20, 3, 44, 50], "the title's byte where both changed");
  2079. assert_eq!(host[1..5], [20, 3, 44, 50], "the copy takes the result");
  2080. assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only");
  2081. }
  2082. /// What shaders wrote reaches a page that is away only while the runtime
  2083. /// changes a mapping; a page that stays away loses it, and nothing else.
  2084. #[test]
  2085. fn a_put_waits_for_a_change_of_mapping() {
  2086. use windows_sys::Win32::System::Memory::{
  2087. MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree,
  2088. };
  2089. // SAFETY: a reservation of ours, nothing of it committed.
  2090. let at = unsafe { VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS) } as usize;
  2091. assert_ne!(at, 0);
  2092. put_changed(at, &[0; 64], &[3; 64]);
  2093. let (began, wait) = std::sync::mpsc::channel();
  2094. let change = std::thread::spawn(move || {
  2095. let _changing = crate::watch::title_memory_remapping();
  2096. began.send(()).unwrap();
  2097. std::thread::sleep(std::time::Duration::from_millis(50));
  2098. // SAFETY: the reservation's first page.
  2099. assert!(!unsafe { VirtualAlloc(at as _, 4096, MEM_COMMIT, PAGE_READWRITE) }.is_null());
  2100. });
  2101. wait.recv().unwrap();
  2102. put_changed(at, &[0; 64], &[1; 64]);
  2103. change.join().unwrap();
  2104. // SAFETY: committed by now.
  2105. assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 64) }, [1; 64]);
  2106. // SAFETY: our reservation.
  2107. unsafe { VirtualFree(at as _, 0, MEM_RELEASE) };
  2108. }
  2109. /// Whole dwords around every changed byte and no other, whatever the
  2110. /// alignment; small gaps joined only when asked.
  2111. #[test]
  2112. fn dword_runs_hold_the_dwords_that_changed() {
  2113. let title: Vec<u8> = (0..200u32).map(|i| (i * 7 + 3) as u8).collect();
  2114. for at in [0x1000usize, 0x1001, 0x1002, 0x1003] {
  2115. for changes in [vec![0], vec![199], vec![5, 6], vec![8, 12, 40, 41, 43, 120]] {
  2116. let mut merged = title.clone();
  2117. for &c in &changes {
  2118. merged[c] ^= 0x55;
  2119. }
  2120. let runs = dword_runs(at, &title, &merged, 0);
  2121. let held: Vec<usize> = runs.iter().flat_map(|&(a, n)| a..a + n).collect();
  2122. let mut expect: Vec<usize> = (0..200).filter(|i| changes.iter().any(|c| (at + c) / 4 == (at + i) / 4)).collect();
  2123. expect.dedup();
  2124. assert_eq!(held, expect, "{at:#x} {changes:?}");
  2125. let joined = dword_runs(at, &title, &merged, 32);
  2126. assert!(joined.len() <= runs.len());
  2127. assert!(runs.iter().all(|r| joined.iter().any(|j| j.0 <= r.0 && r.0 + r.1 <= j.0 + j.1)));
  2128. }
  2129. }
  2130. assert!(dword_runs(0, &title, &title, 0).is_empty());
  2131. }
  2132. /// The runs hold exactly the bytes that differ: putting them into the
  2133. /// old bytes gives the new ones, and no run holds an equal byte.
  2134. /// What looking at a page that did not change costs, against the look
  2135. /// eight bytes at a time that it was (a frame has some 250 of them, on
  2136. /// the submitting thread). Run with `--ignored --nocapture`.
  2137. #[test]
  2138. #[ignore]
  2139. fn runs_of_equal_pages() {
  2140. let (a, b) = (vec![7u8; 64 << 10], vec![7u8; 64 << 10]);
  2141. let eights = || {
  2142. let (now, was) = (std::hint::black_box(&a), std::hint::black_box(&b));
  2143. let mut i = 0;
  2144. while i + 8 <= now.len() && now[i..i + 8] == was[i..i + 8] {
  2145. i += 8;
  2146. }
  2147. std::hint::black_box(i);
  2148. };
  2149. let best = |f: &dyn Fn()| {
  2150. (0..500)
  2151. .map(|_| {
  2152. let t = std::time::Instant::now();
  2153. f();
  2154. t.elapsed().as_secs_f64() * 1e6
  2155. })
  2156. .fold(f64::MAX, f64::min)
  2157. };
  2158. let runs = || drop(std::hint::black_box(changed_runs(std::hint::black_box(&a), std::hint::black_box(&b))));
  2159. println!("64 KiB that are the same: {:.1} us by eights, {:.1} us now", best(&eights), best(&runs));
  2160. }
  2161. #[test]
  2162. fn changed_runs_are_exactly_the_bytes_that_differ() {
  2163. let was: Vec<u8> = (0..300u32).map(|i| (i * 13 + 5) as u8).collect();
  2164. for changes in [vec![], vec![0], vec![299], vec![7, 8, 9], vec![7, 9], vec![15, 16, 17, 23, 24, 64, 65, 66, 67, 68, 69, 70, 71, 72, 298, 299]] {
  2165. let mut now = was.clone();
  2166. for &at in &changes {
  2167. now[at] ^= 0x41;
  2168. }
  2169. let runs = changed_runs(&now, &was);
  2170. let mut put = was.clone();
  2171. let mut held = Vec::new();
  2172. for &(at, n) in &runs {
  2173. assert!(n > 0);
  2174. put[at..at + n].copy_from_slice(&now[at..at + n]);
  2175. held.extend(at..at + n);
  2176. }
  2177. assert_eq!(put, now, "{changes:?}");
  2178. assert_eq!(held, changes, "{changes:?}");
  2179. // Runs do not touch: two that did would be one.
  2180. assert!(runs.windows(2).all(|w| w[0].0 + w[0].1 < w[1].0), "{changes:?}");
  2181. }
  2182. assert!(changed_runs(&[], &[]).is_empty());
  2183. }
  2184. }
  2185. /// Host copies alive (also those only a list, a descriptor pass or a
  2186. /// snapshot still holds) and the bytes of title memory they copy.
  2187. static LIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  2188. impl Drop for Shadow {
  2189. fn drop(&mut self) {
  2190. if self.place.is_some() {
  2191. // Never counted with the copies (`Shadow::placed`).
  2192. crate::inplace::gone(self.window, self.len);
  2193. return;
  2194. }
  2195. LIVE[0].fetch_sub(1, Ordering::Relaxed);
  2196. LIVE[1].fetch_sub(self.len, Ordering::Relaxed);
  2197. if self.kept.get_mut().unwrap_or_else(|e| e.into_inner()).1 {
  2198. KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed);
  2199. }
  2200. let window = self.window;
  2201. if self.mapped {
  2202. WINDOW_MAPPED_BYTES.fetch_sub(self.len, Ordering::Relaxed);
  2203. }
  2204. if let Some(card) = &mut self.card {
  2205. if window {
  2206. WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed);
  2207. } else {
  2208. CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed);
  2209. }
  2210. if card.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() {
  2211. CARD_BYTES[1].fetch_sub(card_hash_bytes(card.size), Ordering::Relaxed);
  2212. }
  2213. }
  2214. }
  2215. }
  2216. /// Whether a copy's snapshot is kept from one submission to the next and
  2217. /// only the pieces that changed in between are taken again
  2218. /// (`VICTORY_KEEP_SNAPSHOTS=1`; off by default).
  2219. ///
  2220. /// A snapshot is the copy's bytes before a submission, to find what its
  2221. /// shaders wrote. Taken anew for every submission it is 1,050 MB of copying
  2222. /// a frame (72-86 ms in gameplay, runs 61 and 62) for buffers of which
  2223. /// 100 MB changed. Kept, a piece of it is taken again only after something
  2224. /// changed the copy there: a refresh from title memory ([`Shadow::copy`]),
  2225. /// shader writes found after a submission, or the bytes put back then
  2226. /// ([`Shadow::copy_back`]).
  2227. ///
  2228. /// What it assumes, and why it is not on by default: that nothing else
  2229. /// writes a copy. A shader that writes a buffer through a view we did not
  2230. /// declare as written (we declare the unordered-access views of shaders
  2231. /// that can store) changes the copy unseen; with a fresh snapshot that
  2232. /// write is simply never put back, with a kept one it would be taken for a
  2233. /// write of a later submission and put back then, over whatever the title
  2234. /// wrote there since.
  2235. fn keeps() -> bool {
  2236. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2237. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_SNAPSHOTS").is_some_and(|v| v == "1"))
  2238. }
  2239. /// Bytes of the snapshots kept, and the most that may be.
  2240. static KEPT_BYTES: AtomicU64 = AtomicU64::new(0);
  2241. /// `VICTORY_KEEP_SNAPSHOTS_MB`, 256 unless set (it was 768: run 80, with
  2242. /// kept snapshots beside copies in the card's memory, ran the PC out of
  2243. /// memory in 27 s; kept snapshots are the PC's memory, all of it resident).
  2244. fn kept_most() -> u64 {
  2245. static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  2246. *MOST.get_or_init(|| {
  2247. std::env::var("VICTORY_KEEP_SNAPSHOTS_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(256) << 20
  2248. })
  2249. }
  2250. /// The 64 KiB pieces, cut at multiples of 64 KiB of title memory, that
  2251. /// hold offsets `[from, to)` of a copy of memory from `start` on
  2252. /// (`from < to`); piece 0 holds offset 0.
  2253. fn pieces_of(start: usize, from: usize, to: usize) -> std::ops::Range<usize> {
  2254. let first = start / PIECE;
  2255. (start + from) / PIECE - first..(start + to - 1) / PIECE - first + 1
  2256. }
  2257. /// The offsets that piece `piece` holds of a copy of `len` bytes of memory
  2258. /// from `start` on.
  2259. fn piece_at(start: usize, len: usize, piece: usize) -> (usize, usize) {
  2260. let first = start / PIECE;
  2261. let lo = ((first + piece) * PIECE).saturating_sub(start);
  2262. let hi = ((first + piece + 1) * PIECE - start).min(len);
  2263. (lo, hi)
  2264. }
  2265. #[cfg(test)]
  2266. mod piece_tests {
  2267. use super::{PIECE, piece_at, pieces_of};
  2268. /// The pieces cover a copy without gaps, each cut where the compare
  2269. /// cuts (at multiples of 64 KiB of title memory).
  2270. #[test]
  2271. fn pieces_cover_the_copy_as_the_compare_cuts_it() {
  2272. for start in [0usize, 1, 4096, PIECE - 1, PIECE, PIECE + 77, 5 * PIECE + 12345] {
  2273. for len in [1usize, 100, PIECE - 1, PIECE, PIECE + 1, 3 * PIECE + 500] {
  2274. let count = pieces_of(start, 0, len).end;
  2275. let mut at = 0;
  2276. for piece in 0..count {
  2277. let (lo, hi) = piece_at(start, len, piece);
  2278. assert_eq!(lo, at, "{start} {len} {piece}");
  2279. // As `Shadow::differing` cuts: to the next multiple.
  2280. let n = (PIECE - (start + at) % PIECE).min(len - at);
  2281. assert_eq!(hi, at + n, "{start} {len} {piece}");
  2282. assert_eq!(pieces_of(start, lo, hi), piece..piece + 1);
  2283. assert_eq!(pieces_of(start, hi - 1, hi), piece..piece + 1);
  2284. at = hi;
  2285. }
  2286. assert_eq!(at, len, "{start} {len}");
  2287. assert_eq!(pieces_of(start, 0, len), 0..count);
  2288. }
  2289. }
  2290. }
  2291. }
  2292. /// The pages of `[a, e)` (title addresses, `a < e`) that a copy whose
  2293. /// first page is `base` must take from title memory before it holds the
  2294. /// title's bytes: those it never took (`copied` 0), whether or not the
  2295. /// title wrote them since tracking began, and those `written` (as
  2296. /// `crate::watch::writes` gives it, by page in order) shows written after
  2297. /// the copy took them. As [`Shadow::copy_stale`] decides it.
  2298. ///
  2299. /// [`Shadow::stale_under_writes`] and [`Shadow::merge_under_writes`] looked
  2300. /// at `written` alone, so a page of a range shaders may be writing that the
  2301. /// copy never took, and the title had not written lately, was neither
  2302. /// merged nor a reason to settle; the refresh leaves such ranges alone, and
  2303. /// shaders read zeros there (fxceless/victory-fork#206: missing geometry
  2304. /// with `VICTORY_LATE_WAIT`/`VICTORY_RELAY`).
  2305. fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec<usize> {
  2306. (a / PAGE..e.div_ceil(PAGE))
  2307. .filter(|&page| page >= base)
  2308. .filter(|&page| match copied.get(page - base) {
  2309. None => false,
  2310. Some(0) => true,
  2311. Some(&at) => written
  2312. .binary_search_by_key(&page, |&(p, _)| p)
  2313. .is_ok_and(|i| written[i].1 > at),
  2314. })
  2315. .collect()
  2316. }
  2317. /// `runs` (from, to, whether the copy held it before), cut in those of pages
  2318. /// held before (`pages`: page number and asking, in order) to the parts of
  2319. /// each page that were written since (`parts`: a bit for each 4 KiB).
  2320. fn by_parts(runs: Vec<(usize, usize, bool)>, pages: &[(usize, u64)], parts: &[u16]) -> Vec<(usize, usize, bool)> {
  2321. const PART: usize = PAGE / 16;
  2322. if parts.iter().all(|&p| p == u16::MAX) {
  2323. return runs;
  2324. }
  2325. let mut out: Vec<(usize, usize, bool)> = Vec::with_capacity(runs.len() + pages.len());
  2326. let mut pages = pages.iter().zip(parts).peekable();
  2327. for (from, to, known) in runs {
  2328. if !known {
  2329. out.push((from, to, known));
  2330. continue;
  2331. }
  2332. while let Some((&(page, _), &parts)) = pages.next_if(|((page, _), _)| page * PAGE < to) {
  2333. for k in (0..16).filter(|k| parts >> k & 1 != 0) {
  2334. let (a, b) = ((page * PAGE + k * PART).max(from), (page * PAGE + (k + 1) * PART).min(to));
  2335. if a >= b {
  2336. continue;
  2337. }
  2338. match out.last_mut() {
  2339. Some((_, end, true)) if *end == a => *end = b,
  2340. _ => out.push((a, b, true)),
  2341. }
  2342. }
  2343. }
  2344. }
  2345. out
  2346. }
  2347. #[cfg(test)]
  2348. mod parts_tests {
  2349. use super::{PAGE, by_parts};
  2350. #[test]
  2351. fn runs_are_cut_to_the_parts_written() {
  2352. const P: usize = PAGE / 16;
  2353. let at = |page: usize, part: usize| page * PAGE + part * P;
  2354. // Pages 10 and 11 again (from the middle of 10's part 1 on), 12
  2355. // never taken, 14 again.
  2356. let runs = vec![
  2357. (at(10, 1) + 100, at(12, 0), true),
  2358. (at(12, 0), at(13, 0), false),
  2359. (at(14, 0), at(14, 9) + 7, true),
  2360. ];
  2361. let pages = [(10, 5), (11, 5), (14, 6)];
  2362. assert_eq!(by_parts(runs.clone(), &pages, &[u16::MAX; 3]), runs);
  2363. assert_eq!(
  2364. by_parts(runs, &pages, &[0b1000_0000_0000_0011, 0b11, 0b10_0000_0000]),
  2365. [
  2366. (at(10, 1) + 100, at(10, 2), true),
  2367. (at(10, 15), at(11, 2), true),
  2368. (at(12, 0), at(13, 0), false),
  2369. (at(14, 9), at(14, 9) + 7, true),
  2370. ]
  2371. );
  2372. }
  2373. }
  2374. #[cfg(test)]
  2375. mod stale_tests {
  2376. use super::*;
  2377. #[test]
  2378. fn pages_never_taken_are_stale_written_or_not() {
  2379. let base = 0x100;
  2380. let copied = [5, 0, 5, 5];
  2381. let at = |page: usize| page * PAGE;
  2382. // Page 0x101 was never taken; page 0x102 was written after it was
  2383. // taken, page 0x103 before.
  2384. let written = [(0x102, 6), (0x103, 4)];
  2385. assert_eq!(stale_pages_in(base, &copied, at(0x100), at(0x104), &written), [0x101, 0x102]);
  2386. // Part of a page counts as the page; pages outside the copy do not.
  2387. assert_eq!(stale_pages_in(base, &copied, at(0x101) + 8, at(0x101) + 16, &[]), [0x101]);
  2388. assert!(stale_pages_in(base, &copied, at(0x104), at(0x106), &[(0x104, 9)]).is_empty());
  2389. }
  2390. }
  2391. /// Copies of windows outside buffers let go since the start, and their
  2392. /// bytes.
  2393. static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
  2394. /// For the memory line: the windows let go since the start and their
  2395. /// bytes, and of the bytes of the windows alive, how many lie between the
  2396. /// lowest and the highest address ever asked for in each.
  2397. #[cfg(feature = "diagnostics")]
  2398. pub(crate) fn windows() -> [u64; 3] {
  2399. let asked: u64 = {
  2400. let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  2401. loose
  2402. .values()
  2403. .map(|s| {
  2404. let low = s.asked[0].load(Ordering::Relaxed);
  2405. let high = s.asked[1].load(Ordering::Relaxed);
  2406. high.saturating_sub(low)
  2407. })
  2408. .sum()
  2409. };
  2410. [LET_GO[0].load(Ordering::Relaxed), LET_GO[1].load(Ordering::Relaxed), asked]
  2411. }
  2412. /// For the memory line, of the windows alive: the bytes of their pages
  2413. /// ever copied from title memory (the rest of each window is memory the
  2414. /// host zeroed and nothing read: what a window made no bigger than what is
  2415. /// read would not hold); the windows a descriptor slot shows and their
  2416. /// bytes (they stay until the title writes the slot again); the windows a
  2417. /// list or a pass over the heap holds and their bytes; the windows asked
  2418. /// for without a length (root views, which keep the 4 MiB grid) and their
  2419. /// bytes; and the window grid in bytes ([`window`]).
  2420. #[cfg(feature = "diagnostics")]
  2421. pub(crate) fn window_use() -> [u64; 8] {
  2422. let mut out = [0u64; 8];
  2423. let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  2424. for s in loose.values() {
  2425. let copied = s.copied.lock().unwrap_or_else(|e| e.into_inner());
  2426. let pages = copied.iter().filter(|&&at| at != 0).count() as u64;
  2427. out[0] += (pages * PAGE as u64).min(s.len);
  2428. if crate::host::references(&s.buffer) > 1 {
  2429. out[1] += 1;
  2430. out[2] += s.len;
  2431. }
  2432. if Arc::strong_count(s) > 1 {
  2433. out[3] += 1;
  2434. out[4] += s.len;
  2435. }
  2436. if s.unsized_asks.load(Ordering::Relaxed) > 0 {
  2437. out[5] += 1;
  2438. out[6] += s.len;
  2439. }
  2440. }
  2441. out[7] = window();
  2442. out
  2443. }
  2444. /// Lets go of the copies of windows outside buffers that nothing names any
  2445. /// more. They were never freed, and the world's streaming keeps asking for
  2446. /// new ones: 648 windows (2.8 GB) when the cutscene began, 974 (4.3 GB)
  2447. /// eight minutes later (run 24). A window goes when
  2448. /// - only the table of windows holds its copy: no list not yet reset reads
  2449. /// or writes it, no pass over the heap keeps its range, no submission is
  2450. /// comparing it;
  2451. /// - only the copy holds its host buffer: no descriptor slot views it (a
  2452. /// slot keeps the buffer it views, `HostHeap::kept`), so no draw can read
  2453. /// it through a slot made earlier;
  2454. /// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames.
  2455. ///
  2456. /// The next read of that memory makes a new copy and copies the window
  2457. /// again. Called before a submission starts, by the thread that submits.
  2458. pub(crate) fn let_go_idle() {
  2459. const IDLE_FRAMES: u64 = 4;
  2460. let gone: Vec<Arc<Shadow>> = {
  2461. // Held from the look to the removal: `loose` hands a copy out
  2462. // under the same lock, so none is handed out in between.
  2463. let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  2464. if map.is_empty() {
  2465. return;
  2466. }
  2467. let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram());
  2468. let idle: Vec<(u64, u64)> = map
  2469. .iter()
  2470. .filter(|(_, s)| {
  2471. Arc::strong_count(s) == 1
  2472. && crate::host::long_ago(s.used.load(Ordering::Relaxed), idle_ms, IDLE_FRAMES)
  2473. && crate::host::references(&s.buffer) == 1
  2474. })
  2475. .map(|(key, _)| *key)
  2476. .collect();
  2477. idle.into_iter().filter_map(|key| map.remove(&key)).collect()
  2478. };
  2479. if !gone.is_empty() {
  2480. let (went, bytes) = (gone.len(), gone.iter().map(|s| s.len).sum::<u64>());
  2481. crate::host::trail(|| {
  2482. format!("sweep: {went} host copies of windows of title memory let go ({} KiB), held by no list and no slot", bytes >> 10)
  2483. });
  2484. }
  2485. for shadow in gone {
  2486. LET_GO[0].fetch_add(1, Ordering::Relaxed);
  2487. LET_GO[1].fetch_add(shadow.len, Ordering::Relaxed);
  2488. // Nothing runs now and nothing names it: freed at once unless a
  2489. // submission is running after all.
  2490. crate::host::retire(shadow);
  2491. }
  2492. }
  2493. /// For the memory line: host copies alive and their bytes, of them the
  2494. /// windows of memory outside buffers and their bytes, and the snapshot
  2495. /// buffers kept for reuse and the bytes they reserve.
  2496. #[cfg(feature = "diagnostics")]
  2497. pub(crate) fn memory() -> [u64; 6] {
  2498. let (windows, window_bytes) = {
  2499. let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  2500. // Each copy once: a window may stand under several keys.
  2501. let mut seen = std::collections::HashSet::new();
  2502. let bytes: u64 = loose
  2503. .values()
  2504. .filter(|s| seen.insert(Arc::as_ptr(s) as usize))
  2505. .map(|s| s.len)
  2506. .sum();
  2507. (seen.len() as u64, bytes)
  2508. };
  2509. let (kept, kept_bytes) = {
  2510. let pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
  2511. (pool.len() as u64, pool.iter().map(|v| v.capacity() as u64).sum::<u64>())
  2512. };
  2513. [
  2514. LIVE[0].load(Ordering::Relaxed),
  2515. LIVE[1].load(Ordering::Relaxed),
  2516. windows,
  2517. window_bytes,
  2518. kept,
  2519. kept_bytes,
  2520. ]
  2521. }
  2522. // SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping
  2523. // written only on the submitting thread.
  2524. unsafe impl Send for Shadow {}
  2525. // SAFETY: as above.
  2526. unsafe impl Sync for Shadow {}
  2527. impl Shadow {
  2528. /// The host GPU address of a title address inside the buffer.
  2529. pub(crate) fn gpu(&self, address: u64) -> u64 {
  2530. self.gpu + (address - self.start)
  2531. }
  2532. /// The title memory the copy is of: its start and length.
  2533. pub(crate) fn span(&self) -> (u64, u64) {
  2534. (self.start, self.len)
  2535. }
  2536. /// The offset of a title address in the copy, if it lies in it.
  2537. pub(crate) fn offset_in(&self, address: u64) -> Option<u64> {
  2538. address.checked_sub(self.start).filter(|&at| at < self.len)
  2539. }
  2540. /// Bytes from a title address to the buffer's end.
  2541. pub(crate) fn left(&self, address: u64) -> u64 {
  2542. (self.start + self.len).saturating_sub(address)
  2543. }
  2544. /// Whether the memory behind the copy turned out not to be write-watched:
  2545. /// every refresh then copies its whole range.
  2546. pub(crate) fn unwatched(&self) -> bool {
  2547. self.watched.load(Ordering::Relaxed) == NOT_WATCHED
  2548. }
  2549. /// Whether a submission asks the kernel about the copy's ranges ahead:
  2550. /// not of memory that is not watched, nor of view memory, which the
  2551. /// kernel would refuse (and with it the ranges asked about together).
  2552. pub(crate) fn asked_ahead(&self) -> bool {
  2553. let watched = self.watched.load(Ordering::Relaxed);
  2554. watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light())
  2555. }
  2556. /// The copy's own number (see the field).
  2557. pub(crate) fn id(&self) -> u64 {
  2558. self.id
  2559. }
  2560. /// Whether it is no copy but title memory in place (`crate::inplace`).
  2561. pub(crate) fn in_place(&self) -> bool {
  2562. self.place.is_some()
  2563. }
  2564. /// Offset of a title address from the buffer's start.
  2565. pub(crate) fn offset(&self, address: u64) -> u64 {
  2566. address - self.start + self.place.as_ref().map_or(0, |place| place.1)
  2567. }
  2568. /// Title memory `[start, start + len)` in place: `placed` is a buffer
  2569. /// over it in a heap opened on it. Shaped as a copy so that everything
  2570. /// that binds, views or keeps a copy works on it unchanged; what
  2571. /// copies does nothing ([`Shadow::update`], [`Shadow::gpu_writes`]).
  2572. fn placed(placed: crate::inplace::Placed, start: u64, len: u64, window: bool) -> Shadow {
  2573. crate::host::name(&placed.buffer, || format!("title memory {start:#x}+{len:#x} in place"));
  2574. let mut shadow = Shadow::new(placed.buffer, start as *mut u8, placed.gpu, start, len);
  2575. // Not a copy: not counted with them, and nothing asks what the
  2576. // title wrote there.
  2577. LIVE[0].fetch_sub(1, Ordering::Relaxed);
  2578. LIVE[1].fetch_sub(len, Ordering::Relaxed);
  2579. *shadow.watched.get_mut() = NOT_WATCHED;
  2580. shadow.window = window;
  2581. shadow.place = Some((placed.heap, placed.bias));
  2582. shadow
  2583. }
  2584. /// Brings `len` bytes at `address` up to date when `list` is submitted,
  2585. /// and keeps the copy alive until the list is reset.
  2586. pub(crate) fn refresh(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
  2587. let len = len.min(self.start + self.len - address);
  2588. list.defer_refresh(self, address as usize, len as usize);
  2589. }
  2590. /// The bytes of the host buffer.
  2591. pub(crate) fn width(&self) -> u64 {
  2592. // SAFETY: a live buffer.
  2593. *self.width.get_or_init(|| unsafe { self.buffer.GetDesc() }.Width)
  2594. }
  2595. fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow {
  2596. let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64;
  2597. LIVE[0].fetch_add(1, Ordering::Relaxed);
  2598. LIVE[1].fetch_add(len, Ordering::Relaxed);
  2599. Shadow {
  2600. width: Default::default(),
  2601. buffer,
  2602. data,
  2603. gpu,
  2604. start,
  2605. len,
  2606. copied: Mutex::new(vec![0; pages as usize]),
  2607. ranged: Mutex::default(),
  2608. watched: AtomicU8::new(0),
  2609. pending: Mutex::default(),
  2610. flights: Mutex::default(),
  2611. before: Mutex::default(),
  2612. merging: RwLock::default(),
  2613. kept: Mutex::default(),
  2614. used: AtomicU64::new(crate::host::moment()),
  2615. asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)],
  2616. unsized_asks: AtomicU64::new(0),
  2617. written: Default::default(),
  2618. id: {
  2619. static NEXT: AtomicU64 = AtomicU64::new(1);
  2620. NEXT.fetch_add(1, Ordering::Relaxed)
  2621. },
  2622. card: None,
  2623. window: false,
  2624. changes_only: Default::default(),
  2625. mapped: false,
  2626. place: None,
  2627. }
  2628. }
  2629. /// `[address, address + len)` cut to the buffer, as offsets in the copy.
  2630. fn inside(&self, address: usize, len: usize) -> (usize, usize) {
  2631. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  2632. let from = address.clamp(start, end);
  2633. (from - start, (address + len).clamp(from, end) - start)
  2634. }
  2635. /// Shaders of `list` may write `[address, address + len)` of the copy
  2636. /// (unordered access): after the list's submission has run, the range
  2637. /// is copied back into title memory, where the title reads it; until
  2638. /// then no refresh copies title memory over it. Call after the
  2639. /// [`Shadow::refresh`] that gives the shaders the title's data.
  2640. ///
  2641. /// shortcut: what shaders wrote is found by keeping the range's bytes
  2642. /// before the submission (a copy per declared range and submission);
  2643. /// a GPU-side dirty mask would save that if big ranges make it slow.
  2644. pub(crate) fn gpu_writes(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
  2645. // In place the shaders write title memory itself: no snapshot, no
  2646. // compare, nothing to copy back, and no wait on its account.
  2647. // shortcut: another host copy of the same bytes (a title buffer
  2648. // inside this one with a copy of its own, a texture in it) is not
  2649. // told: the card's writes are not seen by write watching.
  2650. if self.place.is_some() {
  2651. return;
  2652. }
  2653. self.written.store(true, Ordering::Relaxed);
  2654. let len = len.min(self.left(address));
  2655. list.defer_gpu_write(self, address as usize, len as usize);
  2656. }
  2657. /// At submission, after the range's refresh: a submitted list's shaders
  2658. /// write this range. Its bytes are kept to tell later what the GPU wrote:
  2659. /// one snapshot per copy and submission, each byte taken once, when the
  2660. /// first range holding it is declared (the world declares overlapping
  2661. /// views of its 174 MB heap dozens of times, from different offsets: a
  2662. /// snapshot grown to cover each was copied whole every time), in reused
  2663. /// memory (fresh snapshots cost ~2.3 million page faults per world
  2664. /// frame).
  2665. pub(crate) fn writing(&self, address: usize, len: usize) {
  2666. if self.place.is_some() {
  2667. return;
  2668. }
  2669. let range = (address, address + len);
  2670. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
  2671. // With the copy-back on its own thread: counted for this submission
  2672. // (once), whether or not an earlier one still holds the range.
  2673. if relay() {
  2674. self.flights.lock().unwrap_or_else(|e| e.into_inner()).declare(range, PREPARED.load(Ordering::Relaxed));
  2675. }
  2676. // Dispatches declare the same ranges thousands of times.
  2677. if pending.contains(&range) {
  2678. return;
  2679. }
  2680. // In the card's memory: no snapshot. What shaders wrote is found on
  2681. // the card (`Host::card_before` reads the declared ranges from the
  2682. // lists).
  2683. if self.card.is_some() {
  2684. pending.push(range);
  2685. return;
  2686. }
  2687. // The parts no declared range holds yet: their bytes are taken now,
  2688. // just after the range's refresh (a part declared earlier has not
  2689. // been refreshed since, and keeps the bytes taken then).
  2690. let mut parts = vec![self.inside(address, len)];
  2691. for &(a, e) in pending.iter() {
  2692. let (a, e) = self.inside(a, e - a);
  2693. let mut rest = Vec::with_capacity(parts.len() + 1);
  2694. for (from, to) in parts {
  2695. if e <= from || a >= to {
  2696. rest.push((from, to));
  2697. continue;
  2698. }
  2699. if from < a {
  2700. rest.push((from, a));
  2701. }
  2702. if e < to {
  2703. rest.push((e, to));
  2704. }
  2705. }
  2706. parts = rest;
  2707. }
  2708. pending.push(range);
  2709. let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum();
  2710. BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed);
  2711. let total = self.len as usize;
  2712. let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
  2713. let snapshot = before.get_or_insert_with(|| pooled(total));
  2714. if keeps() {
  2715. // Piece by piece, and only the pieces not known current. A
  2716. // piece the part holds whole is current from now on; of a
  2717. // piece it holds partly only the part's bytes are taken, as
  2718. // without the switch, and it is taken again next time (the
  2719. // rest of it may belong to a range declared earlier, whose
  2720. // bytes stay as they were taken).
  2721. let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  2722. if kept.0.is_empty() {
  2723. kept.0 = vec![false; self.pieces(0, total.max(1)).end];
  2724. }
  2725. for (from, to) in parts {
  2726. if from >= to {
  2727. continue;
  2728. }
  2729. for piece in self.pieces(from, to) {
  2730. if kept.0[piece] {
  2731. continue;
  2732. }
  2733. let (lo, hi) = self.piece(piece);
  2734. let whole = from <= lo && hi <= to;
  2735. let (lo, hi) = (lo.max(from), hi.min(to));
  2736. // SAFETY: as below; `hi <= total`.
  2737. unsafe {
  2738. std::ptr::copy_nonoverlapping(self.data.add(lo), snapshot.as_mut_ptr().add(lo), hi - lo);
  2739. }
  2740. kept.0[piece] = whole;
  2741. }
  2742. }
  2743. return;
  2744. }
  2745. if wide_back() {
  2746. // Noted, and taken with the submission's other snapshots when
  2747. // its refreshes are done (`take_snapshots`): the range is
  2748. // declared from here on, so nothing changes its bytes before
  2749. // then. The snapshot's memory stays where it is until the
  2750. // range is done with (`copy_back_done`).
  2751. let mut snaps = SNAPS.lock().unwrap_or_else(|e| e.into_inner());
  2752. let (data, snapshot) = (self.data as usize, snapshot.as_mut_ptr() as usize);
  2753. snaps.extend(parts.into_iter().filter(|&(from, to)| from < to).map(|(from, to)| (data + from, snapshot + from, to - from)));
  2754. return;
  2755. }
  2756. for (from, to) in parts {
  2757. if from < to {
  2758. // SAFETY: the copy's mapping and the snapshot's allocation
  2759. // (`pooled`) both hold `total` bytes, and `to <= total`.
  2760. unsafe {
  2761. copy_wide(self.data.add(from), snapshot.as_mut_ptr().add(from), to - from);
  2762. }
  2763. }
  2764. }
  2765. }
  2766. /// After the submission ran: copies the bytes its shaders wrote back
  2767. /// into title memory (unmapped pages left alone), and only those: the
  2768. /// title's threads write the same buffers while the GPU runs (its
  2769. /// command memory shares the big GPU heap with what shaders write), and
  2770. /// putting back the copy's older bytes there broke the title's own
  2771. /// records (a fence list read as -1, title+0x4e9b54a). Returns the bytes
  2772. /// written. The range must lie in ranges declared with
  2773. /// [`Shadow::writing`] and not yet done: `Host::execute` passes the
  2774. /// union of a submission's ranges, each byte once, then calls
  2775. /// [`Shadow::copy_back_done`].
  2776. pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize {
  2777. self.copy_back_with(address, len, None)
  2778. }
  2779. /// [`Shadow::copy_back`]; `found`, if given, is the pieces of the range
  2780. /// that differ from the snapshot, found beforehand ([`find_all`]).
  2781. pub(crate) fn copy_back_with(&self, address: usize, len: usize, found: Option<Vec<(usize, usize)>>) -> usize {
  2782. if self.place.is_some() {
  2783. return 0;
  2784. }
  2785. let snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner());
  2786. let mut written = 0;
  2787. let (from, to) = self.inside(address, len);
  2788. let start = self.start as usize;
  2789. self.compared(from, to);
  2790. if let Some(before) = &*snapshot
  2791. && from < to
  2792. {
  2793. // SAFETY: `writing` set the snapshot's bytes of every declared
  2794. // range, at the copy's offsets.
  2795. let before = unsafe { std::slice::from_raw_parts(before.as_ptr().add(from), to - from) };
  2796. // By 64 KiB piece: the copy compared with its bytes before the
  2797. // submission (on several threads: gigabytes a frame, bound by
  2798. // memory speed), title memory read only where the GPU wrote.
  2799. #[cfg(feature = "diagnostics")]
  2800. let scanning = std::time::Instant::now();
  2801. let differing = match found {
  2802. Some(found) => found,
  2803. None => self.differing(from, to, before),
  2804. };
  2805. #[cfg(feature = "diagnostics")]
  2806. let syncing = {
  2807. use crate::copystat::{C, add};
  2808. add(C::BackScanUs, scanning.elapsed().as_micros() as u64);
  2809. add(C::BackDiffer, differing.len() as u64);
  2810. std::time::Instant::now()
  2811. };
  2812. // Where the copy changes (the GPU wrote, and below the title's
  2813. // bytes come in), a kept snapshot is no longer current.
  2814. for &(at, n) in &differing {
  2815. self.changed(at, at + n);
  2816. }
  2817. // Sized to each stretch read (`back_piece`): a zeroed 64 KiB per
  2818. // range, most of whose ranges differ nowhere, was most of the
  2819. // work for small ranges.
  2820. let (mut title, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new());
  2821. for (at, n) in differing {
  2822. // SAFETY: inside the mapping; only the submitting thread
  2823. // writes it.
  2824. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
  2825. let old = &before[at - from..at - from + n];
  2826. let read = |first: usize, title: &mut [u8]| crate::host::read_into((start + at + first) as *const u8, title);
  2827. let Some((first, n)) = back_piece(host, old, &mut title, &mut mask, &mut runs, read) else {
  2828. continue;
  2829. };
  2830. // Title memory as read, beside it with the card's bytes put
  2831. // in: only the dwords that differ are written.
  2832. let was: Vec<u8> = title.iter().zip(&mask).map(|(now, changed)| now ^ changed).collect();
  2833. if !runs.is_empty() {
  2834. written += put_changed(start + at + first, &was[..n], &title[..n]);
  2835. }
  2836. }
  2837. // Our write shows as a title write at the copy's next refresh,
  2838. // which copies those pages once more (some dozens of MB a
  2839. // frame). Asking about the whole range here, to note them
  2840. // current, cost more: 19-31 askings a frame over 110-174 MB of
  2841. // view memory, each a walk of its guards.
  2842. #[cfg(feature = "diagnostics")]
  2843. crate::copystat::add(crate::copystat::C::BackSyncUs, syncing.elapsed().as_micros() as u64);
  2844. }
  2845. written
  2846. }
  2847. /// Offsets `[from, to)` of the copy are compared with the snapshot: for
  2848. /// the frame line's counts.
  2849. fn compared(&self, from: usize, to: usize) {
  2850. #[cfg(feature = "diagnostics")]
  2851. crate::copystat::add(crate::copystat::C::BackCompared, (to - from) as u64);
  2852. let (bytes, ranges) = if self.window { (2, 5) } else { (3, 6) };
  2853. BACK_CLASS[bytes].fetch_add((to - from) as u64, Ordering::Relaxed);
  2854. BACK_CLASS[ranges].fetch_add(1, Ordering::Relaxed);
  2855. if !self.window && self.len >= 1 << 20 {
  2856. BACK_CLASS[4].fetch_add((to - from) as u64, Ordering::Relaxed);
  2857. }
  2858. }
  2859. /// [`relay`]: the declared range `[address, address + len)` of a copy
  2860. /// in the PC's memory is about to be looked through
  2861. /// (`crate::shadow::find_all`) by the thread that settles: counted as
  2862. /// [`Shadow::copy_back_with`] counts it.
  2863. pub(crate) fn relay_compared(&self, address: usize, len: usize) {
  2864. let (from, to) = self.inside(address, len);
  2865. self.compared(from, to);
  2866. }
  2867. /// [`relay`], for a copy in the PC's memory: offsets `[at, at + n)`
  2868. /// are a 64 KiB piece of a declared range that differed from the
  2869. /// snapshot when it was looked through. What the card wrote there
  2870. /// since the snapshot was last brought up goes into title memory, from
  2871. /// the first to the last such byte, and into the snapshot, so that the
  2872. /// next flight's merge finds only what the card writes from now on.
  2873. /// The copy is read once and never written: a later flight's shaders
  2874. /// may be writing it at this moment. Under the snapshot's lock, which
  2875. /// [`Shadow::merge_under_writes`] holds while it reads title memory
  2876. /// and puts the title's bytes into the copy and the snapshot: the two
  2877. /// never see each other half done. `now` and `title` are scratch
  2878. /// memory. Returns the bytes written to title memory.
  2879. pub(crate) fn relay_merge(&self, at: usize, n: usize, now: &mut Vec<u8>, title: &mut Vec<u8>) -> usize {
  2880. let start = self.start as usize;
  2881. if self.card.is_some() || n == 0 || at + n > self.len as usize {
  2882. return 0;
  2883. }
  2884. let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner());
  2885. let Some(before) = snapshot.as_mut() else {
  2886. return 0;
  2887. };
  2888. now.clear();
  2889. now.reserve(n);
  2890. // SAFETY: inside the copy's mapping (checked above), read into
  2891. // room just reserved; the card may write the mapping meanwhile, and
  2892. // each byte read is one it held at some moment.
  2893. unsafe {
  2894. std::ptr::copy_nonoverlapping(self.data.add(at), now.as_mut_ptr(), n);
  2895. now.set_len(n);
  2896. }
  2897. // SAFETY: the snapshot's allocation holds the copy's length
  2898. // (`writing`), and these offsets are in a range declared and not
  2899. // done with, whose bytes it holds; nothing else touches them
  2900. // without the lock held here.
  2901. let held = unsafe { std::slice::from_raw_parts_mut(before.as_mut_ptr().add(at), n) };
  2902. let Some(first) = first_difference(now, held) else {
  2903. return 0;
  2904. };
  2905. let last = last_difference(now, held).unwrap_or(first);
  2906. let (at, n) = (at + first, last + 1 - first);
  2907. let (now, held) = (&now[first..=last], &mut held[first..=last]);
  2908. title.clear();
  2909. title.resize(n, 0);
  2910. // Title memory not there: looked at again when the next flight
  2911. // that declared the range lands (the snapshot stays as it is).
  2912. if !crate::host::read_into((start + at) as *const u8, title) {
  2913. return 0;
  2914. }
  2915. let was = title.clone();
  2916. if !merge_piece(now, held, title) {
  2917. return 0;
  2918. }
  2919. put_changed(start + at, &was, title)
  2920. }
  2921. /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory) of
  2922. /// `[from, to)` of the copy that differ from `before` (the bytes from
  2923. /// `from` on), as (offset, bytes) in order; compared on several threads
  2924. /// when the range is big.
  2925. fn differing(&self, from: usize, to: usize, before: &[u8]) -> Vec<(usize, usize)> {
  2926. let (start, data) = (self.start as usize, self.data as usize);
  2927. let scan = |a: usize, b: usize| -> Vec<(usize, usize)> {
  2928. let mut found = Vec::new();
  2929. let mut at = a;
  2930. while at < b {
  2931. let n = (PIECE - (start + at) % PIECE).min(b - at);
  2932. // SAFETY: inside the mapping, which nothing writes while a
  2933. // submission's results are compared.
  2934. let host = unsafe { std::slice::from_raw_parts((data + at) as *const u8, n) };
  2935. if host != &before[at - from..at - from + n] {
  2936. found.push((at, n));
  2937. }
  2938. at += n;
  2939. }
  2940. found
  2941. };
  2942. const PER_THREAD: usize = 16 << 20;
  2943. let threads = ((to - from) / PER_THREAD).clamp(1, 8);
  2944. if threads == 1 {
  2945. return scan(from, to);
  2946. }
  2947. // Cut on piece boundaries, so that every thread sees whole pieces.
  2948. let cut = |i: usize| {
  2949. if i == threads {
  2950. return to;
  2951. }
  2952. let at = from + (to - from) / threads * i;
  2953. (at - (start + at) % PIECE).max(from)
  2954. };
  2955. let scan = &scan;
  2956. std::thread::scope(|s| {
  2957. let parts: Vec<_> = (0..threads)
  2958. .map(|i| {
  2959. let (a, b) = (cut(i), cut(i + 1));
  2960. s.spawn(move || scan(a, b))
  2961. })
  2962. .collect();
  2963. parts
  2964. .into_iter()
  2965. .flat_map(|part| match part.join() {
  2966. Ok(found) => found,
  2967. Err(panic) => std::panic::resume_unwind(panic),
  2968. })
  2969. .collect()
  2970. })
  2971. }
  2972. /// After [`Shadow::copy_back`] of a submission's ranges: every submitted
  2973. /// step that declared one of `ranges` (`(address, end)`, as declared) is
  2974. /// done with it (one submission runs at a time), and the snapshot with
  2975. /// the last range.
  2976. ///
  2977. /// With [`relay`] several submissions may hold a range: `ranges` are
  2978. /// those of one of them (each once), and a range is done with when the
  2979. /// last submission that declared it is ([`Flights`]).
  2980. pub(crate) fn copy_back_done(&self, ranges: &[(usize, usize)]) {
  2981. if self.place.is_some() {
  2982. return;
  2983. }
  2984. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
  2985. if relay() {
  2986. let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges);
  2987. pending.retain(|r| free.binary_search(r).is_err());
  2988. } else {
  2989. pending.retain(|r| !ranges.contains(r));
  2990. }
  2991. if !pending.is_empty() || self.card.is_some() {
  2992. return;
  2993. }
  2994. if keeps() {
  2995. // Kept for the next submission, if it is worth it (a megabyte
  2996. // or more) and there is room.
  2997. let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  2998. if !kept.1 && self.len >= 1 << 20 {
  2999. if KEPT_BYTES.fetch_add(self.len, Ordering::Relaxed) + self.len <= kept_most() {
  3000. kept.1 = true;
  3001. } else {
  3002. KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed);
  3003. }
  3004. }
  3005. if kept.1 {
  3006. return;
  3007. }
  3008. // Given back: nothing of it is current next time. (The lock
  3009. // on the pieces ends here: `copy_back` takes it while it holds
  3010. // the snapshot's.)
  3011. kept.0.clear();
  3012. }
  3013. if let Some(bytes) = self.before.lock().unwrap_or_else(|e| e.into_inner()).take() {
  3014. give_back(bytes);
  3015. }
  3016. }
  3017. /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory, as
  3018. /// [`Shadow::differing`] cuts them) that hold offsets `[from, to)` of
  3019. /// the copy; `from < to`.
  3020. fn pieces(&self, from: usize, to: usize) -> std::ops::Range<usize> {
  3021. pieces_of(self.start as usize, from, to)
  3022. }
  3023. /// The offsets in the copy that piece `piece` holds.
  3024. fn piece(&self, piece: usize) -> (usize, usize) {
  3025. piece_at(self.start as usize, self.len as usize, piece)
  3026. }
  3027. /// The copy's bytes at offsets `[from, to)` change: a kept snapshot is
  3028. /// not current there any more.
  3029. fn changed(&self, from: usize, to: usize) {
  3030. if !keeps() || from >= to {
  3031. return;
  3032. }
  3033. let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  3034. if kept.0.is_empty() {
  3035. return;
  3036. }
  3037. for piece in self.pieces(from, to) {
  3038. kept.0[piece] = false;
  3039. }
  3040. }
  3041. /// Whether shaders of a submission not yet copied back may be writing
  3042. /// the copy.
  3043. pub(crate) fn writes_pending(&self) -> bool {
  3044. !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
  3045. }
  3046. /// Whether one of those submissions may be writing in title memory
  3047. /// `[from, to)`.
  3048. pub(crate) fn writes_pending_in(&self, from: usize, to: usize) -> bool {
  3049. self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from)
  3050. }
  3051. /// Whether [`Shadow::update`] of `[address, address + len)` would leave
  3052. /// title bytes behind: a range shaders may be writing holds a page the
  3053. /// title wrote since the copy last took it. The answer comes from the
  3054. /// write-watch journal alone, as the submission's one asking left it
  3055. /// (`crate::watch::asked`); where the journal cannot say (memory not
  3056. /// write-watched, a range not asked about) it is yes. A page the copy
  3057. /// never took whole counts as written if the title ever wrote it.
  3058. ///
  3059. /// For submissions sent to the card without a wait
  3060. /// (`crate::host::late`): the ranges are those of flights in the air,
  3061. /// which are then settled before this refresh.
  3062. pub(crate) fn stale_under_writes(&self, address: usize, len: usize) -> bool {
  3063. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3064. let (from, to) = (address.max(start), (address + len).min(end));
  3065. if from >= to {
  3066. return false;
  3067. }
  3068. let busy: Vec<(usize, usize)> = self
  3069. .pending
  3070. .lock()
  3071. .unwrap_or_else(|e| e.into_inner())
  3072. .iter()
  3073. .filter(|&&(a, e)| a < to && e > from)
  3074. .map(|&(a, e)| (a.max(from), e.min(to)))
  3075. .collect();
  3076. if busy.is_empty() {
  3077. return false;
  3078. }
  3079. if self.watched.load(Ordering::Relaxed) == NOT_WATCHED {
  3080. return true;
  3081. }
  3082. let base = start / PAGE;
  3083. let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3084. busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) {
  3085. Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(),
  3086. None => true,
  3087. })
  3088. }
  3089. /// Where [`Shadow::stale_under_writes`] says yes: puts the bytes the
  3090. /// title changed into the copy, in the ranges shaders may be writing,
  3091. /// and only those bytes, so that what the shaders write beside them
  3092. /// stays (`crate::host::late_exact`). For each page of such a range
  3093. /// that the title wrote since the copy last took it, title memory as
  3094. /// it is now is compared with what the copy held when the range was
  3095. /// given to the shaders: the copy's CPU side for a copy in the card's
  3096. /// memory (the changed runs go up before the next submission, each a
  3097. /// copy of its own bytes, `runs_left` of them at most), the snapshot
  3098. /// for the others (the changed bytes go into the copy and into the
  3099. /// snapshot, so the compare after the card ran takes them for the
  3100. /// title's and not the shaders').
  3101. ///
  3102. /// Whether the caller must still settle the flights: the journal
  3103. /// cannot say what was written, a snapshot is missing, or `runs_left`
  3104. /// ran out. Pages done before that stay done.
  3105. pub(crate) fn merge_under_writes(&self, address: usize, len: usize, runs_left: &mut usize) -> bool {
  3106. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3107. let (from, to) = (address.max(start), (address + len).min(end));
  3108. if from >= to {
  3109. return false;
  3110. }
  3111. let busy: Vec<(usize, usize)> = self
  3112. .pending
  3113. .lock()
  3114. .unwrap_or_else(|e| e.into_inner())
  3115. .iter()
  3116. .filter(|&&(a, e)| a < to && e > from)
  3117. .map(|&(a, e)| (a.max(from), e.min(to)))
  3118. .collect();
  3119. if busy.is_empty() {
  3120. return false;
  3121. }
  3122. if self.watched.load(Ordering::Relaxed) == NOT_WATCHED {
  3123. note_stale(0);
  3124. return true;
  3125. }
  3126. // The declared ranges overlap (views of the title's whole heap from
  3127. // dozens of offsets): as one range each page is asked about and
  3128. // compared once. Every byte of it is in a declared range, and of a
  3129. // copy in the PC's memory in the snapshot.
  3130. let busy = if crate::watch::light() { joined(busy) } else { busy };
  3131. let base = start / PAGE;
  3132. let mut title = vec![0u8; PAGE];
  3133. for (a, e) in busy {
  3134. // As the refresh itself asks (`update_free`): the journal if
  3135. // the submission's asking covered the range, else the kernel,
  3136. // else the guards. The journal alone said nothing for copies
  3137. // of view memory, which is guarded and not write-watched, and
  3138. // those were all of run 99's cases: the flights were settled
  3139. // 4-5 times a frame for "0 pages looked at".
  3140. let Some((now, written)) = crate::watch::writes(a, e, true) else {
  3141. note_stale(1);
  3142. return true;
  3143. };
  3144. let stale: Vec<usize> = {
  3145. let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3146. stale_pages_in(base, &copied, a, e, &written)
  3147. };
  3148. for page in stale {
  3149. let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e));
  3150. if lo >= hi {
  3151. continue;
  3152. }
  3153. let n = hi - lo;
  3154. let title = &mut title[..n];
  3155. // The lock of the copy's reference (the snapshot, or the
  3156. // CPU's side of a copy in the card's memory), from before
  3157. // title memory is read until the title's bytes are in: with
  3158. // the copy-back on its own thread ([`relay`]) that thread
  3159. // puts what the card wrote into title memory and into the
  3160. // reference under the same lock, and a page read before
  3161. // such a merge and compared after it would take the card's
  3162. // bytes for the title's.
  3163. let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
  3164. let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
  3165. // A page that is not there is left as it is, and looked at
  3166. // again next time.
  3167. if !crate::host::read_into(lo as *const u8, title) {
  3168. continue;
  3169. }
  3170. MERGED[0].fetch_add(1, Ordering::Relaxed);
  3171. let at = lo - start;
  3172. if self.card.is_some() {
  3173. // SAFETY: inside the mapping of the copy's CPU side,
  3174. // which only the submitting thread writes.
  3175. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
  3176. // Whole words go up as pairs, all of them in one
  3177. // dispatch: only what is a copy of its own counts.
  3178. let runs = if crate::host::words_under() { dword_runs(lo, title, held, 0) } else { changed_runs(title, held) };
  3179. let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m);
  3180. let copies = runs.iter().filter(own).count();
  3181. if copies > *runs_left {
  3182. note_stale(2);
  3183. return true;
  3184. }
  3185. *runs_left -= copies;
  3186. let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec());
  3187. for &(r, m) in &runs {
  3188. held[r..r + m].copy_from_slice(&title[r..r + m]);
  3189. MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
  3190. }
  3191. MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3192. self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m)));
  3193. if let Some(was) = was {
  3194. crate::host::upcheck::note(self.id, at, &was, held);
  3195. }
  3196. } else {
  3197. let Some(snapshot) = before.as_mut() else {
  3198. note_stale(3);
  3199. return true;
  3200. };
  3201. // SAFETY: the snapshot's allocation holds the copy's
  3202. // bytes at the copy's offsets (`writing`), and these
  3203. // are in a declared range.
  3204. let held = unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) };
  3205. for (r, m) in changed_runs(title, held) {
  3206. // SAFETY: inside the copy's mapping. The card may be
  3207. // writing the copy beside these bytes; they are
  3208. // written here and nothing around them.
  3209. unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) };
  3210. held[r..r + m].copy_from_slice(&title[r..r + m]);
  3211. MERGED[1].fetch_add(1, Ordering::Relaxed);
  3212. MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
  3213. }
  3214. }
  3215. drop(before);
  3216. drop(_merging);
  3217. // Taken, if the range holds all of the page that is in the
  3218. // copy; else the rest of it is the refresh's, which notes
  3219. // only whole pages, and the page is looked at again.
  3220. if (page * PAGE).max(start) >= a && ((page + 1) * PAGE).min(end) <= e {
  3221. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3222. if let Some(at) = copied.get_mut(page - base) {
  3223. *at = now;
  3224. }
  3225. }
  3226. }
  3227. }
  3228. false
  3229. }
  3230. /// At submission: copies what changed of `[address, address + len)`
  3231. /// since it was last copied (all of it if the memory is not
  3232. /// write-watched). Returns the bytes copied.
  3233. pub(crate) fn update(&self, address: usize, len: usize) -> usize {
  3234. // In place: the card reads title memory itself.
  3235. if self.place.is_some() {
  3236. return 0;
  3237. }
  3238. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3239. let (from, to) = (address.max(start), (address + len).min(end));
  3240. if from >= to {
  3241. return 0;
  3242. }
  3243. let mut busy: Vec<(usize, usize)> = self
  3244. .pending
  3245. .lock()
  3246. .unwrap_or_else(|e| e.into_inner())
  3247. .iter()
  3248. .copied()
  3249. .filter(|&(a, e)| a < to && e > from)
  3250. .collect();
  3251. if !busy.is_empty() {
  3252. // Around ranges shaders are writing: the gaps, each as below
  3253. // (in the world most submissions have such ranges; copying the
  3254. // gaps whole cost ~1 s per frame).
  3255. busy.sort_unstable();
  3256. let (mut at, mut bytes) = (from, 0);
  3257. for (a, e) in busy {
  3258. if a > at {
  3259. bytes += self.update_free(at, a);
  3260. }
  3261. at = at.max(e);
  3262. }
  3263. if at < to {
  3264. bytes += self.update_free(at, to);
  3265. }
  3266. return bytes;
  3267. }
  3268. self.update_free(from, to)
  3269. }
  3270. /// Whether [`Shadow::update`] of `[address, address + len)` would copy
  3271. /// nothing, and knows it without asking anything
  3272. /// (`crate::watch::nothing_new`). `false` if it would have to ask.
  3273. pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool {
  3274. if self.place.is_some() {
  3275. return true;
  3276. }
  3277. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3278. let (from, to) = (address.max(start), (address + len).min(end));
  3279. if from >= to {
  3280. return true;
  3281. }
  3282. if !matches!(self.watched.load(Ordering::Relaxed), 1 | GUARDED) {
  3283. return false;
  3284. }
  3285. // Around ranges shaders are writing the refresh asks gap by gap.
  3286. if self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) {
  3287. return false;
  3288. }
  3289. let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3290. let same = crate::watch::nothing_new(from, to, start / PAGE, &copied, self.ranged(from, to));
  3291. #[cfg(feature = "diagnostics")]
  3292. if same {
  3293. use crate::copystat::{C, add};
  3294. add(C::Checked, (to - from) as u64);
  3295. add(C::Unchanged, (to - from) as u64);
  3296. }
  3297. same
  3298. }
  3299. /// The latest asking after which a range that holds `[from, to)` was
  3300. /// taken whole (0: none is known). The caller holds `copied`'s lock.
  3301. fn ranged(&self, from: usize, to: usize) -> u64 {
  3302. let ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner());
  3303. ranged.iter().filter(|r| r.0 <= from && to <= r.1).map(|r| r.2).max().unwrap_or(0)
  3304. }
  3305. /// [`Shadow::update`] of `[from, to)` (inside the buffer) where no
  3306. /// shader writes.
  3307. fn update_free(&self, from: usize, to: usize) -> usize {
  3308. if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
  3309. if let Some((now, written)) = crate::watch::writes(from, to, true) {
  3310. // (A range whose blocks rest after a write has no guard now.)
  3311. let guarded = crate::watch::guarded(from, to) || self.watched.load(Ordering::Relaxed) == GUARDED;
  3312. self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed);
  3313. let copied = self.copy_stale(from, to, now, &written);
  3314. self.refresh_check(from, to);
  3315. #[cfg(feature = "diagnostics")]
  3316. {
  3317. use crate::copystat::{C, add};
  3318. add(C::Checked, (to - from) as u64);
  3319. add(C::Unchanged, (to - from).saturating_sub(copied) as u64);
  3320. }
  3321. return copied;
  3322. }
  3323. self.watched.store(NOT_WATCHED, Ordering::Relaxed);
  3324. }
  3325. #[cfg(feature = "diagnostics")]
  3326. crate::copystat::add(crate::copystat::C::WholeBytes, (to - from) as u64);
  3327. #[cfg(feature = "diagnostics")]
  3328. let started = std::time::Instant::now();
  3329. self.copy(from, to);
  3330. #[cfg(feature = "diagnostics")]
  3331. crate::copystat::whole(from, to - from, started.elapsed().as_micros() as u64);
  3332. to - from
  3333. }
  3334. /// Diagnostic (`VICTORY_REFRESH_CHECK=1`; off by default): after a
  3335. /// refresh of `[from, to)` that trusted the write watch or the guards,
  3336. /// the first 256 bytes of every 64 KiB block of it are read from title
  3337. /// memory and compared with the copy. A block that differs on three
  3338. /// refreshes in a row was changed with nothing to tell of it (a write
  3339. /// through another view of its pages, as DirectStorage's page
  3340. /// destinations make) and the card reads old bytes there: said with
  3341. /// the copy and the address. One that differs once is a write of the
  3342. /// title's that arrived between the refresh and the look.
  3343. fn refresh_check(&self, from: usize, to: usize) {
  3344. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  3345. if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1")) {
  3346. return;
  3347. }
  3348. const SAMPLE: usize = 256;
  3349. // Blocks found differing: how many refreshes in a row.
  3350. static DIFFERING: Mutex<Option<std::collections::HashMap<usize, u32>>> = Mutex::new(None);
  3351. static SAID: AtomicU64 = AtomicU64::new(0);
  3352. let start = self.start as usize;
  3353. let mut title = [0u8; SAMPLE];
  3354. let mut at = from;
  3355. while at < to {
  3356. let n = SAMPLE.min(to - at);
  3357. if crate::host::read_into(at as *const u8, &mut title[..n]) {
  3358. // SAFETY: `[from, to)` lies inside the buffer (`update`),
  3359. // so these bytes are inside the copy's mapping.
  3360. let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) };
  3361. let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner());
  3362. let map = map.get_or_insert_with(Default::default);
  3363. if copy == &title[..n] {
  3364. map.remove(&at);
  3365. } else {
  3366. let times = map.entry(at).or_insert(0);
  3367. *times += 1;
  3368. if *times == 3 {
  3369. let said = SAID.fetch_add(1, Ordering::Relaxed) + 1;
  3370. if said <= 64 || said.is_power_of_two() {
  3371. tracing::warn!(
  3372. said,
  3373. copy = self.id,
  3374. copy_start = format_args!("{start:#x}"),
  3375. copy_bytes = self.len,
  3376. address = format_args!("{at:#x}"),
  3377. refreshed = format_args!("{from:#x}..{to:#x}"),
  3378. on_the_card = self.card.is_some(),
  3379. window = self.window,
  3380. "a host copy of title memory is stale after its refresh, three times in a row: the memory changed with nothing to tell of it (VICTORY_REFRESH_CHECK=1)"
  3381. );
  3382. }
  3383. }
  3384. }
  3385. }
  3386. // The first bytes of the next 64 KiB block.
  3387. at = (at / PAGE + 1) * PAGE;
  3388. }
  3389. }
  3390. /// Copies the pages of `[from, to)` written after their last copy
  3391. /// (`written`: last writes by page, in page order; `now`: this
  3392. /// asking), whole pages within the buffer.
  3393. fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize {
  3394. let base = self.start as usize / PAGE;
  3395. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3396. let mut writes = written.iter().peekable();
  3397. // Pages the range holds in part are never noted in `copied`, and
  3398. // were copied again at every refresh of the range, written or not:
  3399. // of the heap's buffer views alone two ends for each of 4,400
  3400. // copies, every frame. A range that was taken whole, and not written
  3401. // since, is as it was.
  3402. let ranged = if crate::watch::light() { self.ranged(from, to) } else { 0 };
  3403. let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>);
  3404. // Pages taken before and written since: in the order of their runs.
  3405. let mut again_at: Vec<(usize, u64)> = Vec::new();
  3406. let last = (to - 1) / PAGE;
  3407. for page in from / PAGE..=last {
  3408. let write = match writes.peek() {
  3409. Some(&&(p, w)) if p == page => {
  3410. writes.next();
  3411. w
  3412. }
  3413. _ => 0,
  3414. };
  3415. let at = &mut copied[page - base];
  3416. let taken = (*at).max(ranged);
  3417. if taken == 0 || write > taken {
  3418. // A page only partly in the range is copied in part: it
  3419. // stays stale for the rest.
  3420. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3421. if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to {
  3422. *at = now;
  3423. }
  3424. // Cut where pages taken before meet pages never taken.
  3425. let again = taken != 0;
  3426. if again {
  3427. again_at.push((page, taken));
  3428. }
  3429. if let Some((first, known)) = run
  3430. && known != again
  3431. {
  3432. runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known));
  3433. run = None;
  3434. }
  3435. run.get_or_insert((page, again));
  3436. } else if let Some((first, known)) = run.take() {
  3437. runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known));
  3438. }
  3439. }
  3440. // Cut to the range: next to it shaders may be writing the copy.
  3441. if let Some((first, known)) = run {
  3442. runs.push(((first * PAGE).max(from), ((last + 1) * PAGE).min(to), known));
  3443. }
  3444. let runs = by_parts(runs, &again_at, &crate::watch::parts_written(&again_at));
  3445. let bytes = self.take_all(runs);
  3446. if crate::watch::light() {
  3447. // All of the range is in the copy as of this asking.
  3448. let mut ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner());
  3449. ranged[0] = (from, to, now);
  3450. if to - from >= ranged[1].1 - ranged[1].0 {
  3451. ranged[1] = (from, to, now);
  3452. }
  3453. }
  3454. bytes
  3455. }
  3456. /// [`Shadow::take`] of `runs` (from, to, known), on several threads if
  3457. /// they are long: the big heap's copy has some 4 MB of them in each of
  3458. /// 14 refreshes a frame, on one thread while the others had nothing.
  3459. fn take_all(&self, runs: Vec<(usize, usize, bool)>) -> usize {
  3460. const LONG: usize = 1 << 20;
  3461. const PART: usize = 256 << 10;
  3462. let bytes = runs.iter().map(|r| r.1 - r.0).sum();
  3463. if bytes < LONG || !crate::watch::light() {
  3464. for (from, to, known) in runs {
  3465. self.take(from, to, known);
  3466. }
  3467. return bytes;
  3468. }
  3469. let mut parts = Vec::with_capacity(bytes / PART + runs.len());
  3470. for (from, to, known) in runs {
  3471. let mut at = from;
  3472. while at < to {
  3473. // Whole pages to a part.
  3474. let next = ((at / PAGE) * PAGE + PART).min(to);
  3475. parts.push((at, next, known));
  3476. at = next;
  3477. }
  3478. }
  3479. let this = std::ptr::from_ref(self) as usize;
  3480. wide_each(parts.len(), move |i| {
  3481. // SAFETY: `wide_each` returns when every part is done, before
  3482. // the borrow of `self` ends. The parts lie apart.
  3483. let this = unsafe { &*(this as *const Shadow) };
  3484. let (from, to, known) = parts[i];
  3485. this.take(from, to, known);
  3486. });
  3487. bytes
  3488. }
  3489. /// Copies title memory `[from, to)` (inside the buffer) into the copy;
  3490. /// `known`: the copy held it before ([`send_changed`]).
  3491. fn take(&self, from: usize, to: usize, known: bool) -> usize {
  3492. thread_local! {
  3493. /// A page of title memory, as read.
  3494. static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
  3495. }
  3496. let Some(card) = self.card.as_ref().filter(|_| self.changes_only.load(Ordering::Relaxed) || send_changed()) else {
  3497. return self.copy(from, to);
  3498. };
  3499. let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none();
  3500. let start = self.start as usize;
  3501. TITLE.with_borrow_mut(|title| {
  3502. title.resize(PAGE, 0);
  3503. let mut at = from;
  3504. while at < to {
  3505. let n = (PAGE - at % PAGE).min(to - at);
  3506. let title = &mut title[..n];
  3507. // (Pages that are not there read as zeros.)
  3508. crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false);
  3509. // SAFETY: inside the mapping of the copy's CPU side, which
  3510. // nothing else reads or writes there (the card copies from
  3511. // it): no shader's range holds it, and the parts of a
  3512. // refresh lie apart.
  3513. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) };
  3514. let was = crate::host::upcheck::on().then(|| held.to_vec());
  3515. let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) };
  3516. for &(a, len) in &runs {
  3517. held[a..a + len].copy_from_slice(&title[a..a + len]);
  3518. self.changed(at - start + a, at - start + a + len);
  3519. }
  3520. self.card_changed_runs(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len)));
  3521. if let Some(was) = was {
  3522. crate::host::upcheck::note(self.id, at - start, &was, held);
  3523. }
  3524. SEND[0].fetch_add(n as u64, Ordering::Relaxed);
  3525. if runs.is_empty() {
  3526. SEND[1].fetch_add(n as u64, Ordering::Relaxed);
  3527. }
  3528. SEND[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed);
  3529. SEND[3].fetch_add(runs.len() as u64, Ordering::Relaxed);
  3530. at += n;
  3531. }
  3532. });
  3533. to - from
  3534. }
  3535. /// Copies title memory `[from, to)`, cut to the buffer, into the copy.
  3536. fn copy(&self, from: usize, to: usize) -> usize {
  3537. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  3538. let (from, to) = (from.max(start), to.min(end));
  3539. // SAFETY: inside the mapping (`from` and `to` are within the buffer).
  3540. let at = unsafe { self.data.add(from - start) };
  3541. if self.card.is_some() && from < to && crate::host::upcheck::on() {
  3542. for_pieces_of(from - start, to - start, |a, b| {
  3543. let was = self.card_held(a, b - a);
  3544. // SAFETY: inside the mapping, as above.
  3545. crate::host::copy_mapped(unsafe { self.data.add(a) }, (start + a) as *const u8, b - a, false);
  3546. crate::host::upcheck::note(self.id, a, &was, &self.card_held(a, b - a));
  3547. });
  3548. } else {
  3549. crate::host::copy_mapped(at, from as *const u8, to - from, false);
  3550. }
  3551. // After the bytes are in: a snapshot taken meanwhile is not current.
  3552. self.changed(from - start, to - start);
  3553. self.card_changed(from - start, to - start);
  3554. to - from
  3555. }
  3556. /// Whether shaders read and write this copy in the card's own memory
  3557. /// ([`cards`]).
  3558. pub(crate) fn carded(&self) -> bool {
  3559. self.card.is_some()
  3560. }
  3561. /// Shaders store in it what is not declared: from here on only the dwords
  3562. /// the title changes go up ([`by_address`]).
  3563. pub(crate) fn keep_stores(&self) {
  3564. self.changes_only.store(true, Ordering::Relaxed);
  3565. }
  3566. /// Offsets `[from, to)` go up again whole, as the CPU's side has them.
  3567. pub(crate) fn resend(&self, from: usize, to: usize) {
  3568. self.card_changed(from, to);
  3569. }
  3570. /// The CPU side's bytes at offsets `[from, to)` changed: they go to the
  3571. /// card's side before the next submission.
  3572. fn card_changed(&self, from: usize, to: usize) {
  3573. self.card_changed_runs(std::iter::once((from, to)));
  3574. }
  3575. /// [`Shadow::card_changed`] of each of `runs`.
  3576. fn card_changed_runs(&self, runs: impl Iterator<Item = (usize, usize)>) {
  3577. let Some(card) = &self.card else {
  3578. return;
  3579. };
  3580. let mut runs = runs.filter(|r| r.0 < r.1).peekable();
  3581. if runs.peek().is_none() {
  3582. return;
  3583. }
  3584. let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
  3585. for (from, to) in runs {
  3586. match dirty.last_mut() {
  3587. Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)),
  3588. _ => dirty.push((from, to)),
  3589. }
  3590. }
  3591. // (Under the lock: what takes the list sees it or finds it set.)
  3592. card.touched.store(true, Ordering::Release);
  3593. }
  3594. /// Whether shaders were ever declared to write it.
  3595. pub(crate) fn written(&self) -> bool {
  3596. self.written.load(Ordering::Relaxed)
  3597. }
  3598. /// `bytes` were put into title memory at `address`, and the submission
  3599. /// being prepared copies the same to the copy at that copy's place in its
  3600. /// list: the reference (the CPU's side of a copy in the card's memory, the
  3601. /// snapshot) takes them and nothing is sent. What the card makes of them
  3602. /// is then what differs from them when the submission has run. The range
  3603. /// is declared written by it, and its sends are taken.
  3604. pub(crate) fn placed_copy(&self, address: usize, bytes: &[u8]) {
  3605. let (from, to) = self.inside(address, bytes.len());
  3606. if from >= to || self.place.is_some() {
  3607. return;
  3608. }
  3609. let bytes = &bytes[self.start as usize + from - address..][..to - from];
  3610. let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
  3611. if self.card.is_some() {
  3612. // SAFETY: inside the mapping of the CPU's side, in a range no
  3613. // refresh writes; the lock keeps the landing out.
  3614. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.data.add(from), bytes.len()) };
  3615. } else if let Some(snapshot) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
  3616. // SAFETY: the snapshot's allocation holds the copy's length.
  3617. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), snapshot.as_mut_ptr().add(from), bytes.len()) };
  3618. }
  3619. self.changed(from, to);
  3620. }
  3621. /// Of a copy in the card's memory: where its CPU side is.
  3622. pub(crate) fn card_data(&self) -> *const u8 {
  3623. self.data
  3624. }
  3625. /// Diagnostics: of a copy in the card's memory, what its CPU side holds
  3626. /// at offsets `[at, at + len)` (cut to the copy).
  3627. pub(crate) fn card_held(&self, at: usize, len: usize) -> Vec<u8> {
  3628. let to = (at + len).min(self.len as usize);
  3629. if self.card.is_none() || at >= to {
  3630. return Vec::new();
  3631. }
  3632. // SAFETY: inside the mapping; the caller holds the submission lock,
  3633. // under which it is written but for what is being landed.
  3634. unsafe { std::slice::from_raw_parts(self.data.add(at).cast_const(), to - at) }.to_vec()
  3635. }
  3636. /// Diagnostics: the offsets whose bytes have not gone to the card's side
  3637. /// yet.
  3638. pub(crate) fn card_dirty_now(&self) -> Vec<(usize, usize)> {
  3639. self.card.as_ref().map_or_else(Vec::new, |c| c.dirty.lock().unwrap_or_else(|e| e.into_inner()).clone())
  3640. }
  3641. /// Of a copy in the card's memory: the CPU's side (PC memory), the
  3642. /// card side's bytes from before if made yet, and their size.
  3643. pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option<ID3D12Resource>, u64)> {
  3644. let card = self.card.as_ref()?;
  3645. let before = card.before.lock().unwrap_or_else(|e| e.into_inner()).clone();
  3646. Some((&card.staging, before, card.size))
  3647. }
  3648. /// Shader writes are declared for a copy in the card's memory: makes
  3649. /// its "before" twin with `make` (bytes to buffer) if it has none.
  3650. /// Whether one was made now: the caller fills it, whole, from the
  3651. /// card's side before the submission's lists run. Without one (no
  3652. /// memory) every piece of a declared range is fetched.
  3653. pub(crate) fn card_make_before(&self, make: impl FnOnce(u64) -> Option<ID3D12Resource>) -> bool {
  3654. let Some(card) = &self.card else {
  3655. return false;
  3656. };
  3657. let mut before = card.before.lock().unwrap_or_else(|e| e.into_inner());
  3658. if before.is_some() {
  3659. return false;
  3660. }
  3661. *before = make(card.size);
  3662. if before.is_some() {
  3663. CARD_BYTES[1].fetch_add(card_hash_bytes(card.size), Ordering::Relaxed);
  3664. }
  3665. before.is_some()
  3666. }
  3667. /// The declared range `[address, end)` as the compare on the card
  3668. /// takes it; `None` if none of it lies in the copy.
  3669. pub(crate) fn card_span(&self, address: usize, end: usize) -> Option<CardSpan> {
  3670. let (from, to) = self.inside(address, end.saturating_sub(address));
  3671. (from < to).then(|| card_span_of(self.start as usize, from, to))
  3672. }
  3673. /// The pieces that hold offsets `[from, to)` of the copy (cut to it),
  3674. /// as the card's hashing takes them.
  3675. pub(crate) fn card_run(&self, from: usize, to: usize) -> CardSpan {
  3676. let to = to.min(self.len as usize);
  3677. card_span_of(self.start as usize, from.min(to.saturating_sub(1)), to)
  3678. }
  3679. /// The offsets of piece `i` of `span` that lie in the span.
  3680. pub(crate) fn card_piece(&self, span: &CardSpan, i: u32) -> (usize, usize) {
  3681. card_piece_of(self.start as usize, self.len as usize, span, i)
  3682. }
  3683. /// The piece that holds offset `at`.
  3684. pub(crate) fn card_piece_of(&self, at: usize) -> u32 {
  3685. self.pieces(at, at + 1).start as u32
  3686. }
  3687. /// The offsets the compare on the card hashes of a piece: what lies of
  3688. /// it in the card's buffer (which may be longer than the copy), widened
  3689. /// to 16 bytes.
  3690. pub(crate) fn card_hashed(&self, piece: u32) -> (usize, usize) {
  3691. let size = self.card.as_ref().map_or(self.len, |c| c.size) as usize;
  3692. card_hashed_of(self.start as usize, size, piece as usize)
  3693. }
  3694. /// The walls trace (`crate::host::walls_trace`): a piece of `fetched`
  3695. /// bytes of this copy came back from the card and `written` of them
  3696. /// went into title memory. Summed per buffer and logged once a frame:
  3697. /// which shader-written buffers the title's CPU could see fresh in
  3698. /// that frame, and how much of each changed.
  3699. pub(crate) fn walls_merged(&self, fetched: usize, written: usize) {
  3700. if !crate::host::walls_trace() {
  3701. return;
  3702. }
  3703. static SEEN: Mutex<(u64, BTreeMap<u64, (u64, u32, u64, u64)>)> = Mutex::new((0, BTreeMap::new()));
  3704. let frame = crate::frame::current();
  3705. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  3706. if seen.0 != frame {
  3707. let buffers: Vec<String> = seen
  3708. .1
  3709. .iter()
  3710. .map(|(at, v)| format!("{at:#x}+{:#x}: {} pieces, {} fetched, {} written", v.0, v.1, v.2, v.3))
  3711. .take(32)
  3712. .collect();
  3713. if !buffers.is_empty() {
  3714. tracing::info!(
  3715. frame = seen.0,
  3716. count = seen.1.len(),
  3717. buffers = ?buffers,
  3718. "walls trace: shader-written card buffers merged into title memory in this frame"
  3719. );
  3720. }
  3721. seen.1.clear();
  3722. seen.0 = frame;
  3723. }
  3724. let entry = seen.1.entry(self.start).or_insert((self.len, 0, 0, 0));
  3725. entry.1 += 1;
  3726. entry.2 += fetched as u64;
  3727. entry.3 += written as u64;
  3728. }
  3729. /// After a submission, for a copy in the card's memory: `gpu` is what
  3730. /// the card's side holds at offset `at` on, in a piece the compare
  3731. /// found differing. The bytes shaders wrote (those that differ from the
  3732. /// CPU's side, which is what the card's side held when they started)
  3733. /// go into title memory, from the first to the last of them, as
  3734. /// [`Shadow::copy_back`] puts them; the CPU's side takes the result and
  3735. /// sends it up before the next submission. `title` is scratch memory.
  3736. /// Returns the bytes written to title memory.
  3737. pub(crate) fn card_merge(&self, at: usize, gpu: &[u8], title: &mut Vec<u8>) -> usize {
  3738. let start = self.start as usize;
  3739. if self.card.is_none() || at + gpu.len() > self.len as usize {
  3740. return 0;
  3741. }
  3742. // SAFETY: inside the mapping (checked above); only the submitting
  3743. // thread writes it.
  3744. let old = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) };
  3745. let Some(first) = first_difference(gpu, old) else {
  3746. return 0;
  3747. };
  3748. let last = last_difference(gpu, old).unwrap_or(first);
  3749. let (at, n) = (at + first, last + 1 - first);
  3750. let (gpu, old) = (&gpu[first..=last], &mut old[first..=last]);
  3751. title.clear();
  3752. title.resize(n, 0);
  3753. let mut written = 0;
  3754. if crate::host::read_into((start + at) as *const u8, title) {
  3755. // The stretch as read: what the card did not change is the
  3756. // title's, and may have been written again since.
  3757. // As in `copy_back`: the card's byte where it is not what it
  3758. // was before the submission, else the title's.
  3759. let mut differs = 0u8;
  3760. let was = title.clone();
  3761. for ((t, g), o) in title.iter_mut().zip(gpu).zip(old.iter_mut()) {
  3762. let wrote = if *g != *o { 0xffu8 } else { 0 };
  3763. let merged = (*t & !wrote) | (*g & wrote);
  3764. differs |= merged ^ *t;
  3765. *t = merged;
  3766. *o = merged;
  3767. }
  3768. if differs != 0 {
  3769. written = put_changed(start + at, &was, title);
  3770. }
  3771. } else {
  3772. // Title memory is not mapped there: the copy keeps what the
  3773. // card wrote, as before.
  3774. old.copy_from_slice(gpu);
  3775. }
  3776. // The card's side and its "before" take the result.
  3777. self.card_changed(at, at + n);
  3778. written
  3779. }
  3780. /// [`relay`], for a copy in the card's memory: `gpu` is what the
  3781. /// card's side held at offset `at` on when a fetch sent after send
  3782. /// `fetched_after` (`crate::host`'s order of the queue) ran, in a piece
  3783. /// the compare found differing. The bytes that differ from the CPU's
  3784. /// side are what shaders wrote; they go into title memory, from the
  3785. /// first to the last of them, and into the CPU's side. Nothing is sent
  3786. /// up afterwards (the card holds these bytes or newer ones: sending
  3787. /// them up could undo a later flight's write), and the title's other
  3788. /// bytes are left to the refresh.
  3789. ///
  3790. /// Left out: bytes of the CPU's side that hold title bytes the card
  3791. /// had not received when the fetch ran, those still to go up and those
  3792. /// that went up with a later send. There the card's side is the older
  3793. /// one, and taking it for a shader's write would put it over what the
  3794. /// title wrote. Under the CPU side's lock (the snapshot's, which such
  3795. /// a copy has no other use for), as [`Shadow::merge_under_writes`].
  3796. /// `title` is scratch memory. Returns the bytes written to title
  3797. /// memory.
  3798. pub(crate) fn card_merge_relay(&self, at: usize, gpu: &[u8], fetched_after: u64, title: &mut Vec<u8>) -> usize {
  3799. let start = self.start as usize;
  3800. let Some(card) = &self.card else {
  3801. return 0;
  3802. };
  3803. if at + gpu.len() > self.len as usize {
  3804. return 0;
  3805. }
  3806. let _side = self.before.lock().unwrap_or_else(|e| e.into_inner());
  3807. // SAFETY: inside the mapping (checked above). The offsets are in a
  3808. // range declared and not done with, which no refresh writes; what
  3809. // does write it (the title's bytes put in under shader writes)
  3810. // holds the lock held here.
  3811. let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) };
  3812. let Some(first) = first_difference(gpu, held) else {
  3813. return 0;
  3814. };
  3815. let last = last_difference(gpu, held).unwrap_or(first);
  3816. let (at, n) = (at + first, last + 1 - first);
  3817. let (gpu, held) = (&gpu[first..=last], &mut held[first..=last]);
  3818. let skip: Vec<(usize, usize)> = {
  3819. let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
  3820. let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner());
  3821. let mut skip: Vec<(usize, usize)> = dirty.iter().copied().filter(|&(a, b)| a < at + n && b > at).collect();
  3822. sent.near(fetched_after, at, at + n, &mut skip);
  3823. skip
  3824. };
  3825. title.clear();
  3826. title.resize(n, 0);
  3827. let mapped = crate::host::read_into((start + at) as *const u8, title);
  3828. let was = title.clone();
  3829. let mut changed = false;
  3830. for (a, b) in outside(at, at + n, skip) {
  3831. let (a, b) = (a - at, b - at);
  3832. // Title memory that is not mapped: the CPU's side keeps what
  3833. // the card wrote, as before; `title` is scratch then.
  3834. changed |= merge_piece(&gpu[a..b], &mut held[a..b], &mut title[a..b]);
  3835. }
  3836. if !mapped || !changed {
  3837. return 0;
  3838. }
  3839. put_changed(start + at, &was, title)
  3840. }
  3841. }
  3842. /// For tests: copies with no host buffer behind them.
  3843. #[cfg(test)]
  3844. impl Shadow {
  3845. /// A copy at `data` of title memory `[start, start + len)`, with a card
  3846. /// side if `card`. It is never let go: there is no buffer to release.
  3847. pub(crate) fn unbacked(start: u64, data: *mut u8, len: u64, card: bool) -> Arc<Shadow> {
  3848. // SAFETY: an interface pointer nothing calls.
  3849. let none = || unsafe { std::mem::transmute::<usize, ID3D12Resource>(8) };
  3850. let mut shadow = Shadow::new(none(), data, 0, start, len);
  3851. if card {
  3852. shadow.card = Some(Card {
  3853. staging: none(),
  3854. before: Mutex::default(),
  3855. dirty: Mutex::default(),
  3856. sent: Mutex::default(),
  3857. touched: Default::default(),
  3858. size: len.next_multiple_of(PIECE as u64),
  3859. });
  3860. }
  3861. let shadow = Arc::new(shadow);
  3862. std::mem::forget(shadow.clone());
  3863. shadow
  3864. }
  3865. /// What shaders wrote goes into title memory ([`put_changed`]).
  3866. pub(crate) fn put(at: usize, title: &[u8], merged: &[u8]) {
  3867. put_changed(at, title, merged);
  3868. }
  3869. /// What is to go up to the card, noted as sent with `number`, as
  3870. /// [`card_dirty`] does; notes of sends up to `merged` go.
  3871. pub(crate) fn send_up(&self, number: u64, merged: u64) -> Vec<(usize, usize)> {
  3872. let card = self.card.as_ref().unwrap();
  3873. let mut dirty = card.dirty.lock().unwrap();
  3874. let ranges = std::mem::take(&mut *dirty);
  3875. let mut sent = card.sent.lock().unwrap();
  3876. sent.forget(merged);
  3877. sent.note(number, ranges.clone());
  3878. ranges
  3879. }
  3880. /// What is to go up to the card, taken.
  3881. pub(crate) fn take_dirty(&self) -> Vec<(usize, usize)> {
  3882. std::mem::take(&mut *self.card.as_ref().unwrap().dirty.lock().unwrap())
  3883. }
  3884. }
  3885. impl Shadow {
  3886. /// [`Shadow::card_merge_relay`] of several pieces, each within one
  3887. /// 64 KiB block of title memory: from and to (offsets in the copy), and
  3888. /// where the fetched bytes are. On any thread: several may land pieces
  3889. /// of one copy, no two the same bytes. Returns the bytes put into title
  3890. /// memory.
  3891. ///
  3892. /// What is left out is as there, asked once for all of them: the notes
  3893. /// of bytes that went up (or are to go up) behind the fetch only move
  3894. /// from `dirty` to `sent`, with a later number, and grow only by
  3895. /// [`Shadow::merge_under_writes`], which the lock held here keeps out.
  3896. ///
  3897. /// # Safety
  3898. /// The third of each piece is the address of its bytes, which stay as
  3899. /// they are during the call.
  3900. pub(crate) unsafe fn land_card(&self, pieces: &[(usize, usize, usize)], fetched_after: u64, notes: &mut crate::land::Notes) -> u64 {
  3901. let Some(card) = &self.card else {
  3902. return 0;
  3903. };
  3904. let waiting = std::time::Instant::now();
  3905. let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner());
  3906. crate::land::spent(crate::land::stat::LOCK, waiting);
  3907. let (from, to) = pieces.iter().fold((usize::MAX, 0), |(a, b), p| (a.min(p.0), b.max(p.1)));
  3908. let skip: Vec<(usize, usize)> = {
  3909. let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
  3910. let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner());
  3911. let mut skip: Vec<(usize, usize)> = dirty.iter().copied().filter(|&(a, b)| a < to && b > from).collect();
  3912. sent.near(fetched_after, from, to, &mut skip);
  3913. skip
  3914. };
  3915. let mut put = 0;
  3916. for &(lo, hi, now) in pieces {
  3917. if lo >= hi || hi > self.len as usize {
  3918. continue;
  3919. }
  3920. let near: Vec<(usize, usize)> = skip.iter().copied().filter(|&(a, b)| a < hi && b > lo).collect();
  3921. let parts: Vec<(usize, usize)> = outside(lo, hi, near).into_iter().map(|(a, b)| (a - lo, b - lo)).collect();
  3922. // SAFETY: inside the mapping (checked above), in a range
  3923. // declared and not done with, which no refresh writes; the
  3924. // title's bytes are kept out by the lock; the caller's.
  3925. // Where title memory is not mapped the CPU's side keeps what
  3926. // the card wrote, as before.
  3927. let merged =
  3928. unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes, self) };
  3929. self.walls_merged(hi - lo, merged as usize);
  3930. put += merged;
  3931. }
  3932. put
  3933. }
  3934. /// [`Shadow::relay_merge`] of a piece `[at, at + n)` (within one 64 KiB
  3935. /// block of title memory) of a copy in the PC's memory; on any thread,
  3936. /// as [`Shadow::land_card`]. The copy is read once and never written.
  3937. /// Returns the bytes put into title memory.
  3938. pub(crate) fn land_back(&self, at: usize, n: usize, notes: &mut crate::land::Notes) -> u64 {
  3939. if self.card.is_some() || n == 0 || at + n > self.len as usize {
  3940. return 0;
  3941. }
  3942. let waiting = std::time::Instant::now();
  3943. let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner());
  3944. crate::land::spent(crate::land::stat::LOCK, waiting);
  3945. // The snapshot's memory stays where it is until the range is done
  3946. // with (`copy_back_done`), which comes after this.
  3947. let Some(held) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut().map(Vec::as_mut_ptr) else {
  3948. return 0;
  3949. };
  3950. // SAFETY: inside the copy's mapping (checked above), which only the
  3951. // card writes there, and inside the snapshot's allocation, which
  3952. // holds the copy's length (`writing`): these offsets are in a range
  3953. // declared and not done with, whose bytes it holds, and the lock
  3954. // keeps out what else writes them. Title memory that is not there
  3955. // is looked at again when the next flight that declared the range
  3956. // lands.
  3957. unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes, self) }
  3958. }
  3959. /// What shaders wrote in 64 KiB block `block` (of title memory) of this
  3960. /// copy was put into title memory beside the guard, which was noted as a
  3961. /// write with number `now`, `before` the number of the block's last write
  3962. /// before. If the copy held title memory's bytes of the block ahead of
  3963. /// that it holds them still, and is noted to ([`crate::land`] says why);
  3964. /// whether it was.
  3965. ///
  3966. /// That it did: it took the whole block after that write, and no other
  3967. /// came that is not noted yet. Looked at after the note, whatever comes
  3968. /// later has a number above it: a write of the title's takes the block's
  3969. /// bit, until an asking has noted it.
  3970. pub(crate) fn landed(&self, block: usize, before: u64, now: u64) -> bool {
  3971. let Some(page) = block.checked_sub(self.start as usize / PAGE) else {
  3972. return false;
  3973. };
  3974. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  3975. let Some(at) = copied.get_mut(page) else {
  3976. return false;
  3977. };
  3978. let held = *at != 0 && *at >= before && crate::watch::block_published(block);
  3979. if held {
  3980. *at = (*at).max(now);
  3981. }
  3982. held
  3983. }
  3984. }
  3985. #[cfg(test)]
  3986. mod land_tests {
  3987. use super::{Card, PIECE, Shadow};
  3988. use std::sync::Mutex;
  3989. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  3990. /// A copy in the card's memory of title memory at `title` (its card side
  3991. /// is never looked at here), all bytes 0 on the CPU's side.
  3992. fn copy_of(title: usize, len: usize) -> Option<Shadow> {
  3993. let (buffer, data) = crate::host::host()?.shared_buffer(len as u64)?;
  3994. // SAFETY: the mapping, `len` bytes.
  3995. unsafe { std::ptr::write_bytes(data, 0, len) };
  3996. let mut shadow = Shadow::new(buffer.clone(), data, 0, title as u64, len as u64);
  3997. shadow.card = Some(Card {
  3998. staging: buffer,
  3999. before: Mutex::default(),
  4000. dirty: Mutex::default(),
  4001. sent: Mutex::default(),
  4002. touched: Default::default(),
  4003. size: len as u64,
  4004. });
  4005. Some(shadow)
  4006. }
  4007. /// Memory that stays (`crate::watch` knows its addresses): private, or a
  4008. /// view noted as the runtime notes the title's.
  4009. fn memory(len: usize, view: bool) -> usize {
  4010. use windows_sys::Win32::System::Memory as mem;
  4011. // SAFETY: plain allocations of our own.
  4012. unsafe {
  4013. if !view {
  4014. return mem::VirtualAlloc(std::ptr::null(), len, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize;
  4015. }
  4016. let section = mem::CreateFileMappingW(-1isize as _, std::ptr::null(), mem::PAGE_READWRITE, 0, len as u32, std::ptr::null());
  4017. let at = mem::MapViewOfFile(section, mem::FILE_MAP_WRITE, 0, 0, len).Value as usize;
  4018. crate::inplace::title_memory_section(section as usize, len as u64, true);
  4019. crate::title_memory_remapped(at, len);
  4020. crate::inplace::title_memory_view(at, len, section as usize, 0);
  4021. at
  4022. }
  4023. }
  4024. fn random(seed: &mut u64) -> usize {
  4025. *seed ^= *seed << 13;
  4026. *seed ^= *seed >> 7;
  4027. *seed ^= *seed << 17;
  4028. (*seed >> 8) as usize
  4029. }
  4030. /// [`Shadow::land_card`] leaves title memory and the CPU's side as
  4031. /// [`Shadow::card_merge_relay`] does, with title bytes that went up
  4032. /// behind the fetch, or have not gone up, left out.
  4033. #[test]
  4034. fn pieces_land_as_the_merge_one_by_one_lands_them() {
  4035. assert!(crate::safecopy::on());
  4036. const LEN: usize = 3 * PIECE;
  4037. let mut seed = 0x1234_5678_9abcu64;
  4038. for view in [false, true] {
  4039. let (a, b) = (memory(LEN, view), memory(LEN, view));
  4040. let (Some(one), Some(many)) = (copy_of(a, LEN), copy_of(b, LEN)) else {
  4041. return; // no host GPU
  4042. };
  4043. // SAFETY: the two memories and the two mappings.
  4044. let bytes = |at: usize| unsafe { std::slice::from_raw_parts_mut(at as *mut u8, LEN) };
  4045. for round in 0..40u32 {
  4046. let base: Vec<u8> = (0..LEN).map(|_| random(&mut seed) as u8).collect();
  4047. let (mut held, mut title, mut now) = (base.clone(), base.clone(), base);
  4048. let (mut dirty, mut sent) = (Vec::new(), Vec::new());
  4049. for k in 0..120 {
  4050. let at = random(&mut seed) % LEN / 4 * 4;
  4051. let n = (random(&mut seed) % 900 / 4 * 4).min(LEN - at);
  4052. match k % 4 {
  4053. 0 | 1 => now[at..at + n].fill(random(&mut seed) as u8),
  4054. 2 => title[at..at + n].fill(random(&mut seed) as u8),
  4055. // Title bytes put into the CPU's side meanwhile.
  4056. _ => {
  4057. let byte = random(&mut seed) as u8;
  4058. held[at..at + n].fill(byte);
  4059. title[at..at + n].fill(byte);
  4060. if k % 8 == 3 {
  4061. dirty.push((at, at + n));
  4062. } else {
  4063. sent.push((at, at + n, u64::from(round % 3) + (k as u64 / 16)));
  4064. }
  4065. }
  4066. }
  4067. }
  4068. let after = 4u64;
  4069. for (shadow, at) in [(&one, a), (&many, b)] {
  4070. crate::watch::writing(at, LEN);
  4071. bytes(at).copy_from_slice(&title);
  4072. bytes(shadow.data as usize).copy_from_slice(&held);
  4073. let card = shadow.card.as_ref().expect("made with one");
  4074. *card.dirty.lock().unwrap() = dirty.clone();
  4075. *card.sent.lock().unwrap() = super::SentRuns::of(&sent);
  4076. }
  4077. let pieces: Vec<(usize, usize)> = (0..3).map(|p| (p * PIECE + 16, (p + 1) * PIECE - 4)).collect();
  4078. let mut scratch = Vec::new();
  4079. for &(lo, hi) in &pieces {
  4080. one.card_merge_relay(lo, &now[lo..hi], after, &mut scratch);
  4081. }
  4082. let addressed: Vec<(usize, usize, usize)> =
  4083. pieces.iter().map(|&(lo, hi)| (lo, hi, now.as_ptr() as usize + lo)).collect();
  4084. let mut notes = crate::land::Notes::default();
  4085. // SAFETY: the fetched bytes are `now`'s.
  4086. unsafe { many.land_card(&addressed, after, &mut notes) };
  4087. notes.flush();
  4088. assert!(bytes(a) == bytes(b), "title memory, round {round}");
  4089. assert!(bytes(one.data as usize) == bytes(many.data as usize), "the CPU's side, round {round}");
  4090. }
  4091. }
  4092. }
  4093. /// Landings of one copy on several threads, the title writing dwords of
  4094. /// the same blocks, and the title's bytes put into the CPU's side under
  4095. /// the shaders' writes ([`Shadow::merge_under_writes`]), all at once. The
  4096. /// card has never received the title's bytes: what is fetched holds older
  4097. /// ones there, which must not be taken for shaders' writes.
  4098. #[test]
  4099. fn landings_and_title_bytes_going_in_keep_each_others_bytes() {
  4100. assert!(crate::safecopy::on());
  4101. const BLOCKS: usize = 16;
  4102. const LEN: usize = BLOCKS * PIECE;
  4103. let title = memory(LEN, true);
  4104. let Some(shadow) = copy_of(title, LEN) else {
  4105. return; // no host GPU
  4106. };
  4107. shadow.pending.lock().unwrap().push((title, title + LEN));
  4108. // SAFETY: committed, aligned; touched as atomics or by the landing's
  4109. // stores of whole dwords.
  4110. let dword = |i: usize| unsafe { &*((title + i * 4) as *const AtomicU32) };
  4111. let stop = AtomicBool::new(false);
  4112. std::thread::scope(|s| {
  4113. let writer = s.spawn(|| {
  4114. let mut value = 1u32;
  4115. while !stop.load(Ordering::Relaxed) {
  4116. for i in (1..LEN / 4).step_by(4 * 331) {
  4117. assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone");
  4118. }
  4119. value += 1;
  4120. std::thread::sleep(std::time::Duration::from_micros(200));
  4121. }
  4122. value - 1
  4123. });
  4124. s.spawn(|| {
  4125. while !stop.load(Ordering::Relaxed) {
  4126. let mut runs = usize::MAX;
  4127. assert!(!shadow.merge_under_writes(title, LEN, &mut runs));
  4128. // Sent up, as the preparing of a submission would: noted
  4129. // with a number behind the fetches'.
  4130. let card = shadow.card.as_ref().expect("made with one");
  4131. let mut dirty = card.dirty.lock().unwrap();
  4132. let mut sent = card.sent.lock().unwrap();
  4133. sent.note(9, std::mem::take(&mut *dirty));
  4134. }
  4135. });
  4136. let mut now = vec![0u8; LEN];
  4137. for round in 1..200u32 {
  4138. for block in (0..BLOCKS).filter(|b| (*b as u32 * 5 + round) % 3 != 0) {
  4139. for i in (block * PIECE / 4 + 3..(block + 1) * PIECE / 4).step_by(4) {
  4140. now[i * 4..i * 4 + 4].copy_from_slice(&(round << 20 | i as u32).to_le_bytes());
  4141. }
  4142. }
  4143. let at = now.as_ptr() as usize;
  4144. crate::land::each(BLOCKS, &|b| {
  4145. let mut notes = crate::land::Notes::default();
  4146. let (lo, hi) = (b * PIECE, (b + 1) * PIECE);
  4147. // SAFETY: the fetched bytes are `now`'s; each block once.
  4148. unsafe { shadow.land_card(&[(lo, hi, at + lo)], 8, &mut notes) };
  4149. notes.flush();
  4150. });
  4151. for i in (3..LEN / 4).step_by(4 * 53) {
  4152. let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four"));
  4153. assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}");
  4154. }
  4155. }
  4156. stop.store(true, Ordering::Relaxed);
  4157. let last = writer.join().expect("nothing undone");
  4158. assert!((1..LEN / 4).step_by(4 * 331).all(|i| dword(i).load(Ordering::Relaxed) == last));
  4159. });
  4160. }
  4161. }
  4162. struct Entry {
  4163. end: u64,
  4164. shadow: Option<Arc<Shadow>>,
  4165. }
  4166. /// Title buffers by (start address, resource), with their copy once made.
  4167. ///
  4168. /// Read by every view a draw names, on all recording threads at once, and
  4169. /// written when a buffer comes, goes or gets its copy: readers share it.
  4170. static BUFFERS: std::sync::RwLock<BTreeMap<(u64, usize), Entry>> = std::sync::RwLock::new(BTreeMap::new());
  4171. fn buffers() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> {
  4172. let map = BUFFERS.write().unwrap_or_else(|e| e.into_inner());
  4173. // What threads remember of it ([`FOUND`]) is of before.
  4174. BUFFERS_CHANGED.fetch_add(1, Ordering::SeqCst);
  4175. map
  4176. }
  4177. /// How often [`BUFFERS`] was taken to be changed.
  4178. static BUFFERS_CHANGED: AtomicU64 = AtomicU64::new(1);
  4179. /// Answers a thread remembers.
  4180. const FOUND_MOST: usize = 1024;
  4181. /// An ask (address, bytes), the count of changes it was answered at, and the
  4182. /// answer.
  4183. type Found = (u64, u64, u64, std::sync::Weak<Shadow>);
  4184. thread_local! {
  4185. /// The last answers of [`lookup`] out of [`BUFFERS`], by a hash of the
  4186. /// ask: the same buffers are asked about draw after draw, from five
  4187. /// threads, each time through the map's lock and a dozen of its nodes
  4188. /// (7 % of the recording threads' time, profile waits-1).
  4189. static FOUND: std::cell::RefCell<Vec<Found>> = const { std::cell::RefCell::new(Vec::new()) };
  4190. }
  4191. /// Whether [`FOUND`] is kept (`VICTORY_QUICK_FIND=0`: not).
  4192. fn quick_find() -> bool {
  4193. crate::toggled!("VICTORY_QUICK_FIND")
  4194. }
  4195. fn found_at(address: u64, len: u64) -> usize {
  4196. let h = (address ^ len.rotate_left(32)).wrapping_mul(0x9E37_79B9_7F4A_7C15);
  4197. (h >> 54) as usize % FOUND_MOST
  4198. }
  4199. /// What this thread remembers of an ask, if nothing changed since.
  4200. fn found(address: u64, len: u64) -> Option<Arc<Shadow>> {
  4201. let changed = BUFFERS_CHANGED.load(Ordering::SeqCst);
  4202. let shadow = FOUND.with(|f| {
  4203. let f = f.borrow();
  4204. let (a, n, at, shadow) = f.get(found_at(address, len))?;
  4205. ((*a, *n, *at) == (address, len, changed)).then(|| shadow.upgrade()).flatten()
  4206. })?;
  4207. // Whoever takes the map to let a copy go that nobody holds finds it held
  4208. // now, or had counted before: then it is not handed out.
  4209. std::sync::atomic::fence(Ordering::SeqCst);
  4210. (BUFFERS_CHANGED.load(Ordering::SeqCst) == changed).then_some(shadow)
  4211. }
  4212. /// Remembers an answer given while `changed` was the count.
  4213. fn remember(address: u64, len: u64, changed: u64, shadow: &Arc<Shadow>) {
  4214. FOUND.with(|f| {
  4215. let mut f = f.borrow_mut();
  4216. if f.is_empty() {
  4217. f.resize_with(FOUND_MOST, || (0, 0, 0, std::sync::Weak::new()));
  4218. }
  4219. f[found_at(address, len)] = (address, len, changed, Arc::downgrade(shadow));
  4220. });
  4221. }
  4222. fn buffers_read() -> std::sync::RwLockReadGuard<'static, BTreeMap<(u64, usize), Entry>> {
  4223. BUFFERS.read().unwrap_or_else(|e| e.into_inner())
  4224. }
  4225. /// A title buffer exists at `start` (`len` bytes).
  4226. pub(crate) fn register(resource: usize, start: u64, len: u64) {
  4227. buffers().insert(
  4228. (start, resource),
  4229. Entry {
  4230. end: start + len,
  4231. shadow: None,
  4232. },
  4233. );
  4234. }
  4235. /// The title released it; lists that still hold its copy keep it alive.
  4236. pub(crate) fn unregister(resource: usize, start: u64) {
  4237. buffers().remove(&(start, resource));
  4238. }
  4239. /// The title buffer holding `address`, as (start, length), without making
  4240. /// its copy (diagnostics: which buffer a dropped program's root view names).
  4241. #[cfg(feature = "diagnostics")]
  4242. pub(crate) fn extent(address: u64) -> Option<(u64, u64)> {
  4243. buffers()
  4244. .range(..=(address, usize::MAX))
  4245. .rev()
  4246. .take(64)
  4247. .find(|(_, e)| e.end > address)
  4248. .map(|(k, e)| (k.0, e.end - k.0))
  4249. }
  4250. /// Title memory `[at, at + len)` is about to show something else or be
  4251. /// given up: what is in place there (`crate::inplace`) is taken out of the
  4252. /// tables, so that the next ask makes a copy or opens the memory anew, and
  4253. /// goes when no list and no slot holds it any more. Returns how many.
  4254. pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 {
  4255. let end = at.saturating_add(len);
  4256. let mut gone: Vec<Arc<Shadow>> = Vec::new();
  4257. {
  4258. let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  4259. let keys: Vec<(u64, u64)> = map
  4260. .range((at.saturating_sub(WINDOW), 0)..(end, 0))
  4261. .filter(|(key, shadow)| shadow.place.is_some() && key.0 + key.1 > at)
  4262. .map(|(key, _)| *key)
  4263. .collect();
  4264. gone.extend(keys.into_iter().filter_map(|key| map.remove(&key)));
  4265. }
  4266. {
  4267. // As `lookup` finds a buffer: among the 256 that start below.
  4268. let mut map = buffers();
  4269. for (_, entry) in map.range_mut(..(end, 0)).rev().take(256) {
  4270. if entry.end > at && entry.shadow.as_ref().is_some_and(|s| s.place.is_some()) {
  4271. gone.extend(entry.shadow.take());
  4272. }
  4273. }
  4274. }
  4275. let n = gone.len() as u64;
  4276. for shadow in gone {
  4277. crate::host::retire(shadow);
  4278. }
  4279. n
  4280. }
  4281. /// For the in-place census (`crate::inplace`): the title buffers (start,
  4282. /// bytes, false) and the windows outside buffers that have a copy (start,
  4283. /// bytes, true).
  4284. pub(crate) fn spans() -> Vec<(u64, u64, bool)> {
  4285. let mut spans: Vec<(u64, u64, bool)> = buffers_read().iter().map(|(key, entry)| (key.0, entry.end - key.0, false)).collect();
  4286. let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  4287. spans.extend(loose.keys().map(|&(start, len)| (start, len, true)));
  4288. spans
  4289. }
  4290. /// The copy of the innermost title buffer holding `[address, address +
  4291. /// len)`, made on first use. A `len` of 0 or 1 is an ask without a length
  4292. /// (a root view: the caller reads on to the copy's end).
  4293. pub(crate) fn find(address: u64, len: u64) -> Option<Arc<Shadow>> {
  4294. lookup(address, len, false)
  4295. }
  4296. /// As [`find`], for an ask that is done with the copy when its list has
  4297. /// run (a draw's vertex and index buffers, indirect arguments): outside
  4298. /// buffer objects it takes a window that is there already and holds the
  4299. /// range ([`holder`]), and makes one of its own only if none does.
  4300. ///
  4301. /// [`find`] names a window by the ask alone, which a descriptor slot needs
  4302. /// (the slot shows the window its view found when it was made, and the
  4303. /// pass that brings it up to date must find the same one). A draw needs no
  4304. /// such thing: it binds the copy it found and brings that copy up to date.
  4305. /// Named by the ask alone, every draw's range was a window of its own
  4306. /// wherever the windows are cut finer than 4 MiB: draws that bind
  4307. /// different ranges of the same memory then each copied their range, and
  4308. /// windows nothing asked for again for ten seconds were let go and made
  4309. /// (and copied) anew. Run 71, on a 256 KiB grid: 350 MB copied per frame
  4310. /// against 120 MB, 7,087 write-watch askings against 2,600, and 5,263
  4311. /// windows (4.5 GB) let go in two minutes against 393 in a whole run.
  4312. pub(crate) fn find_any(address: u64, len: u64) -> Option<Arc<Shadow>> {
  4313. // With whole windows (the default) there is one window to a cell and
  4314. // nothing to choose: exactly `find`.
  4315. if !fine() {
  4316. return find(address, len);
  4317. }
  4318. lookup(address, len, true)
  4319. }
  4320. /// The copy [`find`] gives for a range inside a title buffer, if it was made.
  4321. pub(crate) fn peek(address: u64, len: u64) -> Option<Arc<Shadow>> {
  4322. let end = address.checked_add(len.max(1))?;
  4323. buffers_read().range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).and_then(|(_, e)| e.shadow.clone())
  4324. }
  4325. fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> {
  4326. let quick = quick_find();
  4327. if quick && let Some(shadow) = found(address, len) {
  4328. return Some(shadow);
  4329. }
  4330. let end = address.checked_add(len.max(1))?;
  4331. {
  4332. let map = buffers_read();
  4333. match map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end) {
  4334. // The copy is made already (nearly always).
  4335. Some((_, Entry { shadow: Some(shadow), .. })) => {
  4336. if quick {
  4337. // (Nobody changes the map while this lock is held.)
  4338. remember(address, len, BUFFERS_CHANGED.load(Ordering::SeqCst), shadow);
  4339. }
  4340. return Some(shadow.clone());
  4341. }
  4342. Some(_) => {}
  4343. None => {
  4344. drop(map);
  4345. return loose(address, end, len <= 1, any);
  4346. }
  4347. }
  4348. }
  4349. let mut map = buffers();
  4350. let key = map
  4351. .range(..=(address, usize::MAX))
  4352. .rev()
  4353. .take(64)
  4354. .find(|(_, e)| e.end >= end)
  4355. .map(|(k, _)| *k);
  4356. let Some(key) = key else {
  4357. drop(map);
  4358. return loose(address, end, len <= 1, any);
  4359. };
  4360. let entry = map.get_mut(&key)?;
  4361. if entry.shadow.is_none() {
  4362. let len = entry.end - key.0;
  4363. // Rounded up so that views ending in the buffer's last 256 bytes fit.
  4364. // Shaders write some buffers (unordered access), so not upload memory.
  4365. let size = len.next_multiple_of(1 << 16);
  4366. // In place, if asked for and the memory can be opened
  4367. // (`crate::inplace::place_for`): the buffer is the title's own
  4368. // memory. Not the big ones `cards` puts in the card's memory: those
  4369. // are read too often to stay in the PC's.
  4370. let big = cards() && (size >= card_limits().0 || card_all());
  4371. if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) {
  4372. entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false)));
  4373. return entry.shadow.clone();
  4374. }
  4375. let (buffer, data) = host()?.shared_buffer(size)?;
  4376. crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0));
  4377. // A big one, with `cards`: shaders get a buffer in the card's own
  4378. // memory, and the one just made is the CPU's side.
  4379. let (buffer, card) = match card_for(size) {
  4380. Some(on_card) => {
  4381. crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0));
  4382. tracing::info!(
  4383. start = format_args!("{:#x}", key.0),
  4384. len,
  4385. "a buffer's host copy is in the card's memory"
  4386. );
  4387. let card = Card {
  4388. staging: buffer,
  4389. before: Mutex::default(),
  4390. dirty: Mutex::default(),
  4391. sent: Mutex::default(),
  4392. touched: Default::default(),
  4393. size,
  4394. };
  4395. (on_card, Some(card))
  4396. }
  4397. None => (buffer, None),
  4398. };
  4399. // SAFETY: a live buffer.
  4400. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4401. if len >= 16 << 20 {
  4402. tracing::info!(
  4403. start = format_args!("{:#x}", key.0),
  4404. len,
  4405. "large buffer copied to the host"
  4406. );
  4407. } else {
  4408. tracing::debug!(
  4409. start = format_args!("{:#x}", key.0),
  4410. len,
  4411. "buffer copied to the host"
  4412. );
  4413. }
  4414. let mut shadow = Shadow::new(buffer, data, gpu, key.0, len);
  4415. shadow.card = card;
  4416. let shadow = Arc::new(shadow);
  4417. if shadow.card.is_some() {
  4418. CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow));
  4419. }
  4420. entry.shadow = Some(shadow);
  4421. }
  4422. entry.shadow.clone()
  4423. }
  4424. /// Titles also use memory outside any buffer object as GPU memory (
  4425. /// the title's interface vertices, from its own allocator). Such memory
  4426. /// gets copies of the aligned windows it touches.
  4427. /// A window nothing names any more is let go ([`let_go_idle`]).
  4428. /// shortcut: a window is 4 MiB however little of it is read (the memory
  4429. /// line says how much was ever asked for, and how much was ever copied);
  4430. /// [`window`] cuts the windows of asks that give a length on a finer grid.
  4431. const WINDOW: u64 = 4 << 20;
  4432. /// The grid the windows of asks with a length are cut on, in bytes: 4 MiB
  4433. /// unless `VICTORY_WINDOW_KB` names a smaller power of two (64 at least).
  4434. /// A window is the PC's memory, all of it, however little of it is read:
  4435. /// 803 windows held 3.3 GB in run 60's gameplay, and all that was ever
  4436. /// asked for in them lay within 1.6 GB. On a grid of 1 MiB or 256 KiB a
  4437. /// window ends nearer to what is read. An ask without a length keeps the
  4438. /// 4 MiB grid whatever is set: a root view reads from its address to its
  4439. /// window's end, and mesh streams bound that way reach megabytes.
  4440. /// shortcut: the default stays 4 MiB until a run with the memory line's
  4441. /// window counts has shown what the finer grids give; the same memory
  4442. /// asked for with different ranges then lies in more than one window.
  4443. fn window() -> u64 {
  4444. static GRID: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  4445. *GRID.get_or_init(|| {
  4446. let kb = std::env::var("VICTORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::<u64>().ok());
  4447. grid(kb)
  4448. })
  4449. }
  4450. /// The window grid in bytes for a setting in KiB: a power of two from
  4451. /// 64 KiB to 4 MiB, 4 MiB for anything else.
  4452. fn grid(kb: Option<u64>) -> u64 {
  4453. match kb {
  4454. Some(kb) if kb.is_power_of_two() && (64..=4096).contains(&kb) => kb << 10,
  4455. _ => WINDOW,
  4456. }
  4457. }
  4458. /// The window (start, bytes) of title memory for an ask of `[address,
  4459. /// end)` on a grid of `grid` bytes.
  4460. fn window_of(address: u64, end: u64, grid: u64) -> (u64, u64) {
  4461. let start = address & !(grid - 1);
  4462. (start, end.next_multiple_of(grid) - start)
  4463. }
  4464. /// Whether the window of an ask without a length begins at the ask instead
  4465. /// of at the 4 MiB line below it. Such an ask (a root view) reads from its
  4466. /// address to the end of its 4 MiB cell; what lies below the lowest
  4467. /// address ever asked for in the cell is memory the host zeroed and nothing
  4468. /// reads (513 of run 65's 782 windows were asked for that way, 2,052 MB;
  4469. /// of all windows' 3,236 MB, 1,988 MB were ever copied). With this on, the
  4470. /// window is the cell's tail from the ask's step on ([`TAIL_STEP`]); an ask
  4471. /// lower in the cell later makes a longer tail, which every ask from then
  4472. /// on takes, and the shorter one goes when nothing holds it any more.
  4473. /// shortcut: off unless `VICTORY_WINDOW_TAILS=1`. A longer tail is another
  4474. /// host buffer than the shorter one: what was bound to the shorter stays
  4475. /// right only because every list brings up to date the copy it bound
  4476. /// (`draw.rs` keeps a root view's copy with its slot). It pays only
  4477. /// together with `VICTORY_WINDOW_KB` below 4096: on the 4 MiB grid an ask
  4478. /// with a length in the same cell makes the whole cell's window, and the
  4479. /// tail is that.
  4480. fn tails() -> bool {
  4481. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  4482. *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOW_TAILS").is_some_and(|v| v == "1"))
  4483. }
  4484. /// Tails begin on multiples of this. A longer tail is a new host buffer,
  4485. /// filled from title memory from its first byte to its last: begun on the
  4486. /// 64 KiB page of each ask, a cell whose asks came from the top down made
  4487. /// up to 63 of them, one after the other (part of run 71's copies). On
  4488. /// this step it is 15 at most, and a tail holds up to 192 KiB it did not
  4489. /// need.
  4490. const TAIL_STEP: u64 = 256 << 10;
  4491. /// The window (start, bytes) a tail ask at `address` makes: from the ask's
  4492. /// step ([`TAIL_STEP`]) to the end of its 4 MiB cell.
  4493. fn tail_of(address: u64, end: u64) -> (u64, u64) {
  4494. let (cell, len) = window_of(address, end, WINDOW);
  4495. let start = address & !(TAIL_STEP - 1);
  4496. (start, cell + len - start)
  4497. }
  4498. /// Of `windows` (start, bytes), the one an ask of `[address, end)` that
  4499. /// may take any window takes ([`find_any`]): the longest that holds the
  4500. /// whole range.
  4501. fn holder(windows: impl Iterator<Item = (u64, u64)>, address: u64, end: u64) -> Option<(u64, u64)> {
  4502. windows
  4503. .filter(|&(start, bytes)| start <= address && start + bytes >= end)
  4504. .max_by_key(|&(start, bytes)| (bytes, std::cmp::Reverse(start)))
  4505. }
  4506. /// Whether windows may be smaller than their 4 MiB cell (a finer grid, or
  4507. /// tails): only then is there more than one window to choose from.
  4508. fn fine() -> bool {
  4509. tails() || window() < WINDOW
  4510. }
  4511. /// For the memory line: the bytes of title memory the windows alive lie
  4512. /// over (each byte once), beside the windows' own bytes in
  4513. /// [`memory`]: the difference is memory that is in more than one window,
  4514. /// which is copied once for each.
  4515. #[cfg(feature = "diagnostics")]
  4516. pub(crate) fn window_cover() -> u64 {
  4517. let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  4518. cover(loose.keys().copied())
  4519. }
  4520. /// The bytes `windows` (start, bytes; in order of start) lie over, each
  4521. /// byte once.
  4522. #[cfg_attr(not(any(test, feature = "diagnostics")), allow(dead_code))]
  4523. fn cover(windows: impl Iterator<Item = (u64, u64)>) -> u64 {
  4524. let (mut covered, mut reached) = (0, 0);
  4525. for (start, bytes) in windows {
  4526. let end = start + bytes;
  4527. if end > reached {
  4528. covered += end - start.max(reached);
  4529. reached = end;
  4530. }
  4531. }
  4532. covered
  4533. }
  4534. /// Of `windows` (start, bytes; in order), the longest tail a tail ask at
  4535. /// `address` can take: the first that begins in the ask's cell at or below
  4536. /// the ask's page and ends where the cell ends.
  4537. fn longest_tail(windows: impl Iterator<Item = (u64, u64)>, address: u64, end: u64) -> Option<(u64, u64)> {
  4538. let (cell, len) = window_of(address, end, WINDOW);
  4539. let step = address & !(TAIL_STEP - 1);
  4540. windows
  4541. .filter(|&(start, bytes)| start >= cell && start <= step && start + bytes == cell + len)
  4542. .min()
  4543. }
  4544. /// Whether `[address, address + len)` lies in one title buffer.
  4545. pub(crate) fn in_buffer(address: u64, len: u64) -> Option<(u64, u64)> {
  4546. let end = address.checked_add(len)?;
  4547. let map = buffers_read();
  4548. let found = map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end);
  4549. found.map(|(k, e)| (k.0, e.end - k.0))
  4550. }
  4551. /// Whether a title buffer of at most `most` bytes lies in `[address, address
  4552. /// + len)`, all of it or in part.
  4553. pub(crate) fn small_buffer_in(address: u64, len: u64, most: u64) -> bool {
  4554. let map = buffers_read();
  4555. map.range((address.saturating_sub(most), 0)..(address + len, 0))
  4556. .any(|(key, entry)| entry.end > address && entry.end - key.0 <= most)
  4557. }
  4558. /// A copy of the memory `[start, start + len)` (an arena of
  4559. /// [`crate::memory`]'s, its directory, title memory around a small buffer)
  4560. /// for the programs that find memory by address, on the card: the structures
  4561. /// rays are traced through, read with every step of every ray.
  4562. ///
  4563. /// What shaders write there by address is not brought back, so the copy is
  4564. /// the only place that has it. The CPU's side holds the bytes as they were
  4565. /// last taken, and only dwords that changed since go up.
  4566. pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> {
  4567. let host = host()?;
  4568. if !cards() || !host.card_ready() {
  4569. return None;
  4570. }
  4571. // At most so much on the card's own memory (4 GiB unless
  4572. // `VICTORY_MEMORY_CARD_MB` says otherwise), and while it has room; past
  4573. // that the side shaders see is in the PC's memory.
  4574. static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  4575. static USED: AtomicU64 = AtomicU64::new(0);
  4576. let most = *MOST.get_or_init(|| {
  4577. let mb = std::env::var("VICTORY_MEMORY_CARD_MB").ok().and_then(|v| v.trim().parse::<u64>().ok());
  4578. mb.unwrap_or(4096) << 20
  4579. });
  4580. let room = host.video_memory().is_none_or(|[budget, used, ..]| used + len < budget / 100 * 97);
  4581. let (staging, data) = host.shared_buffer(len)?;
  4582. let on_card = if room && USED.fetch_add(len, Ordering::Relaxed) + len <= most {
  4583. host.uav_buffer(len)
  4584. } else {
  4585. None
  4586. };
  4587. let buffer = match on_card {
  4588. Some(buffer) => buffer,
  4589. None => host.shared_buffer(len)?.0,
  4590. };
  4591. crate::host::name(&staging, || format!("title memory {start:#x}+{len:#x} by address, the CPU's side"));
  4592. crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} by address"));
  4593. // (Counted down with the windows' on the card when it goes.)
  4594. WINDOW_CARD_BYTES.fetch_add(len, Ordering::Relaxed);
  4595. // SAFETY: a live buffer.
  4596. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4597. let mut shadow = Shadow::new(buffer, data, gpu, start, len);
  4598. shadow.window = true;
  4599. shadow.changes_only.store(true, Ordering::Relaxed);
  4600. shadow.card = Some(Card {
  4601. staging,
  4602. before: Mutex::default(),
  4603. dirty: Mutex::default(),
  4604. sent: Mutex::default(),
  4605. touched: Default::default(),
  4606. size: len,
  4607. });
  4608. let shadow = Arc::new(shadow);
  4609. CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow));
  4610. Some(shadow)
  4611. }
  4612. /// Copies of title memory outside buffers, by (start, length).
  4613. static LOOSE: std::sync::RwLock<BTreeMap<(u64, u64), Arc<Shadow>>> = std::sync::RwLock::new(BTreeMap::new());
  4614. fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Shadow>> {
  4615. let (cell, _) = window_of(address, end, WINDOW);
  4616. let named = window_of(address, end, if unsized_ask { WINDOW } else { window() });
  4617. // Under the lock, with the handing out: see `let_go_idle`.
  4618. let note = |shadow: &Shadow| {
  4619. // (Read first: the lines are shared by all recording threads.)
  4620. let now = crate::host::moment();
  4621. if shadow.used.load(Ordering::Relaxed) != now {
  4622. shadow.used.store(now, Ordering::Relaxed);
  4623. }
  4624. if shadow.asked[0].load(Ordering::Relaxed) > address {
  4625. shadow.asked[0].fetch_min(address, Ordering::Relaxed);
  4626. }
  4627. if shadow.asked[1].load(Ordering::Relaxed) < end {
  4628. shadow.asked[1].fetch_max(end, Ordering::Relaxed);
  4629. }
  4630. if unsized_ask {
  4631. shadow.unsized_asks.fetch_add(1, Ordering::Relaxed);
  4632. }
  4633. };
  4634. // The window is there already (nearly always): readers share the lock.
  4635. if !(unsized_ask && tails()) && !(any && fine() && !unsized_ask) {
  4636. let map = LOOSE.read().unwrap_or_else(|e| e.into_inner());
  4637. if let Some(shadow) = map.get(&named) {
  4638. note(shadow);
  4639. return Some(shadow.clone());
  4640. }
  4641. }
  4642. let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner());
  4643. let (start, len) = if unsized_ask && tails() {
  4644. let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key);
  4645. longest_tail(there, address, end).unwrap_or_else(|| tail_of(address, end))
  4646. } else if any && fine() && !unsized_ask {
  4647. // The windows that begin in the ask's cell at or below the ask (one
  4648. // that begins in a cell below and reaches this far is passed over:
  4649. // the ask then makes its own).
  4650. let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key);
  4651. holder(there, address, end).unwrap_or(named)
  4652. } else {
  4653. named
  4654. };
  4655. if let Some(shadow) = map.get(&(start, len)) {
  4656. note(shadow);
  4657. return Some(shadow.clone());
  4658. }
  4659. // In place, if asked for and the window's memory can be opened: the
  4660. // window is the title's own memory, with nothing to copy.
  4661. if let Some(placed) = crate::inplace::place_for(start, len, true) {
  4662. let shadow = Arc::new(Shadow::placed(placed, start, len, true));
  4663. note(&shadow);
  4664. map.insert((start, len), shadow.clone());
  4665. return Some(shadow);
  4666. }
  4667. // One buffer in the card's memory, filled by the CPU through the bus.
  4668. if let Some((buffer, data)) = window_mapped_for(len) {
  4669. crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} mapped on the card"));
  4670. // SAFETY: a live buffer.
  4671. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4672. let mut shadow = Shadow::new(buffer, data, gpu, start, len);
  4673. shadow.window = true;
  4674. shadow.mapped = true;
  4675. let shadow = Arc::new(shadow);
  4676. note(&shadow);
  4677. map.insert((start, len), shadow.clone());
  4678. return Some(shadow);
  4679. }
  4680. let (buffer, data) = host()?.shared_buffer(len)?;
  4681. crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}"));
  4682. // With room for windows on the card (`window_card_most`): shaders get a
  4683. // buffer there, and the one just made is the CPU's side.
  4684. let (buffer, card) = match window_card_for(len) {
  4685. Some(on_card) => {
  4686. crate::host::name(&on_card, || format!("title memory {start:#x}+{len:#x} on the card"));
  4687. let card = Card {
  4688. staging: buffer,
  4689. before: Mutex::default(),
  4690. dirty: Mutex::default(),
  4691. sent: Mutex::default(),
  4692. touched: Default::default(),
  4693. size: len,
  4694. };
  4695. (on_card, Some(card))
  4696. }
  4697. None => (buffer, None),
  4698. };
  4699. // SAFETY: a live buffer.
  4700. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4701. tracing::debug!(
  4702. start = format_args!("{start:#x}"),
  4703. len,
  4704. "loose memory copied to the host"
  4705. );
  4706. let mut shadow = Shadow::new(buffer, data, gpu, start, len);
  4707. shadow.window = true;
  4708. shadow.card = card;
  4709. let shadow = Arc::new(shadow);
  4710. if shadow.card.is_some() {
  4711. CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow));
  4712. }
  4713. note(&shadow);
  4714. map.insert((start, len), shadow.clone());
  4715. Some(shadow)
  4716. }
  4717. /// Copies of single buffer views' own bytes ([`exact`]), by (start,
  4718. /// bytes), each with the asking that last took it; and the askings so far.
  4719. #[allow(clippy::type_complexity)]
  4720. static EXACT: Mutex<(u64, BTreeMap<(u64, u64), (Arc<Shadow>, u64)>)> = Mutex::new((0, BTreeMap::new()));
  4721. /// Since the last frame line: askings for such copies, and copies made.
  4722. static EXACT_STATS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
  4723. /// A copy of the title memory `[address, address + len)` that starts at
  4724. /// `address` itself: for a buffer view whose bytes do not start on an
  4725. /// element of the copy its buffer has (`descriptor/host.rs` `view_home`).
  4726. /// A host view counts its first element from its buffer's start; a console
  4727. /// view starts at any address, and the title places views at ring
  4728. /// positions inside its big GPU heap. Such a view was refused and its slot
  4729. /// read zeros ("buffer view not on an element of its host copy", in every
  4730. /// run; upstream VIctory 86a5ed6 found its meshlet culling constants and
  4731. /// colour-bake parameter blocks among them and gives each a copy of its
  4732. /// own bytes, as here).
  4733. ///
  4734. /// The copy is brought up to date and written back like any other (a list
  4735. /// refreshes the copy its view's slot shows, `buffer_copy`). Kept by
  4736. /// (start, bytes) for as long as a list or a slot holds it; of the others,
  4737. /// those not asked for lately go once there are many (ring positions
  4738. /// change every frame).
  4739. pub(crate) fn exact(address: u64, len: u64) -> Option<Arc<Shadow>> {
  4740. /// Copies kept before the idle ones are looked for, and the askings an
  4741. /// idle one stays for.
  4742. const MANY: usize = 256;
  4743. const LATELY: u64 = 512;
  4744. /// The largest, and no view the title made on purpose: off its dwords.
  4745. const MOST: u64 = 64 << 20;
  4746. if len == 0 || len > MOST || !address.is_multiple_of(4) {
  4747. return None;
  4748. }
  4749. EXACT_STATS[0].fetch_add(1, Ordering::Relaxed);
  4750. let mut guard = EXACT.lock().unwrap_or_else(|e| e.into_inner());
  4751. let (tick, map) = &mut *guard;
  4752. *tick += 1;
  4753. let now = *tick;
  4754. if let Some((shadow, used)) = map.get_mut(&(address, len)) {
  4755. *used = now;
  4756. shadow.used.store(crate::host::moment(), Ordering::Relaxed);
  4757. return Some(shadow.clone());
  4758. }
  4759. if map.len() >= MANY {
  4760. // Held by the map alone (no list), its buffer by the copy alone (no
  4761. // slot shows it), and not asked for lately.
  4762. map.retain(|_, (shadow, used)| {
  4763. Arc::strong_count(shadow) > 1 || crate::host::references(&shadow.buffer) > 1 || *used + LATELY > now
  4764. });
  4765. }
  4766. let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?;
  4767. crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}"));
  4768. // SAFETY: a live buffer.
  4769. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  4770. let shadow = Arc::new(Shadow::new(buffer, data, gpu, address, len));
  4771. map.insert((address, len), (shadow.clone(), now));
  4772. EXACT_STATS[1].fetch_add(1, Ordering::Relaxed);
  4773. OWN_MADE.fetch_add(1, Ordering::Relaxed);
  4774. Some(shadow)
  4775. }
  4776. /// Copies of single views' bytes made since the start.
  4777. pub(crate) static OWN_MADE: AtomicU64 = AtomicU64::new(0);
  4778. /// With the frame line: the buffer views that got a copy of their own
  4779. /// bytes ([`exact`]), per frame over `frames`, and the copies kept now.
  4780. /// Nothing while there are none.
  4781. pub(crate) fn exact_line(frames: f64) {
  4782. let [asked, made] = [0, 1].map(|i| EXACT_STATS[i].swap(0, Ordering::Relaxed));
  4783. if asked == 0 {
  4784. return;
  4785. }
  4786. let kept = EXACT.lock().unwrap_or_else(|e| e.into_inner()).1.len();
  4787. tracing::info!(
  4788. "buffer views off their copy's elements (they were refused and read zeros; VICTORY_VIEW_BYTES=0 refuses them again): \
  4789. {:.1} asked for per frame, {:.1} copies of their own bytes made per frame, {kept} kept",
  4790. asked as f64 / frames,
  4791. made as f64 / frames
  4792. );
  4793. }
  4794. #[cfg(test)]
  4795. mod window_tests {
  4796. use super::{
  4797. WINDOW, cover, default_card_limits_mb, grid, holder, longest_tail, resolve_card_limits,
  4798. tail_of, window_of,
  4799. };
  4800. #[test]
  4801. fn card_limits_scale_with_local_vram_budget() {
  4802. const GIB: u64 = 1 << 30;
  4803. const MIB: u64 = 1 << 20;
  4804. // Unknown (WARP / query failure) and <= 12 GiB keep the 12 GB baseline.
  4805. assert_eq!(default_card_limits_mb(None), (16, 512));
  4806. assert_eq!(default_card_limits_mb(Some(8 * GIB)), (16, 512));
  4807. assert_eq!(default_card_limits_mb(Some(11 * GIB)), (16, 512));
  4808. assert_eq!(default_card_limits_mb(Some(12 * GIB)), (16, 512));
  4809. // 16 GB tier (> 12 GiB, < 20 GiB), including WDDM budgets around 13.5–15 GiB.
  4810. assert_eq!(default_card_limits_mb(Some(13 * GIB)), (4, 2048));
  4811. assert_eq!(default_card_limits_mb(Some(14 * GIB)), (4, 2048));
  4812. assert_eq!(default_card_limits_mb(Some(15 * GIB)), (4, 2048));
  4813. assert_eq!(default_card_limits_mb(Some(16 * GIB)), (4, 2048));
  4814. // 24–32+ GB tier (>= 20 GiB): 1 MiB min, 25% of budget capped at 8192 MiB.
  4815. assert_eq!(default_card_limits_mb(Some(20 * GIB)), (1, 5120));
  4816. assert_eq!(default_card_limits_mb(Some(24 * GIB)), (1, 6144));
  4817. assert_eq!(default_card_limits_mb(Some(32 * GIB)), (1, 8192));
  4818. assert_eq!(default_card_limits_mb(Some(48 * GIB)), (1, 8192));
  4819. // Explicit env overrides always win, clamp min to >= 1 MiB, and saturate on overflow.
  4820. assert_eq!(resolve_card_limits(Some(32 * GIB), Some(8), Some(4096)), (8 * MIB, 4096 * MIB));
  4821. assert_eq!(resolve_card_limits(Some(12 * GIB), Some(0), Some(1024)), (MIB, 1024 * MIB));
  4822. assert_eq!(resolve_card_limits(None, Some(u64::MAX), Some(u64::MAX)), (u64::MAX, u64::MAX));
  4823. assert_eq!(resolve_card_limits(None, None, None), (16 * MIB, 512 * MIB));
  4824. }
  4825. /// An ask that may take any window takes the longest that holds all of
  4826. /// it, and none that holds only a part.
  4827. #[test]
  4828. fn an_ask_takes_the_longest_window_that_holds_it() {
  4829. let cell = 0xd_1200_0000u64;
  4830. let (ask, end) = (cell + 0x9_0000, cell + 0xb_0000);
  4831. assert_eq!(holder([].into_iter(), ask, end), None);
  4832. let there = [
  4833. (cell, 0x4_0000), // ends below the ask
  4834. (cell + 0x8_0000, 0x2_0000), // holds its first half only
  4835. (cell + 0x8_0000, 0x4_0000), // holds it
  4836. (cell + 0x4_0000, 0x10_0000), // holds it, longer
  4837. (cell + 0xa_0000, 0x40_0000), // begins above it
  4838. ];
  4839. assert_eq!(holder(there.into_iter(), ask, end), Some((cell + 0x4_0000, 0x10_0000)));
  4840. // Of two as long, the one that begins lower.
  4841. let two = [(cell + 0x8_0000, 0x8_0000), (cell + 0x4_0000, 0x8_0000)];
  4842. assert_eq!(holder(two.into_iter(), ask, end), Some((cell + 0x4_0000, 0x8_0000)));
  4843. }
  4844. /// What windows lie over counts each byte once.
  4845. #[test]
  4846. fn overlapping_windows_cover_their_memory_once() {
  4847. assert_eq!(cover([].into_iter()), 0);
  4848. let apart = [(0x10_0000u64, 0x4_0000u64), (0x20_0000, 0x4_0000)];
  4849. assert_eq!(cover(apart.into_iter()), 0x8_0000);
  4850. // One inside another, one overlapping its end, one touching.
  4851. let over = [
  4852. (0x10_0000u64, 0x10_0000u64),
  4853. (0x14_0000, 0x4_0000),
  4854. (0x1c_0000, 0x8_0000),
  4855. (0x24_0000, 0x4_0000),
  4856. ];
  4857. assert_eq!(cover(over.into_iter()), 0x18_0000);
  4858. }
  4859. /// A tail runs from the ask's page to the end of its 4 MiB cell, and an
  4860. /// ask takes the longest tail there is that holds it.
  4861. #[test]
  4862. fn tails_run_to_the_cells_end_and_the_longest_is_taken() {
  4863. let cell = 0xd_1200_0000u64;
  4864. let ask = cell + 0x12_3456;
  4865. assert_eq!(tail_of(ask, ask + 1), (cell + 0x10_0000, WINDOW - 0x10_0000));
  4866. // The cell's first page: the whole cell, the window there always was.
  4867. assert_eq!(tail_of(cell + 0xffff, cell + 0x1_0000), (cell, WINDOW));
  4868. let end = cell + WINDOW;
  4869. let tail = |from: u64| (cell + from, WINDOW - from);
  4870. // Nothing there, or only tails that begin above the ask.
  4871. assert_eq!(longest_tail([].into_iter(), ask, ask + 1), None);
  4872. assert_eq!(longest_tail([tail(0x20_0000)].into_iter(), ask, ask + 1), None);
  4873. // The longest of those that hold the ask; windows that do not reach
  4874. // the cell's end (cut on a finer grid for asks with a length) and
  4875. // windows of other cells are not tails.
  4876. let there = [
  4877. (cell - WINDOW, WINDOW),
  4878. (cell, 0x4_0000),
  4879. tail(0x8_0000),
  4880. tail(0x10_0000),
  4881. (cell + 0x10_0000, 0x4_0000),
  4882. tail(0x20_0000),
  4883. ];
  4884. assert_eq!(longest_tail(there.into_iter(), ask, ask + 1), Some(tail(0x8_0000)));
  4885. let (start, bytes) = tail(0x8_0000);
  4886. assert!(start <= ask && start + bytes == end);
  4887. // The whole cell's window is the longest tail of all.
  4888. let with_whole = [(cell, WINDOW), tail(0x8_0000)];
  4889. assert_eq!(longest_tail(with_whole.into_iter(), ask, ask + 1), Some((cell, WINDOW)));
  4890. }
  4891. /// The setting takes powers of two from 64 KiB to 4 MiB; anything else
  4892. /// leaves the grid as it was.
  4893. #[test]
  4894. fn the_grid_is_a_power_of_two_or_the_default() {
  4895. assert_eq!(grid(None), WINDOW);
  4896. assert_eq!(grid(Some(4096)), WINDOW);
  4897. assert_eq!(grid(Some(1024)), 1 << 20);
  4898. assert_eq!(grid(Some(256)), 256 << 10);
  4899. assert_eq!(grid(Some(64)), 64 << 10);
  4900. for bad in [0, 32, 100, 1000, 8192] {
  4901. assert_eq!(grid(Some(bad)), WINDOW, "{bad}");
  4902. }
  4903. }
  4904. /// A window holds its ask and is cut on the grid; on the default grid
  4905. /// it is the window there always was.
  4906. #[test]
  4907. fn windows_hold_their_ask_on_the_grid() {
  4908. let (address, end) = (0xd_1234_5678u64, 0xd_1234_5678u64 + 0x9000);
  4909. assert_eq!(window_of(address, end, WINDOW), (0xd_1200_0000, 4 << 20));
  4910. assert_eq!(window_of(address, end, 1 << 20), (0xd_1230_0000, 1 << 20));
  4911. assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 256 << 10));
  4912. // An ask across a grid line takes both cells.
  4913. let end = address + 0x4_0000;
  4914. assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 512 << 10));
  4915. for g in [64u64 << 10, 256 << 10, 1 << 20, WINDOW] {
  4916. let (start, len) = window_of(address, end, g);
  4917. assert!(start <= address && start + len >= end);
  4918. assert!(start % g == 0 && len % g == 0);
  4919. }
  4920. }
  4921. }
  4922. /// For device-removed reports: the copy of title memory whose host range
  4923. /// starts closest below host GPU address `va`, and where `va` is in it.
  4924. pub(crate) fn near(va: u64) -> String {
  4925. let mut all: Vec<(u64, u64, u64)> = buffers()
  4926. .values()
  4927. .filter_map(|e| e.shadow.as_deref().map(|s| (s.gpu, s.start, s.len)))
  4928. .collect();
  4929. all.extend(
  4930. LOOSE
  4931. .read()
  4932. .unwrap_or_else(|e| e.into_inner())
  4933. .values()
  4934. .map(|s| (s.gpu, s.start, s.len)),
  4935. );
  4936. let below = all.iter().filter(|c| c.0 <= va).max();
  4937. let above = all.iter().filter(|c| c.0 > va).min();
  4938. let mut text = match below {
  4939. Some(&(gpu, start, len)) => format!(
  4940. "; the nearest title memory copy below it: {start:#x}+{len:#x} at host {gpu:#x}, offset {:#x}",
  4941. va - gpu
  4942. ),
  4943. None => "; no title memory copy below it".into(),
  4944. };
  4945. if let Some(&(gpu, start, len)) = above {
  4946. text.push_str(&format!(
  4947. "; the nearest above: {start:#x}+{len:#x} at host {gpu:#x} ({} copies in all)",
  4948. all.len()
  4949. ));
  4950. }
  4951. text
  4952. }