watch.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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.
  14. //!
  15. //! shortcut: writes into physical pages through another view (xmem's
  16. //! `write_physical`, DirectStorage's page destinations) are not seen at
  17. //! the guarded addresses; they go to the texture pool, whose textures are
  18. //! hashed, not guarded. A system call writing into a guarded block fails
  19. //! (none is known to).
  20. use std::collections::{BTreeMap, BTreeSet};
  21. use std::sync::Mutex;
  22. /// The unit tracked and copied: 64 KiB, the console's page (the kernel's
  23. /// 4 KiB pages fold into it). Finer units made the checks of the world's
  24. /// big buffers cost more than the copies they saved.
  25. pub(crate) const PAGE: usize = 64 << 10;
  26. /// The kernel's page, the unit of its answers.
  27. const KERNEL_PAGE: usize = 4096;
  28. struct Journal {
  29. /// Numbers the askings; 0 is "never".
  30. asked: u64,
  31. /// Page number → the asking that last found it written.
  32. written: BTreeMap<usize, u64>,
  33. /// Room for the kernel's answer.
  34. found: Vec<usize>,
  35. }
  36. static JOURNAL: Mutex<Journal> = Mutex::new(Journal {
  37. asked: 0,
  38. written: BTreeMap::new(),
  39. found: Vec::new(),
  40. });
  41. /// The pages of `[start, end)` (whole pages) as last written, for pages
  42. /// written since tracking began: `(page number, asking)` in page order, and
  43. /// this asking's number, which is higher than any in the list but those the
  44. /// kernel just reported. `None` if the memory is not write-watched (nor,
  45. /// with `guarded`, view memory, which is then guarded).
  46. pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> {
  47. use windows_sys::Win32::System::Memory::GetWriteWatch;
  48. const WRITE_WATCH_FLAG_RESET: u32 = 1;
  49. let (first, last) = (start / PAGE, end.div_ceil(PAGE));
  50. let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
  51. let j = &mut *j;
  52. let mut count = (last - first) * PAGE / KERNEL_PAGE;
  53. j.found.resize(count.max(j.found.len()), 0);
  54. let mut granularity = 0;
  55. #[cfg(feature = "diagnostics")]
  56. let started = std::time::Instant::now();
  57. // SAFETY: the answer buffer holds `count` entries.
  58. let failed = unsafe {
  59. GetWriteWatch(
  60. WRITE_WATCH_FLAG_RESET,
  61. (first * PAGE) as *const _,
  62. (last - first) * PAGE,
  63. j.found.as_mut_ptr().cast(),
  64. &mut count,
  65. &mut granularity,
  66. )
  67. } != 0;
  68. let guarded = if failed {
  69. count = 0;
  70. if !guarded {
  71. return None;
  72. }
  73. guard(first * PAGE, last * PAGE)?
  74. } else {
  75. Vec::new()
  76. };
  77. #[cfg(feature = "diagnostics")]
  78. {
  79. use crate::copystat::{C, add};
  80. add(C::Watches, 1);
  81. add(C::WatchUs, started.elapsed().as_micros() as u64);
  82. }
  83. j.asked += 1;
  84. let now = j.asked;
  85. let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded);
  86. for page in pages.collect::<Vec<_>>() {
  87. j.written.insert(page, now);
  88. }
  89. Some((
  90. now,
  91. j.written
  92. .range(first..last)
  93. .map(|(&p, &w)| (p, w))
  94. .collect(),
  95. ))
  96. }
  97. /// Guarded blocks of view memory.
  98. const BLOCK: usize = PAGE;
  99. struct Guards {
  100. /// Blocks we made read-only.
  101. protected: BTreeSet<usize>,
  102. /// Of those, the ones not written since a copy took them.
  103. clean: BTreeSet<usize>,
  104. }
  105. static GUARDS: Mutex<Guards> = Mutex::new(Guards {
  106. protected: BTreeSet::new(),
  107. clean: BTreeSet::new(),
  108. });
  109. fn guards() -> std::sync::MutexGuard<'static, Guards> {
  110. GUARDS.lock().unwrap_or_else(|e| e.into_inner())
  111. }
  112. /// For view memory: the pages of `[start, end)`'s blocks written since
  113. /// they were last guarded (all of a block's pages), guarding them again
  114. /// before the caller copies them. `None` if the memory is not a view.
  115. fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
  116. use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery};
  117. // SAFETY: plain data filled in by the query.
  118. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  119. // SAFETY: a valid out pointer of the right size.
  120. let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) };
  121. if n == 0 || info.Type != MEM_MAPPED {
  122. return None;
  123. }
  124. install();
  125. let mut g = guards();
  126. let mut written = Vec::new();
  127. let mut run: Option<usize> = None;
  128. let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
  129. for block in first..=last {
  130. let open = block < last && !g.clean.contains(&block);
  131. if open {
  132. written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE);
  133. if g.protected.contains(&block) {
  134. // Written through the runtime, still read-only.
  135. g.clean.insert(block);
  136. } else {
  137. run.get_or_insert(block);
  138. continue;
  139. }
  140. }
  141. if let Some(from) = run.take() {
  142. protect(&mut g, from, block);
  143. }
  144. }
  145. Some(written)
  146. }
  147. /// Makes blocks `[from, to)` read-only and notes them guarded and clean;
  148. /// block by block if they span views, leaving out any that fail (unmapped).
  149. fn protect(g: &mut Guards, from: usize, to: usize) {
  150. use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
  151. let set = |from: usize, to: usize| {
  152. let mut old = 0;
  153. // SAFETY: title view memory; only its protection changes.
  154. unsafe {
  155. VirtualProtect(
  156. (from * BLOCK) as *const _,
  157. (to - from) * BLOCK,
  158. PAGE_READONLY,
  159. &mut old,
  160. ) != 0
  161. }
  162. };
  163. let note = |g: &mut Guards, from: usize, to: usize| {
  164. g.protected.extend(from..to);
  165. g.clean.extend(from..to);
  166. };
  167. if set(from, to) {
  168. note(g, from, to);
  169. return;
  170. }
  171. for block in from..to {
  172. if set(block, block + 1) {
  173. note(g, block, block + 1);
  174. }
  175. }
  176. }
  177. /// Gives write access back to the guarded blocks of `[start, end)` and
  178. /// notes them written; true if any was guarded.
  179. fn open(g: &mut Guards, start: usize, end: usize) -> bool {
  180. use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
  181. let blocks: Vec<usize> = g
  182. .protected
  183. .range(start / BLOCK..end.div_ceil(BLOCK))
  184. .copied()
  185. .collect();
  186. for &block in &blocks {
  187. g.protected.remove(&block);
  188. g.clean.remove(&block);
  189. let mut old = 0;
  190. // SAFETY: a block we made read-only.
  191. unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) };
  192. }
  193. !blocks.is_empty()
  194. }
  195. /// Before our own write into title memory `[at, at + len)` through the
  196. /// kernel (which does not fault into our handler): opens its guarded blocks.
  197. /// The runtime calls it (as `kernel_will_write`) before the title's kernel
  198. /// reads into its own memory.
  199. pub fn writing(at: usize, len: usize) {
  200. // The length is the title's (`fread`'s size times count, saturated).
  201. open(&mut guards(), at, at.saturating_add(len));
  202. }
  203. /// The runtime mapped or unmapped title memory `[at, at + len)`: what it
  204. /// shows is new and read-write, so it is no longer guarded.
  205. pub fn title_memory_remapped(at: usize, len: usize) {
  206. let mut g = guards();
  207. let blocks: Vec<usize> = g
  208. .protected
  209. .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK))
  210. .copied()
  211. .collect();
  212. for block in blocks {
  213. g.protected.remove(&block);
  214. g.clean.remove(&block);
  215. }
  216. }
  217. /// Registers the handler that takes writes to guarded blocks, once, ahead
  218. /// of the crash reporter's.
  219. fn install() {
  220. use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
  221. use windows_sys::Win32::System::Diagnostics::Debug::{
  222. AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH,
  223. EXCEPTION_POINTERS,
  224. };
  225. unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 {
  226. // SAFETY: the system passes the exception being dispatched.
  227. let r = unsafe { &*(*info).ExceptionRecord };
  228. const WRITE: usize = 1;
  229. if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS
  230. || r.NumberParameters < 2
  231. || r.ExceptionInformation[0] != WRITE
  232. {
  233. return EXCEPTION_CONTINUE_SEARCH;
  234. }
  235. let at = r.ExceptionInformation[1];
  236. // Held across both checks: another thread may have opened the block
  237. // since this one faulted, and a copy may have guarded it again since
  238. // (then it is ours again, not read-only for some other reason).
  239. let mut g = guards();
  240. if open(&mut g, at, at + 1) {
  241. #[cfg(feature = "diagnostics")]
  242. crate::copystat::add(crate::copystat::C::GuardFaults, 1);
  243. return EXCEPTION_CONTINUE_EXECUTION;
  244. }
  245. if writable(at) {
  246. EXCEPTION_CONTINUE_EXECUTION
  247. } else {
  248. EXCEPTION_CONTINUE_SEARCH
  249. }
  250. }
  251. static ONCE: std::sync::Once = std::sync::Once::new();
  252. // SAFETY: the handler only touches our guard state and protections.
  253. ONCE.call_once(|| unsafe {
  254. AddVectoredExceptionHandler(1, Some(on_write));
  255. });
  256. }
  257. /// Whether `at` is committed read-write memory now.
  258. fn writable(at: usize) -> bool {
  259. use windows_sys::Win32::System::Memory::{
  260. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery,
  261. };
  262. // SAFETY: plain data filled in by the query.
  263. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  264. // SAFETY: a valid out pointer of the right size.
  265. let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
  266. n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE
  267. }
  268. #[cfg(test)]
  269. mod tests {
  270. use super::*;
  271. use windows_sys::Win32::System::Memory::{
  272. MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree,
  273. };
  274. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  275. #[test]
  276. fn written_pages_are_reported_to_every_asker() {
  277. // SAFETY: a fresh write-watched allocation, freed at the end.
  278. let p = unsafe {
  279. VirtualAlloc(
  280. std::ptr::null(),
  281. 4 * PAGE,
  282. MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
  283. PAGE_READWRITE,
  284. )
  285. } as usize;
  286. assert_ne!(p, 0);
  287. let (start, end) = (p, p + 4 * PAGE);
  288. let (_, before) = writes(start, end, false).expect("watched");
  289. assert!(before.is_empty());
  290. // SAFETY: committed pages of ours.
  291. unsafe { ((p + PAGE + 8) as *mut u8).write(1) };
  292. let (now, after) = writes(start, end, false).expect("watched");
  293. assert_eq!(after, [(p / PAGE + 1, now)]);
  294. // Another asker after the kernel's bit was cleared still sees it.
  295. let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched");
  296. assert!(later > now);
  297. assert_eq!(again, [(p / PAGE + 1, now)]);
  298. let mut plain = vec![0u8; PAGE];
  299. assert!(
  300. writes(
  301. plain.as_mut_ptr() as usize,
  302. plain.as_ptr() as usize + PAGE,
  303. true
  304. )
  305. .is_none()
  306. );
  307. // SAFETY: our allocation.
  308. unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
  309. }
  310. /// A kernel read into a guarded view block fails; opened first, it
  311. /// lands and the block counts as written.
  312. #[test]
  313. fn kernel_reads_into_guarded_blocks_after_opening() {
  314. use std::io::{Read, Seek, Write};
  315. use windows_sys::Win32::System::Memory::{
  316. CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
  317. };
  318. // SAFETY: a pagefile section of two blocks, mapped read-write.
  319. let view = unsafe {
  320. let section = CreateFileMappingW(
  321. -1isize as _,
  322. std::ptr::null(),
  323. PAGE_READWRITE,
  324. 0,
  325. (2 * BLOCK) as u32,
  326. std::ptr::null(),
  327. );
  328. assert!(!section.is_null());
  329. MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize
  330. };
  331. assert_ne!(view, 0);
  332. assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only
  333. let mut file = tempfile::tempfile().unwrap();
  334. file.write_all(b"from the disk").unwrap();
  335. // `ReadFile` inside: the kernel writes the view.
  336. let read = |file: &mut std::fs::File| {
  337. file.rewind().unwrap();
  338. // SAFETY: 13 bytes of our view, nothing else refers to them.
  339. let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) };
  340. file.read(into).is_ok_and(|n| n == 13)
  341. };
  342. assert!(!read(&mut file), "the kernel does not fault into our handler");
  343. writing(view + 100, 13);
  344. assert!(read(&mut file));
  345. // SAFETY: the bytes just read.
  346. assert_eq!(unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, b"from the disk");
  347. assert_eq!(guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()));
  348. // SAFETY: our view.
  349. unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) };
  350. title_memory_remapped(view, 2 * BLOCK);
  351. }
  352. /// A write or mapping that runs past the end of the address space (a
  353. /// title's `fread` with a huge count) covers up to the end; the sum used
  354. /// to overflow. Up there no test has guarded blocks.
  355. #[test]
  356. fn ranges_past_the_address_space_end_do_not_overflow() {
  357. let top = usize::MAX - 16;
  358. writing(top, PAGE);
  359. title_memory_remapped(top, usize::MAX);
  360. }
  361. }