shadow.rs 184 KB

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