shadow.rs 219 KB

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