safecopy.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. //! Copies between our memory and the title's that fail instead of faulting.
  2. //!
  3. //! Title memory may be unmapped, remapped or made read-only by the title's
  4. //! other threads while we copy it, so copies went through the kernel
  5. //! (`ReadProcessMemory`, `NtWriteVirtualMemory`), which reports a missing
  6. //! page instead of faulting: some 35,000 calls a frame, each of which locks
  7. //! the pages it copies, 39 ms of kernel time on the submitting thread alone.
  8. //!
  9. //! [`copy`] is one `rep movsb`. A fault in it is taken by the handler of
  10. //! [`crate::watch`] (`on_write`, the first in the process), which opens a
  11. //! block we guard ourselves and lets the copy go on, and otherwise sends it
  12. //! to its failing exit. `VICTORY_SAFE_COPY=0`: through the kernel, as before.
  13. use std::sync::OnceLock;
  14. std::arch::global_asm!(
  15. ".globl victory_safe_copy",
  16. ".globl victory_safe_copy_at",
  17. ".globl victory_safe_copy_after",
  18. ".globl victory_safe_copy_failed",
  19. // rcx destination, rdx source, r8 bytes; eax: whether all were copied.
  20. // A leaf that leaves the stack alone (the two registers it must give
  21. // back are kept in volatile ones), so a stack walk through it works.
  22. "victory_safe_copy:",
  23. "mov r10, rsi",
  24. "mov r11, rdi",
  25. "mov rdi, rcx",
  26. "mov rsi, rdx",
  27. "mov rcx, r8",
  28. "victory_safe_copy_at:",
  29. "rep movsb",
  30. "victory_safe_copy_after:",
  31. "mov eax, 1",
  32. "mov rsi, r10",
  33. "mov rdi, r11",
  34. "ret",
  35. "victory_safe_copy_failed:",
  36. "xor eax, eax",
  37. "mov rsi, r10",
  38. "mov rdi, r11",
  39. "ret",
  40. ".globl victory_safe_put",
  41. ".globl victory_safe_put_at",
  42. ".globl victory_safe_put_after",
  43. ".globl victory_safe_put_failed",
  44. // rcx destination, rdx what was there, r8 what is to be there, r9 blocks
  45. // of eight dwords: stores the dwords in which the two differ, and no
  46. // other byte. eax: whether all could be stored.
  47. "victory_safe_put:",
  48. "test r9, r9",
  49. "jz 4f",
  50. "vpcmpeqd ymm3, ymm3, ymm3",
  51. "2:",
  52. "vmovdqu ymm1, ymmword ptr [r8]",
  53. "vpcmpeqd ymm2, ymm1, ymmword ptr [rdx]",
  54. "vmovmskps eax, ymm2",
  55. "cmp eax, 255",
  56. "je 3f",
  57. "vpxor ymm2, ymm2, ymm3",
  58. "victory_safe_put_at:",
  59. "vpmaskmovd ymmword ptr [rcx], ymm2, ymm1",
  60. "victory_safe_put_after:",
  61. "nop",
  62. "3:",
  63. "add rcx, 32",
  64. "add rdx, 32",
  65. "add r8, 32",
  66. "dec r9",
  67. "jnz 2b",
  68. "vzeroupper",
  69. "4:",
  70. "mov eax, 1",
  71. "ret",
  72. "victory_safe_put_failed:",
  73. "vzeroupper",
  74. "xor eax, eax",
  75. "ret",
  76. ".globl victory_safe_merge",
  77. ".globl victory_safe_merge_at",
  78. ".globl victory_safe_merge_after",
  79. ".globl victory_safe_merge_failed",
  80. // rcx title memory, rdx what the card holds, r8 what it held when last
  81. // looked at, r9 blocks of 32 bytes, fifth where the two counts go. Where
  82. // a byte of the second differs from the third, it goes into title memory
  83. // (as whole dwords, and only dwords that then differ from what is there)
  84. // and into the third; each block of title memory is read just before it
  85. // is written. rax: the blocks left when a page of title memory could not
  86. // be read or written (0: all done). The counts: blocks in which the
  87. // second and third differed, dwords stored in title memory.
  88. "victory_safe_merge:",
  89. "xor r10d, r10d",
  90. "xor r11d, r11d",
  91. "test r9, r9",
  92. "jz 6f",
  93. "vpcmpeqd ymm5, ymm5, ymm5",
  94. "2:",
  95. "vmovdqu ymm0, ymmword ptr [rdx]",
  96. "vpcmpeqb ymm1, ymm0, ymmword ptr [r8]",
  97. "vpmovmskb eax, ymm1",
  98. "cmp eax, -1",
  99. "je 5f",
  100. "victory_safe_merge_at:",
  101. "vmovdqu ymm2, ymmword ptr [rcx]",
  102. "vpblendvb ymm3, ymm0, ymm2, ymm1",
  103. "vpcmpeqd ymm4, ymm3, ymm2",
  104. "vmovmskps eax, ymm4",
  105. "xor eax, 255",
  106. "jz 4f",
  107. "cmp eax, 255",
  108. "je 3f",
  109. "vpxor ymm4, ymm4, ymm5",
  110. "vpmaskmovd ymmword ptr [rcx], ymm4, ymm3",
  111. "jmp 7f",
  112. "3:",
  113. "vmovdqu ymmword ptr [rcx], ymm3",
  114. "victory_safe_merge_after:",
  115. "7:",
  116. "popcnt eax, eax",
  117. "add r11, rax",
  118. "4:",
  119. "inc r10",
  120. "vmovdqu ymmword ptr [r8], ymm0",
  121. "5:",
  122. "add rcx, 32",
  123. "add rdx, 32",
  124. "add r8, 32",
  125. "dec r9",
  126. "jnz 2b",
  127. "6:",
  128. "victory_safe_merge_failed:",
  129. "vzeroupper",
  130. "mov rax, qword ptr [rsp + 40]",
  131. "mov qword ptr [rax], r10",
  132. "mov qword ptr [rax + 8], r11",
  133. "mov rax, r9",
  134. "ret",
  135. );
  136. unsafe extern "system" {
  137. fn victory_safe_copy(dst: *mut u8, src: *const u8, len: usize) -> u32;
  138. fn victory_safe_copy_at();
  139. fn victory_safe_copy_after();
  140. fn victory_safe_copy_failed();
  141. fn victory_safe_put(dst: *mut u8, was: *const u8, now: *const u8, blocks: usize) -> u32;
  142. fn victory_safe_put_at();
  143. fn victory_safe_put_after();
  144. fn victory_safe_put_failed();
  145. fn victory_safe_merge(title: *mut u8, now: *const u8, held: *mut u8, blocks: usize, counts: *mut [u64; 2]) -> usize;
  146. fn victory_safe_merge_at();
  147. fn victory_safe_merge_after();
  148. fn victory_safe_merge_failed();
  149. }
  150. /// What [`merge`] did.
  151. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
  152. pub(crate) struct Merged {
  153. /// Blocks of 32 bytes in which the card's bytes were new.
  154. pub(crate) new: u64,
  155. /// Dwords stored in title memory.
  156. pub(crate) dwords: u64,
  157. /// Whether title memory could be read and written wherever it had to be.
  158. pub(crate) there: bool,
  159. }
  160. /// What shaders wrote goes into title memory: every byte of `now` that
  161. /// differs from the one in `held` goes to `title` and into `held`, every
  162. /// other byte of both stays as it is. Title memory is read 32 bytes at a
  163. /// time, each just before what changes of them is stored, and only the
  164. /// dwords that change are stored (at ends that are no dword's, bytes): the
  165. /// title's own threads may be writing those beside them.
  166. ///
  167. /// Where title memory cannot be read or written, the rest of `held` takes
  168. /// `now` if `take` says so (the caller has the card's bytes nowhere else),
  169. /// else it stays.
  170. ///
  171. /// # Safety
  172. /// `now` and `held` are `len` bytes of ours, not overlapping, that nothing
  173. /// else writes (but for `now` the card: it is read once); `title` is as
  174. /// [`copy`]'s. The stretch lies in one page of 4 KiB of title memory. [`on`]
  175. /// must have been asked.
  176. pub(crate) unsafe fn merge(title: *mut u8, now: *const u8, held: *mut u8, len: usize, take: bool) -> Merged {
  177. let mut out = Merged { there: true, ..Merged::default() };
  178. let mut at = 0;
  179. while at < len {
  180. let address = title.addr() + at;
  181. let left = len - at;
  182. if !address.is_multiple_of(4) || left < 4 {
  183. // A dword only partly in the stretch: its bytes one by one.
  184. // SAFETY: inside the stretch.
  185. unsafe {
  186. let byte = now.add(at).read_volatile();
  187. let mut there = 0u8;
  188. if byte != held.add(at).read() {
  189. out.new += 1;
  190. let mut ok = copy(&mut there, title.add(at), 1);
  191. if ok && there != byte {
  192. ok = copy(title.add(at), &byte, 1);
  193. out.dwords += u64::from(ok);
  194. }
  195. out.there &= ok;
  196. if ok || take {
  197. held.add(at).write(byte);
  198. }
  199. }
  200. }
  201. at += 1;
  202. continue;
  203. }
  204. let into = address % 32;
  205. let mut counts = [0u64; 2];
  206. if into != 0 || left < 32 {
  207. // Part of a block: in a block of its own, equal beside the part.
  208. let n = (32 - into).min(left) & !3;
  209. let (mut new, mut old) = ([0u8; 32], [0u8; 32]);
  210. // SAFETY: inside the stretch; the block of title memory around
  211. // it lies in the same page, and nothing of it outside the part
  212. // is stored (the two arrays are equal there).
  213. unsafe {
  214. std::ptr::copy_nonoverlapping(now.add(at), new.as_mut_ptr().add(into), n);
  215. std::ptr::copy_nonoverlapping(held.add(at), old.as_mut_ptr().add(into), n);
  216. let stuck = victory_safe_merge(title.wrapping_add(at).wrapping_sub(into), new.as_ptr(), old.as_mut_ptr(), 1, &mut counts);
  217. out.there &= stuck == 0;
  218. let from = if stuck != 0 && take { new.as_ptr() } else { old.as_ptr() };
  219. std::ptr::copy_nonoverlapping(from.add(into), held.add(at), n);
  220. }
  221. at += n;
  222. } else {
  223. let blocks = left / 32;
  224. // SAFETY: whole blocks of the stretch.
  225. let stuck = unsafe { victory_safe_merge(title.add(at), now.add(at), held.add(at), blocks, &mut counts) };
  226. if stuck != 0 {
  227. out.there = false;
  228. if take {
  229. let from = at + (blocks - stuck) * 32;
  230. // SAFETY: the blocks that were not done.
  231. unsafe { std::ptr::copy_nonoverlapping(now.add(from), held.add(from), stuck * 32) };
  232. }
  233. }
  234. at += blocks * 32;
  235. }
  236. out.new += counts[0];
  237. out.dwords += counts[1];
  238. }
  239. out
  240. }
  241. /// Whether the `len` bytes at `a` and `b` differ.
  242. ///
  243. /// # Safety
  244. /// Both are `len` bytes that can be read; the card may be writing them.
  245. pub(crate) unsafe fn differ(a: *const u8, b: *const u8, len: usize) -> bool {
  246. use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_or_si256, _mm256_setzero_si256, _mm256_testz_si256, _mm256_xor_si256};
  247. /// # Safety
  248. /// [`differ`]'s; the processor has AVX2 (as the code above assumes).
  249. #[target_feature(enable = "avx2")]
  250. unsafe fn blocks(a: *const u8, b: *const u8, n: usize) -> bool {
  251. let mut at = 0;
  252. while at < n {
  253. let mut any = _mm256_setzero_si256();
  254. for k in at..n.min(at + 4) {
  255. // SAFETY: block `k`, inside both.
  256. let (x, y) = unsafe {
  257. (_mm256_loadu_si256(a.add(k * 32).cast::<__m256i>()), _mm256_loadu_si256(b.add(k * 32).cast::<__m256i>()))
  258. };
  259. any = _mm256_or_si256(any, _mm256_xor_si256(x, y));
  260. }
  261. if _mm256_testz_si256(any, any) == 0 {
  262. return true;
  263. }
  264. at += 4;
  265. }
  266. false
  267. }
  268. // SAFETY: the caller's.
  269. if unsafe { blocks(a, b, len / 32) } {
  270. return true;
  271. }
  272. // SAFETY: the bytes behind the blocks.
  273. (len / 32 * 32..len).any(|i| unsafe { a.add(i).read_volatile() != b.add(i).read_volatile() })
  274. }
  275. /// Puts `now` at `dst` where it differs from `was`, whole dwords (as `dst`
  276. /// is aligned) and not a byte beside them: other threads may be writing
  277. /// those. At the ends, single bytes of a dword only partly in the stretch.
  278. /// False if a page could not be written; then some may have been.
  279. ///
  280. /// # Safety
  281. /// As [`copy`]'s.
  282. pub(crate) unsafe fn put_changed(dst: *mut u8, was: &[u8], now: &[u8]) -> bool {
  283. assert_eq!(was.len(), now.len());
  284. let n = now.len();
  285. let head = dst.addr().wrapping_neg() & 3;
  286. let head = head.min(n);
  287. let blocks = (n - head) / 32;
  288. let tail = head + blocks * 32;
  289. let mut all = true;
  290. if blocks > 0 {
  291. // SAFETY: the two slices hold the blocks; the destination's faults
  292. // leave through the failing exit.
  293. all &= unsafe { victory_safe_put(dst.add(head), was[head..].as_ptr(), now[head..].as_ptr(), blocks) != 0 };
  294. }
  295. let single = |from: usize, to: usize| {
  296. let mut all = true;
  297. let mut i = from;
  298. while i < to {
  299. // A whole aligned dword, or the bytes there are of one.
  300. let len = (4 - (dst.addr() + i) % 4).min(to - i);
  301. if was[i..i + len] != now[i..i + len] {
  302. // SAFETY: inside the stretch.
  303. all &= unsafe { copy(dst.add(i), now[i..].as_ptr(), len) };
  304. }
  305. i += len;
  306. }
  307. all
  308. };
  309. all &= single(0, head);
  310. all &= single(tail, n);
  311. all
  312. }
  313. /// Whether copies are made here and not by the kernel.
  314. pub(crate) fn on() -> bool {
  315. static ON: OnceLock<bool> = OnceLock::new();
  316. *ON.get_or_init(|| {
  317. let on = std::env::var_os("VICTORY_SAFE_COPY").is_none_or(|v| v != "0");
  318. if on {
  319. crate::watch::install();
  320. }
  321. on
  322. })
  323. }
  324. /// Copies `len` bytes. False if a page of the source cannot be read or one
  325. /// of the destination cannot be written; then some of the bytes may have
  326. /// been copied.
  327. ///
  328. /// # Safety
  329. /// Of the two ranges, what is not title memory must be valid, and no Rust
  330. /// reference may cover the destination. [`on`] must have been asked.
  331. pub(crate) unsafe fn copy(dst: *mut u8, src: *const u8, len: usize) -> bool {
  332. // SAFETY: a fault on either side leaves through the failing exit
  333. // ([`failing_exit`]); the rest is the caller's.
  334. unsafe { victory_safe_copy(dst, src, len) != 0 }
  335. }
  336. /// For the fault handler: where a fault at instruction `at` is to go on, if
  337. /// it is [`copy`]'s.
  338. pub(crate) fn failing_exit(at: usize) -> Option<usize> {
  339. let (from, to) = (victory_safe_copy_at as *const () as usize, victory_safe_copy_after as *const () as usize);
  340. if (from..to).contains(&at) {
  341. return Some(victory_safe_copy_failed as *const () as usize);
  342. }
  343. let (from, to) = (victory_safe_put_at as *const () as usize, victory_safe_put_after as *const () as usize);
  344. if (from..to).contains(&at) {
  345. return Some(victory_safe_put_failed as *const () as usize);
  346. }
  347. let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize);
  348. (from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize)
  349. }
  350. #[cfg(test)]
  351. mod tests {
  352. use super::*;
  353. use windows_sys::Win32::System::Memory::{
  354. MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, VirtualAlloc,
  355. VirtualFree, VirtualProtect,
  356. };
  357. struct Pages(*mut u8, usize);
  358. impl Pages {
  359. fn new(len: usize) -> Pages {
  360. // SAFETY: plain allocation.
  361. let at = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) };
  362. assert!(!at.is_null());
  363. Pages(at.cast(), len)
  364. }
  365. fn fill(&self) {
  366. for i in 0..self.1 {
  367. // SAFETY: inside the allocation.
  368. unsafe { self.0.add(i).write((i * 31 + 7) as u8) };
  369. }
  370. }
  371. }
  372. impl Drop for Pages {
  373. fn drop(&mut self) {
  374. // SAFETY: our allocation.
  375. unsafe { VirtualFree(self.0.cast(), 0, MEM_RELEASE) };
  376. }
  377. }
  378. #[test]
  379. fn copies_every_length_and_alignment() {
  380. assert!(on());
  381. let (a, b) = (Pages::new(1 << 16), Pages::new(1 << 16));
  382. a.fill();
  383. for len in [0usize, 1, 3, 4, 8, 31, 64, 255, 4095, 4096, 4097, 60_000] {
  384. for (da, sa) in [(0usize, 0usize), (1, 0), (0, 3), (5, 2)] {
  385. // SAFETY: inside the two allocations.
  386. unsafe {
  387. std::ptr::write_bytes(b.0, 0xEE, b.1);
  388. assert!(copy(b.0.add(da), a.0.add(sa), len));
  389. let (to, from) = (std::slice::from_raw_parts(b.0, b.1), std::slice::from_raw_parts(a.0, a.1));
  390. assert_eq!(to[da..da + len], from[sa..sa + len]);
  391. assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE));
  392. }
  393. }
  394. }
  395. }
  396. /// The dwords that changed are stored, and no byte of any other, at
  397. /// every alignment and length; a page that is not there fails.
  398. #[test]
  399. fn only_changed_dwords_are_put() {
  400. assert!(on());
  401. let pages = Pages::new(3 << 12);
  402. for at in [0usize, 1, 2, 3, 4, 13, 4090] {
  403. for len in [0usize, 1, 3, 4, 5, 31, 32, 33, 64, 100, 1000, 4096] {
  404. let was: Vec<u8> = (0..len).map(|i| (i * 13 + 1) as u8).collect();
  405. for step in [1usize, 5, 17, 64, 10_000] {
  406. let mut now = was.clone();
  407. for i in (0..len).step_by(step) {
  408. now[i] ^= 0x5A;
  409. }
  410. // Other threads changed everything meanwhile.
  411. // SAFETY: inside the allocation.
  412. unsafe {
  413. std::ptr::write_bytes(pages.0, 0xC3, pages.1);
  414. assert!(put_changed(pages.0.add(at), &was, &now));
  415. let there = std::slice::from_raw_parts(pages.0, pages.1);
  416. let base = pages.0.addr();
  417. for (k, &byte) in there.iter().enumerate() {
  418. let expect = if (at..at + len).contains(&k) {
  419. let dword = (base + k) / 4;
  420. let changed = (0..len).any(|i| now[i] != was[i] && (base + at + i) / 4 == dword);
  421. if changed { now[k - at] } else { 0xC3 }
  422. } else {
  423. 0xC3
  424. };
  425. if byte != expect {
  426. panic!("at {at} len {len} step {step} byte {k}: {byte:#x}, not {expect:#x}");
  427. }
  428. if k > at + len + 64 {
  429. break;
  430. }
  431. }
  432. }
  433. }
  434. }
  435. }
  436. // SAFETY: pages of our allocation.
  437. unsafe {
  438. VirtualFree(pages.0.add(4096).cast(), 4096, MEM_DECOMMIT);
  439. let (was, now) = (vec![0u8; 8192], vec![1u8; 8192]);
  440. assert!(!put_changed(pages.0, &was, &now));
  441. // Nothing differs on the page that is not there: nothing fails.
  442. let mut now = was.clone();
  443. now[0] = 1;
  444. assert!(put_changed(pages.0, &was, &now));
  445. }
  446. }
  447. /// [`merge`] against what it is to do, byte by byte, for every kind of
  448. /// start, end and change: the bytes the card changed arrive in title
  449. /// memory and in what it held, no dword without one is stored.
  450. #[test]
  451. fn a_merge_puts_what_the_card_changed_and_nothing_else() {
  452. assert!(on());
  453. let pages = Pages::new(1 << 12);
  454. let mut seed = 1u32;
  455. let mut random = move || {
  456. seed ^= seed << 13;
  457. seed ^= seed >> 17;
  458. seed ^= seed << 5;
  459. seed
  460. };
  461. for round in 0..4000u32 {
  462. let at = random() as usize % 100;
  463. let len = random() as usize % 300;
  464. let (from, to) = (at, (at + len).min(400));
  465. let n = to - from;
  466. let base: Vec<u8> = (0..512).map(|_| random() as u8).collect();
  467. let was: Vec<u8> = base[from..to].to_vec();
  468. let mut held = was.clone();
  469. let mut now = was.clone();
  470. let mut title = base.clone();
  471. // The card's writes: dwords and single bytes; the title's: some
  472. // in the same dwords, some the same values.
  473. for _ in 0..random() % 12 {
  474. if n > 0 {
  475. let i = random() as usize % n;
  476. now[i] = random() as u8;
  477. }
  478. let i = random() as usize % 512;
  479. title[i] = if (from..to).contains(&i) && round % 3 == 0 { now[i - from] } else { random() as u8 };
  480. }
  481. if round % 7 == 0 {
  482. now.iter_mut().for_each(|b| *b = b.wrapping_add(1));
  483. }
  484. // SAFETY: inside the allocation and the vectors.
  485. let done = unsafe {
  486. std::ptr::copy_nonoverlapping(title.as_ptr(), pages.0, 512);
  487. merge(pages.0.add(from), now.as_ptr(), held.as_mut_ptr(), n, round % 2 == 0)
  488. };
  489. assert!(done.there);
  490. // SAFETY: inside the allocation.
  491. let there = unsafe { std::slice::from_raw_parts(pages.0, 512) };
  492. for i in 0..512 {
  493. let wrote = (from..to).contains(&i) && now[i - from] != was[i - from];
  494. let expect = if wrote { now[i - from] } else { title[i] };
  495. assert_eq!(there[i], expect, "round {round} byte {i} of {from}..{to}");
  496. }
  497. assert_eq!(held, now, "round {round}");
  498. assert_eq!(done.new == 0, was == now);
  499. // Found merged already.
  500. // SAFETY: as above.
  501. let again = unsafe { merge(pages.0.add(from), now.as_ptr(), held.as_mut_ptr(), n, false) };
  502. assert_eq!(again, Merged { new: 0, dwords: 0, there: true });
  503. }
  504. }
  505. /// Title memory that is not there: what the card wrote stays to be
  506. /// looked at again, or is taken, as asked; a page that only cannot be
  507. /// written counts the same.
  508. #[test]
  509. fn a_merge_into_missing_memory_fails() {
  510. assert!(on());
  511. let pages = Pages::new(1 << 13);
  512. let mut old = 0;
  513. for (missing, take) in [(true, false), (true, true), (false, false), (false, true)] {
  514. for (at, len) in [(0usize, 4096usize), (4, 64), (7, 1), (40, 100)] {
  515. let was = vec![1u8; len];
  516. let mut now = was.clone();
  517. now[len - 1] = 9;
  518. let mut held = was.clone();
  519. // SAFETY: our allocation.
  520. let done = unsafe {
  521. if missing {
  522. VirtualFree(pages.0.cast(), 4096, MEM_DECOMMIT);
  523. } else {
  524. VirtualProtect(pages.0.cast(), 4096, PAGE_READONLY, &mut old);
  525. }
  526. let done = merge(pages.0.add(at), now.as_ptr(), held.as_mut_ptr(), len, take);
  527. VirtualAlloc(pages.0.cast(), 4096, MEM_COMMIT, PAGE_READWRITE);
  528. VirtualProtect(pages.0.cast(), 4096, PAGE_READWRITE, &mut old);
  529. done
  530. };
  531. assert!(!done.there);
  532. assert_eq!(held, if take { now.clone() } else { was.clone() }, "{missing} {take} {at} {len}");
  533. // Nothing to put: nothing fails.
  534. let mut held = now.clone();
  535. // SAFETY: as above; the addresses are no one's.
  536. let done = unsafe { merge(std::ptr::without_provenance_mut(0x1000 + at), now.as_ptr(), held.as_mut_ptr(), len, take) };
  537. assert!(done.there && done.new == 0);
  538. }
  539. }
  540. }
  541. /// [`merge`] beside threads that write other dwords of the same memory:
  542. /// none of their writes is lost or undone.
  543. #[test]
  544. fn merges_undo_no_write_of_other_threads() {
  545. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  546. assert!(on());
  547. let pages = Pages::new(1 << 12);
  548. let base = pages.0 as usize;
  549. // SAFETY: committed, aligned memory, only touched as atomics or by
  550. // the merge's stores of whole dwords.
  551. let dword = |i: usize| unsafe { &*((base + i * 4) as *const AtomicU32) };
  552. let stop = AtomicBool::new(false);
  553. std::thread::scope(|s| {
  554. let writers: Vec<_> = (0..2usize)
  555. .map(|w| {
  556. let stop = &stop;
  557. s.spawn(move || {
  558. let mut value = 1u32;
  559. while !stop.load(Ordering::Relaxed) {
  560. for i in (w..1024).step_by(4) {
  561. // This thread's own dword: nobody else's value.
  562. assert_eq!(dword(i).load(Ordering::Relaxed), value - 1, "dword {i}");
  563. dword(i).store(value, Ordering::Relaxed);
  564. }
  565. value += 1;
  566. }
  567. })
  568. })
  569. .collect();
  570. // The card's dwords: every fourth, from the third on.
  571. let mut held = vec![0u8; 4096];
  572. for round in 1..3000u32 {
  573. let mut now = held.clone();
  574. for i in (2..1024).step_by(4) {
  575. if i * 7 % 5 != round as usize % 5 {
  576. now[i * 4..i * 4 + 4].copy_from_slice(&(round + i as u32).to_le_bytes());
  577. }
  578. }
  579. // SAFETY: the allocation, whole.
  580. let done = unsafe { merge(base as *mut u8, now.as_ptr(), held.as_mut_ptr(), 4096, false) };
  581. assert!(done.there);
  582. for i in (2..1024).step_by(4) {
  583. let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().unwrap());
  584. assert_eq!(dword(i).load(Ordering::Relaxed), expect);
  585. }
  586. for i in (3..1024).step_by(4) {
  587. assert_eq!(dword(i).load(Ordering::Relaxed), 0);
  588. }
  589. }
  590. stop.store(true, Ordering::Relaxed);
  591. for w in writers {
  592. w.join().expect("no write was undone");
  593. }
  594. });
  595. }
  596. #[test]
  597. fn differences_are_seen_wherever_they_are() {
  598. for len in [0usize, 1, 31, 32, 33, 127, 128, 129, 200] {
  599. let a = vec![7u8; len];
  600. // SAFETY: the vectors' bytes.
  601. assert!(!unsafe { differ(a.as_ptr(), a.clone().as_ptr(), len) });
  602. for at in 0..len {
  603. let mut b = a.clone();
  604. b[at] = 8;
  605. // SAFETY: as above.
  606. assert!(unsafe { differ(a.as_ptr(), b.as_ptr(), len) }, "{len} {at}");
  607. }
  608. }
  609. }
  610. /// What the copies cost (ignored: a measurement): 64 KiB pieces of
  611. /// scattered memory into a buffer the card reads, by the kernel and here.
  612. #[test]
  613. #[ignore]
  614. fn copy_costs() {
  615. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  616. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  617. assert!(on());
  618. let Some(host) = crate::host::host() else { return };
  619. const N: usize = 128 << 20;
  620. let from = Pages::new(N);
  621. from.fill();
  622. let (_buffer, shared) = host.shared_buffer(N as u64).expect("a shared buffer");
  623. let plain = Pages::new(N);
  624. plain.fill();
  625. for (what, to) in [("a buffer the card reads", shared), ("plain memory", plain.0)] {
  626. for piece in [256usize, 4 << 10, 64 << 10] {
  627. let count = (N / piece).min(4096);
  628. // A different, scattered piece each time.
  629. let at = |i: usize| (i * 7919 % (N / piece)) * piece;
  630. let time = |f: &dyn Fn(usize) -> bool| {
  631. let mut best = f64::MAX;
  632. for _ in 0..5 {
  633. let t = std::time::Instant::now();
  634. for i in 0..count {
  635. assert!(f(at(i)));
  636. }
  637. best = best.min(t.elapsed().as_secs_f64());
  638. }
  639. (best * 1e6 / count as f64, count as f64 * piece as f64 / best / 1e9)
  640. };
  641. // SAFETY: inside the buffers.
  642. let kernel = time(&|o| unsafe {
  643. let mut done = 0;
  644. ReadProcessMemory(GetCurrentProcess(), from.0.add(o).cast(), to.add(o).cast(), piece, &mut done) != 0
  645. });
  646. // SAFETY: as above.
  647. let here = time(&|o| unsafe { copy(to.add(o), from.0.add(o), piece) });
  648. // SAFETY: as above.
  649. let std_copy = time(&|o| unsafe {
  650. std::ptr::copy_nonoverlapping(from.0.add(o), to.add(o), piece);
  651. true
  652. });
  653. println!(
  654. "{piece:>6} bytes into {what}: kernel {:.2} us ({:.1} GB/s), rep movsb {:.2} us ({:.1} GB/s), memcpy {:.2} us ({:.1} GB/s)",
  655. kernel.0, kernel.1, here.0, here.1, std_copy.0, std_copy.1
  656. );
  657. }
  658. }
  659. }
  660. /// Missing, forbidden and read-only pages: the copy fails, at any byte,
  661. /// and the process goes on.
  662. #[test]
  663. fn faults_are_failures() {
  664. assert!(on());
  665. let (a, b) = (Pages::new(3 << 12), Pages::new(3 << 12));
  666. a.fill();
  667. let mut old = 0;
  668. // SAFETY: pages of our allocations.
  669. unsafe {
  670. assert!(copy(b.0, a.0, b.1));
  671. VirtualProtect(a.0.add(4096).cast(), 4096, PAGE_NOACCESS, &mut old);
  672. assert!(!copy(b.0, a.0, b.1));
  673. assert!(copy(b.0, a.0, 4096));
  674. assert!(!copy(b.0, a.0.add(8191), 1));
  675. assert!(copy(b.0, a.0.add(8192), 4096));
  676. VirtualProtect(a.0.add(4096).cast(), 4096, PAGE_READWRITE, &mut old);
  677. VirtualFree(a.0.add(8192).cast(), 4096, MEM_DECOMMIT);
  678. assert!(!copy(b.0, a.0, b.1));
  679. VirtualProtect(b.0.add(4096).cast(), 4096, PAGE_READONLY, &mut old);
  680. assert!(!copy(b.0, a.0, 8192));
  681. assert!(!copy(std::ptr::without_provenance_mut(0x10), a.0, 4));
  682. assert!(!copy(b.0, std::ptr::without_provenance(usize::MAX - 7), 4));
  683. VirtualProtect(b.0.add(4096).cast(), 4096, PAGE_READWRITE, &mut old);
  684. }
  685. // Many faults, on several threads at once.
  686. let at = a.0 as usize;
  687. std::thread::scope(|s| {
  688. for _ in 0..4 {
  689. s.spawn(move || {
  690. let mut to = [0u8; 64];
  691. for _ in 0..500 {
  692. // SAFETY: a decommitted page and our own buffer.
  693. assert!(!unsafe { copy(to.as_mut_ptr(), (at + 8192) as *const u8, 64) });
  694. }
  695. });
  696. }
  697. });
  698. }
  699. }