tests.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. use super::*;
  2. use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize};
  3. use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, PAGE_READWRITE};
  4. struct Random(u64);
  5. impl Random {
  6. fn next(&mut self) -> usize {
  7. self.0 ^= self.0 << 13;
  8. self.0 ^= self.0 >> 7;
  9. self.0 ^= self.0 << 17;
  10. (self.0 >> 8) as usize
  11. }
  12. }
  13. /// View memory as the runtime makes the title's: a view of a section, noted
  14. /// as it notes it. Kept: the journal of what was written (`crate::watch`)
  15. /// knows its addresses, which must not become another test's fresh memory.
  16. struct Title {
  17. at: usize,
  18. len: usize,
  19. }
  20. impl Title {
  21. fn new(len: usize) -> Title {
  22. // SAFETY: a pagefile section of our own and a view of it.
  23. unsafe {
  24. let section =
  25. CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  26. assert!(!section.is_null());
  27. let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
  28. assert_ne!(at, 0);
  29. crate::inplace::title_memory_section(section as usize, len as u64, true);
  30. crate::title_memory_remapped(at, len);
  31. crate::inplace::title_memory_view(at, len, section as usize, 0);
  32. Title { at, len }
  33. }
  34. }
  35. fn bytes(&self) -> &[u8] {
  36. // SAFETY: the view.
  37. unsafe { std::slice::from_raw_parts(self.at as *const u8, self.len) }
  38. }
  39. }
  40. /// Every number once, whatever the count and the threads, batch after batch
  41. /// and from several callers.
  42. #[test]
  43. fn the_pool_calls_every_number_once() {
  44. for threads in [1usize, 2, 4, 7] {
  45. let pool = Pool::new(threads);
  46. std::thread::scope(|s| {
  47. for _ in 0..3 {
  48. s.spawn(|| {
  49. for round in 0..300usize {
  50. let count = round * 7 % 50;
  51. let calls: Vec<AtomicUsize> = (0..count).map(|_| AtomicUsize::new(0)).collect();
  52. pool.each(count, &|i| {
  53. calls[i].fetch_add(1, Ordering::Relaxed);
  54. });
  55. assert!(calls.iter().all(|c| c.load(Ordering::Relaxed) == 1));
  56. }
  57. });
  58. }
  59. });
  60. }
  61. }
  62. /// A job that panics is told to the caller, and the pool goes on.
  63. #[test]
  64. fn a_panicking_job_reaches_the_caller() {
  65. let pool = Pool::new(3);
  66. for bad in 0..8usize {
  67. let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
  68. pool.each(8, &|i| assert_ne!(i, bad, "(expected)"));
  69. }));
  70. assert!(ran.is_err());
  71. let n = AtomicUsize::new(0);
  72. pool.each(20, &|i| {
  73. n.fetch_add(i, Ordering::Relaxed);
  74. });
  75. assert_eq!(n.into_inner(), 190);
  76. }
  77. }
  78. /// The order pieces are landed in holds every byte of every piece, under its
  79. /// copy, and no other; blocks come in order, pieces of several copies in one
  80. /// block stay in the order given, and jobs never cut a block.
  81. #[test]
  82. fn ordered_pieces_hold_the_same_bytes() {
  83. let mut random = Random(99);
  84. for _ in 0..400 {
  85. let count = random.next() % 40;
  86. let pieces: Vec<Piece> = (0..count)
  87. .map(|_| {
  88. let block = random.next() % 12 * BLOCK;
  89. let from = random.next() % BLOCK / 4 * 4;
  90. let to = (from + 4 + random.next() % BLOCK / 4 * 4).min(BLOCK);
  91. (random.next() as u64 % 3, block + from, to - from)
  92. })
  93. .collect();
  94. let out = ordered(&pieces);
  95. let bytes = |copy: u64, at: usize, all: &[Piece]| all.iter().any(|p| p.0 == copy && p.1 <= at && at < p.1 + p.2);
  96. let landed: Vec<Piece> = out.iter().map(|&(i, at, len)| (pieces[i].0, at, len)).collect();
  97. for copy in 0..3 {
  98. for at in (0..12 * BLOCK).step_by(1024 * 4) {
  99. assert_eq!(bytes(copy, at, &pieces), bytes(copy, at, &landed), "{pieces:?}");
  100. }
  101. }
  102. assert!(out.iter().all(|&(_, at, len)| len > 0 && at / BLOCK == (at + len - 1) / BLOCK));
  103. assert!(out.windows(2).all(|w| w[0].1 / BLOCK <= w[1].1 / BLOCK));
  104. for block in 0..12 {
  105. let given: Vec<Piece> = pieces.iter().copied().filter(|p| p.1 / BLOCK == block).collect();
  106. let here: Vec<Piece> = landed.iter().copied().filter(|p| p.1 / BLOCK == block).collect();
  107. if given.iter().any(|p| p.0 != given[0].0) {
  108. assert_eq!(here, given);
  109. } else {
  110. assert!(here.windows(2).all(|w| w[0].1 + w[0].2 < w[1].1), "apart, in order");
  111. }
  112. }
  113. let cut: Vec<(usize, usize)> = out.iter().map(|&(_, at, len)| (at, len)).collect();
  114. let jobs = jobs(&cut);
  115. assert_eq!(jobs.iter().cloned().flatten().collect::<Vec<_>>(), (0..cut.len()).collect::<Vec<_>>());
  116. for w in jobs.windows(2) {
  117. assert_ne!(cut[w[0].end - 1].0 / BLOCK, cut[w[1].start].0 / BLOCK);
  118. }
  119. }
  120. }
  121. /// A piece is left out only if a fetch behind its own flight, or behind a
  122. /// later one, brought all of it, and is forgotten when that flight is done.
  123. #[test]
  124. fn only_what_a_fetch_behind_the_flight_brought_is_left_out() {
  125. let mut had = Had::default();
  126. had.fetched(7, [(1, BLOCK, BLOCK), (2, 0x100, 0x200)].into_iter());
  127. assert!(had.holds(6, (1, BLOCK, BLOCK)) && had.holds(7, (1, BLOCK + 64, 128)));
  128. assert!(!had.holds(8, (1, BLOCK, BLOCK)), "the fetch ran ahead of flight 8");
  129. assert!(!had.holds(7, (3, BLOCK, BLOCK)) && !had.holds(7, (1, 0, 64)));
  130. assert!(had.holds(7, (2, 0x100, 0x200)) && !had.holds(7, (2, 0x100, 0x204)) && !had.holds(7, (2, 0xfc, 8)));
  131. had.landing(7);
  132. assert!(had.holds(7, (1, BLOCK, BLOCK)));
  133. had.landing(8);
  134. assert!(had.0.is_empty());
  135. }
  136. /// A piece landed through either address holds what the merge of one thread
  137. /// and one pass ([`crate::safecopy::merge`]) is to leave, with parts left
  138. /// out, wherever it begins and ends.
  139. #[test]
  140. fn a_piece_lands_what_the_card_wrote_in_its_parts() {
  141. assert!(crate::safecopy::on());
  142. let title = Title::new(2 * BLOCK);
  143. let mut random = Random(5);
  144. for round in 0..300usize {
  145. let from = (random.next() % 5000) & !3;
  146. let len = (random.next() % BLOCK).min(BLOCK - from).max(1);
  147. let base: Vec<u8> = (0..len).map(|_| random.next() as u8).collect();
  148. let (mut now, mut held) = (base.clone(), base.clone());
  149. for _ in 0..random.next() % 60 {
  150. let at = random.next() % len;
  151. let n = (random.next() % 300).min(len - at);
  152. for b in &mut now[at..at + n] {
  153. *b = random.next() as u8;
  154. }
  155. }
  156. let mut there = base.clone();
  157. for _ in 0..random.next() % 60 {
  158. there[random.next() % len] ^= 0x11;
  159. }
  160. // Left out: some ranges, anywhere.
  161. let mut parts = vec![(0, len)];
  162. for _ in 0..round % 4 {
  163. let a = random.next() % len;
  164. let b = (a + random.next() % 200).min(len);
  165. parts = parts
  166. .into_iter()
  167. .flat_map(|(x, y)| [(x, y.min(a)), (x.max(b), y)])
  168. .filter(|(x, y)| x < y)
  169. .collect();
  170. }
  171. // SAFETY: inside the view; `kernel_will_write`'s rule for our own
  172. // writes: the guard goes first.
  173. unsafe {
  174. crate::watch::writing(title.at, 2 * BLOCK);
  175. std::ptr::copy_nonoverlapping(there.as_ptr(), (title.at + from) as *mut u8, len);
  176. }
  177. // Guarded, as after a refresh, in two rounds of three.
  178. if round % 3 != 0 {
  179. assert!(crate::watch::writes(title.at, title.at + 2 * BLOCK, true).is_some());
  180. assert_eq!(crate::watch::writes(title.at, title.at + 2 * BLOCK, true).map(|w| w.1.len() > 2), Some(false));
  181. }
  182. let asked = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view").0;
  183. let mut notes = Notes::default();
  184. // SAFETY: vectors of `len` bytes.
  185. let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes, std::ptr::null()) };
  186. notes.flush();
  187. let mut expect_held = base.clone();
  188. let mut expect = there.clone();
  189. for &(a, b) in &parts {
  190. for i in a..b {
  191. if now[i] != base[i] {
  192. expect[i] = now[i];
  193. expect_held[i] = now[i];
  194. }
  195. }
  196. }
  197. assert!(held == expect_held, "round {round}");
  198. assert!(title.bytes()[from..from + len] == expect[..], "round {round}");
  199. // Told: a refresh from now on takes the block again.
  200. let (_, written) = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view");
  201. let told = written.iter().any(|&(page, at)| page == title.at / BLOCK && at > asked);
  202. assert!(told || put == 0, "round {round}: {put} bytes, {written:?} after {asked}");
  203. }
  204. }
  205. /// A piece whose title memory is away only while the runtime changes a
  206. /// mapping lands when that is done; where it stays away the copy's CPU side
  207. /// takes the card's bytes (`take`) or not.
  208. #[test]
  209. fn a_piece_waits_for_a_change_of_mapping() {
  210. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, VirtualAlloc, VirtualFree};
  211. assert!(crate::safecopy::on());
  212. // SAFETY: a reservation of ours, nothing of it committed.
  213. let at = unsafe { VirtualAlloc(std::ptr::null(), BLOCK, MEM_RESERVE, PAGE_NOACCESS) } as usize;
  214. assert_ne!(at, 0);
  215. let now = [9u8; 100];
  216. for take in [true, false] {
  217. let mut held = [0u8; 100];
  218. // SAFETY: arrays of 100 bytes.
  219. let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], take, &mut Notes::default(), std::ptr::null()) };
  220. assert_eq!((put, held), (0, [if take { 9 } else { 0 }; 100]));
  221. }
  222. let (began, wait) = std::sync::mpsc::channel();
  223. let change = std::thread::spawn(move || {
  224. let _changing = crate::watch::title_memory_remapping();
  225. began.send(()).unwrap();
  226. std::thread::sleep(std::time::Duration::from_millis(50));
  227. // SAFETY: the reservation's first page.
  228. assert!(!unsafe { VirtualAlloc(at as _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null());
  229. });
  230. wait.recv().unwrap();
  231. let mut held = [0u8; 100];
  232. // SAFETY: as above.
  233. let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], true, &mut Notes::default(), std::ptr::null()) };
  234. change.join().unwrap();
  235. assert_eq!((put, held), (100, now));
  236. // SAFETY: committed by now.
  237. assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 100) }, now);
  238. // SAFETY: our reservation.
  239. unsafe { VirtualFree(at as _, 0, MEM_RELEASE) };
  240. }
  241. /// Landings on several threads beside title threads that write the same
  242. /// blocks (other dwords) and a thread that refreshes a copy, guarding what
  243. /// it takes: no write of the title's is lost or undone, all the card wrote
  244. /// arrives, and once everything stands still the next refresh takes the
  245. /// last of it (no note is lost).
  246. #[test]
  247. fn landings_beside_the_title_and_its_refreshes_lose_nothing() {
  248. assert!(crate::safecopy::on());
  249. const BLOCKS: usize = 24;
  250. const LEN: usize = BLOCKS * BLOCK;
  251. let title = Title::new(LEN);
  252. let at = title.at;
  253. // SAFETY: committed, aligned, touched as atomics or by the landing's
  254. // stores of whole dwords.
  255. let dword = |i: usize| unsafe { &*((at + i * 4) as *const AtomicU32) };
  256. let stop = AtomicBool::new(false);
  257. // The copy: its bytes, and per block the asking that last took it.
  258. let copy: Mutex<(Vec<u8>, Vec<u64>)> = Mutex::new((vec![0; LEN], vec![0; BLOCKS]));
  259. let refresh = || {
  260. let mut copy = copy.lock().unwrap_or_else(|e| e.into_inner());
  261. let (now, written) = crate::watch::writes(at, at + LEN, true).expect("a view");
  262. let (bytes, taken) = &mut *copy;
  263. for block in 0..BLOCKS {
  264. let write = written.iter().find(|w| w.0 == at / BLOCK + block).map_or(0, |w| w.1);
  265. if taken[block] == 0 || write > taken[block] {
  266. taken[block] = now;
  267. let part = &mut bytes[block * BLOCK..(block + 1) * BLOCK];
  268. // SAFETY: inside the view; whoever writes it meanwhile is
  269. // noted, and the block taken again.
  270. assert!(unsafe { crate::safecopy::copy(part.as_mut_ptr(), (at + block * BLOCK) as *const u8, BLOCK) });
  271. }
  272. }
  273. };
  274. let mut held = vec![0u8; LEN];
  275. std::thread::scope(|s| {
  276. let writers: Vec<_> = (0..3usize)
  277. .map(|w| {
  278. let stop = &stop;
  279. s.spawn(move || {
  280. let mut value = 1u32;
  281. while !stop.load(Ordering::Relaxed) {
  282. // Its own dwords, in every other block (in the rest
  283. // only landings change anything).
  284. for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) {
  285. assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone");
  286. }
  287. value += 1;
  288. }
  289. value - 1
  290. })
  291. })
  292. .collect();
  293. s.spawn(|| {
  294. while !stop.load(Ordering::Relaxed) {
  295. refresh();
  296. }
  297. });
  298. let mut random = Random(77);
  299. for round in 1..250u32 {
  300. // The card's dwords: every fourth, from the third on, in some
  301. // pages of some blocks.
  302. let mut now = held.clone();
  303. for _ in 0..60 {
  304. let page = random.next() % (LEN / PAGE);
  305. for i in (page * 1024 + 3..(page + 1) * 1024).step_by(4) {
  306. now[i * 4..i * 4 + 4].copy_from_slice(&(round * 4096 + i as u32).to_le_bytes());
  307. }
  308. }
  309. let pieces: Vec<Piece> = (0..BLOCKS).map(|b| (1, at + b * BLOCK, BLOCK)).collect();
  310. let order = ordered(&pieces);
  311. let cut: Vec<(usize, usize)> = order.iter().map(|&(_, at, len)| (at, len)).collect();
  312. let jobs = jobs(&cut);
  313. let into = held.as_mut_ptr() as usize;
  314. each(jobs.len(), &|j| {
  315. let mut notes = Notes::default();
  316. for &(address, len) in &cut[jobs[j].clone()] {
  317. let offset = address - at;
  318. // SAFETY: each job its own pieces of the two vectors.
  319. unsafe {
  320. piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes, std::ptr::null());
  321. }
  322. }
  323. notes.flush();
  324. });
  325. assert!(held == now, "round {round}");
  326. for i in (3..LEN / 4).step_by(4 * 61) {
  327. let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four"));
  328. assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}");
  329. }
  330. }
  331. stop.store(true, Ordering::Relaxed);
  332. for (w, writer) in writers.into_iter().enumerate() {
  333. let last = writer.join().expect("nothing undone");
  334. for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) {
  335. assert_eq!(dword(i).load(Ordering::Relaxed), last);
  336. }
  337. }
  338. });
  339. refresh();
  340. let copy = copy.into_inner().unwrap_or_else(|e| e.into_inner());
  341. assert!(copy.0 == title.bytes(), "a write was not told to the copy");
  342. }
  343. /// What a frame's landing costs (ignored: a measurement): 1,536 pieces of
  344. /// 64 KiB, 96 MB, of a 174 MB heap of view memory in 15 landings, each block
  345. /// guarded by a refresh before it; three quarters of the pages of a piece
  346. /// with new bytes, every dword of them. As before, and here on one thread
  347. /// and more, through the title's address and through a view of ours.
  348. #[test]
  349. #[ignore]
  350. fn what_landing_costs() {
  351. assert!(crate::safecopy::on());
  352. const HEAP: usize = 2784 * BLOCK;
  353. const COUNT: usize = 1536;
  354. let title = Title::new(HEAP);
  355. let mut held = vec![0u8; HEAP];
  356. let mut card = vec![0u8; COUNT * BLOCK];
  357. let busy = AtomicBool::new(true);
  358. // The pieces: runs of eight blocks, scattered.
  359. let pieces: Vec<usize> = (0..COUNT).map(|i| (i / 8 * 1021 % (HEAP / BLOCK / 8)) * 8 + i % 8).collect();
  360. std::thread::scope(|s| {
  361. // Other threads of the process at work (what a protection change
  362. // has to reach).
  363. for _ in 0..6 {
  364. s.spawn(|| {
  365. let mut v = vec![0u64; 1 << 14];
  366. while busy.load(Ordering::Relaxed) {
  367. for (i, x) in v.iter_mut().enumerate() {
  368. *x = x.wrapping_mul(31).wrapping_add(i as u64);
  369. }
  370. }
  371. });
  372. }
  373. let mut round = 0u32;
  374. // `guarded`: 2 as a refresh leaves them, 1 opened again before (that
  375. // is timed beside), 0 not at all, as they were after the last.
  376. let mut frame = |label: &str, dense: bool, guarded: u8, land: &dyn Fn(&[(usize, usize, usize)])| {
  377. let mut best = f64::MAX;
  378. let (mut guards, mut opening) = (f64::MAX, f64::MAX);
  379. for _ in 0..5 {
  380. round += 1;
  381. for (k, &block) in pieces.iter().enumerate() {
  382. for page in 0..16 {
  383. if page % 4 == 3 {
  384. continue;
  385. }
  386. let from = k * BLOCK + page * PAGE;
  387. let step = if dense { 4 } else { 64 };
  388. // (The rest as held.)
  389. let old = block * BLOCK + page * PAGE;
  390. card[from..from + PAGE].copy_from_slice(&held[old..old + PAGE]);
  391. for b in card[from..from + PAGE].chunks_exact_mut(step) {
  392. b[..4].copy_from_slice(&round.wrapping_mul(0x0101_0101).to_le_bytes());
  393. }
  394. }
  395. let (a, b) = (k * BLOCK + 12 * PAGE, block * BLOCK + 12 * PAGE);
  396. for page in [3usize, 7, 11, 15] {
  397. let (a, b) = (a - 12 * PAGE + page * PAGE, b - 12 * PAGE + page * PAGE);
  398. card[a..a + PAGE].copy_from_slice(&held[b..b + PAGE]);
  399. }
  400. }
  401. let t = std::time::Instant::now();
  402. if guarded > 0 {
  403. assert!(crate::watch::writes(title.at, title.at + HEAP, true).is_some());
  404. }
  405. guards = guards.min(t.elapsed().as_secs_f64() * 1e3);
  406. let t = std::time::Instant::now();
  407. if guarded == 1 {
  408. pieces.iter().for_each(|block| crate::watch::landing(title.at + block * BLOCK, BLOCK));
  409. }
  410. opening = opening.min(t.elapsed().as_secs_f64() * 1e3);
  411. let all: Vec<(usize, usize, usize)> = pieces
  412. .iter()
  413. .enumerate()
  414. .map(|(k, &block)| {
  415. (title.at + block * BLOCK, card.as_ptr() as usize + k * BLOCK, held.as_mut_ptr() as usize + block * BLOCK)
  416. })
  417. .collect();
  418. let t = std::time::Instant::now();
  419. for landing in all.chunks(COUNT / 15 + 1) {
  420. land(landing);
  421. }
  422. best = best.min(t.elapsed().as_secs_f64() * 1e3);
  423. }
  424. println!("{label}: {best:.1} ms a frame to land; the guards before it {guards:.1} ms, opening them {opening:.1} ms");
  425. };
  426. for dense in [true, false] {
  427. println!("{}", if dense { "every dword of three pages in four new" } else { "every sixteenth dword of them new" });
  428. let before: &dyn Fn(&[(usize, usize, usize)]) = &|landing| {
  429. let mut scratch: Vec<u8> = Vec::new();
  430. for &(at, now, held) in landing {
  431. crate::shadow::land_as_before(at, now, held, BLOCK, &mut scratch);
  432. }
  433. };
  434. frame("as before", dense, 2, before);
  435. frame("as before, guards opened ahead", dense, 1, before);
  436. frame("as before, nothing guarded", dense, 0, before);
  437. for threads in [1usize, 2, 3, 4, 5, 6, 8] {
  438. let pool = Pool::new(threads);
  439. for beside in [false, true] {
  440. frame(&format!("{threads} threads, beside {beside}"), dense, 2, &|landing| {
  441. let cut: Vec<(usize, usize)> = landing.iter().map(|p| (p.0, BLOCK)).collect();
  442. let jobs = jobs(&cut);
  443. pool.each(jobs.len(), &|j| {
  444. let mut notes = Notes::default();
  445. for &(at, now, held) in &landing[jobs[j].clone()] {
  446. // SAFETY: each its own bytes.
  447. unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside, std::ptr::null()) };
  448. }
  449. notes.flush();
  450. });
  451. });
  452. }
  453. }
  454. }
  455. busy.store(false, Ordering::Relaxed);
  456. });
  457. }