watch.rs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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::Mutex;
  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. struct Journal {
  31. /// Numbers the askings; 0 is "never".
  32. asked: u64,
  33. /// Page number → the asking that last found it written.
  34. written: BTreeMap<usize, u64>,
  35. /// Room for the kernel's answer.
  36. found: Vec<usize>,
  37. /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`])
  38. /// and the asking that did: `writes` answers for a range inside one
  39. /// from the journal, without another kernel call.
  40. ahead: Vec<(usize, usize)>,
  41. ahead_asked: u64,
  42. /// The ahead asking stands for a whole submission ([`ask_once`]): no
  43. /// other ahead asking is made, and `ahead` stays, until
  44. /// [`ask_once_end`].
  45. kept: bool,
  46. }
  47. static JOURNAL: Mutex<Journal> = Mutex::new(Journal {
  48. asked: 0,
  49. written: BTreeMap::new(),
  50. found: Vec::new(),
  51. ahead: Vec::new(),
  52. ahead_asked: 0,
  53. kept: false,
  54. });
  55. /// Ranges of one submission closer than this are asked about together:
  56. /// walking the pages between them costs less than another kernel call (a
  57. /// call that resets written pages costs 30-70 microseconds whatever the
  58. /// range).
  59. const AHEAD_GAP: usize = (8 << 20) / PAGE;
  60. /// The most one asking covers (its answer needs 8 bytes per 4 KiB page).
  61. const AHEAD_MAX: usize = (1 << 30) / PAGE;
  62. /// Asks the kernel about many ranges `(start, end)` at once, before the
  63. /// [`writes`] of each: ranges close together are one asking, and `writes`
  64. /// then answers from the journal until [`ask_ahead_done`]. The world's
  65. /// submissions refresh thousands of host copies (6,664 askings a frame,
  66. /// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are
  67. /// left to `writes`.
  68. pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
  69. let mut pieces: Vec<(usize, usize)> = ranges
  70. .iter()
  71. .filter(|r| r.0 < r.1)
  72. .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE)))
  73. .collect();
  74. if pieces.len() < 2 {
  75. return;
  76. }
  77. pieces.sort_unstable();
  78. let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
  79. let j = &mut *j;
  80. // The submission's one asking stands ([`ask_once`]): what it does not
  81. // hold is left to `writes`.
  82. if j.kept {
  83. return;
  84. }
  85. j.asked += 1;
  86. j.ahead_asked = j.asked;
  87. j.ahead.clear();
  88. let mut i = 0;
  89. while i < pieces.len() {
  90. let first = pieces[i].0;
  91. let mut last = pieces[i].1;
  92. let mut k = i + 1;
  93. while k < pieces.len()
  94. && pieces[k].0 <= last + AHEAD_GAP
  95. && last.max(pieces[k].1) - first <= AHEAD_MAX
  96. {
  97. last = last.max(pieces[k].1);
  98. k += 1;
  99. }
  100. ask_run(j, &pieces[i..k]);
  101. i = k;
  102. }
  103. }
  104. /// Since the last frame line: the kernel askings that took a millisecond
  105. /// or more, their microseconds, and the longest asking's. An asking walks
  106. /// page tables, some ten microseconds for most ranges; in run 75 the 2,644
  107. /// askings of a frame took 219 ms in the lines where the pass over the
  108. /// heap's views ran long, 25-50 ms in the others. These numbers say
  109. /// whether a few askings wait for something or all of them are slow.
  110. #[cfg(feature = "diagnostics")]
  111. static SLOW: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  112. #[cfg(feature = "diagnostics")]
  113. fn slow(us: u64) {
  114. use std::sync::atomic::Ordering::Relaxed;
  115. if us >= 1000 {
  116. SLOW[0].fetch_add(1, Relaxed);
  117. SLOW[1].fetch_add(us, Relaxed);
  118. }
  119. SLOW[2].fetch_max(us, Relaxed);
  120. }
  121. /// [`SLOW`], taken.
  122. #[cfg(feature = "diagnostics")]
  123. pub(crate) fn slow_asks() -> [u64; 3] {
  124. [0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed))
  125. }
  126. /// The submission's refreshes are done: `writes` asks the kernel again.
  127. pub(crate) fn ask_ahead_done() {
  128. let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
  129. if !j.kept {
  130. j.ahead.clear();
  131. }
  132. }
  133. /// Whether a submission asks the kernel once, before its first refresh,
  134. /// about every range its lists refresh (`VICTORY_ASK_ONCE=1`; off by
  135. /// default).
  136. ///
  137. /// A submission's refreshes are done in groups, between the title's own
  138. /// buffer copies (each copy flushes the refreshes recorded before it), and
  139. /// every group asked the kernel again: 2,644 askings a frame, 70 a
  140. /// submission. With the switch the journal answers all of them from one
  141. /// asking made when the submission starts.
  142. ///
  143. /// What changes: memory the title's other threads write while the
  144. /// submission is being prepared is seen by the next submission's asking,
  145. /// not by this one's later groups. What this submission's lists read was
  146. /// written before they were submitted, so before the asking. Our own
  147. /// writes into title memory while preparing are told to the journal
  148. /// ([`wrote`]) or end the asking ([`ask_once_end`]).
  149. pub(crate) fn once() -> bool {
  150. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  151. // On by default since run 81 (with card buffers: 375-450 ms a frame
  152. // against 573-647, the picture unchanged over four minutes);
  153. // `VICTORY_ASK_ONCE=0` asks per range, as before.
  154. *ON.get_or_init(|| std::env::var_os("VICTORY_ASK_ONCE").is_none_or(|v| v != "0"))
  155. }
  156. /// With [`once`]: asks about `ranges` (everything a submission's lists
  157. /// refresh) as [`ask_ahead`] does, and lets that asking stand until
  158. /// [`ask_once_end`].
  159. pub(crate) fn ask_once(ranges: &[(usize, usize)]) {
  160. if !once() {
  161. return;
  162. }
  163. ask_once_end();
  164. ask_ahead(ranges);
  165. let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
  166. let j = &mut *j;
  167. if j.ahead.is_empty() {
  168. // `ask_ahead` asked nothing (fewer than two ranges).
  169. j.asked += 1;
  170. j.ahead_asked = j.asked;
  171. }
  172. // `ask_ahead` leaves a range that lies alone to `writes`, which asks
  173. // once per flush: with one asking for the submission that was every
  174. // such range asked again at each of its 70 flushes (run 76: 2,300
  175. // askings a frame with the switch on, as without it). They are asked
  176. // here, once; what is not write-watched stays with `writes`.
  177. for &(start, end) in ranges {
  178. if start >= end {
  179. continue;
  180. }
  181. let (first, last) = (start / PAGE, end.div_ceil(PAGE));
  182. if !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) && ask_kernel(j, first, last) {
  183. j.ahead.push((first, last));
  184. }
  185. }
  186. j.kept = !j.ahead.is_empty();
  187. }
  188. /// The submission's one asking stands no longer: its refreshes are done,
  189. /// or title memory was written in a way the journal was not told.
  190. pub(crate) fn ask_once_end() {
  191. let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
  192. if j.kept {
  193. j.kept = false;
  194. j.ahead.clear();
  195. }
  196. }
  197. /// We wrote title memory `[at, at + len)` while a submission's one asking
  198. /// stands (the title's buffer copies, done at submission): its pages count
  199. /// as written after that asking, so the refreshes that follow copy them.
  200. pub(crate) fn wrote(at: usize, len: usize) {
  201. let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
  202. if !j.kept || len == 0 {
  203. return;
  204. }
  205. j.asked += 1;
  206. let now = j.asked;
  207. for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) {
  208. j.written.insert(page, now);
  209. }
  210. }
  211. /// One kernel asking for `pieces` (page ranges in order); by halves if it
  212. /// fails, as a run across two reservations or into memory that is not
  213. /// write-watched does. A piece alone is left to [`writes`].
  214. fn ask_run(j: &mut Journal, pieces: &[(usize, usize)]) {
  215. if pieces.len() < 2 {
  216. return;
  217. }
  218. let first = pieces[0].0;
  219. let last = pieces.iter().map(|p| p.1).max().unwrap_or(first);
  220. if ask_kernel(j, first, last) {
  221. j.ahead.push((first, last));
  222. return;
  223. }
  224. let (a, b) = pieces.split_at(pieces.len() / 2);
  225. ask_run(j, a);
  226. ask_run(j, b);
  227. }
  228. /// Asks the kernel for the written pages of pages `[first, last)` and notes
  229. /// them in the journal under the ahead asking; false (and nothing changed)
  230. /// if the range is not write-watched memory of one reservation.
  231. fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool {
  232. use windows_sys::Win32::System::Memory::GetWriteWatch;
  233. const WRITE_WATCH_FLAG_RESET: u32 = 1;
  234. let mut count = (last - first) * PAGE / KERNEL_PAGE;
  235. j.found.resize(count.max(j.found.len()), 0);
  236. let mut granularity = 0;
  237. #[cfg(feature = "diagnostics")]
  238. let started = std::time::Instant::now();
  239. // SAFETY: the answer buffer holds `count` entries.
  240. let failed = unsafe {
  241. GetWriteWatch(
  242. WRITE_WATCH_FLAG_RESET,
  243. (first * PAGE) as *const _,
  244. (last - first) * PAGE,
  245. j.found.as_mut_ptr().cast(),
  246. &mut count,
  247. &mut granularity,
  248. )
  249. } != 0;
  250. if failed {
  251. return false;
  252. }
  253. #[cfg(feature = "diagnostics")]
  254. {
  255. use crate::copystat::{C, add};
  256. add(C::Watches, 1);
  257. add(C::WatchUs, started.elapsed().as_micros() as u64);
  258. slow(started.elapsed().as_micros() as u64);
  259. }
  260. let now = j.ahead_asked;
  261. for k in 0..count {
  262. let page = j.found[k] / PAGE;
  263. j.written.insert(page, now);
  264. }
  265. true
  266. }
  267. /// What [`writes`] would say of `[start, end)` from the journal alone, if
  268. /// the range lies in one asked ahead ([`ask_ahead`], [`ask_once`]): the
  269. /// pages written since tracking began and the asking that last found each
  270. /// written, with the number of the asking that stands (as [`writes`] gives
  271. /// it). `None` if the kernel would have to be asked.
  272. pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> {
  273. let (first, last) = (start / PAGE, end.div_ceil(PAGE));
  274. let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
  275. j.ahead
  276. .iter()
  277. .any(|&(a, b)| a <= first && last <= b)
  278. .then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect()))
  279. }
  280. /// The pages of `[start, end)` (whole pages) as last written, for pages
  281. /// written since tracking began: `(page number, asking)` in page order, and
  282. /// this asking's number, which is higher than any in the list but those the
  283. /// kernel just reported. `None` if the memory is not write-watched (nor,
  284. /// with `guarded`, view memory, which is then guarded).
  285. pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> {
  286. use windows_sys::Win32::System::Memory::GetWriteWatch;
  287. const WRITE_WATCH_FLAG_RESET: u32 = 1;
  288. let (first, last) = (start / PAGE, end.div_ceil(PAGE));
  289. let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
  290. let j = &mut *j;
  291. // Asked ahead with the submission's other ranges: the journal has it.
  292. if j.ahead.iter().any(|&(a, b)| a <= first && last <= b) {
  293. return Some((
  294. j.ahead_asked,
  295. j.written
  296. .range(first..last)
  297. .map(|(&p, &w)| (p, w))
  298. .collect(),
  299. ));
  300. }
  301. let mut count = (last - first) * PAGE / KERNEL_PAGE;
  302. j.found.resize(count.max(j.found.len()), 0);
  303. let mut granularity = 0;
  304. #[cfg(feature = "diagnostics")]
  305. let started = std::time::Instant::now();
  306. // SAFETY: the answer buffer holds `count` entries.
  307. let failed = unsafe {
  308. GetWriteWatch(
  309. WRITE_WATCH_FLAG_RESET,
  310. (first * PAGE) as *const _,
  311. (last - first) * PAGE,
  312. j.found.as_mut_ptr().cast(),
  313. &mut count,
  314. &mut granularity,
  315. )
  316. } != 0;
  317. let guarded = if failed {
  318. count = 0;
  319. if !guarded {
  320. return None;
  321. }
  322. #[cfg(feature = "diagnostics")]
  323. let guarding = std::time::Instant::now();
  324. let written = guard(first * PAGE, last * PAGE);
  325. #[cfg(feature = "diagnostics")]
  326. crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64);
  327. written?
  328. } else {
  329. Vec::new()
  330. };
  331. #[cfg(feature = "diagnostics")]
  332. {
  333. use crate::copystat::{C, add};
  334. add(C::Watches, 1);
  335. add(C::WatchUs, started.elapsed().as_micros() as u64);
  336. slow(started.elapsed().as_micros() as u64);
  337. }
  338. j.asked += 1;
  339. let now = j.asked;
  340. let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded);
  341. for page in pages.collect::<Vec<_>>() {
  342. j.written.insert(page, now);
  343. }
  344. Some((
  345. now,
  346. j.written
  347. .range(first..last)
  348. .map(|(&p, &w)| (p, w))
  349. .collect(),
  350. ))
  351. }
  352. /// Guarded blocks of view memory.
  353. const BLOCK: usize = PAGE;
  354. struct Guards {
  355. /// Blocks we made read-only.
  356. protected: BTreeSet<usize>,
  357. /// Of those, the ones not written since a copy took them.
  358. clean: BTreeSet<usize>,
  359. /// Blocks already copied as zeros. While they remain wholly uncommitted,
  360. /// the copy can skip hundreds of MB of failing kernel reads per world frame.
  361. absent: BTreeSet<usize>,
  362. }
  363. static GUARDS: Mutex<Guards> = Mutex::new(Guards {
  364. protected: BTreeSet::new(),
  365. clean: BTreeSet::new(),
  366. absent: BTreeSet::new(),
  367. });
  368. fn guards() -> std::sync::MutexGuard<'static, Guards> {
  369. GUARDS.lock().unwrap_or_else(|e| e.into_inner())
  370. }
  371. /// For view memory: the pages of `[start, end)`'s blocks written since
  372. /// they were last guarded (all of a block's pages), guarding them again
  373. /// before the caller copies them. `None` if the memory is not a view.
  374. fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
  375. // A range whose first block the guards hold already (read-only by our
  376. // hand, or noted absent) is a view: no question to Windows. The
  377. // question walks the page tables to the end of the pages that share the
  378. // first one's state, and a guarded view is one long run of read-only
  379. // pages: 0.6 ms for the title's 174 MB heap, 16 times a frame, and most
  380. // of the 68 ms a frame of "guards" (run 58).
  381. // `VICTORY_GUARD_ASK=1` asks every time, as before.
  382. static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  383. let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && {
  384. let g = guards();
  385. let first = start / BLOCK;
  386. g.protected.contains(&first) || g.absent.contains(&first)
  387. };
  388. if !known && !is_view(start, end) {
  389. return None;
  390. }
  391. install();
  392. let mut g = guards();
  393. let mut written = Vec::new();
  394. let mut run: Option<usize> = None;
  395. let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
  396. // The range's clean blocks, in order: read off the set in one pass,
  397. // not looked up one block at a time. A frame asks about some 10 GB of
  398. // view memory, 150,000 blocks, nearly all clean: the lookups were most
  399. // of the 60-90 ms a frame of "guards" (run 54). What the loop adds to
  400. // the set meanwhile is the block it stands at or ones before it.
  401. let clean: Vec<usize> = g.clean.range(first..last).copied().collect();
  402. if clean.len() == last - first {
  403. // Nothing written, mapped or new since the range was last taken.
  404. return Some(written);
  405. }
  406. let mut next_clean = 0;
  407. let mut uncommitted_until = first;
  408. for block in first..=last {
  409. while next_clean < clean.len() && clean[next_clean] < block {
  410. next_clean += 1;
  411. }
  412. let is_clean = next_clean < clean.len() && clean[next_clean] == block;
  413. let mut open = block < last && !is_clean;
  414. if open && g.absent.contains(&block) {
  415. // Ordinary commits need no runtime mapping notification. Reuse
  416. // this asking's query for the following blocks in the same region.
  417. if block >= uncommitted_until {
  418. uncommitted_until = uncommitted_end(block);
  419. }
  420. open = block >= uncommitted_until;
  421. if open {
  422. g.absent.remove(&block);
  423. }
  424. }
  425. if open {
  426. written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE);
  427. if g.protected.contains(&block) {
  428. // Written through the runtime, still read-only.
  429. g.clean.insert(block);
  430. } else {
  431. run.get_or_insert(block);
  432. continue;
  433. }
  434. }
  435. if let Some(from) = run.take() {
  436. protect(&mut g, from, block);
  437. }
  438. }
  439. Some(written)
  440. }
  441. /// Whether `[start, end)` is view memory. The title's views lie in
  442. /// placeholders, mapped and unmapped block by block as it streams, so a
  443. /// range can begin in a block that is not mapped right now: the first
  444. /// pages of the range that are there decide. A range with nothing there
  445. /// counts as a view (its blocks are noted absent, and looked at again when
  446. /// the runtime maps them).
  447. ///
  448. /// Looking at the first address only took such a range for "not a view":
  449. /// its copy was marked not watched for good and copied whole at every
  450. /// refresh, around its unmapped pages (run 54: 300 such ranges, 570 MB
  451. /// copied a frame for them, 255 copies a frame reading around holes).
  452. /// `VICTORY_GUARD_HOLES=0` looks at the first address only, as before.
  453. fn is_view(start: usize, end: usize) -> bool {
  454. use windows_sys::Win32::System::Memory::{
  455. MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery,
  456. };
  457. static HOLES: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  458. let holes = *HOLES.get_or_init(|| std::env::var_os("VICTORY_GUARD_HOLES").is_none_or(|v| v != "0"));
  459. let mut at = start;
  460. loop {
  461. // SAFETY: plain data filled in by the query.
  462. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  463. // SAFETY: a valid out pointer of the right size.
  464. let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
  465. if n == 0 {
  466. return false;
  467. }
  468. if info.Type == MEM_MAPPED {
  469. return true;
  470. }
  471. // Committed memory that is no view (the title's heaps, ours), or
  472. // the answer as it was before.
  473. if info.State == MEM_COMMIT || !holes {
  474. return false;
  475. }
  476. // A hole (a placeholder, or free): on to what follows it.
  477. let next = (info.BaseAddress as usize).saturating_add(info.RegionSize);
  478. if next <= at || next >= end {
  479. return true;
  480. }
  481. at = next;
  482. }
  483. }
  484. /// Makes blocks `[from, to)` read-only and notes them guarded and clean;
  485. /// block by block if they span views, leaving out any that fail, and
  486. /// noting those not committed (unmapped) absent.
  487. fn protect(g: &mut Guards, from: usize, to: usize) {
  488. use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
  489. let set = |from: usize, to: usize| {
  490. let mut old = 0;
  491. // SAFETY: title view memory; only its protection changes.
  492. unsafe {
  493. VirtualProtect(
  494. (from * BLOCK) as *const _,
  495. (to - from) * BLOCK,
  496. PAGE_READONLY,
  497. &mut old,
  498. ) != 0
  499. }
  500. };
  501. let note = |g: &mut Guards, from: usize, to: usize| {
  502. g.protected.extend(from..to);
  503. g.clean.extend(from..to);
  504. };
  505. if set(from, to) {
  506. note(g, from, to);
  507. return;
  508. }
  509. for block in from..to {
  510. if set(block, block + 1) {
  511. note(g, block, block + 1);
  512. } else if block < uncommitted_end(block) {
  513. g.absent.insert(block);
  514. }
  515. }
  516. }
  517. /// The end (exclusive) of the whole uncommitted blocks starting at `block`.
  518. fn uncommitted_end(block: usize) -> usize {
  519. use windows_sys::Win32::System::Memory::{
  520. MEM_FREE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, VirtualQuery,
  521. };
  522. // SAFETY: plain data filled in by the query.
  523. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  524. // SAFETY: a valid out pointer of the right size.
  525. let n = unsafe { VirtualQuery((block * BLOCK) as *const _, &mut info, size_of_val(&info)) };
  526. if n != 0 && matches!(info.State, MEM_RESERVE | MEM_FREE) {
  527. (info.BaseAddress as usize).saturating_add(info.RegionSize) / BLOCK
  528. } else {
  529. block
  530. }
  531. }
  532. /// Gives write access back to the guarded blocks of `[start, end)` and
  533. /// notes them written; true if any was guarded.
  534. fn open(g: &mut Guards, start: usize, end: usize) -> bool {
  535. use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
  536. let blocks: Vec<usize> = g
  537. .protected
  538. .range(start / BLOCK..end.div_ceil(BLOCK))
  539. .copied()
  540. .collect();
  541. for &block in &blocks {
  542. g.protected.remove(&block);
  543. g.clean.remove(&block);
  544. let mut old = 0;
  545. // SAFETY: a block we made read-only.
  546. unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) };
  547. }
  548. !blocks.is_empty()
  549. }
  550. /// Before our own write into title memory `[at, at + len)` through the
  551. /// kernel (which does not fault into our handler): opens its guarded blocks.
  552. /// The runtime calls it (as `kernel_will_write`) before the title's kernel
  553. /// reads into its own memory.
  554. pub fn writing(at: usize, len: usize) {
  555. // The length is the title's (`fread`'s size times count, saturated).
  556. open(&mut guards(), at, at.saturating_add(len));
  557. // A placed texture there changes with no descriptor written.
  558. crate::descriptor::host::remapped(at, len);
  559. }
  560. /// Held shared by a read of title memory in place, and alone by the runtime
  561. /// while it changes what title memory shows.
  562. ///
  563. /// The runtime does not change a mapping in one step. To unmap one page of
  564. /// a view it unmaps the whole view and maps what stays again
  565. /// (`xmem.rs` `unmap`), and a view it maps is a reservation until the next
  566. /// call commits it (`map`, then `commit`). For that moment pages the title
  567. /// never gave up are "reserved, never committed", and a thread reading
  568. /// them in place takes an access violation: run 71 in `Layout::detile`,
  569. /// run 74 in the hash before it, both under `Staging::refresh_now`, which
  570. /// had asked whether the texture was all mapped and been told yes. Asking
  571. /// cannot help; not changing the mapping while such a read is under way
  572. /// does.
  573. static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(());
  574. /// What the runtime holds while it changes what title memory shows
  575. /// ([`title_memory_remapping`]).
  576. pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>);
  577. /// The runtime is about to map, unmap or move physical pages of title
  578. /// memory: until what it returns is dropped, no read of title memory in
  579. /// place is under way and none begins ([`title_memory_reading`]). Taken
  580. /// around the whole change, the unmapping and the mapping again.
  581. pub fn title_memory_remapping() -> Remapping {
  582. Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner()))
  583. }
  584. /// What a read of title memory in place holds ([`title_memory_reading`]).
  585. pub struct Reading(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>);
  586. /// For reading title memory in place: until what it returns is dropped,
  587. /// the runtime changes no mapping, so memory found mapped stays mapped.
  588. /// Not to be taken twice by one thread, nor held across anything that
  589. /// maps title memory.
  590. pub fn title_memory_reading() -> Reading {
  591. Reading(MAPPING.read().unwrap_or_else(|e| e.into_inner()))
  592. }
  593. /// [`title_memory_reading`] if it can be had at once: `None` while the
  594. /// runtime changes a mapping (or waits to), for a caller that has another
  595. /// way to read and would rather not wait.
  596. pub fn title_memory_reading_now() -> Option<Reading> {
  597. match MAPPING.try_read() {
  598. Ok(guard) => Some(Reading(guard)),
  599. Err(std::sync::TryLockError::Poisoned(e)) => Some(Reading(e.into_inner())),
  600. Err(std::sync::TryLockError::WouldBlock) => None,
  601. }
  602. }
  603. /// The runtime mapped or unmapped title memory `[at, at + len)`: what it
  604. /// shows is new and read-write, so it is no longer guarded (nor known
  605. /// unmapped).
  606. pub fn title_memory_remapped(at: usize, len: usize) {
  607. // A placed texture there arrives, goes or changes with no descriptor
  608. // written.
  609. crate::descriptor::host::remapped(at, len);
  610. // The views the runtime told us of there are no longer what it shows.
  611. crate::inplace::views_gone(at, len);
  612. // And nothing stays in place over it.
  613. crate::inplace::title_memory_freeing(at, len);
  614. let mut g = guards();
  615. let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK);
  616. let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect();
  617. for block in absent {
  618. g.absent.remove(&block);
  619. }
  620. let blocks: Vec<usize> = g.protected.range(range).copied().collect();
  621. for block in blocks {
  622. g.protected.remove(&block);
  623. g.clean.remove(&block);
  624. }
  625. }
  626. /// Registers the handler that takes writes to guarded blocks, once, ahead
  627. /// of the crash reporter's.
  628. fn install() {
  629. use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
  630. use windows_sys::Win32::System::Diagnostics::Debug::{
  631. AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH,
  632. EXCEPTION_POINTERS,
  633. };
  634. unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 {
  635. // SAFETY: the system passes the exception being dispatched.
  636. let r = unsafe { &*(*info).ExceptionRecord };
  637. const WRITE: usize = 1;
  638. if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS
  639. || r.NumberParameters < 2
  640. || r.ExceptionInformation[0] != WRITE
  641. {
  642. return EXCEPTION_CONTINUE_SEARCH;
  643. }
  644. let at = r.ExceptionInformation[1];
  645. // Held across both checks: another thread may have opened the block
  646. // since this one faulted, and a copy may have guarded it again since
  647. // (then it is ours again, not read-only for some other reason).
  648. let mut g = guards();
  649. if open(&mut g, at, at + 1) {
  650. #[cfg(feature = "diagnostics")]
  651. crate::copystat::add(crate::copystat::C::GuardFaults, 1);
  652. return EXCEPTION_CONTINUE_EXECUTION;
  653. }
  654. if writable(at) {
  655. EXCEPTION_CONTINUE_EXECUTION
  656. } else {
  657. EXCEPTION_CONTINUE_SEARCH
  658. }
  659. }
  660. static ONCE: std::sync::Once = std::sync::Once::new();
  661. // SAFETY: the handler only touches our guard state and protections.
  662. ONCE.call_once(|| unsafe {
  663. AddVectoredExceptionHandler(1, Some(on_write));
  664. });
  665. }
  666. /// Whether `at` is committed read-write memory now.
  667. fn writable(at: usize) -> bool {
  668. use windows_sys::Win32::System::Memory::{
  669. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery,
  670. };
  671. // SAFETY: plain data filled in by the query.
  672. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  673. // SAFETY: a valid out pointer of the right size.
  674. let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
  675. n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE
  676. }
  677. #[cfg(test)]
  678. mod tests {
  679. use super::*;
  680. use windows_sys::Win32::System::Memory::{
  681. MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree,
  682. };
  683. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  684. #[test]
  685. fn written_pages_are_reported_to_every_asker() {
  686. // SAFETY: a fresh write-watched allocation, freed at the end.
  687. let p = unsafe {
  688. VirtualAlloc(
  689. std::ptr::null(),
  690. 4 * PAGE,
  691. MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
  692. PAGE_READWRITE,
  693. )
  694. } as usize;
  695. assert_ne!(p, 0);
  696. let (start, end) = (p, p + 4 * PAGE);
  697. let (_, before) = writes(start, end, false).expect("watched");
  698. assert!(before.is_empty());
  699. // SAFETY: committed pages of ours.
  700. unsafe { ((p + PAGE + 8) as *mut u8).write(1) };
  701. let (now, after) = writes(start, end, false).expect("watched");
  702. assert_eq!(after, [(p / PAGE + 1, now)]);
  703. // Another asker after the kernel's bit was cleared still sees it.
  704. let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched");
  705. assert!(later > now);
  706. assert_eq!(again, [(p / PAGE + 1, now)]);
  707. let mut plain = vec![0u8; PAGE];
  708. assert!(
  709. writes(
  710. plain.as_mut_ptr() as usize,
  711. plain.as_ptr() as usize + PAGE,
  712. true
  713. )
  714. .is_none()
  715. );
  716. // SAFETY: our allocation.
  717. unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
  718. }
  719. /// A kernel read into a guarded view block fails; opened first, it
  720. /// lands and the block counts as written.
  721. #[test]
  722. fn kernel_reads_into_guarded_blocks_after_opening() {
  723. use std::io::{Read, Seek, Write};
  724. use windows_sys::Win32::System::Memory::{
  725. CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
  726. };
  727. // SAFETY: a pagefile section of two blocks, mapped read-write.
  728. let view = unsafe {
  729. let section = CreateFileMappingW(
  730. -1isize as _,
  731. std::ptr::null(),
  732. PAGE_READWRITE,
  733. 0,
  734. (2 * BLOCK) as u32,
  735. std::ptr::null(),
  736. );
  737. assert!(!section.is_null());
  738. MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize
  739. };
  740. assert_ne!(view, 0);
  741. assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only
  742. let mut file = tempfile::tempfile().unwrap();
  743. file.write_all(b"from the disk").unwrap();
  744. // `ReadFile` inside: the kernel writes the view.
  745. let read = |file: &mut std::fs::File| {
  746. file.rewind().unwrap();
  747. // SAFETY: 13 bytes of our view, nothing else refers to them.
  748. let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) };
  749. file.read(into).is_ok_and(|n| n == 13)
  750. };
  751. assert!(
  752. !read(&mut file),
  753. "the kernel does not fault into our handler"
  754. );
  755. writing(view + 100, 13);
  756. assert!(read(&mut file));
  757. // SAFETY: the bytes just read.
  758. let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) };
  759. assert_eq!(landed, b"from the disk");
  760. assert_eq!(
  761. guard(view, view + 2 * BLOCK),
  762. Some((view / PAGE..view / PAGE + 1).collect())
  763. );
  764. // SAFETY: our view.
  765. unsafe {
  766. UnmapViewOfFile(
  767. windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS {
  768. Value: view as *mut _,
  769. },
  770. )
  771. };
  772. title_memory_remapped(view, 2 * BLOCK);
  773. }
  774. #[test]
  775. fn writes_in_partly_committed_view_blocks_are_reported() {
  776. use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
  777. use windows_sys::Win32::System::Memory::{
  778. CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile,
  779. SEC_RESERVE, UnmapViewOfFile,
  780. };
  781. const SIZE: usize = 3 * BLOCK;
  782. struct View(MEMORY_MAPPED_VIEW_ADDRESS);
  783. impl Drop for View {
  784. fn drop(&mut self) {
  785. title_memory_remapped(self.0.Value as usize, SIZE);
  786. // SAFETY: our view is still mapped.
  787. unsafe { UnmapViewOfFile(self.0) };
  788. }
  789. }
  790. // SAFETY: a new reserved pagefile section. The view holds its own
  791. // reference after we close the handle, including on assertion failure.
  792. let view = unsafe {
  793. let section = CreateFileMappingW(
  794. INVALID_HANDLE_VALUE,
  795. std::ptr::null(),
  796. PAGE_READWRITE | SEC_RESERVE,
  797. 0,
  798. SIZE as u32,
  799. std::ptr::null(),
  800. );
  801. assert!(!section.is_null());
  802. let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, SIZE);
  803. CloseHandle(section);
  804. assert!(!view.Value.is_null());
  805. View(view)
  806. };
  807. let start = view.0.Value as usize;
  808. let commit = |at: usize, len| {
  809. // SAFETY: these pages belong to our reserved view.
  810. let committed = unsafe { VirtualAlloc(at as _, len, MEM_COMMIT, PAGE_READWRITE) };
  811. assert_eq!(committed as usize, at);
  812. };
  813. let early = start + BLOCK + 3 * KERNEL_PAGE;
  814. let late = start + 2 * BLOCK + 3 * KERNEL_PAGE;
  815. commit(start, BLOCK);
  816. commit(early, KERNEL_PAGE);
  817. let refresh = || guard(start, start + SIZE).unwrap();
  818. assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]);
  819. // The last block is still entirely reserved.
  820. assert!(!refresh().contains(&(late / PAGE)));
  821. commit(late, KERNEL_PAGE); // Ordinary commit, without a runtime mapping notification.
  822. for at in [early, late] {
  823. assert!(writable(at));
  824. // SAFETY: each address is inside its committed read-write page.
  825. unsafe { (at as *mut u8).write_volatile(1) };
  826. }
  827. assert_eq!(refresh(), [early / PAGE, late / PAGE]);
  828. }
  829. /// A range of view memory whose first block is not mapped is a view
  830. /// all the same: its blocks are reported once, then the ones written
  831. /// or mapped since.
  832. #[test]
  833. fn a_range_that_begins_in_an_unmapped_block_is_guarded() {
  834. use windows_sys::Win32::System::Memory::{
  835. CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER,
  836. MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2,
  837. VirtualAlloc2,
  838. };
  839. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  840. // SAFETY: a fresh placeholder of three blocks and a pagefile
  841. // section of three; the middle block is mapped first.
  842. let (p, section) = unsafe {
  843. let p = VirtualAlloc2(
  844. GetCurrentProcess(),
  845. std::ptr::null(),
  846. 3 * BLOCK,
  847. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  848. PAGE_NOACCESS,
  849. std::ptr::null_mut(),
  850. 0,
  851. ) as usize;
  852. assert_ne!(p, 0);
  853. let section = CreateFileMappingW(
  854. -1isize as _,
  855. std::ptr::null(),
  856. PAGE_READWRITE,
  857. 0,
  858. (3 * BLOCK) as u32,
  859. std::ptr::null(),
  860. );
  861. assert!(!section.is_null());
  862. (p, section)
  863. };
  864. let map = |block: usize| {
  865. // SAFETY: splits the placeholder at the block and maps the
  866. // section's block there.
  867. let view = unsafe {
  868. VirtualFree(
  869. (p + block * BLOCK) as *mut _,
  870. BLOCK,
  871. MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
  872. );
  873. MapViewOfFile3(
  874. section,
  875. GetCurrentProcess(),
  876. (p + block * BLOCK) as *const _,
  877. (block * BLOCK) as u64,
  878. BLOCK,
  879. MEM_REPLACE_PLACEHOLDER,
  880. PAGE_READWRITE,
  881. std::ptr::null_mut(),
  882. 0,
  883. )
  884. };
  885. assert_eq!(view.Value as usize, p + block * BLOCK);
  886. view
  887. };
  888. let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE;
  889. let all: Vec<usize> = (0..3).flat_map(pages).collect();
  890. // Nothing mapped at all: a view with every block absent.
  891. assert!(is_view(p, p + 3 * BLOCK));
  892. let middle = map(1);
  893. title_memory_remapped(p + BLOCK, BLOCK);
  894. // The range begins in the placeholder, its middle block is a view.
  895. assert!(is_view(p, p + 3 * BLOCK));
  896. assert_eq!(guard(p, p + 3 * BLOCK), Some(all));
  897. assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since");
  898. // SAFETY: inside the mapped middle block.
  899. unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) };
  900. assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
  901. let first = map(0);
  902. title_memory_remapped(p, BLOCK);
  903. assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect()));
  904. assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
  905. // Memory of ours that is no view stays none.
  906. let mut local = [0u8; 16];
  907. let at = local.as_mut_ptr() as usize;
  908. assert!(!is_view(at, at + local.len()));
  909. // SAFETY: our views and placeholder.
  910. unsafe {
  911. UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
  912. UnmapViewOfFile2(GetCurrentProcess(), middle, MEM_PRESERVE_PLACEHOLDER);
  913. for block in 0..3 {
  914. VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
  915. }
  916. windows_sys::Win32::Foundation::CloseHandle(section);
  917. }
  918. title_memory_remapped(p, 3 * BLOCK);
  919. }
  920. /// Blocks of a placeholder between views are reported once, then not
  921. /// again (they cannot be guarded) until the runtime maps them.
  922. #[test]
  923. fn unmapped_blocks_are_reported_once_until_mapped() {
  924. use windows_sys::Win32::System::Memory::{
  925. CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER,
  926. MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2,
  927. VirtualAlloc2,
  928. };
  929. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  930. // SAFETY: a fresh placeholder of three blocks and a pagefile
  931. // section of two; block 0 shows the section's first block, as the
  932. // runtime maps physical pages.
  933. let (p, section) = unsafe {
  934. let p = VirtualAlloc2(
  935. GetCurrentProcess(),
  936. std::ptr::null(),
  937. 3 * BLOCK,
  938. MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
  939. PAGE_NOACCESS,
  940. std::ptr::null_mut(),
  941. 0,
  942. ) as usize;
  943. assert_ne!(p, 0);
  944. let section = CreateFileMappingW(
  945. -1isize as _,
  946. std::ptr::null(),
  947. PAGE_READWRITE,
  948. 0,
  949. (2 * BLOCK) as u32,
  950. std::ptr::null(),
  951. );
  952. assert!(!section.is_null());
  953. (p, section)
  954. };
  955. let map = |block: usize| {
  956. // SAFETY: splits the placeholder at the block and maps the
  957. // section's block there.
  958. let view = unsafe {
  959. VirtualFree(
  960. (p + block * BLOCK) as *mut _,
  961. BLOCK,
  962. MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
  963. );
  964. MapViewOfFile3(
  965. section,
  966. GetCurrentProcess(),
  967. (p + block * BLOCK) as *const _,
  968. (block * BLOCK) as u64,
  969. BLOCK,
  970. MEM_REPLACE_PLACEHOLDER,
  971. PAGE_READWRITE,
  972. std::ptr::null_mut(),
  973. 0,
  974. )
  975. };
  976. assert_eq!(view.Value as usize, p + block * BLOCK);
  977. view
  978. };
  979. let first = map(0);
  980. let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE;
  981. let all: Vec<usize> = (0..3).flat_map(pages).collect();
  982. assert_eq!(guard(p, p + 3 * BLOCK), Some(all));
  983. assert_eq!(
  984. guard(p, p + 3 * BLOCK),
  985. Some(Vec::new()),
  986. "nothing written since"
  987. );
  988. let second = map(1);
  989. title_memory_remapped(p + BLOCK, BLOCK);
  990. assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
  991. assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
  992. // SAFETY: our views and placeholder.
  993. unsafe {
  994. UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
  995. UnmapViewOfFile2(GetCurrentProcess(), second, MEM_PRESERVE_PLACEHOLDER);
  996. for block in 0..3 {
  997. VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
  998. }
  999. windows_sys::Win32::Foundation::CloseHandle(section);
  1000. }
  1001. title_memory_remapped(p, 3 * BLOCK);
  1002. }
  1003. /// A write or mapping that runs past the end of the address space (a
  1004. /// title's `fread` with a huge count) covers up to the end; the sum used
  1005. /// to overflow. Up there no test has guarded blocks.
  1006. #[test]
  1007. fn ranges_past_the_address_space_end_do_not_overflow() {
  1008. let top = usize::MAX - 16;
  1009. writing(top, PAGE);
  1010. title_memory_remapped(top, usize::MAX);
  1011. }
  1012. }
  1013. #[cfg(test)]
  1014. mod mapping_tests {
  1015. use super::{title_memory_reading, title_memory_remapping};
  1016. use std::sync::atomic::{AtomicBool, Ordering};
  1017. use std::sync::{Arc, mpsc};
  1018. use std::time::Duration;
  1019. /// A change of mapping waits for a read in place that is under way, and
  1020. /// a read in place waits for a change of mapping.
  1021. #[test]
  1022. fn reads_in_place_and_remappings_wait_for_each_other() {
  1023. // A reader holds; the change does not begin until it lets go.
  1024. let changed = Arc::new(AtomicBool::new(false));
  1025. let reading = title_memory_reading();
  1026. let (began, wait) = mpsc::channel();
  1027. let change = {
  1028. let changed = changed.clone();
  1029. std::thread::spawn(move || {
  1030. began.send(()).unwrap();
  1031. let _changing = title_memory_remapping();
  1032. changed.store(true, Ordering::SeqCst);
  1033. })
  1034. };
  1035. wait.recv().unwrap();
  1036. std::thread::sleep(Duration::from_millis(100));
  1037. assert!(!changed.load(Ordering::SeqCst), "the mapping changed under a read in place");
  1038. drop(reading);
  1039. change.join().unwrap();
  1040. assert!(changed.load(Ordering::SeqCst));
  1041. // A change holds; the read does not begin until it is done.
  1042. let read = Arc::new(AtomicBool::new(false));
  1043. let changing = title_memory_remapping();
  1044. let (began, wait) = mpsc::channel();
  1045. let reader = {
  1046. let read = read.clone();
  1047. std::thread::spawn(move || {
  1048. began.send(()).unwrap();
  1049. let _reading = title_memory_reading();
  1050. read.store(true, Ordering::SeqCst);
  1051. })
  1052. };
  1053. wait.recv().unwrap();
  1054. std::thread::sleep(Duration::from_millis(100));
  1055. assert!(!read.load(Ordering::SeqCst), "a read in place began during a change of mapping");
  1056. drop(changing);
  1057. reader.join().unwrap();
  1058. assert!(read.load(Ordering::SeqCst));
  1059. }
  1060. }