watch.rs 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395
  1. //! Which title memory the title wrote since a host copy took it (decision
  2. //! 0007, "Copies of title memory"). The runtime reserves title GPU memory
  3. //! with write watching (`victory-hle` xmem), so the kernel keeps a dirty bit
  4. //! per 4 KiB page; asking for a range's written pages also clears them. Host
  5. //! copies of the same memory can overlap (nested buffers, textures in
  6. //! buffers), so what one asks is kept here for the others: a journal of
  7. //! each page's last write, numbered by the asking.
  8. //!
  9. //! Physical-page views (xmem's sections) cannot be write-watched. There a
  10. //! copy leaves each 64 KiB block it took read-only, and our vectored handler
  11. //! takes the first write to it: it notes the block as written and gives the
  12. //! write access back. The runtime tells us when it maps or unmaps views
  13. //! ([`title_memory_remapped`]), which resets their protection. Blocks found
  14. //! wholly uncommitted are skipped while they remain so; one query can
  15. //! confirm a whole region, including ordinary reservations between views.
  16. //!
  17. //! The title shows one physical page at several addresses, and writes it
  18. //! through one while the card reads it at another. So a block is clean, and
  19. //! known by its bit, only while every view of its page is read-only
  20. //! ([`cover`]): a write through any of them faults, opens them all and takes
  21. //! clean and bit from all of them ([`open`]). A view mapped anew of a page
  22. //! that is guarded elsewhere has the others looked at again
  23. //! ([`views_mapped`]). What we write ourselves is told at one address and
  24. //! counts at all ([`writing`], [`landed_beside`], [`wrote`]). Not so for a
  25. //! page shown in more than [`MANY_VIEWS`] places (what the title shows where
  26. //! it has nothing). `VICTORY_VIEW_GUARD=0`: each address for itself, as
  27. //! before.
  28. use std::collections::{BTreeMap, BTreeSet};
  29. use std::sync::{Condvar, Mutex, RwLock};
  30. /// The unit tracked and copied: 64 KiB, the console's page (the kernel's
  31. /// 4 KiB pages fold into it). Finer units made the checks of the world's
  32. /// big buffers cost more than the copies they saved.
  33. pub(crate) const PAGE: usize = 64 << 10;
  34. /// The kernel's page, the unit of its answers.
  35. const KERNEL_PAGE: usize = 4096;
  36. /// Numbers the askings; 0 is "never". Counted up with the journal held
  37. /// (shared will do: what notes an answer holds it alone).
  38. static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  39. fn next_asking() -> u64 {
  40. ASKED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
  41. }
  42. /// A title-memory range whose changed pages another subsystem needs to read.
  43. pub(crate) struct Tracked {
  44. start: usize,
  45. end: usize,
  46. seen: Mutex<BTreeMap<usize, u64>>,
  47. }
  48. /// Tracks a runtime GPU-memory range, including physical-page views when
  49. /// `views` is true. Other process memory is not tracked.
  50. pub(crate) fn track(start: usize, len: usize, views: bool) -> Option<Tracked> {
  51. let end = start.checked_add(len)?;
  52. if len == 0 || writes(start, end, views).is_none() {
  53. return None;
  54. }
  55. Some(Tracked {
  56. start,
  57. end,
  58. seen: Mutex::default(),
  59. })
  60. }
  61. struct Journal {
  62. /// Page number → the asking that last found it written.
  63. written: BTreeMap<usize, u64>,
  64. /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`])
  65. /// and the asking that did: `writes` answers for a range inside one
  66. /// from the journal, without another kernel call.
  67. ahead: Vec<(usize, usize)>,
  68. ahead_asked: u64,
  69. /// The ahead asking stands for a whole submission ([`ask_once`]): no
  70. /// other ahead asking is made, and `ahead` stays, until
  71. /// [`ask_once_end`].
  72. kept: bool,
  73. }
  74. /// Read by many threads at once (a submission's refreshes run on several),
  75. /// written only to note an answer: the kernel is asked, and view memory
  76. /// guarded, with the range held in [`ASKING`] and not under this lock. Under
  77. /// one lock for all of it those threads ran one at a time: 22 of 96 looks at
  78. /// the submitting thread, and one in six of those at the six threads beside
  79. /// it, found it waiting for that lock (run pooloff1).
  80. static JOURNAL: RwLock<Journal> = RwLock::new(Journal {
  81. written: BTreeMap::new(),
  82. ahead: Vec::new(),
  83. ahead_asked: 0,
  84. kept: false,
  85. });
  86. fn journal() -> std::sync::RwLockReadGuard<'static, Journal> {
  87. JOURNAL.read().unwrap_or_else(|e| e.into_inner())
  88. }
  89. fn journal_mut() -> std::sync::RwLockWriteGuard<'static, Journal> {
  90. JOURNAL.write().unwrap_or_else(|e| e.into_inner())
  91. }
  92. /// The page ranges some thread is asking about: asking forgets what it
  93. /// answers, so until the answer is in the journal no other thread may ask
  94. /// about any of the same pages (it would be told they were not written).
  95. /// Taken before the journal's lock, never under it.
  96. static ASKING: (Mutex<Vec<(usize, usize)>>, Condvar) = (Mutex::new(Vec::new()), Condvar::new());
  97. /// Pages `[first, last)` held in [`ASKING`] until dropped.
  98. struct Asking(usize, usize);
  99. impl Asking {
  100. fn hold(first: usize, last: usize) -> Asking {
  101. let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner());
  102. while held.iter().any(|&(a, b)| a < last && first < b) {
  103. held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner());
  104. }
  105. held.push((first, last));
  106. Asking(first, last)
  107. }
  108. /// Everything: an asking for a whole submission.
  109. fn hold_all() -> Asking {
  110. Asking::hold(0, usize::MAX)
  111. }
  112. }
  113. impl Drop for Asking {
  114. fn drop(&mut self) {
  115. let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner());
  116. if let Some(i) = held.iter().position(|&r| r == (self.0, self.1)) {
  117. held.swap_remove(i);
  118. }
  119. drop(held);
  120. ASKING.1.notify_all();
  121. }
  122. }
  123. thread_local! {
  124. /// Room for the kernel's answer.
  125. static FOUND: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
  126. }
  127. /// The pages of `[first, last)` the kernel says were written since it was
  128. /// last asked, in order, each once; `None` if the range is not write-watched
  129. /// memory of one reservation. The caller holds the range ([`Asking`]).
  130. fn kernel_written(first: usize, last: usize) -> Option<Vec<usize>> {
  131. use windows_sys::Win32::System::Memory::GetWriteWatch;
  132. const WRITE_WATCH_FLAG_RESET: u32 = 1;
  133. FOUND.with(|found| {
  134. let mut found = found.borrow_mut();
  135. let mut count = (last - first) * PAGE / KERNEL_PAGE;
  136. if found.len() < count {
  137. found.resize(count, 0);
  138. }
  139. let mut granularity = 0;
  140. #[cfg(feature = "diagnostics")]
  141. let started = std::time::Instant::now();
  142. // SAFETY: the answer buffer holds `count` entries.
  143. let failed = unsafe {
  144. GetWriteWatch(
  145. WRITE_WATCH_FLAG_RESET,
  146. (first * PAGE) as *const _,
  147. (last - first) * PAGE,
  148. found.as_mut_ptr().cast(),
  149. &mut count,
  150. &mut granularity,
  151. )
  152. } != 0;
  153. #[cfg(feature = "diagnostics")]
  154. {
  155. tally(10, u64::from(failed));
  156. tally(11, started.elapsed().as_nanos() as u64);
  157. }
  158. if failed {
  159. return None;
  160. }
  161. #[cfg(feature = "diagnostics")]
  162. {
  163. tally(12, count as u64);
  164. use crate::copystat::{C, add};
  165. add(C::Watches, 1);
  166. add(C::WatchUs, started.elapsed().as_micros() as u64);
  167. slow(started.elapsed().as_micros() as u64);
  168. tally(0, 1);
  169. tally(1, ((last - first) * (PAGE >> 10)) as u64);
  170. }
  171. let mut pages: Vec<usize> = found[..count].iter().map(|&at| at / PAGE).collect();
  172. pages.dedup();
  173. Some(pages)
  174. })
  175. }
  176. /// Ranges of one submission closer than this are asked about together:
  177. /// walking the pages between them costs less than another kernel call (a
  178. /// call that resets written pages costs 30-70 microseconds whatever the
  179. /// range).
  180. const AHEAD_GAP: usize = (8 << 20) / PAGE;
  181. /// The most one asking covers (its answer needs 8 bytes per 4 KiB page).
  182. const AHEAD_MAX: usize = (1 << 30) / PAGE;
  183. /// Asks the kernel about many ranges `(start, end)` at once, before the
  184. /// [`writes`] of each: ranges close together are one asking, and `writes`
  185. /// then answers from the journal until [`ask_ahead_done`]. The world's
  186. /// submissions refresh thousands of host copies (6,664 askings a frame,
  187. /// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are
  188. /// left to `writes`.
  189. pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
  190. let mut pieces: Vec<(usize, usize)> = ranges
  191. .iter()
  192. // Not view memory known by its bits: the kernel would refuse the
  193. // asking (and, asked together with others, theirs).
  194. .filter(|r| r.0 < r.1 && !published(r.0, r.1))
  195. .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE)))
  196. .collect();
  197. if pieces.len() < 2 {
  198. return;
  199. }
  200. pieces.sort_unstable();
  201. // The submission's one asking stands ([`ask_once`]): what it does not
  202. // hold is left to `writes`.
  203. if journal().kept {
  204. return;
  205. }
  206. let _all = Asking::hold_all();
  207. let (mut asked, mut written) = (Vec::new(), Vec::new());
  208. let mut i = 0;
  209. while i < pieces.len() {
  210. let first = pieces[i].0;
  211. let mut last = pieces[i].1;
  212. let mut k = i + 1;
  213. while k < pieces.len()
  214. && pieces[k].0 <= last + AHEAD_GAP
  215. && last.max(pieces[k].1) - first <= AHEAD_MAX
  216. {
  217. last = last.max(pieces[k].1);
  218. k += 1;
  219. }
  220. ask_run(&pieces[i..k], &mut asked, &mut written);
  221. i = k;
  222. }
  223. let mut j = journal_mut();
  224. j.ahead_asked = next_asking();
  225. j.ahead = asked;
  226. let now = j.ahead_asked;
  227. j.written.extend(written.into_iter().map(|page| (page, now)));
  228. }
  229. /// Since the last frame line: the kernel askings that took a millisecond
  230. /// or more, their microseconds, and the longest asking's. An asking walks
  231. /// page tables, some ten microseconds for most ranges; in run 75 the 2,644
  232. /// askings of a frame took 219 ms in the lines where the pass over the
  233. /// heap's views ran long, 25-50 ms in the others. These numbers say
  234. /// whether a few askings wait for something or all of them are slow.
  235. #[cfg(feature = "diagnostics")]
  236. static SLOW: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  237. #[cfg(feature = "diagnostics")]
  238. fn slow(us: u64) {
  239. use std::sync::atomic::Ordering::Relaxed;
  240. if us >= 1000 {
  241. SLOW[0].fetch_add(1, Relaxed);
  242. SLOW[1].fetch_add(us, Relaxed);
  243. }
  244. SLOW[2].fetch_max(us, Relaxed);
  245. }
  246. /// [`SLOW`], taken.
  247. #[cfg(feature = "diagnostics")]
  248. pub(crate) fn slow_asks() -> [u64; 3] {
  249. [0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed))
  250. }
  251. /// The submission's refreshes are done: `writes` asks the kernel again.
  252. pub(crate) fn ask_ahead_done() {
  253. let mut j = journal_mut();
  254. if !j.kept {
  255. j.ahead.clear();
  256. }
  257. }
  258. /// Whether a submission asks the kernel once, before its first refresh,
  259. /// about every range its lists refresh (`VICTORY_ASK_ONCE=1`; off by
  260. /// default).
  261. ///
  262. /// A submission's refreshes are done in groups, between the title's own
  263. /// buffer copies (each copy flushes the refreshes recorded before it), and
  264. /// every group asked the kernel again: 2,644 askings a frame, 70 a
  265. /// submission. With the switch the journal answers all of them from one
  266. /// asking made when the submission starts.
  267. ///
  268. /// What changes: memory the title's other threads write while the
  269. /// submission is being prepared is seen by the next submission's asking,
  270. /// not by this one's later groups. What this submission's lists read was
  271. /// written before they were submitted, so before the asking. Our own
  272. /// writes into title memory while preparing are told to the journal
  273. /// ([`wrote`]) or end the asking ([`ask_once_end`]).
  274. pub(crate) fn once() -> bool {
  275. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  276. // On by default since run 81 (with card buffers: 375-450 ms a frame
  277. // against 573-647, the picture unchanged over four minutes);
  278. // `VICTORY_ASK_ONCE=0` asks per range, as before.
  279. *ON.get_or_init(|| std::env::var_os("VICTORY_ASK_ONCE").is_none_or(|v| v != "0"))
  280. }
  281. /// With [`once`]: asks about `ranges` (everything a submission's lists
  282. /// refresh) as [`ask_ahead`] does, and lets that asking stand until
  283. /// [`ask_once_end`].
  284. pub(crate) fn ask_once(ranges: &[(usize, usize)]) {
  285. if !once() {
  286. return;
  287. }
  288. ask_once_end();
  289. ask_ahead(ranges);
  290. ask_rest(ranges);
  291. }
  292. /// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the
  293. /// asking stands.
  294. fn ask_rest(ranges: &[(usize, usize)]) {
  295. let _all = Asking::hold_all();
  296. let mut ahead = {
  297. let mut j = journal_mut();
  298. std::mem::take(&mut j.ahead)
  299. };
  300. // `ask_ahead` leaves a range that lies alone to `writes`, which asks
  301. // once per flush: with one asking for the submission that was every
  302. // such range asked again at each of its 70 flushes (run 76: 2,300
  303. // askings a frame with the switch on, as without it). They are asked
  304. // here, once; what is not write-watched stays with `writes`.
  305. let mut written = Vec::new();
  306. for &(start, end) in ranges {
  307. if start >= end || published(start, end) {
  308. continue;
  309. }
  310. let (first, last) = (start / PAGE, end.div_ceil(PAGE));
  311. if !ahead.iter().any(|&(a, b)| a <= first && last <= b)
  312. && let Some(pages) = kernel_written(first, last)
  313. {
  314. written.extend(pages);
  315. ahead.push((first, last));
  316. }
  317. }
  318. let mut j = journal_mut();
  319. // A number of its own, and the one this asking stands under: between
  320. // the two parts another thread may have asked about a range of the
  321. // second, copied it, and the title written it since. Under the first
  322. // part's number that write was older than the copy, and never copied.
  323. let now = next_asking();
  324. j.ahead_asked = now;
  325. j.written.extend(written.into_iter().map(|page| (page, now)));
  326. j.kept = !ahead.is_empty();
  327. j.ahead = ahead;
  328. }
  329. /// The submission's one asking stands no longer: its refreshes are done,
  330. /// or title memory was written in a way the journal was not told.
  331. pub(crate) fn ask_once_end() {
  332. let mut j = journal_mut();
  333. if j.kept {
  334. j.kept = false;
  335. j.ahead.clear();
  336. }
  337. }
  338. /// We wrote title memory `[at, at + len)` while a submission's one asking
  339. /// stands (the title's buffer copies, done at submission): its pages count
  340. /// as written after that asking, so the refreshes that follow copy them.
  341. pub(crate) fn wrote(at: usize, len: usize) {
  342. let mut j = journal_mut();
  343. if !j.kept || len == 0 {
  344. return;
  345. }
  346. let now = next_asking();
  347. // What is copied from now on counts as copied after these writes (fork
  348. // PR 410): answers older than the writes in them made every refresh
  349. // until the next asking copy the pages again.
  350. j.ahead_asked = now;
  351. for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) {
  352. j.written.insert(page, now);
  353. }
  354. for (_, others) in elsewhere(at, len) {
  355. j.written.extend(others.into_iter().map(|other| (other / PAGE, now)));
  356. }
  357. }
  358. /// The blocks of `[at, at + len)` whose pages the title shows at other
  359. /// addresses too, and there.
  360. fn elsewhere(at: usize, len: usize) -> Vec<(usize, Vec<usize>)> {
  361. if !view_guard() || len == 0 {
  362. return Vec::new();
  363. }
  364. crate::inplace::shown_elsewhere(at / BLOCK * BLOCK, at.saturating_add(len))
  365. }
  366. /// One kernel asking for `pieces` (page ranges in order); by halves if it
  367. /// fails, as a run across two reservations or into memory that is not
  368. /// write-watched does. A piece alone is left to [`writes`]. Adds what was
  369. /// asked to `asked` and the pages found written to `written`.
  370. fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec<usize>) {
  371. if pieces.len() < 2 {
  372. return;
  373. }
  374. let first = pieces[0].0;
  375. let last = pieces.iter().map(|p| p.1).max().unwrap_or(first);
  376. if let Some(pages) = kernel_written(first, last) {
  377. written.extend(pages);
  378. asked.push((first, last));
  379. return;
  380. }
  381. let (a, b) = pieces.split_at(pieces.len() / 2);
  382. ask_run(a, asked, written);
  383. ask_run(b, asked, written);
  384. }
  385. /// What [`writes`] would say of `[start, end)` from the journal alone, if
  386. /// the range lies in one asked ahead ([`ask_ahead`], [`ask_once`]): the
  387. /// pages written since tracking began and the asking that last found each
  388. /// written, with the number of the asking that stands (as [`writes`] gives
  389. /// it). `None` if the kernel would have to be asked.
  390. pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> {
  391. let (first, last) = (start / PAGE, end.div_ceil(PAGE));
  392. let j = journal();
  393. j.ahead
  394. .iter()
  395. .any(|&(a, b)| a <= first && last <= b)
  396. .then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect()))
  397. }
  398. /// The pages of `[start, end)` (whole pages) as last written, for pages
  399. /// written since tracking began: `(page number, asking)` in page order, and
  400. /// this asking's number, which is higher than any in the list but those the
  401. /// kernel just reported. `None` if the memory is not write-watched (nor,
  402. /// with `guarded`, view memory, which is then guarded).
  403. pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> {
  404. let (first, last) = (start / PAGE, end.div_ceil(PAGE));
  405. let of = |j: &Journal| -> Vec<(usize, u64)> { j.written.range(first..last).map(|(&p, &w)| (p, w)).collect() };
  406. // Asked ahead with the submission's other ranges: the journal has it.
  407. let ahead = |j: &Journal| j.ahead.iter().any(|&(a, b)| a <= first && last <= b).then(|| (j.ahead_asked, of(j)));
  408. if let Some(known) = ahead(&journal()) {
  409. return Some(known);
  410. }
  411. // Read-only since an asking noted it: the bits first, then the journal.
  412. if guarded && published(start, end) {
  413. #[cfg(feature = "diagnostics")]
  414. tally(2, 1);
  415. let j = journal();
  416. return Some((next_asking(), of(&j)));
  417. }
  418. // Asked, and the answer noted, with the range held: nothing else asks
  419. // about any of it in between.
  420. let _range = Asking::hold(first, last);
  421. if let Some(known) = ahead(&journal()) {
  422. return Some(known);
  423. }
  424. let mut guards_asked = false;
  425. let pages = match kernel_written(first, last) {
  426. Some(pages) => pages,
  427. None => {
  428. guards_asked = true;
  429. if !guarded {
  430. return None;
  431. }
  432. #[cfg(feature = "diagnostics")]
  433. let guarding = std::time::Instant::now();
  434. let written = guard(first * PAGE, last * PAGE);
  435. #[cfg(feature = "diagnostics")]
  436. {
  437. use crate::copystat::{C, add};
  438. let us = guarding.elapsed().as_micros() as u64;
  439. add(C::GuardUs, us);
  440. if written.is_some() {
  441. add(C::Watches, 1);
  442. add(C::WatchUs, us);
  443. slow(us);
  444. }
  445. }
  446. written?
  447. }
  448. };
  449. if pages.is_empty() {
  450. // Nothing to note: the others may go on reading.
  451. let j = journal();
  452. return Some((next_asking(), of(&j)));
  453. }
  454. let answer = {
  455. let mut j = journal_mut();
  456. let now = next_asking();
  457. j.written.extend(pages.iter().map(|&page| (page, now)));
  458. (now, of(&j))
  459. };
  460. // Noted: what the guards made clean of it is known by its bits from
  461. // now on. (The range is still held: no other asking of any of it came
  462. // between.)
  463. if guards_asked && light() {
  464. publish(&pages);
  465. }
  466. Some(answer)
  467. }
  468. /// Whether nothing of `[start, end)` was written that a copy with the notes
  469. /// `copied` (the asking after which each page from page `base` on was taken)
  470. /// and `ranged` (the asking after which a range that holds this one was
  471. /// taken whole, or 0) does not hold, as [`writes`] would answer with nothing
  472. /// asked: the submission's asking covers the range, or its blocks are known
  473. /// by their bits. `false` if something would have to be asked.
  474. pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool {
  475. let (first, last) = (start / PAGE, end.div_ceil(PAGE));
  476. // The bits first, then the journal, as in `writes`.
  477. let known = published(start, end);
  478. let j = journal();
  479. if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) {
  480. return false;
  481. }
  482. let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else {
  483. return false;
  484. };
  485. (ranged != 0 || taken.iter().all(|&at| at != 0))
  486. && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged))
  487. }
  488. impl Tracked {
  489. /// Takes changed pages of `[from, to)`, cut to the tracked range. A
  490. /// partial page stays changed so a later take can read its other bytes.
  491. pub(crate) fn take(&self, from: usize, to: usize) -> Vec<(usize, usize)> {
  492. let (from, to) = (from.max(self.start), to.min(self.end));
  493. if from >= to {
  494. return Vec::new();
  495. }
  496. let Some((_, pages)) = writes(from, to, true) else {
  497. return Vec::new();
  498. };
  499. let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
  500. let mut ranges: Vec<(usize, usize)> = Vec::new();
  501. for (page, write) in pages {
  502. if seen.get(&page).is_some_and(|&last| last >= write) {
  503. continue;
  504. }
  505. let (start, end) = ((page * PAGE).max(from), ((page + 1) * PAGE).min(to));
  506. if start >= end {
  507. continue;
  508. }
  509. // Keep partial pages dirty: the caller has not taken the rest.
  510. if (page * PAGE).max(self.start) >= from
  511. && ((page + 1) * PAGE).min(self.end) <= to
  512. {
  513. seen.insert(page, write);
  514. }
  515. match ranges.last_mut() {
  516. Some((_, last)) if *last == start => *last = end,
  517. _ => ranges.push((start, end)),
  518. }
  519. }
  520. ranges
  521. }
  522. }
  523. /// Guarded blocks of view memory.
  524. const BLOCK: usize = PAGE;
  525. /// Whether the refreshes of host copies go the light way
  526. /// (`VICTORY_LIGHT_REFRESH=0`: as before): view memory nothing wrote since
  527. /// it was last asked about is known by its bits ([`PUBLISHED`]), a copy
  528. /// nothing of whose range changed is told so before any thread is woken
  529. /// for it (`crate::host`, `Shadow::nothing_new`), and the ends of a range,
  530. /// pages the range holds in part, are not copied again at every refresh
  531. /// (`Shadow::copy_stale`).
  532. ///
  533. /// A frame asked about view memory some 1,500 times, for nearly all of it
  534. /// to hear that nothing was written, on up to seven threads at once, each
  535. /// asking under the guards' one lock and behind [`ASKING`]'s: 94 ms a frame
  536. /// of all threads' time (run record-1), most of it waiting.
  537. pub(crate) fn light() -> bool {
  538. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  539. *ON.get_or_init(|| std::env::var_os("VICTORY_LIGHT_REFRESH").is_none_or(|v| v != "0"))
  540. }
  541. /// A bit per block of the address space, in pieces made when first needed
  542. /// and never let go.
  543. struct Bits([std::sync::atomic::AtomicPtr<BitsPiece>; Bits::PIECES]);
  544. /// The bits of 4 GiB.
  545. type BitsPiece = [std::sync::atomic::AtomicU64; Bits::WORDS];
  546. impl Bits {
  547. const WORDS: usize = 1 << 10;
  548. /// 128 TiB, what a process has.
  549. const PIECES: usize = 1 << 15;
  550. const fn new() -> Bits {
  551. Bits([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Bits::PIECES])
  552. }
  553. fn piece(&self, word: usize) -> Option<&BitsPiece> {
  554. let piece = self.0.get(word / Bits::WORDS)?.load(std::sync::atomic::Ordering::Acquire);
  555. // SAFETY: null, or a piece made by `set`, which is never freed.
  556. unsafe { piece.as_ref() }
  557. }
  558. /// One caller at a time (under the guards' lock).
  559. fn set(&self, block: usize) {
  560. use std::sync::atomic::Ordering::{Relaxed, Release};
  561. let word = block / 64;
  562. let Some(place) = self.0.get(word / Bits::WORDS) else {
  563. return;
  564. };
  565. if place.load(Relaxed).is_null() {
  566. let piece: Box<BitsPiece> = Box::new([const { std::sync::atomic::AtomicU64::new(0) }; Bits::WORDS]);
  567. place.store(Box::into_raw(piece), Release);
  568. }
  569. if let Some(piece) = self.piece(word) {
  570. piece[word % Bits::WORDS].fetch_or(1 << (block % 64), Release);
  571. }
  572. }
  573. fn clear(&self, block: usize) {
  574. let word = block / 64;
  575. if let Some(piece) = self.piece(word) {
  576. // Ahead of the protection's change, and seen by whoever the
  577. // writer tells of its write.
  578. piece[word % Bits::WORDS].fetch_and(!(1 << (block % 64)), std::sync::atomic::Ordering::SeqCst);
  579. }
  580. }
  581. /// Whether a bit of `[first, last)` is set.
  582. fn any(&self, first: usize, last: usize) -> bool {
  583. let mut block = first;
  584. while block < last {
  585. let word = block / 64;
  586. let until = ((word + 1) * 64).min(last);
  587. let mask = (u64::MAX >> (64 - (until - block))) << (block % 64);
  588. match self.piece(word) {
  589. Some(piece) => {
  590. if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::SeqCst) & mask != 0 {
  591. return true;
  592. }
  593. block = until;
  594. }
  595. // None of the piece's.
  596. None => block = (word / Bits::WORDS + 1) * Bits::WORDS * 64,
  597. }
  598. }
  599. false
  600. }
  601. /// Whether the bits of all of `[first, last)` are set (not so of none).
  602. fn all(&self, first: usize, last: usize) -> bool {
  603. let mut block = first;
  604. while block < last {
  605. let word = block / 64;
  606. let until = ((word + 1) * 64).min(last);
  607. let mask = (u64::MAX >> (64 - (until - block))) << (block % 64);
  608. let Some(piece) = self.piece(word) else {
  609. return false;
  610. };
  611. if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::Acquire) & mask != mask {
  612. return false;
  613. }
  614. block = until;
  615. }
  616. first < last
  617. }
  618. }
  619. /// The blocks that are read-only by our hand, not written since, and of
  620. /// which the journal holds every write from before that: for those, what
  621. /// [`writes`] answers is in the journal, and neither the kernel, nor the
  622. /// guards' lock, nor [`ASKING`] need be asked.
  623. ///
  624. /// Why that is so: a block's bit is set under the guards' lock while the
  625. /// block is clean, by the asking that made it clean, after that asking noted
  626. /// in the journal what it found ([`publish`]). It is cleared under the same
  627. /// lock, before the block becomes writable again ([`open`]) or is forgotten
  628. /// ([`title_memory_remapped`]). So while the bit is set nothing can have
  629. /// written the block through this address, and who sees the bit and looks
  630. /// at the journal after that finds every earlier write in it. A write that
  631. /// comes while the bit is looked at is no different from one that comes just
  632. /// after an asking: the next asking finds the block open.
  633. ///
  634. /// So too for the blocks of placeholders that were copied as zeros
  635. /// (`Guards::held`): nothing can be there before the runtime maps it, and
  636. /// it tells of that ([`title_memory_remapped`]) before the title is.
  637. static PUBLISHED: Bits = Bits::new();
  638. /// The blocks read-only by our hand, or about to be: set under the guards'
  639. /// lock ahead of the protection, cleared under it when the block is open
  640. /// again. Who finds none set has no guard to open and need not wait for the
  641. /// lock ([`writing`]): some 700 pieces a frame are landed in memory that is
  642. /// no view.
  643. static PROTECTED: Bits = Bits::new();
  644. /// An asking made blocks of `pages` clean and noted them in the journal.
  645. fn publish(pages: &[usize]) {
  646. let g = guards();
  647. for page in pages {
  648. if g.clean.contains(page) || g.held.contains(page) {
  649. PUBLISHED.set(*page);
  650. }
  651. }
  652. }
  653. /// Whether placeholders are known for what they are (`VICTORY_KNOWN_HOLES=0`:
  654. /// every hole is looked at at every asking, as before).
  655. ///
  656. /// Most ranges asked about have holes, reservations the title maps its pages
  657. /// into as it streams (231,000 regions, 1,125 of a frame's 1,530 asked view
  658. /// ranges, run next1-1). Such a range was never known whole: each asking put
  659. /// a question to Windows for each of its holes, under the guards' lock, and
  660. /// 111 ms a frame of all threads' time went into waiting for that lock.
  661. fn known_holes() -> bool {
  662. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  663. *ON.get_or_init(|| std::env::var_os("VICTORY_KNOWN_HOLES").is_none_or(|v| v != "0") && light())
  664. }
  665. /// Whether `block` lies in a placeholder: a reservation in which pages come
  666. /// to be only by mapping a view (or an allocation) in its place, which an
  667. /// ordinary commit cannot do.
  668. fn placeholder(block: usize) -> bool {
  669. /// `MEMORY_REGION_INFORMATION` (ntddk).
  670. #[repr(C)]
  671. #[derive(Default)]
  672. struct Region {
  673. allocation_base: usize,
  674. allocation_protect: u32,
  675. region_type: u32,
  676. region_size: usize,
  677. commit_size: usize,
  678. partition_id: usize,
  679. node_preference: usize,
  680. }
  681. #[link(name = "ntdll", kind = "raw-dylib")]
  682. unsafe extern "system" {
  683. fn NtQueryVirtualMemory(
  684. process: *mut std::ffi::c_void,
  685. at: *const std::ffi::c_void,
  686. class: u32,
  687. out: *mut std::ffi::c_void,
  688. len: usize,
  689. returned: *mut usize,
  690. ) -> i32;
  691. }
  692. // (Class 3 answers with the kind of memory in that word, not the flags.)
  693. const MEMORY_REGION_INFORMATION_EX: u32 = 7;
  694. const PLACEHOLDER_RESERVATION: u32 = 1 << 8;
  695. let mut region = Region::default();
  696. // SAFETY: the answer's room and its size.
  697. let status = unsafe {
  698. NtQueryVirtualMemory(
  699. windows_sys::Win32::System::Threading::GetCurrentProcess(),
  700. (block * BLOCK) as *const _,
  701. MEMORY_REGION_INFORMATION_EX,
  702. (&raw mut region).cast(),
  703. size_of::<Region>(),
  704. std::ptr::null_mut(),
  705. )
  706. };
  707. status >= 0 && region.region_type & PLACEHOLDER_RESERVATION != 0
  708. }
  709. /// The runtime gave the title memory at `[at, at + len)`, allocated or
  710. /// committed: what was known of holes there is asked again.
  711. pub fn title_memory_allocated(at: usize, len: usize) {
  712. if len == 0 || !known_holes() {
  713. return;
  714. }
  715. let mut g = guards();
  716. let blocks: Vec<usize> = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect();
  717. for block in blocks {
  718. g.held.remove(&block);
  719. PUBLISHED.clear(block);
  720. }
  721. }
  722. /// Once a frame: a hundredth of the known holes are looked at, in case one
  723. /// was filled with nobody telling ([`title_memory_allocated`],
  724. /// [`title_memory_remapped`]), which no title we know does.
  725. pub(crate) fn look_at_holes() {
  726. const PARTS: usize = 100;
  727. if !known_holes() {
  728. return;
  729. }
  730. static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
  731. let blocks: Vec<usize> = {
  732. let g = guards();
  733. let from = FROM.load(std::sync::atomic::Ordering::Relaxed);
  734. let part: Vec<usize> = g.held.range(from..).take(g.held.len() / PARTS + 1).copied().collect();
  735. FROM.store(part.last().map_or(0, |b| b + 1), std::sync::atomic::Ordering::Relaxed);
  736. part
  737. };
  738. let mut until = 0;
  739. for block in blocks {
  740. if block >= until {
  741. until = uncommitted_end(block);
  742. }
  743. if block >= until {
  744. // (Or unmapped memory was mapped since the part was taken: told
  745. // already, and forgotten.)
  746. let mut g = guards();
  747. if g.held.remove(&block) {
  748. PUBLISHED.clear(block);
  749. static SAID: std::sync::Once = std::sync::Once::new();
  750. SAID.call_once(|| {
  751. tracing::warn!(
  752. address = format_args!("{:#x}", block * BLOCK),
  753. "a placeholder of the title's was filled with nobody telling (VICTORY_KNOWN_HOLES=0 asks every time)"
  754. );
  755. });
  756. }
  757. }
  758. }
  759. }
  760. /// Whether a block of `[start, end)` is view memory read-only by our hand:
  761. /// the kernel keeps no written pages of it and would refuse an asking.
  762. pub(crate) fn guarded(start: usize, end: usize) -> bool {
  763. PROTECTED.any(start / BLOCK, end.div_ceil(BLOCK))
  764. }
  765. /// Whether nothing of `[start, end)` can have been written since an asking
  766. /// noted it in the journal ([`PUBLISHED`]).
  767. fn published(start: usize, end: usize) -> bool {
  768. light() && PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK))
  769. }
  770. /// Since the last frame line: what asking about title memory was. Kernel
  771. /// askings and the KiB they walked; view ranges answered by their bits, by
  772. /// the guards whole clean, and block by block; blocks made read-only; blocks
  773. /// opened by ourselves; nanoseconds waiting for the guards' lock and
  774. /// nanoseconds of changing protections (all threads); questions to Windows
  775. /// about holes; kernel askings refused; nanoseconds in kernel askings; the
  776. /// 4 KiB pages they found written.
  777. #[cfg(feature = "diagnostics")]
  778. static ASKS: [std::sync::atomic::AtomicU64; 13] = [const { std::sync::atomic::AtomicU64::new(0) }; 13];
  779. #[cfg(feature = "diagnostics")]
  780. fn tally(what: usize, n: u64) {
  781. ASKS[what].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
  782. }
  783. /// [`ASKS`], taken.
  784. #[cfg(feature = "diagnostics")]
  785. pub(crate) fn asks() -> [u64; 13] {
  786. std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
  787. }
  788. /// The guards' lock, the wait for it counted.
  789. fn guards_timed() -> std::sync::MutexGuard<'static, Guards> {
  790. #[cfg(feature = "diagnostics")]
  791. let started = std::time::Instant::now();
  792. let g = guards();
  793. #[cfg(feature = "diagnostics")]
  794. tally(7, started.elapsed().as_nanos() as u64);
  795. g
  796. }
  797. struct Guards {
  798. /// Blocks we made read-only.
  799. protected: BTreeSet<usize>,
  800. /// Of those, the ones not written since a copy took them.
  801. clean: BTreeSet<usize>,
  802. /// Blocks already copied as zeros. While they remain wholly uncommitted,
  803. /// the copy can skip hundreds of MB of failing kernel reads per world frame.
  804. absent: BTreeSet<usize>,
  805. /// Of those, the ones in placeholders ([`known_holes`]).
  806. held: BTreeSet<usize>,
  807. /// Blocks that were absent and turned out to be other memory than views
  808. /// when something was there again: never guarded, copied every time.
  809. foreign: BTreeSet<usize>,
  810. /// Blocks (first, past the last) the kernel writes now
  811. /// ([`kernel_writing`]), and blocks the runtime has unmapped in a change
  812. /// not yet done ([`title_memory_unmapping`]). Not in the sets above, and
  813. /// left as they are by [`guard`], which reports them written.
  814. kernel: Vec<(usize, usize)>,
  815. changing: Vec<(usize, usize)>,
  816. /// Blocks whose page is shown at other addresses too and that were made
  817. /// read-only together with those (which are in it as well): what opens
  818. /// one opens them all. (A write's range can be huge, `fread`'s, so only
  819. /// these are looked up.)
  820. aliased: BTreeSet<usize>,
  821. }
  822. impl Guards {
  823. fn left_alone(&self, block: usize) -> bool {
  824. self.kernel.iter().chain(&self.changing).any(|&(first, last)| (first..last).contains(&block))
  825. }
  826. }
  827. static GUARDS: Mutex<Guards> = Mutex::new(Guards {
  828. protected: BTreeSet::new(),
  829. clean: BTreeSet::new(),
  830. absent: BTreeSet::new(),
  831. held: BTreeSet::new(),
  832. foreign: BTreeSet::new(),
  833. kernel: Vec::new(),
  834. changing: Vec::new(),
  835. aliased: BTreeSet::new(),
  836. });
  837. fn guards() -> std::sync::MutexGuard<'static, Guards> {
  838. GUARDS.lock().unwrap_or_else(|e| e.into_inner())
  839. }
  840. /// The 4 KiB pages of title memory that what shaders wrote was put into,
  841. /// and the frame it last was.
  842. static LANDED: Mutex<Option<std::collections::HashMap<usize, u64, std::hash::BuildHasherDefault<PageHash>>>> = Mutex::new(None);
  843. /// A page's number, spread: some 20,000 a frame are noted in [`LANDED`].
  844. #[derive(Default)]
  845. struct PageHash(u64);
  846. impl std::hash::Hasher for PageHash {
  847. fn finish(&self) -> u64 {
  848. self.0
  849. }
  850. fn write(&mut self, bytes: &[u8]) {
  851. for &byte in bytes {
  852. self.write_u64(u64::from(byte));
  853. }
  854. }
  855. fn write_u64(&mut self, n: u64) {
  856. self.0 = (self.0 ^ n).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(26).wrapping_mul(0x9e37_79b9_7f4a_7c15);
  857. }
  858. fn write_usize(&mut self, n: usize) {
  859. self.write_u64(n as u64);
  860. }
  861. }
  862. /// What shaders wrote is about to go into title memory at `[at, at + len)`.
  863. pub(crate) fn landing(at: usize, len: usize) {
  864. {
  865. let frame = crate::frame::current();
  866. let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
  867. let landed = landed.get_or_insert_with(Default::default);
  868. let (first, last) = (at / KERNEL_PAGE, (at + len.max(1) - 1) / KERNEL_PAGE);
  869. landed.extend((first..=last).map(|page| (page, frame)));
  870. for (block, others) in elsewhere(at, len) {
  871. let block = block / KERNEL_PAGE;
  872. let here = first.max(block)..=last.min(block + BLOCK / KERNEL_PAGE - 1);
  873. for other in others {
  874. landed.extend(here.clone().map(|page| (page - block + other / KERNEL_PAGE, frame)));
  875. }
  876. }
  877. }
  878. writing(at, len);
  879. }
  880. /// What shaders wrote went into title memory through another view of the
  881. /// same pages (`crate::inplace::beside`): `pages` (of 4 KiB, by number)
  882. /// hold some of it, all of them in `spans` (address, bytes).
  883. ///
  884. /// Nothing faulted and no guard was opened. A guarded block stays read-only,
  885. /// clean, and known by its bit ([`PUBLISHED`]), all of which say that the
  886. /// title wrote nothing there: our write is an entry of the journal, which
  887. /// every answer about the block comes from, the quick ones and the guards'
  888. /// alike (a block whose guard is off they report anyway). So neither the
  889. /// guards' lock nor a protection is touched here, or by the next refresh.
  890. /// Noted after the bytes are in, never before: a copy that read the block
  891. /// before they were did so with the number of an asking made before that,
  892. /// which is under the one given here, and takes it again; noted before, a
  893. /// copy could read the older bytes with a number above the note's.
  894. ///
  895. /// Returns the note's number, and for each 64 KiB block noted the number of
  896. /// the block's last write before (0: none is known).
  897. pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, Vec<(usize, u64)>) {
  898. let mut before = Vec::with_capacity(spans.len());
  899. let noted;
  900. // The same pages at other addresses: copies of the memory there have not
  901. // what was put in either.
  902. let elsewhere: Vec<(usize, Vec<usize>)> = spans.iter().flat_map(|&(at, len)| elsewhere(at, len)).collect();
  903. {
  904. let frame = crate::frame::current();
  905. let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
  906. let landed = landed.get_or_insert_with(Default::default);
  907. for &page in pages {
  908. landed.insert(page, frame);
  909. }
  910. for (block, others) in &elsewhere {
  911. let first = block / KERNEL_PAGE;
  912. for &page in pages.iter().filter(|&&page| (first..first + BLOCK / KERNEL_PAGE).contains(&page)) {
  913. landed.extend(others.iter().map(|other| (page - first + other / KERNEL_PAGE, frame)));
  914. }
  915. }
  916. }
  917. {
  918. let mut j = journal_mut();
  919. let now = next_asking();
  920. noted = now;
  921. let mut last = usize::MAX;
  922. for &page in pages {
  923. let block = page * KERNEL_PAGE / PAGE;
  924. if block != last {
  925. before.push((block, j.written.insert(block, now).unwrap_or(0)));
  926. last = block;
  927. }
  928. }
  929. for (_, others) in &elsewhere {
  930. j.written.extend(others.iter().map(|other| (other / PAGE, now)));
  931. }
  932. }
  933. for &(at, len) in spans {
  934. // A placed texture there changes with no descriptor written.
  935. crate::descriptor::host::remapped(at, len);
  936. }
  937. for other in elsewhere.into_iter().flat_map(|(_, others)| others) {
  938. crate::descriptor::host::remapped(other, BLOCK);
  939. }
  940. (noted, before)
  941. }
  942. /// Whether every write of the title's to 64 KiB block `block` so far is in
  943. /// the journal ([`PUBLISHED`]).
  944. pub(crate) fn block_published(block: usize) -> bool {
  945. light() && PUBLISHED.all(block, block + 1)
  946. }
  947. /// Whether shaders' writes went into a page of `[at, at + len)` in the last
  948. /// `frames` frames.
  949. pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool {
  950. let since = crate::frame::current().saturating_sub(frames);
  951. let landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
  952. landed.as_ref().is_some_and(|landed| {
  953. (at / 4096..=(at + len.max(1) - 1) / 4096).any(|page| landed.get(&page).is_some_and(|&f| f >= since))
  954. })
  955. }
  956. /// Whether every block of `[at, at + len)` is view memory written since a
  957. /// host copy last took it: guarded then, and the guard is off. (Written by
  958. /// the title, or by us putting a flight's shader writes into it, if not
  959. /// beside the guard, [`landed_beside`].) Not for
  960. /// blocks no copy ever took, which were never guarded: the caller's range
  961. /// lies in a copy a flight was given, which took all of it. (Nor for blocks
  962. /// read-only by way of another view of their page: whether they were written
  963. /// since is not known.)
  964. pub(crate) fn written_since_taken(at: usize, len: usize) -> bool {
  965. if len == 0 {
  966. return false;
  967. }
  968. let g = guards();
  969. (at / BLOCK..=(at + len - 1) / BLOCK)
  970. .all(|b| !g.clean.contains(&b) && !g.absent.contains(&b) && !g.protected.contains(&b))
  971. }
  972. /// For view memory: the pages of `[start, end)`'s blocks written since
  973. /// they were last guarded (all of a block's pages), guarding them again
  974. /// before the caller copies them. `None` if the memory is not a view.
  975. fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
  976. // A range whose first block the guards hold already (read-only by our
  977. // hand, or noted absent) is a view: no question to Windows. The
  978. // question walks the page tables to the end of the pages that share the
  979. // first one's state, and a guarded view is one long run of read-only
  980. // pages: 0.6 ms for the title's 174 MB heap, 16 times a frame, and most
  981. // of the 68 ms a frame of "guards" (run 58).
  982. // `VICTORY_GUARD_ASK=1` asks every time, as before.
  983. static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  984. let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
  985. let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1"))
  986. && (PROTECTED.any(first, first + 1) || {
  987. let g = guards_timed();
  988. g.protected.contains(&first) || g.absent.contains(&first)
  989. });
  990. if !known && !is_view(start, end) {
  991. return None;
  992. }
  993. install();
  994. // The holes that an ordinary commit may have filled, with no word of the
  995. // runtime's. Windows is asked with the lock not held (the range is, no
  996. // other thread asks about it: `ASKING`); what the runtime tells meanwhile
  997. // takes the block out of the set, and it is looked at as any other.
  998. let unsure: Vec<usize> = {
  999. let g = guards_timed();
  1000. if g.clean.range(first..last).count() == last - first {
  1001. // Nothing written, mapped or new since the range was last taken.
  1002. #[cfg(feature = "diagnostics")]
  1003. tally(3, 1);
  1004. return Some(Vec::new());
  1005. }
  1006. g.absent.range(first..last).filter(|block| !g.held.contains(block)).copied().collect()
  1007. };
  1008. let mut came: Vec<(usize, bool)> = Vec::new();
  1009. let mut uncommitted_until = first;
  1010. for block in unsure {
  1011. // One question for the blocks of a region.
  1012. if block >= uncommitted_until {
  1013. uncommitted_until = uncommitted_end(block);
  1014. #[cfg(feature = "diagnostics")]
  1015. tally(9, 1);
  1016. }
  1017. if block >= uncommitted_until {
  1018. // The hole may have been given up, and its address be the
  1019. // title's heap's, or code's, now: not ours to guard.
  1020. came.push((block, is_view(block * BLOCK, (block + 1) * BLOCK)));
  1021. }
  1022. }
  1023. let mut g = guards_timed();
  1024. #[cfg(feature = "diagnostics")]
  1025. tally(4, 1);
  1026. for &(block, view) in &came {
  1027. if g.absent.remove(&block) && !view {
  1028. g.foreign.insert(block);
  1029. }
  1030. }
  1031. let mut written = Vec::new();
  1032. let mut run: Option<usize> = None;
  1033. // The range's clean blocks, and those known to be holes, in order: read
  1034. // off the sets in one pass, not looked up one block at a time. A frame
  1035. // asks about some 10 GB of view memory, 150,000 blocks, nearly all
  1036. // clean: the lookups were most of the 60-90 ms a frame of "guards"
  1037. // (run 54). What the loop adds to the sets meanwhile is the block it
  1038. // stands at or ones before it.
  1039. let clean: Vec<usize> = g.clean.range(first..last).copied().collect();
  1040. let absent: Vec<usize> = g.absent.range(first..last).copied().collect();
  1041. let (mut clean, mut absent) = (clean.into_iter().peekable(), absent.into_iter().peekable());
  1042. for block in first..=last {
  1043. let is_clean = clean.next_if_eq(&block).is_some();
  1044. let is_absent = absent.next_if_eq(&block).is_some();
  1045. if block < last && !is_clean && !is_absent {
  1046. written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE);
  1047. if g.protected.contains(&block) {
  1048. // Read-only by way of another view of its page, or not clean
  1049. // because one could not be made so.
  1050. if cover(&mut g, block, block + 1) {
  1051. g.clean.insert(block);
  1052. }
  1053. } else if !g.foreign.contains(&block) && !g.left_alone(block) {
  1054. run.get_or_insert(block);
  1055. continue;
  1056. }
  1057. }
  1058. if let Some(from) = run.take() {
  1059. protect(&mut g, from, block);
  1060. }
  1061. }
  1062. Some(written)
  1063. }
  1064. /// Whether `[start, end)` is view memory. The title's views lie in
  1065. /// placeholders, mapped and unmapped block by block as it streams, so a
  1066. /// range can begin in a block that is not mapped right now: the first
  1067. /// pages of the range that are there decide. A range with nothing there
  1068. /// counts as a view (its blocks are noted absent, and looked at again when
  1069. /// the runtime maps them).
  1070. ///
  1071. /// Looking at the first address only took such a range for "not a view":
  1072. /// its copy was marked not watched for good and copied whole at every
  1073. /// refresh, around its unmapped pages (run 54: 300 such ranges, 570 MB
  1074. /// copied a frame for them, 255 copies a frame reading around holes).
  1075. /// `VICTORY_GUARD_HOLES=0` looks at the first address only, as before.
  1076. fn is_view(start: usize, end: usize) -> bool {
  1077. use windows_sys::Win32::System::Memory::{
  1078. MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery,
  1079. };
  1080. static HOLES: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1081. let holes = *HOLES.get_or_init(|| std::env::var_os("VICTORY_GUARD_HOLES").is_none_or(|v| v != "0"));
  1082. let mut at = start;
  1083. loop {
  1084. // SAFETY: plain data filled in by the query.
  1085. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  1086. // SAFETY: a valid out pointer of the right size.
  1087. let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
  1088. if n == 0 {
  1089. return false;
  1090. }
  1091. if info.Type == MEM_MAPPED {
  1092. return true;
  1093. }
  1094. // Committed memory that is no view (the title's heaps, ours), or
  1095. // the answer as it was before.
  1096. if info.State == MEM_COMMIT || !holes {
  1097. return false;
  1098. }
  1099. // A hole (a placeholder, or free): on to what follows it.
  1100. let next = (info.BaseAddress as usize).saturating_add(info.RegionSize);
  1101. if next <= at || next >= end {
  1102. return true;
  1103. }
  1104. at = next;
  1105. }
  1106. }
  1107. /// Makes blocks `[from, to)` read-only and notes them guarded and clean;
  1108. /// block by block if they span views, leaving out any that fail, and
  1109. /// noting those not committed (unmapped) absent. The same physical pages
  1110. /// at every other view of them are made read-only too: a write through
  1111. /// one of those is this memory written, and only a fault can say so.
  1112. /// `VICTORY_VIEW_GUARD=0` leaves the other views as they are, as before.
  1113. fn protect(g: &mut Guards, from: usize, to: usize) {
  1114. protect_here(g, from, to);
  1115. cover(g, from, to);
  1116. }
  1117. /// Views of one page past which its views are not guarded together.
  1118. pub(crate) const MANY_VIEWS: usize = 64;
  1119. /// Whether all the views of a guarded page are guarded together
  1120. /// (`VICTORY_VIEW_GUARD`).
  1121. fn view_guard() -> bool {
  1122. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1123. *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_GUARD").is_none_or(|v| v != "0"))
  1124. }
  1125. /// Diagnostics: blocks guarded together with their other views, blocks
  1126. /// opened because another view of theirs was written, and blocks opened
  1127. /// because a view of theirs was mapped; since the start.
  1128. #[cfg(feature = "diagnostics")]
  1129. pub(crate) static ALIASES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  1130. /// Of the blocks `[from, to)`, which are read-only by our hand where they
  1131. /// can be: every other view of their pages is made read-only too. Where one
  1132. /// cannot be (the kernel writes through it now, or the runtime is changing
  1133. /// it), a write through it would not be seen: that block is not clean, and
  1134. /// told as written at every asking, until it can. Whether all are covered.
  1135. fn cover(g: &mut Guards, from: usize, to: usize) -> bool {
  1136. let mut all = true;
  1137. for (page, others) in elsewhere(from * BLOCK, (to - from) * BLOCK) {
  1138. let block = page / BLOCK;
  1139. if !g.protected.contains(&block) {
  1140. continue; // not there, or not ours to guard
  1141. }
  1142. #[cfg(feature = "diagnostics")]
  1143. ALIASES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1144. g.aliased.insert(block);
  1145. let mut covered = true;
  1146. for other in others {
  1147. covered &= protect_alias(g, other / BLOCK);
  1148. }
  1149. if !covered {
  1150. all = false;
  1151. g.clean.remove(&block);
  1152. }
  1153. }
  1154. all
  1155. }
  1156. /// Makes `block` read-only: another view of a page a copy is about to take
  1157. /// through its own, so that a write through this one faults too. It is not
  1158. /// noted clean: the copies of title memory at this view have not taken the
  1159. /// page ([`guard`] tells such a block as written, then notes it clean).
  1160. /// One that is clean stays so: had the page been written since its copies
  1161. /// took it, [`open`] would have opened it. Whether it is read-only now.
  1162. fn protect_alias(g: &mut Guards, block: usize) -> bool {
  1163. use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
  1164. g.aliased.insert(block);
  1165. if g.protected.contains(&block) {
  1166. return true;
  1167. }
  1168. if g.left_alone(block) {
  1169. return false;
  1170. }
  1171. // Ahead of the protection.
  1172. PROTECTED.set(block);
  1173. let mut old = 0;
  1174. #[cfg(feature = "diagnostics")]
  1175. let started = std::time::Instant::now();
  1176. // SAFETY: title view memory; only its protection changes.
  1177. let done = unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READONLY, &mut old) } != 0;
  1178. #[cfg(feature = "diagnostics")]
  1179. {
  1180. tally(5, 1);
  1181. tally(8, started.elapsed().as_nanos() as u64);
  1182. }
  1183. if done && matches!(old, PAGE_READWRITE | PAGE_READONLY) {
  1184. g.protected.insert(block);
  1185. return true;
  1186. }
  1187. if done {
  1188. // Not for us to guard: as it was.
  1189. // SAFETY: as above.
  1190. unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, old, &mut old) };
  1191. }
  1192. PROTECTED.clear(block);
  1193. false
  1194. }
  1195. /// [`protect`] for one range, without the other views of its pages.
  1196. fn protect_here(g: &mut Guards, from: usize, to: usize) {
  1197. use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
  1198. let set = |from: usize, to: usize| {
  1199. let mut old = 0;
  1200. #[cfg(feature = "diagnostics")]
  1201. let started = std::time::Instant::now();
  1202. // SAFETY: title view memory; only its protection changes.
  1203. let mut done = unsafe {
  1204. VirtualProtect(
  1205. (from * BLOCK) as *const _,
  1206. (to - from) * BLOCK,
  1207. PAGE_READONLY,
  1208. &mut old,
  1209. ) != 0
  1210. };
  1211. if done && !matches!(old, PAGE_READWRITE | PAGE_READONLY) {
  1212. // What is there is not for us to guard (code, or memory the
  1213. // title protects itself): as it was.
  1214. // SAFETY: as above.
  1215. unsafe { VirtualProtect((from * BLOCK) as *const _, (to - from) * BLOCK, old, &mut old) };
  1216. done = false;
  1217. }
  1218. #[cfg(feature = "diagnostics")]
  1219. {
  1220. tally(5, (to - from) as u64);
  1221. tally(8, started.elapsed().as_nanos() as u64);
  1222. }
  1223. done
  1224. };
  1225. let note = |g: &mut Guards, from: usize, to: usize| {
  1226. g.protected.extend(from..to);
  1227. g.clean.extend(from..to);
  1228. };
  1229. // Ahead of the protection (`PROTECTED`).
  1230. (from..to).for_each(|block| PROTECTED.set(block));
  1231. if set(from, to) {
  1232. note(g, from, to);
  1233. return;
  1234. }
  1235. let mut uncommitted_until = from;
  1236. for block in from..to {
  1237. // (Not one question a block of a region that is not there.)
  1238. if block >= uncommitted_until && set(block, block + 1) {
  1239. note(g, block, block + 1);
  1240. continue;
  1241. }
  1242. PROTECTED.clear(block);
  1243. if block >= uncommitted_until {
  1244. uncommitted_until = uncommitted_end(block);
  1245. #[cfg(feature = "diagnostics")]
  1246. tally(9, 1);
  1247. }
  1248. if block < uncommitted_until {
  1249. g.absent.insert(block);
  1250. if known_holes() && placeholder(block) {
  1251. g.held.insert(block);
  1252. }
  1253. }
  1254. }
  1255. }
  1256. /// The end (exclusive) of the whole uncommitted blocks starting at `block`.
  1257. fn uncommitted_end(block: usize) -> usize {
  1258. use windows_sys::Win32::System::Memory::{
  1259. MEM_FREE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, VirtualQuery,
  1260. };
  1261. // SAFETY: plain data filled in by the query.
  1262. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  1263. // SAFETY: a valid out pointer of the right size.
  1264. let n = unsafe { VirtualQuery((block * BLOCK) as *const _, &mut info, size_of_val(&info)) };
  1265. if n != 0 && matches!(info.State, MEM_RESERVE | MEM_FREE) {
  1266. (info.BaseAddress as usize).saturating_add(info.RegionSize) / BLOCK
  1267. } else {
  1268. block
  1269. }
  1270. }
  1271. /// Gives write access back to the guarded blocks of `[start, end)` and
  1272. /// notes them written; true if any was guarded. The same physical pages at
  1273. /// every other view of them are opened too: the write that faulted (or is
  1274. /// ours, `crate::host::copy_mapped`) goes through one view, and every
  1275. /// guard over the pages must copy them again.
  1276. fn open(g: &mut Guards, start: usize, end: usize) -> bool {
  1277. let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
  1278. if first >= last {
  1279. return false;
  1280. }
  1281. let mut blocks: Vec<usize> = g.protected.range(first..last).copied().collect();
  1282. let here = blocks.len();
  1283. if !g.aliased.is_empty() {
  1284. let aliased: Vec<usize> = g.aliased.range(first..last).copied().collect();
  1285. for block in aliased {
  1286. g.aliased.remove(&block);
  1287. for other in crate::inplace::pages_of(block * BLOCK) {
  1288. let other = other / BLOCK;
  1289. g.aliased.remove(&other);
  1290. if !(first..last).contains(&other) && g.protected.contains(&other) {
  1291. blocks.push(other);
  1292. }
  1293. }
  1294. }
  1295. #[cfg(feature = "diagnostics")]
  1296. ALIASES[1].fetch_add((blocks.len() - here) as u64, std::sync::atomic::Ordering::Relaxed);
  1297. }
  1298. unguard(g, &blocks);
  1299. here != 0
  1300. }
  1301. /// Gives write access back to `blocks`, guarded ones.
  1302. fn unguard(g: &mut Guards, blocks: &[usize]) {
  1303. use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
  1304. #[cfg(feature = "diagnostics")]
  1305. let started = std::time::Instant::now();
  1306. // All of them before the first can be written: a write through one is a
  1307. // write of the others' bytes.
  1308. for block in blocks {
  1309. g.protected.remove(block);
  1310. g.clean.remove(block);
  1311. PUBLISHED.clear(*block);
  1312. }
  1313. for &block in blocks {
  1314. let mut old = 0;
  1315. // SAFETY: a block we made read-only.
  1316. unsafe {
  1317. if VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) != 0
  1318. && !matches!(old, PAGE_READONLY | PAGE_READWRITE)
  1319. {
  1320. // Not what we left there: the address is other memory's
  1321. // (code's, say), which keeps its protection.
  1322. VirtualProtect((block * BLOCK) as *const _, BLOCK, old, &mut old);
  1323. }
  1324. }
  1325. PROTECTED.clear(block);
  1326. }
  1327. #[cfg(feature = "diagnostics")]
  1328. if !blocks.is_empty() {
  1329. tally(8, started.elapsed().as_nanos() as u64);
  1330. }
  1331. }
  1332. /// Before our own write into title memory `[at, at + len)` through the
  1333. /// kernel (which does not fault into our handler): opens its guarded blocks.
  1334. /// The runtime calls it (as `kernel_will_write`) before the title's kernel
  1335. /// reads into its own memory.
  1336. pub fn writing(at: usize, len: usize) {
  1337. // The length is the title's (`fread`'s size times count, saturated).
  1338. let last = at.saturating_add(len).div_ceil(BLOCK);
  1339. if !light() || PROTECTED.any(at / BLOCK, last) {
  1340. let mut g = guards_timed();
  1341. #[cfg(feature = "diagnostics")]
  1342. let held = g.protected.len();
  1343. open(&mut g, at, at.saturating_add(len));
  1344. #[cfg(feature = "diagnostics")]
  1345. tally(6, (held - g.protected.len()) as u64);
  1346. }
  1347. // A placed texture there changes with no descriptor written.
  1348. crate::descriptor::host::remapped(at, len);
  1349. }
  1350. /// The kernel writes title memory `[at, at + len)` until what this returns
  1351. /// is dropped ([`kernel_writing`]).
  1352. pub struct KernelWrite(usize, usize);
  1353. /// The runtime is about to have the kernel write title memory
  1354. /// `[at, at + len)` (a file read): its guarded blocks are opened, as by
  1355. /// [`writing`], and no refresh guards them again before what this returns is
  1356. /// dropped, at the end of that call. One that did would make the kernel's
  1357. /// write fail (the kernel does not fault into our handler): a read cut
  1358. /// short, which the title takes for what the file holds.
  1359. pub fn kernel_writing(at: usize, len: usize) -> KernelWrite {
  1360. let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK));
  1361. {
  1362. let mut g = guards_timed();
  1363. open(&mut g, at, at.saturating_add(len));
  1364. if len != 0 {
  1365. // Nothing known of them stands while they are left alone.
  1366. let absent: Vec<usize> = g.absent.range(first..last).copied().collect();
  1367. for block in absent {
  1368. g.absent.remove(&block);
  1369. if g.held.remove(&block) {
  1370. PUBLISHED.clear(block);
  1371. }
  1372. }
  1373. g.kernel.push((first, last));
  1374. }
  1375. }
  1376. crate::descriptor::host::remapped(at, len);
  1377. KernelWrite(first, if len == 0 { first } else { last })
  1378. }
  1379. impl Drop for KernelWrite {
  1380. fn drop(&mut self) {
  1381. if self.0 == self.1 {
  1382. return;
  1383. }
  1384. let mut g = guards();
  1385. if let Some(i) = g.kernel.iter().position(|&r| r == (self.0, self.1)) {
  1386. g.kernel.swap_remove(i);
  1387. }
  1388. }
  1389. }
  1390. /// What `VICTORY_PAGE_WRITES` asks to be done with a write the guards do
  1391. /// not see once its bytes are there ([`title_memory_written`]), as bits:
  1392. /// 1, the guarded blocks under it are opened and count as written (host
  1393. /// copies of buffers and textures read through tables take them again);
  1394. /// 2, the placed textures picked by index that lie under it are due again;
  1395. /// 4, both also for reads to plain addresses when they have finished.
  1396. /// Unset or `guards`: bit 1 alone. `0`: nothing, counted only (the default
  1397. /// until run 199). `1`: bits 1 and 2. `slots`: bit 2 alone. `all`:
  1398. /// everything.
  1399. /// (Bit 1 by default: in every run 10,000 to 50,000 guarded blocks of host
  1400. /// copies lay under such writes and kept the bytes from before; runs 197
  1401. /// and 198 opened them, 9,766 and 10,796 blocks, with nothing worse for
  1402. /// it. Bit 2 makes texture slots due and is the one that flooded the
  1403. /// queue in an earlier form: still asked for by name.)
  1404. pub(crate) fn page_writes() -> u8 {
  1405. static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  1406. *MODE.get_or_init(|| match std::env::var("VICTORY_PAGE_WRITES").as_deref().map(str::trim) {
  1407. Ok("0") => 0,
  1408. Ok("1") => 3,
  1409. Ok("slots") => 2,
  1410. Ok("all") => 7,
  1411. _ => 1,
  1412. })
  1413. }
  1414. /// Since the start: writes into physical pages through the runtime's own
  1415. /// views that landed at addresses the title has mapped (one for each run
  1416. /// of addresses); their bytes; guarded blocks that lay under them (host
  1417. /// copies that would otherwise keep the bytes from before); reads to
  1418. /// plain addresses that finished.
  1419. pub(crate) static WRITTEN: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  1420. /// The bytes of a write the guards do not see are there: title memory
  1421. /// `[at, at + len)`. `pages`: DirectStorage wrote them into physical pages
  1422. /// through a view of the runtime's own, and this is an address where the
  1423. /// title has those pages mapped (no title address faulted, nothing was
  1424. /// mapped or unmapped; the shortcut this file's header names). Otherwise a
  1425. /// read to a plain address has finished, of which [`writing`] was told
  1426. /// before it began.
  1427. ///
  1428. /// Upstream's c75fdba does the same for its trackers (its `Writing` marks
  1429. /// the pages once more when dropped; page destinations are reported at
  1430. /// each address showing them). Here it is counted always and acted on as
  1431. /// [`page_writes`] says. Called without the runtime's page-table lock;
  1432. /// takes the guards' lock, then, alone, the lock of the ranges kept for
  1433. /// the texture pass.
  1434. pub fn title_memory_written(at: usize, len: usize, pages: bool) {
  1435. use std::sync::atomic::Ordering::Relaxed;
  1436. if len == 0 {
  1437. return;
  1438. }
  1439. let mode = page_writes();
  1440. let end = at.saturating_add(len);
  1441. if pages {
  1442. WRITTEN[0].fetch_add(1, Relaxed);
  1443. WRITTEN[1].fetch_add(len as u64, Relaxed);
  1444. } else {
  1445. WRITTEN[3].fetch_add(1, Relaxed);
  1446. if mode & 4 == 0 {
  1447. return;
  1448. }
  1449. }
  1450. {
  1451. let mut g = guards();
  1452. let guarded = g.protected.range(at / BLOCK..end.div_ceil(BLOCK)).count() as u64;
  1453. if pages {
  1454. WRITTEN[2].fetch_add(guarded, Relaxed);
  1455. }
  1456. if mode & 1 != 0 && guarded != 0 {
  1457. open(&mut g, at, end);
  1458. }
  1459. }
  1460. // A placed texture there changed with no descriptor written.
  1461. crate::descriptor::host::page_written(at, len);
  1462. }
  1463. /// The runtime mapped a view of the physical bytes `[offset, offset + len)`
  1464. /// of `section` (`crate::inplace::title_memory_view`): the view is
  1465. /// writable, so the same bytes guarded at another view must be checked
  1466. /// again - and are, the pages noted written, which also has the next check
  1467. /// guard the new view ([`cover`]).
  1468. pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) {
  1469. if !view_guard() {
  1470. return;
  1471. }
  1472. let mut ranges = crate::inplace::views_of_section(section, offset, len);
  1473. // (A block is noted in `PROTECTED` ahead of the look at its page's views
  1474. // that did not find this one yet.)
  1475. ranges.retain(|&(at, n)| PROTECTED.any(at / BLOCK, (at + n).div_ceil(BLOCK)));
  1476. if ranges.is_empty() {
  1477. return;
  1478. }
  1479. let mut g = guards();
  1480. for &(at, n) in &ranges {
  1481. let blocks: Vec<usize> = g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).copied().collect();
  1482. #[cfg(feature = "diagnostics")]
  1483. ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed);
  1484. unguard(&mut g, &blocks);
  1485. }
  1486. }
  1487. /// The runtime is about to unmap a view of which it maps a part again at
  1488. /// once ([`title_memory_unmapping`] of all of it comes next): the title's
  1489. /// threads may write through that part before we are told of it
  1490. /// ([`views_mapped`]). What is guarded of its pages at other views is opened,
  1491. /// and not guarded again before the change is done ([`Remapping`]).
  1492. pub fn title_memory_splitting(at: usize, len: usize) {
  1493. let others: Vec<usize> = elsewhere(at, len).into_iter().flat_map(|(_, others)| others).collect();
  1494. if others.is_empty() {
  1495. return;
  1496. }
  1497. let mut g = guards();
  1498. for other in others {
  1499. open(&mut g, other, other + BLOCK);
  1500. if CHANGING.get().0 {
  1501. CHANGING.set((true, true));
  1502. g.changing.push((other / BLOCK, other / BLOCK + 1));
  1503. }
  1504. }
  1505. }
  1506. /// Held shared by a read of title memory in place, and alone by the runtime
  1507. /// while it changes what title memory shows.
  1508. ///
  1509. /// The runtime does not change a mapping in one step. To unmap one page of
  1510. /// a view it unmaps the whole view and maps what stays again
  1511. /// (`xmem.rs` `unmap`), and a view it maps is a reservation until the next
  1512. /// call commits it (`map`, then `commit`). For that moment pages the title
  1513. /// never gave up are "reserved, never committed", and a thread reading
  1514. /// them in place takes an access violation: run 71 in `Layout::detile`,
  1515. /// run 74 in the hash before it, both under `Staging::refresh_now`, which
  1516. /// had asked whether the texture was all mapped and been told yes. Asking
  1517. /// cannot help; not changing the mapping while such a read is under way
  1518. /// does.
  1519. static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(());
  1520. /// What the runtime holds while it changes what title memory shows
  1521. /// ([`title_memory_remapping`]).
  1522. pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>);
  1523. impl Drop for Remapping {
  1524. fn drop(&mut self) {
  1525. // The change is done: what is there now may be guarded.
  1526. if CHANGING.replace((false, false)).1 {
  1527. guards().changing.clear();
  1528. }
  1529. CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
  1530. }
  1531. }
  1532. /// How often the runtime began or ended a change of what title memory
  1533. /// shows: odd while one is under way.
  1534. static CHANGES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1535. thread_local! {
  1536. /// This thread holds [`Remapping`]; and put blocks in
  1537. /// [`Guards::changing`].
  1538. static CHANGING: std::cell::Cell<(bool, bool)> = const { std::cell::Cell::new((false, false)) };
  1539. }
  1540. /// For [`again_after_change`]: to be asked before what may fail.
  1541. pub(crate) fn changes() -> u64 {
  1542. CHANGES.load(std::sync::atomic::Ordering::SeqCst)
  1543. }
  1544. /// `f` failed to read or write title memory, at some time since [`changes`]
  1545. /// said `since`. If the runtime changed a mapping in that time, the pages
  1546. /// may have been away for that moment only ([`MAPPING`]): again, when the
  1547. /// change is done. Whether `f` did it.
  1548. pub(crate) fn again_after_change(since: u64, mut f: impl FnMut() -> bool) -> bool {
  1549. let mut since = since;
  1550. for _ in 0..4 {
  1551. let now = change_done();
  1552. if now == since {
  1553. return false;
  1554. }
  1555. since = now;
  1556. if f() {
  1557. return true;
  1558. }
  1559. }
  1560. false
  1561. }
  1562. /// Returns when the change of a mapping that is under way, if one is, is
  1563. /// over (or has been going on for 2 ms): pages it took away for its moment
  1564. /// are back. Another may have begun.
  1565. pub(crate) fn change_over() {
  1566. let now = changes();
  1567. if now.is_multiple_of(2) {
  1568. return;
  1569. }
  1570. let started = std::time::Instant::now();
  1571. while changes() == now && started.elapsed().as_millis() < 2 {
  1572. for _ in 0..50 {
  1573. std::hint::spin_loop();
  1574. }
  1575. }
  1576. }
  1577. /// [`changes`], when no change is under way (or one has been for a second).
  1578. fn change_done() -> u64 {
  1579. let mut tries = 0;
  1580. let mut started = None;
  1581. loop {
  1582. let now = changes();
  1583. if now.is_multiple_of(2) {
  1584. return now;
  1585. }
  1586. tries += 1;
  1587. if tries < 100 {
  1588. std::hint::spin_loop();
  1589. continue;
  1590. }
  1591. if started.get_or_insert_with(std::time::Instant::now).elapsed().as_secs() >= 1 {
  1592. return now;
  1593. }
  1594. // SAFETY: gives the processor to another thread.
  1595. unsafe { windows_sys::Win32::System::Threading::Sleep(u32::from(tries > 200)) };
  1596. }
  1597. }
  1598. /// Faults of title threads that met a change of mapping and went on after
  1599. /// it ([`came_back`]).
  1600. static MET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1601. /// A title thread's access to `at` (`write`: a write) faulted. Whether it
  1602. /// can be made now: if a change of mapping is under way, after it.
  1603. ///
  1604. /// The console changes one page's mapping and no other's. Here the rest of
  1605. /// a view is unmapped and mapped again ([`MAPPING`]), and a title thread that
  1606. /// uses a page of it just then, which the title never gave up, faulted
  1607. /// ("reserved, never committed", or read-only for the moment between our
  1608. /// forgetting a guarded block and its unmapping). It waits here instead.
  1609. /// Memory that is not there with no change under way is not waited for.
  1610. fn came_back(at: usize, write: bool) -> bool {
  1611. let there = || {
  1612. if !write {
  1613. return readable_view(at);
  1614. }
  1615. // (A refresh may have guarded the page that came back.)
  1616. open(&mut guards(), at, at + 1) || writable(at)
  1617. };
  1618. let before = changes();
  1619. if there() || again_after_change(before, there) {
  1620. MET.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1621. return true;
  1622. }
  1623. false
  1624. }
  1625. /// Whether `at` is in a committed page of a view that can be read.
  1626. fn readable_view(at: usize) -> bool {
  1627. use windows_sys::Win32::System::Memory::{
  1628. MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_READONLY, PAGE_READWRITE, VirtualQuery,
  1629. };
  1630. // SAFETY: plain data filled in by the query.
  1631. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  1632. // SAFETY: a valid out pointer of the right size.
  1633. let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
  1634. n != 0
  1635. && info.State == MEM_COMMIT
  1636. && info.Type == MEM_MAPPED
  1637. && matches!(info.Protect, PAGE_READONLY | PAGE_READWRITE)
  1638. }
  1639. /// Title memory that could not be written with what was to go there (what a
  1640. /// shader wrote, a title's copy): counted, and said at the 1st, 2nd, 4th, 8th
  1641. /// and so on. A page the title unmapped loses nothing by it; a page that is
  1642. /// there does.
  1643. pub(crate) fn lost(what: &'static str, at: usize, len: usize) {
  1644. static LOST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1645. let n = LOST.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  1646. if n.is_power_of_two() {
  1647. let there = writable(at);
  1648. tracing::warn!(n, what, at = format_args!("{at:#x}"), len, there, "title memory not written");
  1649. }
  1650. }
  1651. /// The runtime is about to map, unmap or move physical pages of title
  1652. /// memory: until what it returns is dropped, no read of title memory in
  1653. /// place is under way and none begins ([`title_memory_reading`]). Taken
  1654. /// around the whole change, the unmapping and the mapping again.
  1655. pub fn title_memory_remapping() -> Remapping {
  1656. // For the title's own threads ([`came_back`]).
  1657. install();
  1658. let met = MET.load(std::sync::atomic::Ordering::Relaxed);
  1659. if met != 0 {
  1660. static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1661. if met >= 2 * SAID.load(std::sync::atomic::Ordering::Relaxed) {
  1662. SAID.store(met, std::sync::atomic::Ordering::Relaxed);
  1663. tracing::info!(met, "accesses of title threads that waited for a change of mapping");
  1664. }
  1665. }
  1666. let changing = MAPPING.write().unwrap_or_else(|e| e.into_inner());
  1667. CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
  1668. CHANGING.set((true, false));
  1669. Remapping(changing)
  1670. }
  1671. /// What a read of title memory in place holds ([`title_memory_reading`]).
  1672. pub struct Reading(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>);
  1673. /// For reading title memory in place: until what it returns is dropped,
  1674. /// the runtime changes no mapping, so memory found mapped stays mapped.
  1675. /// Not to be taken twice by one thread, nor held across anything that
  1676. /// maps title memory.
  1677. pub fn title_memory_reading() -> Reading {
  1678. Reading(MAPPING.read().unwrap_or_else(|e| e.into_inner()))
  1679. }
  1680. /// [`title_memory_reading`] if it can be had at once: `None` while the
  1681. /// runtime changes a mapping (or waits to), for a caller that has another
  1682. /// way to read and would rather not wait.
  1683. pub fn title_memory_reading_now() -> Option<Reading> {
  1684. match MAPPING.try_read() {
  1685. Ok(guard) => Some(Reading(guard)),
  1686. Err(std::sync::TryLockError::Poisoned(e)) => Some(Reading(e.into_inner())),
  1687. Err(std::sync::TryLockError::WouldBlock) => None,
  1688. }
  1689. }
  1690. /// The runtime mapped title memory `[at, at + len)`: what it shows is new,
  1691. /// so it is no longer guarded (nor known unmapped), and read-write.
  1692. ///
  1693. /// The view is there before we are told of it, and a copy's refresh on
  1694. /// another thread may have guarded its blocks in between (it finds blocks
  1695. /// it knew absent committed, and holds [`GUARDS`], which we wait for).
  1696. /// Forgetting such a block and leaving it read-only would make the title's
  1697. /// next write to it an access violation nobody takes (`on_write` finds it
  1698. /// neither guarded nor writable) and a kernel read into it fail, so the
  1699. /// write access is given back.
  1700. pub fn title_memory_remapped(at: usize, len: usize) {
  1701. open(&mut title_memory_changed(at, len), at, at.saturating_add(len));
  1702. }
  1703. /// The runtime is about to unmap title memory `[at, at + len)`: it is
  1704. /// nothing of ours any more. Its protection goes with it. Until the change
  1705. /// is done ([`Remapping`]) no refresh guards what is there: one that did
  1706. /// before the unmapping would leave the address guarded, clean and known by
  1707. /// its bits ([`PUBLISHED`]) with no view behind it.
  1708. pub fn title_memory_unmapping(at: usize, len: usize) {
  1709. let mut g = title_memory_changed(at, len);
  1710. if CHANGING.get().0 && len != 0 {
  1711. CHANGING.set((true, true));
  1712. let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK));
  1713. match g.changing.last_mut() {
  1714. Some(before) if before.1 == first => before.1 = last,
  1715. _ => g.changing.push((first, last)),
  1716. }
  1717. }
  1718. let blocks: Vec<usize> = g
  1719. .protected
  1720. .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK))
  1721. .copied()
  1722. .collect();
  1723. for block in blocks {
  1724. g.protected.remove(&block);
  1725. g.clean.remove(&block);
  1726. PUBLISHED.clear(block);
  1727. PROTECTED.clear(block);
  1728. }
  1729. }
  1730. /// The title is about to free or decommit memory of its own,
  1731. /// `[at, at + len)`, or with no length the whole allocation at `at`: what
  1732. /// was noted of its blocks (guarded, clean, absent) would be taken for true
  1733. /// of the next memory at the address.
  1734. pub fn title_memory_freed(at: usize, len: usize) {
  1735. let mut g = guards();
  1736. let first = at / BLOCK;
  1737. let noted = [&g.protected, &g.absent, &g.foreign].map(|set| set.range(first..).next());
  1738. let Some(noted) = noted.into_iter().flatten().min().copied() else {
  1739. return;
  1740. };
  1741. let end = if len != 0 {
  1742. at.saturating_add(len).div_ceil(BLOCK)
  1743. } else {
  1744. allocation_end(at, noted * BLOCK).div_ceil(BLOCK)
  1745. };
  1746. if noted >= end {
  1747. return;
  1748. }
  1749. let absent: Vec<usize> = g.absent.range(first..end).copied().collect();
  1750. for block in absent {
  1751. g.absent.remove(&block);
  1752. if g.held.remove(&block) {
  1753. PUBLISHED.clear(block);
  1754. }
  1755. }
  1756. let foreign: Vec<usize> = g.foreign.range(first..end).copied().collect();
  1757. for block in foreign {
  1758. g.foreign.remove(&block);
  1759. }
  1760. // (Memory that is still a view is not freed by that call, which fails:
  1761. // it must not stay read-only.)
  1762. open(&mut g, at, end * BLOCK);
  1763. }
  1764. /// The end of the allocation at `at`, if `inside` lies in it; else `at`.
  1765. fn allocation_end(at: usize, inside: usize) -> usize {
  1766. use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
  1767. let ask = |address: usize| {
  1768. // SAFETY: plain data filled in by the query.
  1769. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  1770. // SAFETY: a valid out pointer of the right size.
  1771. let n = unsafe { VirtualQuery(address as *const _, &mut info, size_of_val(&info)) };
  1772. (n != 0 && info.AllocationBase as usize == at)
  1773. .then(|| (info.BaseAddress as usize).saturating_add(info.RegionSize))
  1774. };
  1775. let mut end = at;
  1776. let mut next = ask(inside.max(at));
  1777. while let Some(to) = next {
  1778. end = to;
  1779. next = ask(to);
  1780. }
  1781. end
  1782. }
  1783. /// Tells what keeps track of what title memory shows; the guards, with no
  1784. /// block of the range known unmapped.
  1785. fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> {
  1786. // A placed texture there arrives, goes or changes with no descriptor
  1787. // written.
  1788. crate::descriptor::host::remapped(at, len);
  1789. // The views the runtime told us of there are no longer what it shows.
  1790. crate::inplace::views_gone(at, len);
  1791. // And nothing stays in place over it.
  1792. crate::inplace::title_memory_freeing(at, len);
  1793. let mut g = guards();
  1794. let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK);
  1795. let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect();
  1796. for block in absent {
  1797. g.absent.remove(&block);
  1798. if g.held.remove(&block) {
  1799. PUBLISHED.clear(block);
  1800. }
  1801. }
  1802. let foreign: Vec<usize> = g.foreign.range(range.clone()).copied().collect();
  1803. for block in foreign {
  1804. g.foreign.remove(&block);
  1805. }
  1806. let aliased: Vec<usize> = g.aliased.range(range).copied().collect();
  1807. for block in aliased {
  1808. g.aliased.remove(&block);
  1809. }
  1810. g
  1811. }
  1812. /// Registers the handler that takes writes to guarded blocks, once, ahead
  1813. /// of the crash reporter's.
  1814. pub(crate) fn install() {
  1815. use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
  1816. use windows_sys::Win32::System::Diagnostics::Debug::{
  1817. AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH,
  1818. EXCEPTION_POINTERS,
  1819. };
  1820. unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 {
  1821. // SAFETY: the system passes the exception being dispatched.
  1822. let r = unsafe { &*(*info).ExceptionRecord };
  1823. const READ: usize = 0;
  1824. const WRITE: usize = 1;
  1825. // A fault of our own copies (`crate::safecopy`): whatever it is, if
  1826. // it is not a block we guard, the copy fails and goes on from there.
  1827. let ours = crate::safecopy::failing_exit(r.ExceptionAddress as usize);
  1828. let fail = |exit: usize| {
  1829. // SAFETY: the context the system passes, to go on from.
  1830. unsafe { (*(*info).ContextRecord).Rip = exit as u64 };
  1831. EXCEPTION_CONTINUE_EXECUTION
  1832. };
  1833. if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS
  1834. || r.NumberParameters < 2
  1835. || r.ExceptionInformation[0] != WRITE
  1836. {
  1837. return match ours {
  1838. Some(exit) => fail(exit),
  1839. None if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS
  1840. && r.NumberParameters >= 2
  1841. && r.ExceptionInformation[0] == READ
  1842. && came_back(r.ExceptionInformation[1], false) =>
  1843. {
  1844. EXCEPTION_CONTINUE_EXECUTION
  1845. }
  1846. None => EXCEPTION_CONTINUE_SEARCH,
  1847. };
  1848. }
  1849. let at = r.ExceptionInformation[1];
  1850. // Held across both checks: another thread may have opened the block
  1851. // since this one faulted, and a copy may have guarded it again since
  1852. // (then it is ours again, not read-only for some other reason).
  1853. let mut g = guards();
  1854. if open(&mut g, at, at + 1) {
  1855. #[cfg(feature = "diagnostics")]
  1856. crate::copystat::add(crate::copystat::C::GuardFaults, 1);
  1857. return EXCEPTION_CONTINUE_EXECUTION;
  1858. }
  1859. if writable(at) {
  1860. return EXCEPTION_CONTINUE_EXECUTION;
  1861. }
  1862. // (The runtime wants the guards to end a change.)
  1863. drop(g);
  1864. match ours {
  1865. Some(exit) => fail(exit),
  1866. None if came_back(at, true) => EXCEPTION_CONTINUE_EXECUTION,
  1867. None => EXCEPTION_CONTINUE_SEARCH,
  1868. }
  1869. }
  1870. static ONCE: std::sync::Once = std::sync::Once::new();
  1871. // SAFETY: the handler only touches our guard state and protections.
  1872. ONCE.call_once(|| unsafe {
  1873. AddVectoredExceptionHandler(1, Some(on_write));
  1874. });
  1875. }
  1876. /// Whether `at` is committed read-write memory now.
  1877. fn writable(at: usize) -> bool {
  1878. use windows_sys::Win32::System::Memory::{
  1879. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery,
  1880. };
  1881. // SAFETY: plain data filled in by the query.
  1882. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  1883. // SAFETY: a valid out pointer of the right size.
  1884. let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
  1885. n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE
  1886. }
  1887. #[cfg(test)]
  1888. mod tests {
  1889. use super::*;
  1890. use windows_sys::Win32::System::Memory::{
  1891. MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree,
  1892. };
  1893. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  1894. #[test]
  1895. fn written_pages_are_reported_to_every_asker() {
  1896. // SAFETY: a fresh write-watched allocation, freed at the end.
  1897. let p = unsafe {
  1898. VirtualAlloc(
  1899. std::ptr::null(),
  1900. 4 * PAGE,
  1901. MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
  1902. PAGE_READWRITE,
  1903. )
  1904. } as usize;
  1905. assert_ne!(p, 0);
  1906. let (start, end) = (p, p + 4 * PAGE);
  1907. // The journal may hold pages of another test's memory that was here.
  1908. let (none, before) = writes(start, end, false).expect("watched");
  1909. assert!(before.iter().all(|&(_, w)| w < none), "{before:?}");
  1910. // SAFETY: committed pages of ours.
  1911. unsafe { ((p + PAGE + 8) as *mut u8).write(1) };
  1912. let (now, after) = writes(start, end, false).expect("watched");
  1913. let new = |w: Vec<(usize, u64)>| w.into_iter().filter(|w| w.1 > none).collect::<Vec<_>>();
  1914. assert_eq!(new(after), [(p / PAGE + 1, now)]);
  1915. // Another asker after the kernel's bit was cleared still sees it.
  1916. let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched");
  1917. assert!(later > now);
  1918. assert_eq!(new(again), [(p / PAGE + 1, now)]);
  1919. let mut plain = vec![0u8; PAGE];
  1920. assert!(
  1921. writes(
  1922. plain.as_mut_ptr() as usize,
  1923. plain.as_ptr() as usize + PAGE,
  1924. true
  1925. )
  1926. .is_none()
  1927. );
  1928. // SAFETY: our allocation.
  1929. unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
  1930. }
  1931. /// A kernel read into a guarded view block fails; opened first, it
  1932. /// lands and the block counts as written.
  1933. #[test]
  1934. fn kernel_reads_into_guarded_blocks_after_opening() {
  1935. use std::io::{Read, Seek, Write};
  1936. use windows_sys::Win32::System::Memory::{
  1937. CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
  1938. };
  1939. // SAFETY: a pagefile section of two blocks, mapped read-write.
  1940. let view = unsafe {
  1941. let section = CreateFileMappingW(
  1942. -1isize as _,
  1943. std::ptr::null(),
  1944. PAGE_READWRITE,
  1945. 0,
  1946. (2 * BLOCK) as u32,
  1947. std::ptr::null(),
  1948. );
  1949. assert!(!section.is_null());
  1950. MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize
  1951. };
  1952. assert_ne!(view, 0);
  1953. assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only
  1954. let mut file = tempfile::tempfile().unwrap();
  1955. file.write_all(b"from the disk").unwrap();
  1956. // `ReadFile` inside: the kernel writes the view.
  1957. let read = |file: &mut std::fs::File| {
  1958. file.rewind().unwrap();
  1959. // SAFETY: 13 bytes of our view, nothing else refers to them.
  1960. let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) };
  1961. file.read(into).is_ok_and(|n| n == 13)
  1962. };
  1963. assert!(
  1964. !read(&mut file),
  1965. "the kernel does not fault into our handler"
  1966. );
  1967. writing(view + 100, 13);
  1968. assert!(read(&mut file));
  1969. // SAFETY: the bytes just read.
  1970. let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) };
  1971. assert_eq!(landed, b"from the disk");
  1972. assert_eq!(
  1973. guard(view, view + 2 * BLOCK),
  1974. Some((view / PAGE..view / PAGE + 1).collect())
  1975. );
  1976. // Before the view goes, as the runtime does: the address may be
  1977. // another test's the moment it is free.
  1978. title_memory_unmapping(view, 2 * BLOCK);
  1979. // SAFETY: our view.
  1980. unsafe {
  1981. UnmapViewOfFile(
  1982. windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS {
  1983. Value: view as *mut _,
  1984. },
  1985. )
  1986. };
  1987. }
  1988. /// A placeholder of `blocks` blocks, each its own.
  1989. fn placeholder(blocks: usize) -> usize {
  1990. use windows_sys::Win32::System::Memory::{
  1991. MEM_PRESERVE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, VirtualAlloc2,
  1992. };
  1993. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  1994. // SAFETY: a fresh placeholder, split.
  1995. unsafe {
  1996. let p = VirtualAlloc2(
  1997. GetCurrentProcess(),
  1998. std::ptr::null(),
  1999. blocks * BLOCK,
  2000. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  2001. PAGE_NOACCESS,
  2002. std::ptr::null_mut(),
  2003. 0,
  2004. ) as usize;
  2005. assert_ne!(p, 0);
  2006. for block in 0..blocks - 1 {
  2007. assert_ne!(
  2008. VirtualFree((p + block * BLOCK) as *mut _, BLOCK, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER),
  2009. 0
  2010. );
  2011. }
  2012. p
  2013. }
  2014. }
  2015. /// Private memory of `protect` in place of the placeholder of one block.
  2016. fn private_at(at: usize, protect: u32) {
  2017. use windows_sys::Win32::System::Memory::{MEM_REPLACE_PLACEHOLDER, VirtualAlloc2};
  2018. // SAFETY: our placeholder.
  2019. let got = unsafe {
  2020. VirtualAlloc2(
  2021. windows_sys::Win32::System::Threading::GetCurrentProcess(),
  2022. at as *const _,
  2023. BLOCK,
  2024. MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER,
  2025. protect,
  2026. std::ptr::null_mut(),
  2027. 0,
  2028. )
  2029. };
  2030. assert_eq!(got as usize, at);
  2031. }
  2032. fn protection(at: usize) -> u32 {
  2033. use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
  2034. // SAFETY: plain data the query fills in.
  2035. unsafe {
  2036. let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
  2037. VirtualQuery(at as *const _, &mut info, size_of_val(&info));
  2038. info.Protect
  2039. }
  2040. }
  2041. /// A refresh between the opening of a kernel read's destination and the
  2042. /// read itself leaves it open: the read lands, and is seen.
  2043. #[test]
  2044. fn a_refresh_leaves_open_what_the_kernel_is_writing() {
  2045. use std::io::{Read, Seek, Write};
  2046. use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile};
  2047. // SAFETY: a pagefile section of two blocks, mapped read-write.
  2048. let view = unsafe {
  2049. let section = CreateFileMappingW(
  2050. -1isize as _,
  2051. std::ptr::null(),
  2052. PAGE_READWRITE,
  2053. 0,
  2054. (2 * BLOCK) as u32,
  2055. std::ptr::null(),
  2056. );
  2057. assert!(!section.is_null());
  2058. MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK)
  2059. };
  2060. let at = view.Value as usize;
  2061. assert_ne!(at, 0);
  2062. let pages = |block: usize| at / PAGE + block..at / PAGE + block + 1;
  2063. assert!(writes(at, at + 2 * BLOCK, true).is_some());
  2064. assert!(published(at, at + 2 * BLOCK) || !light());
  2065. let mut file = tempfile::tempfile().unwrap();
  2066. file.write_all(b"from the disk").unwrap();
  2067. file.rewind().unwrap();
  2068. let writing = kernel_writing(at + 100, 13);
  2069. // The refresh: the block being written is new to it every time, and
  2070. // stays open; the other is as it was.
  2071. for _ in 0..2 {
  2072. assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect()));
  2073. let (now, found) = writes(at, at + BLOCK, true).expect("a view");
  2074. assert!(found.contains(&(at / PAGE, now)));
  2075. assert!(writable(at) && !writable(at + BLOCK));
  2076. assert!(!published(at, at + BLOCK));
  2077. }
  2078. // SAFETY: 13 bytes of our view, nothing else refers to them.
  2079. let into = unsafe { std::slice::from_raw_parts_mut((at + 100) as *mut u8, 13) };
  2080. assert_eq!(file.read(into).expect("the kernel's write lands"), 13);
  2081. assert_eq!(into, b"from the disk");
  2082. drop(writing);
  2083. // Seen by the next refresh, and guarded again.
  2084. assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect()));
  2085. assert!(!writable(at));
  2086. assert_eq!(guard(at, at + 2 * BLOCK), Some(Vec::new()));
  2087. title_memory_unmapping(at, 2 * BLOCK);
  2088. // SAFETY: our view.
  2089. unsafe { UnmapViewOfFile(view) };
  2090. }
  2091. /// A hole the kernel is to write is no known hole meanwhile, nor is one
  2092. /// the runtime has begun to change; after that it is again.
  2093. #[test]
  2094. fn what_is_left_alone_is_no_known_hole() {
  2095. let p = placeholder(3);
  2096. let known = |block: usize| published(p + block * BLOCK, p + (block + 1) * BLOCK);
  2097. let ask = || writes(p, p + 3 * BLOCK, true).expect("as a view");
  2098. ask();
  2099. let holes = known_holes();
  2100. assert!((0..3).all(known) == holes);
  2101. let writing = kernel_writing(p + BLOCK + 5, 100);
  2102. for _ in 0..2 {
  2103. assert!(known(0) == holes && !known(1) && known(2) == holes);
  2104. let (now, written) = ask();
  2105. assert!(written.contains(&(p / PAGE + 1, now)));
  2106. assert!(written.iter().all(|w| w.0 == p / PAGE + 1 || w.1 < now));
  2107. }
  2108. assert!(!guards().held.contains(&(p / BLOCK + 1)));
  2109. drop(writing);
  2110. ask();
  2111. assert!((0..3).all(known) == holes);
  2112. {
  2113. let _changing = title_memory_remapping();
  2114. title_memory_unmapping(p, BLOCK);
  2115. ask();
  2116. assert!(!known(0) && !guards().held.contains(&(p / BLOCK)));
  2117. }
  2118. ask();
  2119. assert!((0..3).all(known) == holes);
  2120. title_memory_freed(p, BLOCK);
  2121. assert!(!known(0) && !guards().held.contains(&(p / BLOCK)));
  2122. title_memory_unmapping(p, 3 * BLOCK);
  2123. // SAFETY: our placeholders.
  2124. unsafe {
  2125. for block in 0..3 {
  2126. VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
  2127. }
  2128. }
  2129. }
  2130. /// A refresh during a change of mapping guards nothing the runtime has
  2131. /// begun to unmap: no note of it stays behind.
  2132. #[test]
  2133. fn nothing_is_guarded_between_our_forgetting_it_and_its_unmapping() {
  2134. use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile};
  2135. // SAFETY: a pagefile section of a block, mapped read-write.
  2136. let view = unsafe {
  2137. let section =
  2138. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null());
  2139. assert!(!section.is_null());
  2140. MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK)
  2141. };
  2142. let at = view.Value as usize;
  2143. assert_ne!(at, 0);
  2144. assert!(writes(at, at + BLOCK, true).is_some());
  2145. let changing = title_memory_remapping();
  2146. title_memory_unmapping(at, BLOCK);
  2147. assert!(writes(at, at + BLOCK, true).is_some());
  2148. {
  2149. let g = guards();
  2150. assert!(!g.protected.contains(&(at / BLOCK)) && !g.clean.contains(&(at / BLOCK)));
  2151. }
  2152. assert!(!published(at, at + BLOCK));
  2153. // SAFETY: our view.
  2154. unsafe { UnmapViewOfFile(view) };
  2155. drop(changing);
  2156. assert!(!guards().left_alone(at / BLOCK));
  2157. }
  2158. /// Memory at an address where blocks were guarded or absent is not
  2159. /// taken for them: code stays code, private memory is not guarded.
  2160. #[test]
  2161. fn other_memory_at_a_guarded_address_keeps_its_protection() {
  2162. use windows_sys::Win32::System::Memory::{
  2163. CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, MapViewOfFile3, PAGE_EXECUTE_READ,
  2164. PAGE_EXECUTE_READWRITE, UnmapViewOfFile2,
  2165. };
  2166. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  2167. let p = placeholder(3);
  2168. // SAFETY: a section's block in place of the first placeholder.
  2169. let view = unsafe {
  2170. let section =
  2171. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null());
  2172. assert!(!section.is_null());
  2173. MapViewOfFile3(
  2174. section,
  2175. GetCurrentProcess(),
  2176. p as *const _,
  2177. 0,
  2178. BLOCK,
  2179. MEM_REPLACE_PLACEHOLDER,
  2180. PAGE_READWRITE,
  2181. std::ptr::null_mut(),
  2182. 0,
  2183. )
  2184. };
  2185. assert_eq!(view.Value as usize, p);
  2186. // One block guarded, two absent.
  2187. assert_eq!(guard(p, p + 3 * BLOCK).map(|w| w.len()), Some(3));
  2188. // Not told of what comes: the view goes, code is there; and private
  2189. // memory in the holes.
  2190. // SAFETY: our view.
  2191. assert_ne!(unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }, 0);
  2192. private_at(p, PAGE_EXECUTE_READ);
  2193. private_at(p + BLOCK, PAGE_READWRITE);
  2194. private_at(p + 2 * BLOCK, PAGE_EXECUTE_READWRITE);
  2195. // (The runtime's allocations it tells of, or the holes stay known.)
  2196. title_memory_allocated(p + BLOCK, 2 * BLOCK);
  2197. let as_made = || {
  2198. assert_eq!(protection(p), PAGE_EXECUTE_READ);
  2199. assert_eq!(protection(p + BLOCK), PAGE_READWRITE);
  2200. assert_eq!(protection(p + 2 * BLOCK), PAGE_EXECUTE_READWRITE);
  2201. };
  2202. let holes = [p / PAGE + 1, p / PAGE + 2];
  2203. for _ in 0..2 {
  2204. let written = guard(p, p + 3 * BLOCK).expect("as a view");
  2205. assert!(holes.iter().all(|page| written.contains(page)), "copied every time");
  2206. as_made();
  2207. let g = guards();
  2208. assert!(holes.iter().all(|block| !g.held.contains(block) && !g.absent.contains(block)));
  2209. }
  2210. writing(p, BLOCK);
  2211. as_made();
  2212. title_memory_unmapping(p, 3 * BLOCK);
  2213. // SAFETY: our allocations.
  2214. unsafe {
  2215. for block in 0..3 {
  2216. VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
  2217. }
  2218. }
  2219. }
  2220. /// Memory the title frees leaves no note of its blocks, whether it names
  2221. /// its length or the allocation.
  2222. #[test]
  2223. fn freed_memory_leaves_no_notes() {
  2224. let p = placeholder(3);
  2225. let noted = |block: usize| {
  2226. let g = guards();
  2227. let block = p / BLOCK + block;
  2228. g.protected.contains(&block) || g.clean.contains(&block) || g.absent.contains(&block)
  2229. };
  2230. assert!(guard(p, p + 3 * BLOCK).is_some());
  2231. assert!(noted(0) && noted(1) && noted(2));
  2232. // The middle allocation.
  2233. title_memory_freed(p + BLOCK, 0);
  2234. assert!(noted(0) && !noted(1) && noted(2));
  2235. title_memory_freed(p, BLOCK);
  2236. assert!(!noted(0) && noted(2));
  2237. // Nothing noted there: nothing to do, and nothing beside it.
  2238. title_memory_freed(p + BLOCK, 0);
  2239. assert!(noted(2));
  2240. title_memory_freed(p + 2 * BLOCK, 0);
  2241. assert!(!noted(2));
  2242. // SAFETY: our placeholders.
  2243. unsafe {
  2244. for block in 0..3 {
  2245. VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
  2246. }
  2247. }
  2248. }
  2249. /// A write between another thread's asking about a range and the second
  2250. /// part of a submission's one asking is later than what that thread
  2251. /// copied.
  2252. #[test]
  2253. fn the_rest_of_the_one_asking_has_a_number_of_its_own() {
  2254. // SAFETY: a fresh write-watched allocation, freed at the end.
  2255. let p = unsafe {
  2256. VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)
  2257. } as usize;
  2258. assert_ne!(p, 0);
  2259. // One range: `ask_ahead` leaves it.
  2260. let ranges = [(p, p + 4 * PAGE)];
  2261. ask_ahead(&ranges);
  2262. let (copied, _) = writes(p, p + 4 * PAGE, false).expect("watched");
  2263. // SAFETY: committed pages of ours.
  2264. unsafe { ((p + PAGE) as *mut u8).write_volatile(1) };
  2265. ask_rest(&ranges);
  2266. let last = journal().written.get(&(p / PAGE + 1)).copied();
  2267. ask_once_end();
  2268. assert!(last.is_some_and(|last| last > copied), "{last:?} is not after {copied}");
  2269. // SAFETY: our allocation.
  2270. unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
  2271. }
  2272. /// The runtime maps a view and then tells us; a copy's refresh on another
  2273. /// thread can guard it in between. Told, it is the title's to write: a
  2274. /// block left read-only and forgotten would be an access violation in
  2275. /// title code.
  2276. #[test]
  2277. fn a_block_guarded_before_we_were_told_of_its_view_can_be_written() {
  2278. use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
  2279. use windows_sys::Win32::System::Memory::{
  2280. CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
  2281. };
  2282. // SAFETY: a pagefile section of two blocks, mapped read-write; the
  2283. // view holds it.
  2284. let view = unsafe {
  2285. let section = CreateFileMappingW(
  2286. INVALID_HANDLE_VALUE,
  2287. std::ptr::null(),
  2288. PAGE_READWRITE,
  2289. 0,
  2290. (2 * BLOCK) as u32,
  2291. std::ptr::null(),
  2292. );
  2293. assert!(!section.is_null());
  2294. let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK);
  2295. CloseHandle(section);
  2296. view
  2297. };
  2298. let at = view.Value as usize;
  2299. assert_ne!(at, 0);
  2300. // The refresh, then the runtime's word.
  2301. assert!(guard(at, at + 2 * BLOCK).is_some());
  2302. assert!(!writable(at) && !writable(at + BLOCK));
  2303. title_memory_remapped(at, 2 * BLOCK);
  2304. assert!(writable(at) && writable(at + BLOCK));
  2305. // SAFETY: inside the view; a fault would end the process.
  2306. unsafe { ((at + 8) as *mut u8).write_volatile(1) };
  2307. // Looked at again as new, and guarded again.
  2308. assert_eq!(
  2309. guard(at, at + 2 * BLOCK),
  2310. Some((at / PAGE..at / PAGE + 2).collect())
  2311. );
  2312. assert!(!writable(at));
  2313. title_memory_unmapping(at, 2 * BLOCK);
  2314. // SAFETY: our view.
  2315. unsafe { UnmapViewOfFile(view) };
  2316. }
  2317. #[test]
  2318. fn writes_in_partly_committed_view_blocks_are_reported() {
  2319. use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
  2320. use windows_sys::Win32::System::Memory::{
  2321. CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile,
  2322. SEC_RESERVE, UnmapViewOfFile,
  2323. };
  2324. const SIZE: usize = 3 * BLOCK;
  2325. struct View(MEMORY_MAPPED_VIEW_ADDRESS);
  2326. impl Drop for View {
  2327. fn drop(&mut self) {
  2328. title_memory_unmapping(self.0.Value as usize, SIZE);
  2329. // SAFETY: our view is still mapped.
  2330. unsafe { UnmapViewOfFile(self.0) };
  2331. }
  2332. }
  2333. // SAFETY: a new reserved pagefile section. The view holds its own
  2334. // reference after we close the handle, including on assertion failure.
  2335. let view = unsafe {
  2336. let section = CreateFileMappingW(
  2337. INVALID_HANDLE_VALUE,
  2338. std::ptr::null(),
  2339. PAGE_READWRITE | SEC_RESERVE,
  2340. 0,
  2341. SIZE as u32,
  2342. std::ptr::null(),
  2343. );
  2344. assert!(!section.is_null());
  2345. let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, SIZE);
  2346. CloseHandle(section);
  2347. assert!(!view.Value.is_null());
  2348. View(view)
  2349. };
  2350. let start = view.0.Value as usize;
  2351. let commit = |at: usize, len| {
  2352. // SAFETY: these pages belong to our reserved view.
  2353. let committed = unsafe { VirtualAlloc(at as _, len, MEM_COMMIT, PAGE_READWRITE) };
  2354. assert_eq!(committed as usize, at);
  2355. };
  2356. let early = start + BLOCK + 3 * KERNEL_PAGE;
  2357. let late = start + 2 * BLOCK + 3 * KERNEL_PAGE;
  2358. commit(start, BLOCK);
  2359. commit(early, KERNEL_PAGE);
  2360. let refresh = || guard(start, start + SIZE).unwrap();
  2361. assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]);
  2362. // The last block is still entirely reserved.
  2363. assert!(!refresh().contains(&(late / PAGE)));
  2364. commit(late, KERNEL_PAGE); // Ordinary commit, without a runtime mapping notification.
  2365. for at in [early, late] {
  2366. assert!(writable(at));
  2367. // SAFETY: each address is inside its committed read-write page.
  2368. unsafe { (at as *mut u8).write_volatile(1) };
  2369. }
  2370. assert_eq!(refresh(), [early / PAGE, late / PAGE]);
  2371. }
  2372. /// A range of view memory whose first block is not mapped is a view
  2373. /// all the same: its blocks are reported once, then the ones written
  2374. /// or mapped since.
  2375. #[test]
  2376. fn a_range_that_begins_in_an_unmapped_block_is_guarded() {
  2377. use windows_sys::Win32::System::Memory::{
  2378. CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER,
  2379. MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2,
  2380. VirtualAlloc2,
  2381. };
  2382. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  2383. // SAFETY: a fresh placeholder of three blocks and a pagefile
  2384. // section of three; the middle block is mapped first.
  2385. let (p, section) = unsafe {
  2386. let p = VirtualAlloc2(
  2387. GetCurrentProcess(),
  2388. std::ptr::null(),
  2389. 3 * BLOCK,
  2390. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  2391. PAGE_NOACCESS,
  2392. std::ptr::null_mut(),
  2393. 0,
  2394. ) as usize;
  2395. assert_ne!(p, 0);
  2396. let section = CreateFileMappingW(
  2397. -1isize as _,
  2398. std::ptr::null(),
  2399. PAGE_READWRITE,
  2400. 0,
  2401. (3 * BLOCK) as u32,
  2402. std::ptr::null(),
  2403. );
  2404. assert!(!section.is_null());
  2405. (p, section)
  2406. };
  2407. let map = |block: usize| {
  2408. // SAFETY: splits the placeholder at the block and maps the
  2409. // section's block there.
  2410. let view = unsafe {
  2411. VirtualFree(
  2412. (p + block * BLOCK) as *mut _,
  2413. BLOCK,
  2414. MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
  2415. );
  2416. MapViewOfFile3(
  2417. section,
  2418. GetCurrentProcess(),
  2419. (p + block * BLOCK) as *const _,
  2420. (block * BLOCK) as u64,
  2421. BLOCK,
  2422. MEM_REPLACE_PLACEHOLDER,
  2423. PAGE_READWRITE,
  2424. std::ptr::null_mut(),
  2425. 0,
  2426. )
  2427. };
  2428. assert_eq!(view.Value as usize, p + block * BLOCK);
  2429. view
  2430. };
  2431. let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE;
  2432. let all: Vec<usize> = (0..3).flat_map(pages).collect();
  2433. // Nothing mapped at all: a view with every block absent.
  2434. assert!(is_view(p, p + 3 * BLOCK));
  2435. let middle = map(1);
  2436. title_memory_remapped(p + BLOCK, BLOCK);
  2437. // The range begins in the placeholder, its middle block is a view.
  2438. assert!(is_view(p, p + 3 * BLOCK));
  2439. assert_eq!(guard(p, p + 3 * BLOCK), Some(all));
  2440. assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since");
  2441. // SAFETY: inside the mapped middle block.
  2442. unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) };
  2443. assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
  2444. let first = map(0);
  2445. title_memory_remapped(p, BLOCK);
  2446. assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect()));
  2447. assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
  2448. // Memory of ours that is no view stays none.
  2449. let mut local = [0u8; 16];
  2450. let at = local.as_mut_ptr() as usize;
  2451. assert!(!is_view(at, at + local.len()));
  2452. title_memory_unmapping(p, 3 * BLOCK);
  2453. // SAFETY: our views and placeholder.
  2454. unsafe {
  2455. UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
  2456. UnmapViewOfFile2(GetCurrentProcess(), middle, MEM_PRESERVE_PLACEHOLDER);
  2457. for block in 0..3 {
  2458. VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
  2459. }
  2460. windows_sys::Win32::Foundation::CloseHandle(section);
  2461. }
  2462. }
  2463. /// Blocks of a placeholder between views are reported once, then not
  2464. /// again (they cannot be guarded) until the runtime maps them.
  2465. #[test]
  2466. fn unmapped_blocks_are_reported_once_until_mapped() {
  2467. use windows_sys::Win32::System::Memory::{
  2468. CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER,
  2469. MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2,
  2470. VirtualAlloc2,
  2471. };
  2472. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  2473. // SAFETY: a fresh placeholder of three blocks and a pagefile
  2474. // section of two; block 0 shows the section's first block, as the
  2475. // runtime maps physical pages.
  2476. let (p, section) = unsafe {
  2477. let p = VirtualAlloc2(
  2478. GetCurrentProcess(),
  2479. std::ptr::null(),
  2480. 3 * BLOCK,
  2481. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  2482. PAGE_NOACCESS,
  2483. std::ptr::null_mut(),
  2484. 0,
  2485. ) as usize;
  2486. assert_ne!(p, 0);
  2487. let section = CreateFileMappingW(
  2488. -1isize as _,
  2489. std::ptr::null(),
  2490. PAGE_READWRITE,
  2491. 0,
  2492. (2 * BLOCK) as u32,
  2493. std::ptr::null(),
  2494. );
  2495. assert!(!section.is_null());
  2496. (p, section)
  2497. };
  2498. let map = |block: usize| {
  2499. // SAFETY: splits the placeholder at the block and maps the
  2500. // section's block there.
  2501. let view = unsafe {
  2502. VirtualFree(
  2503. (p + block * BLOCK) as *mut _,
  2504. BLOCK,
  2505. MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
  2506. );
  2507. MapViewOfFile3(
  2508. section,
  2509. GetCurrentProcess(),
  2510. (p + block * BLOCK) as *const _,
  2511. (block * BLOCK) as u64,
  2512. BLOCK,
  2513. MEM_REPLACE_PLACEHOLDER,
  2514. PAGE_READWRITE,
  2515. std::ptr::null_mut(),
  2516. 0,
  2517. )
  2518. };
  2519. assert_eq!(view.Value as usize, p + block * BLOCK);
  2520. view
  2521. };
  2522. let first = map(0);
  2523. let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE;
  2524. let all: Vec<usize> = (0..3).flat_map(pages).collect();
  2525. assert_eq!(guard(p, p + 3 * BLOCK), Some(all));
  2526. assert_eq!(
  2527. guard(p, p + 3 * BLOCK),
  2528. Some(Vec::new()),
  2529. "nothing written since"
  2530. );
  2531. let second = map(1);
  2532. title_memory_remapped(p + BLOCK, BLOCK);
  2533. assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
  2534. assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
  2535. title_memory_unmapping(p, 3 * BLOCK);
  2536. // SAFETY: our views and placeholder.
  2537. unsafe {
  2538. UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
  2539. UnmapViewOfFile2(GetCurrentProcess(), second, MEM_PRESERVE_PLACEHOLDER);
  2540. for block in 0..3 {
  2541. VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
  2542. }
  2543. windows_sys::Win32::Foundation::CloseHandle(section);
  2544. }
  2545. }
  2546. /// A pagefile section mapped twice: two views of the same physical
  2547. /// pages, the second left for the test; the section handle, the two
  2548. /// addresses.
  2549. fn two_views(bytes: usize) -> (usize, usize, usize) {
  2550. use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
  2551. use windows_sys::Win32::System::Memory::{
  2552. CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile,
  2553. };
  2554. // SAFETY: a fresh pagefile section, mapped twice; the views keep
  2555. // the section alive and the handle is closed by the caller.
  2556. unsafe {
  2557. let section = CreateFileMappingW(
  2558. INVALID_HANDLE_VALUE,
  2559. std::ptr::null(),
  2560. PAGE_READWRITE,
  2561. 0,
  2562. bytes as u32,
  2563. std::ptr::null(),
  2564. );
  2565. assert!(!section.is_null());
  2566. let one = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize;
  2567. let two = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize;
  2568. assert_ne!(one, 0);
  2569. assert_ne!(two, 0);
  2570. crate::inplace::title_memory_view(one, bytes, section as usize, 0);
  2571. crate::inplace::title_memory_view(two, bytes, section as usize, 0);
  2572. (section as usize, one, two)
  2573. }
  2574. }
  2575. /// The section of [`two_views`] is closed and its views unmapped; the
  2576. /// guard is told they are gone first.
  2577. fn drop_views(section: usize, views: &[usize], bytes: usize) {
  2578. use windows_sys::Win32::Foundation::CloseHandle;
  2579. use windows_sys::Win32::System::Memory::{MEMORY_MAPPED_VIEW_ADDRESS, UnmapViewOfFile};
  2580. for &view in views {
  2581. title_memory_remapped(view, bytes);
  2582. // SAFETY: a view of the section mapped by `two_views`.
  2583. unsafe {
  2584. UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
  2585. Value: view as *mut _,
  2586. })
  2587. };
  2588. }
  2589. // SAFETY: the section's last reference.
  2590. unsafe { CloseHandle(section as *mut std::ffi::c_void) };
  2591. }
  2592. /// The title wrote the pages of a guarded texture through another view
  2593. /// of them: the fault at that view is the guard's to see, and the
  2594. /// guarded view's next check reports the pages written.
  2595. #[test]
  2596. fn a_write_through_another_view_is_reported_at_the_guarded_one() {
  2597. const SIZE: usize = 2 * BLOCK;
  2598. let (section, guarded, other) = two_views(SIZE);
  2599. let pages = |block: usize| (guarded + block * BLOCK) / PAGE;
  2600. // The first check takes it in (and every view of its pages).
  2601. assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
  2602. assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet");
  2603. // Writing through the other view faults into the handler, which
  2604. // opens that view and the guarded one: the next check sees it.
  2605. // SAFETY: the second view, read-write once the handler has opened it.
  2606. unsafe { ((other + BLOCK + 8) as *mut u8).write(1) };
  2607. assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)]));
  2608. assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()));
  2609. drop_views(section, &[guarded, other], SIZE);
  2610. }
  2611. /// A view of guarded pages is mapped anew: it is writable, so the
  2612. /// guarded view checks its pages again (and guards the new view).
  2613. #[test]
  2614. fn a_view_mapped_beside_a_guarded_one_makes_it_check_again() {
  2615. const SIZE: usize = 2 * BLOCK;
  2616. let (section, guarded, other) = two_views(SIZE);
  2617. let pages = |block: usize| (guarded + block * BLOCK) / PAGE;
  2618. assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
  2619. assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet");
  2620. title_memory_remapped(other, SIZE);
  2621. crate::inplace::title_memory_view(other, SIZE, section, 0);
  2622. assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
  2623. assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()));
  2624. drop_views(section, &[guarded, other], SIZE);
  2625. }
  2626. /// A write of the runtime's own, told at one view of the pages
  2627. /// (`writing`): the other views' next checks report the pages written.
  2628. #[test]
  2629. fn a_write_told_at_one_view_is_reported_at_the_others() {
  2630. const SIZE: usize = 2 * BLOCK;
  2631. let (section, guarded, other) = two_views(SIZE);
  2632. let pages = |block: usize| (guarded + block * BLOCK) / PAGE;
  2633. assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
  2634. assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet");
  2635. writing(other + BLOCK, BLOCK);
  2636. assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)]));
  2637. assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()));
  2638. // Half a page and the next: both blocks, not just the first's.
  2639. writing(other + BLOCK / 2, BLOCK);
  2640. assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)]));
  2641. drop_views(section, &[guarded, other], SIZE);
  2642. }
  2643. /// Both views of the pages are checked, each for a copy of its own
  2644. /// (the title shows one physical page at several addresses, and each
  2645. /// address has its host copy): a write through either is reported at
  2646. /// both, whichever is checked first. Guarding the pages for the first
  2647. /// view's check must not note the second view clean, or its copy would
  2648. /// keep the bytes from before the write.
  2649. #[test]
  2650. fn a_write_is_reported_at_every_checked_view() {
  2651. const SIZE: usize = 2 * BLOCK;
  2652. let (section, one, two) = two_views(SIZE);
  2653. let pages = |view: usize, block: usize| (view + block * BLOCK) / PAGE;
  2654. assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0), pages(one, 1)]));
  2655. assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0), pages(two, 1)]), "the second view's first check");
  2656. assert_eq!(guard(one, one + SIZE), Some(Vec::new()), "nothing written yet");
  2657. assert_eq!(guard(two, two + SIZE), Some(Vec::new()), "nothing written yet");
  2658. // SAFETY: the second view, read-write once the handler has opened it.
  2659. unsafe { ((two + BLOCK + 8) as *mut u8).write(1) };
  2660. assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 1)]));
  2661. assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 1)]), "written through this view, checked second");
  2662. // SAFETY: the first view, as above.
  2663. unsafe { ((one + 8) as *mut u8).write(1) };
  2664. assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0)]));
  2665. assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0)]), "written through this view, checked second");
  2666. assert_eq!(guard(one, one + SIZE), Some(Vec::new()));
  2667. assert_eq!(guard(two, two + SIZE), Some(Vec::new()));
  2668. drop_views(section, &[one, two], SIZE);
  2669. }
  2670. /// What is known of a block by its bit is so at every view of its page:
  2671. /// the write through one takes the bits of all.
  2672. #[test]
  2673. fn bits_go_at_every_view() {
  2674. const SIZE: usize = 2 * BLOCK;
  2675. let (section, one, two) = two_views(SIZE);
  2676. let ask = |at: usize| writes(at, at + SIZE, true).expect("a view");
  2677. for at in [one, two, one, two] {
  2678. ask(at);
  2679. }
  2680. assert!(published(one, one + SIZE) && published(two, two + SIZE));
  2681. let (before, _) = ask(two);
  2682. // SAFETY: the first view, opened by the handler.
  2683. unsafe { ((one + BLOCK + 8) as *mut u8).write(1) };
  2684. assert!(published(one, one + BLOCK) && published(two, two + BLOCK), "the other block is as it was");
  2685. assert!(!published(one + BLOCK, one + SIZE) && !published(two + BLOCK, two + SIZE));
  2686. let told = |at: usize| ask(at).1.iter().find(|w| w.0 == (at + BLOCK) / PAGE).map_or(0, |w| w.1);
  2687. assert!(told(two) > before && told(one) > before);
  2688. drop_views(section, &[one, two], SIZE);
  2689. }
  2690. /// While the kernel writes through one view, the same page at another
  2691. /// is told as written at every asking, and the first is not guarded.
  2692. #[test]
  2693. fn what_the_kernel_writes_through_is_not_guarded_for_another_view() {
  2694. let (section, one, two) = two_views(BLOCK);
  2695. let page = one / PAGE;
  2696. assert_eq!(guard(one, one + BLOCK), Some(vec![page]));
  2697. assert_eq!(guard(one, one + BLOCK), Some(Vec::new()));
  2698. let writing = kernel_writing(two, 100);
  2699. for _ in 0..3 {
  2700. assert_eq!(guard(one, one + BLOCK), Some(vec![page]), "the kernel may be writing it");
  2701. assert!(writable(two));
  2702. }
  2703. assert!(!written_since_taken(one, 8), "by whom is not known");
  2704. drop(writing);
  2705. assert_eq!(guard(one, one + BLOCK), Some(vec![page]));
  2706. assert!(!writable(two));
  2707. assert_eq!(guard(one, one + BLOCK), Some(Vec::new()));
  2708. // SAFETY: opened by the handler.
  2709. unsafe { ((two + 8) as *mut u8).write(1) };
  2710. assert_eq!(guard(one, one + BLOCK), Some(vec![page]));
  2711. drop_views(section, &[one, two], BLOCK);
  2712. }
  2713. /// What shaders wrote, put in past the guards and told at one view, is
  2714. /// told at the others, whose copies have not got it; and so is what we
  2715. /// wrote while a submission's one asking stands.
  2716. #[test]
  2717. fn what_is_put_in_beside_the_guards_is_told_at_every_view() {
  2718. let (section, one, two) = two_views(BLOCK);
  2719. writes(two, two + BLOCK, true).expect("a view");
  2720. let (before, _) = writes(two, two + BLOCK, true).expect("a view");
  2721. assert!(published(two, two + BLOCK));
  2722. landed_beside(&[one / 4096 + 3], &[(one + 3 * 4096, 16)]);
  2723. let (_, told) = writes(two, two + BLOCK, true).expect("a view");
  2724. assert!(told.iter().any(|w| w.0 == two / PAGE && w.1 > before), "{told:?} after {before}");
  2725. assert!(landed_lately(two + 3 * 4096, 16, 1) && !landed_lately(two + 4 * 4096, 16, 1));
  2726. drop_views(section, &[one, two], BLOCK);
  2727. }
  2728. /// A view is cut in two by the runtime: until that is done, its pages
  2729. /// count as written wherever else they are shown.
  2730. #[test]
  2731. fn a_view_being_split_leaves_its_pages_unguarded_elsewhere() {
  2732. const SIZE: usize = 3 * BLOCK;
  2733. let (section, one, two) = two_views(SIZE);
  2734. let pages: Vec<usize> = (0..3).map(|k| one / PAGE + k).collect();
  2735. assert_eq!(guard(one, one + SIZE), Some(pages.clone()));
  2736. assert_eq!(guard(one, one + SIZE), Some(Vec::new()));
  2737. let changing = title_memory_remapping();
  2738. title_memory_splitting(two, SIZE);
  2739. title_memory_unmapping(two, SIZE);
  2740. for _ in 0..2 {
  2741. assert_eq!(guard(one, one + SIZE), Some(pages.clone()), "written through the part that stays");
  2742. }
  2743. // The first and last page stay mapped.
  2744. for k in [0, 2] {
  2745. title_memory_remapped(two + k * BLOCK, BLOCK);
  2746. crate::inplace::title_memory_view(two + k * BLOCK, BLOCK, section, (k * BLOCK) as u64);
  2747. }
  2748. drop(changing);
  2749. assert_eq!(guard(one, one + SIZE), Some(pages));
  2750. assert_eq!(guard(one, one + SIZE), Some(Vec::new()));
  2751. assert!(!writable(two) && writable(two + BLOCK) && !writable(two + 2 * BLOCK));
  2752. drop_views(section, &[one, two], SIZE);
  2753. }
  2754. /// A page shown in more than `MANY_VIEWS` views is guarded at each by
  2755. /// itself: the others stay writable, and nothing looks through them all.
  2756. #[test]
  2757. fn a_page_of_many_views_is_guarded_one_view_at_a_time() {
  2758. let (section, one, two) = two_views(BLOCK);
  2759. let filler = one + (1 << 45);
  2760. for n in 0..MANY_VIEWS {
  2761. crate::inplace::title_memory_view(filler + n * BLOCK, BLOCK, section, 0);
  2762. }
  2763. assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE]));
  2764. assert!(writable(two), "another view of it is left alone");
  2765. // SAFETY: the guarded view, opened by the handler.
  2766. unsafe { ((one + 8) as *mut u8).write(1) };
  2767. assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE]));
  2768. title_memory_remapped(filler, MANY_VIEWS * BLOCK);
  2769. drop_views(section, &[one, two], BLOCK);
  2770. }
  2771. /// A write or mapping that runs past the end of the address space (a
  2772. /// title's `fread` with a huge count) covers up to the end; the sum used
  2773. /// to overflow. Up there no test has guarded blocks.
  2774. #[test]
  2775. fn ranges_past_the_address_space_end_do_not_overflow() {
  2776. let top = usize::MAX - 16;
  2777. writing(top, PAGE);
  2778. title_memory_remapped(top, usize::MAX);
  2779. }
  2780. }
  2781. #[cfg(test)]
  2782. mod mapping_tests {
  2783. use super::{title_memory_reading, title_memory_remapping};
  2784. use std::sync::atomic::{AtomicBool, Ordering};
  2785. use std::sync::{Arc, mpsc};
  2786. use std::time::Duration;
  2787. /// A change of mapping waits for a read in place that is under way, and
  2788. /// a read in place waits for a change of mapping.
  2789. #[test]
  2790. fn reads_in_place_and_remappings_wait_for_each_other() {
  2791. // A reader holds; the change does not begin until it lets go.
  2792. let changed = Arc::new(AtomicBool::new(false));
  2793. let reading = title_memory_reading();
  2794. let (began, wait) = mpsc::channel();
  2795. let change = {
  2796. let changed = changed.clone();
  2797. std::thread::spawn(move || {
  2798. began.send(()).unwrap();
  2799. let _changing = title_memory_remapping();
  2800. changed.store(true, Ordering::SeqCst);
  2801. })
  2802. };
  2803. wait.recv().unwrap();
  2804. std::thread::sleep(Duration::from_millis(100));
  2805. assert!(!changed.load(Ordering::SeqCst), "the mapping changed under a read in place");
  2806. drop(reading);
  2807. change.join().unwrap();
  2808. assert!(changed.load(Ordering::SeqCst));
  2809. // A change holds; the read does not begin until it is done.
  2810. let read = Arc::new(AtomicBool::new(false));
  2811. let changing = title_memory_remapping();
  2812. let (began, wait) = mpsc::channel();
  2813. let reader = {
  2814. let read = read.clone();
  2815. std::thread::spawn(move || {
  2816. began.send(()).unwrap();
  2817. let _reading = title_memory_reading();
  2818. read.store(true, Ordering::SeqCst);
  2819. })
  2820. };
  2821. wait.recv().unwrap();
  2822. std::thread::sleep(Duration::from_millis(100));
  2823. assert!(!read.load(Ordering::SeqCst), "a read in place began during a change of mapping");
  2824. drop(changing);
  2825. reader.join().unwrap();
  2826. assert!(read.load(Ordering::SeqCst));
  2827. }
  2828. }
  2829. #[cfg(test)]
  2830. mod many_askers_tests {
  2831. use super::{PAGE, writes};
  2832. use windows_sys::Win32::System::Memory::*;
  2833. /// Threads that write pages and ask about overlapping ranges at the same
  2834. /// time: whoever wrote a page before asking is told of that write (by
  2835. /// its own asking or by one that took the kernel's answer before it).
  2836. #[test]
  2837. fn no_write_is_lost_between_askers() {
  2838. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  2839. const PAGES: usize = 48;
  2840. const THREADS: usize = 8;
  2841. // SAFETY: a reservation of our own, freed at the end.
  2842. let at = unsafe {
  2843. VirtualAlloc(std::ptr::null(), PAGES * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)
  2844. } as usize;
  2845. assert!(at != 0 && at.is_multiple_of(PAGE));
  2846. std::thread::scope(|s| {
  2847. for t in 0..THREADS {
  2848. s.spawn(move || {
  2849. let mut last = [0u64; PAGES];
  2850. let mut seed = t as u64 * 7919 + 1;
  2851. let mut next = |n: usize| {
  2852. seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
  2853. (seed >> 33) as usize % n
  2854. };
  2855. for _ in 0..4000 {
  2856. let page = next(PAGES);
  2857. let from = page - next(page.min(12) + 1);
  2858. let to = page + 1 + next((PAGES - page).min(12));
  2859. // SAFETY: committed memory of ours; what the racing
  2860. // writers leave in it does not matter.
  2861. unsafe { ((at + page * PAGE + t * 8) as *mut u64).write_volatile(1) };
  2862. let (now, written) = writes(at + from * PAGE, at + to * PAGE, false).expect("write-watched");
  2863. let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1);
  2864. assert!(number > last[page], "page {page}: {number} is not after {}", last[page]);
  2865. for l in &mut last[from..to] {
  2866. *l = now;
  2867. }
  2868. }
  2869. });
  2870. }
  2871. });
  2872. // SAFETY: the reservation made above.
  2873. unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) };
  2874. }
  2875. /// The same of view memory, which is guarded: what its bits answer
  2876. /// misses no write either, however often blocks are opened and guarded
  2877. /// again between.
  2878. #[test]
  2879. fn no_write_to_views_is_lost_between_askers() {
  2880. writes_to_views_are_not_lost::<1>();
  2881. }
  2882. /// The same of pages shown at three addresses, each of which has copies
  2883. /// of its own: a write through any of them, or put past the guards, is
  2884. /// told at all. A fourth view comes and goes meanwhile, and is written
  2885. /// too. (The first assertion fails within a few rounds if a guard holds
  2886. /// for one address only, `VICTORY_VIEW_GUARD=0`.)
  2887. #[test]
  2888. fn no_write_through_another_view_is_lost_between_askers() {
  2889. writes_to_views_are_not_lost::<3>();
  2890. }
  2891. fn writes_to_views_are_not_lost<const VIEWS: usize>() {
  2892. const PAGES: usize = 12;
  2893. const THREADS: usize = 8;
  2894. // SAFETY: views of a section of our own.
  2895. let (section, all): (usize, [usize; VIEWS]) = unsafe {
  2896. let section = CreateFileMappingW(
  2897. -1isize as _,
  2898. std::ptr::null(),
  2899. PAGE_READWRITE,
  2900. 0,
  2901. (PAGES * PAGE) as u32,
  2902. std::ptr::null(),
  2903. );
  2904. crate::title_memory_section(section as usize, (PAGES * PAGE) as u64, true);
  2905. let all = std::array::from_fn(|_| {
  2906. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, PAGES * PAGE).Value as usize;
  2907. assert!(at != 0 && at.is_multiple_of(PAGE));
  2908. super::title_memory_remapped(at, PAGES * PAGE);
  2909. crate::title_memory_view(at, PAGES * PAGE, section as usize, 0);
  2910. at
  2911. });
  2912. (section as usize, all)
  2913. };
  2914. let by_bits = std::sync::atomic::AtomicUsize::new(0);
  2915. let past = std::sync::atomic::AtomicUsize::new(0);
  2916. std::thread::scope(|s| {
  2917. if VIEWS > 1 {
  2918. s.spawn(move || {
  2919. let mut last = [0u64; VIEWS];
  2920. for round in 0..300usize {
  2921. let (page, asked) = (round * 5 % PAGES, round % VIEWS);
  2922. // SAFETY (all): a view of one page of the section,
  2923. // this thread's alone.
  2924. let one = unsafe {
  2925. MapViewOfFile(section as _, FILE_MAP_WRITE, 0, (page * PAGE) as u32, PAGE).Value as usize
  2926. };
  2927. assert_ne!(one, 0);
  2928. super::title_memory_remapped(one, PAGE);
  2929. crate::title_memory_view(one, PAGE, section, (page * PAGE) as u64);
  2930. unsafe { ((one + THREADS * 8) as *mut u64).write_volatile(round as u64) };
  2931. let (now, written) =
  2932. writes(all[asked] + page * PAGE, all[asked] + (page + 1) * PAGE, true).expect("a view");
  2933. let number = written.first().map_or(0, |w| w.1);
  2934. assert!(number > last[asked], "page {page}, through a new view: {number} is not after {}", last[asked]);
  2935. last[asked] = now.max(last[asked]);
  2936. {
  2937. let _changing = super::title_memory_remapping();
  2938. super::title_memory_unmapping(one, PAGE);
  2939. unsafe { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: one as *mut _ }) };
  2940. }
  2941. last = [last[asked]; VIEWS];
  2942. }
  2943. });
  2944. }
  2945. for t in 0..THREADS {
  2946. let (by_bits, past) = (&by_bits, &past);
  2947. s.spawn(move || {
  2948. let mut last = [[0u64; PAGES]; VIEWS];
  2949. let mut seed = t as u64 * 7919 + 1;
  2950. let mut next = |n: usize| {
  2951. seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
  2952. (seed >> 33) as usize % n
  2953. };
  2954. for _ in 0..500 {
  2955. let page = next(PAGES);
  2956. let from = page - next(page.min(3) + 1);
  2957. let to = page + 1 + next((PAGES - page).min(3));
  2958. // Written through one view, asked about at another.
  2959. let (through, asked) = (all[next(VIEWS)], next(VIEWS));
  2960. let (at, last) = (all[asked], &mut last[asked]);
  2961. if next(4) != 0 {
  2962. // As in the test above, or after a word of ours,
  2963. // or past the guard.
  2964. let word = through + page * PAGE + t * 8;
  2965. // SAFETY (both): as above.
  2966. // (Waited for: other tests hold changes of mapping.)
  2967. let reading = (next(3) == 0).then(super::title_memory_reading);
  2968. let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8));
  2969. if let Some(to) = beside {
  2970. unsafe { (to as *mut u64).write_volatile(2) };
  2971. super::landed_beside(&[word / 4096], &[(word, 8)]);
  2972. past.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2973. assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere");
  2974. } else {
  2975. if next(4) == 0 {
  2976. super::writing(word, 8);
  2977. }
  2978. unsafe { (word as *mut u64).write_volatile(1) };
  2979. }
  2980. } else {
  2981. // Nothing written: what is asked counts as before.
  2982. by_bits.fetch_add(
  2983. usize::from(super::published(at + from * PAGE, at + to * PAGE)),
  2984. std::sync::atomic::Ordering::Relaxed,
  2985. );
  2986. let (now, _) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view");
  2987. for l in &mut last[from..to] {
  2988. *l = now;
  2989. }
  2990. continue;
  2991. }
  2992. let (now, written) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view");
  2993. let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1);
  2994. assert!(number > last[page], "page {page}: {number} is not after {}", last[page]);
  2995. for l in &mut last[from..to] {
  2996. *l = now;
  2997. }
  2998. }
  2999. });
  3000. }
  3001. });
  3002. assert!(by_bits.into_inner() > 0, "the bits answered none");
  3003. assert!(past.into_inner() > 0, "nothing was put past the guards");
  3004. // (The view stays: at its address other tests' memory would be told
  3005. // of these writes.)
  3006. }
  3007. /// A range of a placeholder with views in it is known whole, its holes
  3008. /// among it, until something is mapped into one, unmapped from it or
  3009. /// allocated there. A hole that is no placeholder's is asked about.
  3010. #[test]
  3011. fn holes_are_known_until_the_runtime_tells() {
  3012. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  3013. const BLOCKS: usize = 8;
  3014. // SAFETY (all): a placeholder and a section of our own, which stay.
  3015. let (at, section) = unsafe {
  3016. let at = VirtualAlloc2(
  3017. GetCurrentProcess(),
  3018. std::ptr::null(),
  3019. BLOCKS * PAGE,
  3020. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  3021. PAGE_NOACCESS,
  3022. std::ptr::null_mut(),
  3023. 0,
  3024. ) as usize;
  3025. let section =
  3026. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null());
  3027. (at, section)
  3028. };
  3029. let map = |block: usize| unsafe {
  3030. let to = at + block * PAGE;
  3031. VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  3032. let view = MapViewOfFile3(
  3033. section,
  3034. GetCurrentProcess(),
  3035. to as *const _,
  3036. (block * PAGE) as u64,
  3037. PAGE,
  3038. MEM_REPLACE_PLACEHOLDER,
  3039. PAGE_READWRITE,
  3040. std::ptr::null_mut(),
  3041. 0,
  3042. );
  3043. assert_eq!(view.Value as usize, to);
  3044. super::title_memory_remapped(to, PAGE);
  3045. };
  3046. map(1);
  3047. map(5);
  3048. assert!(super::placeholder(at / PAGE) && super::placeholder(at / PAGE + 7) && !super::placeholder(at / PAGE + 5));
  3049. let end = at + BLOCKS * PAGE;
  3050. let ask = |since: u64| -> (u64, Vec<usize>) {
  3051. let (now, written) = writes(at, end, true).expect("a view");
  3052. (now, written.into_iter().filter(|w| w.1 > since).map(|w| w.0 - at / PAGE).collect())
  3053. };
  3054. let (first, all) = ask(0);
  3055. assert_eq!(all, (0..BLOCKS).collect::<Vec<_>>());
  3056. assert!(super::published(at, end), "with its holes");
  3057. // Written; mapped into; unmapped.
  3058. unsafe { ((at + 5 * PAGE) as *mut u8).write_volatile(1) };
  3059. assert!(!super::published(at, end));
  3060. let (second, all) = ask(first);
  3061. assert_eq!(all, [5]);
  3062. map(2);
  3063. assert!(!super::published(at, end));
  3064. let (third, all) = ask(second);
  3065. assert_eq!(all, [2]);
  3066. unsafe { ((at + 2 * PAGE) as *mut u8).write_volatile(1) };
  3067. let (fourth, all) = ask(third);
  3068. assert_eq!(all, [2]);
  3069. super::title_memory_unmapping(at + 5 * PAGE, PAGE);
  3070. unsafe {
  3071. let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: (at + 5 * PAGE) as *mut _ };
  3072. UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER);
  3073. }
  3074. let (fifth, all) = ask(fourth);
  3075. assert_eq!(all, [5]);
  3076. assert!(super::published(at, end));
  3077. // Told of memory there, though there is none: asked about again.
  3078. super::title_memory_allocated(at, PAGE);
  3079. assert!(!super::published(at, end));
  3080. let (_, all) = ask(fifth);
  3081. assert_eq!(all, []);
  3082. // A reservation of the ordinary kind is no placeholder.
  3083. let plain = unsafe { VirtualAlloc(std::ptr::null(), PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize;
  3084. assert!(!super::placeholder(plain / PAGE));
  3085. super::look_at_holes();
  3086. assert!(!super::published(at, end), "block 0 stays asked about");
  3087. assert!(super::published(at + PAGE, end), "the others are as they were");
  3088. super::title_memory_unmapping(at, BLOCKS * PAGE);
  3089. }
  3090. /// Pages mapped into a placeholder, written and unmapped again, each by a
  3091. /// thread of its own as the runtime does it, while others ask about all
  3092. /// of it: what was written, and that a page came or went, is told to
  3093. /// whoever asks after it, and blocks are known by their bits meanwhile.
  3094. #[test]
  3095. fn no_mapping_is_lost_between_askers() {
  3096. use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
  3097. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  3098. const BLOCKS: usize = 12;
  3099. // SAFETY (all): a placeholder and a section of our own, which stay.
  3100. let (at, section) = unsafe {
  3101. let at = VirtualAlloc2(
  3102. GetCurrentProcess(),
  3103. std::ptr::null(),
  3104. BLOCKS * PAGE,
  3105. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  3106. PAGE_NOACCESS,
  3107. std::ptr::null_mut(),
  3108. 0,
  3109. ) as usize;
  3110. for block in 0..BLOCKS - 1 {
  3111. VirtualFree((at + block * PAGE) as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
  3112. }
  3113. let section =
  3114. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null());
  3115. (at, section as usize)
  3116. };
  3117. let end = at + BLOCKS * PAGE;
  3118. let (stop, by_bits) = (AtomicBool::new(false), AtomicUsize::new(0));
  3119. let number = |written: &[(usize, u64)], block: usize| written.iter().find(|w| w.0 == at / PAGE + block).map_or(0, |w| w.1);
  3120. std::thread::scope(|s| {
  3121. let mappers: Vec<_> = (0..4usize)
  3122. .map(|t| {
  3123. let number = &number;
  3124. s.spawn(move || {
  3125. for round in 0..120 {
  3126. let block = t * 3 + round % 3;
  3127. let to = at + block * PAGE;
  3128. let (before, _) = writes(at, end, true).expect("a view");
  3129. unsafe {
  3130. let view = MapViewOfFile3(
  3131. section as _,
  3132. GetCurrentProcess(),
  3133. to as *const _,
  3134. (block * PAGE) as u64,
  3135. PAGE,
  3136. MEM_REPLACE_PLACEHOLDER,
  3137. PAGE_READWRITE,
  3138. std::ptr::null_mut(),
  3139. 0,
  3140. );
  3141. assert_eq!(view.Value as usize, to);
  3142. super::title_memory_remapped(to, PAGE);
  3143. (to as *mut u8).write_volatile(round as u8);
  3144. }
  3145. let (mapped, written) = writes(at, end, true).expect("a view");
  3146. assert!(number(&written, block) > before, "mapped and written: not told");
  3147. unsafe { ((to + 9) as *mut u8).write_volatile(round as u8) };
  3148. let (again, written) = writes(to, to + PAGE, true).expect("a view");
  3149. assert!(number(&written, block) > mapped, "written again: not told");
  3150. super::title_memory_unmapping(to, PAGE);
  3151. unsafe {
  3152. let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: to as *mut _ };
  3153. assert_ne!(UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER), 0);
  3154. }
  3155. let _ = again;
  3156. }
  3157. })
  3158. })
  3159. .collect();
  3160. for t in 0..3usize {
  3161. let (stop, by_bits) = (&stop, &by_bits);
  3162. s.spawn(move || {
  3163. let mut k = t;
  3164. while !stop.load(Ordering::Relaxed) {
  3165. k = (k * 5 + 3) % 64;
  3166. let (from, to) = (at + k % 6 * PAGE, end - k / 8 % 5 * PAGE);
  3167. by_bits.fetch_add(usize::from(super::published(from, to)), Ordering::Relaxed);
  3168. assert!(writes(from, to, true).is_some());
  3169. }
  3170. });
  3171. }
  3172. let failed = mappers.into_iter().map(|m| m.join()).filter(Result::is_err).count();
  3173. stop.store(true, Ordering::Relaxed);
  3174. assert_eq!(failed, 0);
  3175. });
  3176. assert!(by_bits.into_inner() > 0, "the bits answered none");
  3177. // All unmapped: known whole, and nothing but holes.
  3178. writes(at, end, true).expect("a view");
  3179. assert!(super::published(at, end));
  3180. super::title_memory_unmapping(at, BLOCKS * PAGE);
  3181. }
  3182. /// A block's bit goes with everything that makes it the title's to write,
  3183. /// or forgets it.
  3184. #[test]
  3185. fn bits_go_with_the_guard() {
  3186. // SAFETY: a view of a section of our own, which stays.
  3187. let at = unsafe {
  3188. let section =
  3189. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (2 * PAGE) as u32, std::ptr::null());
  3190. MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * PAGE).Value as usize
  3191. };
  3192. let end = at + 2 * PAGE;
  3193. let takes: [&dyn Fn(); 4] = [
  3194. &|| super::title_memory_remapped(at, PAGE),
  3195. // SAFETY: the view.
  3196. &|| unsafe { ((at + 8) as *mut u8).write_volatile(1) },
  3197. &|| super::writing(at, 1),
  3198. // (Told again, as of a view mapped there next: it is read-only.)
  3199. &|| {
  3200. super::title_memory_unmapping(at, PAGE);
  3201. assert!(!super::published(at, end), "forgotten");
  3202. super::title_memory_remapped(at, PAGE);
  3203. let mut old = 0;
  3204. // SAFETY: the view.
  3205. unsafe { VirtualProtect(at as *const _, PAGE, PAGE_READWRITE, &mut old) };
  3206. },
  3207. ];
  3208. for (i, take) in takes.iter().enumerate() {
  3209. writes(at, end, true).expect("a view");
  3210. assert!(super::published(at, end), "{i}");
  3211. take();
  3212. assert!(!super::published(at, end), "{i}");
  3213. assert!(super::published(at + PAGE, end), "{i}: the other block");
  3214. }
  3215. super::title_memory_unmapping(at, 2 * PAGE);
  3216. }
  3217. /// A range's bits are all of its blocks', whatever lies beside them.
  3218. #[test]
  3219. fn bits_of_ranges() {
  3220. static BITS: super::Bits = super::Bits::new();
  3221. let blocks = [0usize, 1, 63, 64, 65, 127, 128, 200, 65535, 65536, 65537, 1 << 20, (1 << 31) - 1];
  3222. for &b in &blocks {
  3223. assert!(!BITS.all(b, b + 1));
  3224. BITS.set(b);
  3225. assert!(BITS.all(b, b + 1));
  3226. }
  3227. assert!(BITS.all(0, 2) && BITS.all(63, 66) && BITS.all(127, 129) && BITS.all(65535, 65538));
  3228. assert!(!BITS.all(0, 3) && !BITS.all(62, 64) && !BITS.all(65534, 65536) && !BITS.all(5, 5));
  3229. for b in 300..700 {
  3230. BITS.set(b);
  3231. }
  3232. assert!(BITS.all(300, 700) && !BITS.all(299, 700) && !BITS.all(300, 701));
  3233. BITS.clear(511);
  3234. assert!(!BITS.all(300, 700) && BITS.all(300, 511) && BITS.all(512, 700));
  3235. assert!(!BITS.all(1 << 40, (1 << 40) + 1), "outside the address space");
  3236. }
  3237. }