watch.rs 113 KB

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