watch.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. open(&mut guards(), at, at + len);
  201. }
  202. /// The runtime mapped or unmapped title memory `[at, at + len)`: what it
  203. /// shows is new and read-write, so it is no longer guarded.
  204. pub fn title_memory_remapped(at: usize, len: usize) {
  205. let mut g = guards();
  206. let blocks: Vec<usize> = g
  207. .protected
  208. .range(at / BLOCK..(at + len).div_ceil(BLOCK))
  209. .copied()
  210. .collect();
  211. for block in blocks {
  212. g.protected.remove(&block);
  213. g.clean.remove(&block);
  214. }
  215. }
  216. /// Registers the handler that takes writes to guarded blocks, once, ahead
  217. /// of the crash reporter's.
  218. fn install() {
  219. use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
  220. use windows_sys::Win32::System::Diagnostics::Debug::{
  221. AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH,
  222. EXCEPTION_POINTERS,
  223. };
  224. unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 {
  225. // SAFETY: the system passes the exception being dispatched.
  226. let r = unsafe { &*(*info).ExceptionRecord };
  227. const WRITE: usize = 1;
  228. if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS
  229. || r.NumberParameters < 2
  230. || r.ExceptionInformation[0] != WRITE
  231. {
  232. return EXCEPTION_CONTINUE_SEARCH;
  233. }
  234. let at = r.ExceptionInformation[1];
  235. if open(&mut guards(), at, at + 1) {
  236. #[cfg(feature = "diagnostics")]
  237. crate::copystat::add(crate::copystat::C::GuardFaults, 1);
  238. return EXCEPTION_CONTINUE_EXECUTION;
  239. }
  240. // Another thread may have opened the block since this one faulted.
  241. if writable(at) {
  242. EXCEPTION_CONTINUE_EXECUTION
  243. } else {
  244. EXCEPTION_CONTINUE_SEARCH
  245. }
  246. }
  247. static ONCE: std::sync::Once = std::sync::Once::new();
  248. // SAFETY: the handler only touches our guard state and protections.
  249. ONCE.call_once(|| unsafe {
  250. AddVectoredExceptionHandler(1, Some(on_write));
  251. });
  252. }
  253. /// Whether `at` is committed read-write memory now.
  254. fn writable(at: usize) -> bool {
  255. use windows_sys::Win32::System::Memory::{
  256. MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery,
  257. };
  258. // SAFETY: plain data filled in by the query.
  259. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  260. // SAFETY: a valid out pointer of the right size.
  261. let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
  262. n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE
  263. }
  264. #[cfg(test)]
  265. mod tests {
  266. use super::*;
  267. use windows_sys::Win32::System::Memory::{
  268. MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree,
  269. };
  270. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  271. #[test]
  272. fn written_pages_are_reported_to_every_asker() {
  273. // SAFETY: a fresh write-watched allocation, freed at the end.
  274. let p = unsafe {
  275. VirtualAlloc(
  276. std::ptr::null(),
  277. 4 * PAGE,
  278. MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
  279. PAGE_READWRITE,
  280. )
  281. } as usize;
  282. assert_ne!(p, 0);
  283. let (start, end) = (p, p + 4 * PAGE);
  284. let (_, before) = writes(start, end, false).expect("watched");
  285. assert!(before.is_empty());
  286. // SAFETY: committed pages of ours.
  287. unsafe { ((p + PAGE + 8) as *mut u8).write(1) };
  288. let (now, after) = writes(start, end, false).expect("watched");
  289. assert_eq!(after, [(p / PAGE + 1, now)]);
  290. // Another asker after the kernel's bit was cleared still sees it.
  291. let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched");
  292. assert!(later > now);
  293. assert_eq!(again, [(p / PAGE + 1, now)]);
  294. let mut plain = vec![0u8; PAGE];
  295. assert!(
  296. writes(
  297. plain.as_mut_ptr() as usize,
  298. plain.as_ptr() as usize + PAGE,
  299. true
  300. )
  301. .is_none()
  302. );
  303. // SAFETY: our allocation.
  304. unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
  305. }
  306. /// A kernel read into a guarded view block fails; opened first, it
  307. /// lands and the block counts as written.
  308. #[test]
  309. fn kernel_reads_into_guarded_blocks_after_opening() {
  310. use std::io::{Read, Seek, Write};
  311. use windows_sys::Win32::System::Memory::{
  312. CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
  313. };
  314. // SAFETY: a pagefile section of two blocks, mapped read-write.
  315. let view = unsafe {
  316. let section = CreateFileMappingW(
  317. -1isize as _,
  318. std::ptr::null(),
  319. PAGE_READWRITE,
  320. 0,
  321. (2 * BLOCK) as u32,
  322. std::ptr::null(),
  323. );
  324. assert!(!section.is_null());
  325. MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize
  326. };
  327. assert_ne!(view, 0);
  328. assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only
  329. let mut file = tempfile::tempfile().unwrap();
  330. file.write_all(b"from the disk").unwrap();
  331. // `ReadFile` inside: the kernel writes the view.
  332. let read = |file: &mut std::fs::File| {
  333. file.rewind().unwrap();
  334. // SAFETY: 13 bytes of our view, nothing else refers to them.
  335. let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) };
  336. file.read(into).is_ok_and(|n| n == 13)
  337. };
  338. assert!(!read(&mut file), "the kernel does not fault into our handler");
  339. writing(view + 100, 13);
  340. assert!(read(&mut file));
  341. // SAFETY: the bytes just read.
  342. assert_eq!(unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, b"from the disk");
  343. assert_eq!(guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()));
  344. // SAFETY: our view.
  345. unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) };
  346. title_memory_remapped(view, 2 * BLOCK);
  347. }
  348. }