torn.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. //! Pieces of card copies that came down while a later flight was writing
  2. //! them (`VICTORY_FETCH_CHECK`, with `VICTORY_RELAY_COPY`).
  3. //!
  4. //! On the copy queue a fetch runs beside later submissions (`relay_copy`),
  5. //! so what comes down of a piece may be what it held in the middle of one:
  6. //! a counter cleared and not counted up again, a list half filled. Such
  7. //! bytes went into title memory and the copy's CPU side, to be put right by
  8. //! that submission's own landing, which fetches what its compare flagged.
  9. //! But the compare flags a piece only if it is not, at the submission's end,
  10. //! what it was at the end of the one before. A piece cleared and filled
  11. //! again with the same is not flagged, is not fetched, and the CPU's side
  12. //! keeps the bytes from in between: until they go up with a refresh of
  13. //! their 64 KiB, over the right ones.
  14. //!
  15. //! So the compare gives each piece's hash with its flag, and what came down
  16. //! is hashed here too. The same hash: it is what the flight ended with. Not
  17. //! the same: the piece is suspect (another flight was at it, or the title's
  18. //! bytes went up to it meanwhile), and the next flight that may write it
  19. //! fetches it whatever its compare says, until a fetch is found whole.
  20. //!
  21. //! What it costs: pieces are fetched whole where a flight declared a part
  22. //! of one, and 64 KiB of what came down are hashed (some 4 us) just before
  23. //! they are merged, on the thread that merges them (`crate::land`).
  24. use std::collections::{HashMap, HashSet};
  25. use std::sync::atomic::AtomicU8;
  26. use super::*;
  27. /// `VICTORY_FETCH_CHECK=1`; off by default until a run has shown how often a
  28. /// piece is caught (the frame-rate line says so) and what the hashes cost
  29. /// (3-4 ms for 96 MB beside the merge, spread over the threads that land).
  30. pub(super) fn on() -> bool {
  31. static ON: OnceLock<bool> = OnceLock::new();
  32. *ON.get_or_init(|| std::env::var_os("VICTORY_FETCH_CHECK").is_some_and(|v| v == "1"))
  33. }
  34. /// A piece: its copy's number, and the piece.
  35. pub(super) type Piece = (u64, u32);
  36. /// Since the last frame-rate line: pieces fetched and hashed, those found
  37. /// suspect, and those fetched because an earlier fetch was.
  38. pub(super) static STATS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  39. /// The pieces whose last fetch was not what a flight ended with.
  40. #[derive(Default)]
  41. pub(super) struct Suspects(HashSet<Piece>);
  42. impl Suspects {
  43. /// Whether a flight that may write `piece` fetches it, its compare
  44. /// having flagged it or not.
  45. pub(super) fn wanted(&self, piece: Piece, flagged: bool) -> bool {
  46. flagged || (!self.0.is_empty() && self.0.contains(&piece))
  47. }
  48. /// `piece` was fetched; `same`: it was what the last of the flights
  49. /// landed ended with.
  50. pub(super) fn fetched(&mut self, piece: Piece, same: bool) {
  51. STATS[0].fetch_add(1, Ordering::Relaxed);
  52. if same {
  53. if self.0.remove(&piece) {
  54. STATS[2].fetch_add(1, Ordering::Relaxed);
  55. }
  56. } else {
  57. self.0.insert(piece);
  58. STATS[1].fetch_add(1, Ordering::Relaxed);
  59. }
  60. }
  61. }
  62. /// What is landed: its copy, its offsets from and to, and where it comes
  63. /// down.
  64. pub(super) type Landed = (std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64);
  65. /// The pieces of a landing's fetch, whole, and what is known of them.
  66. pub(super) struct Check {
  67. /// What is copied down: whole pieces, as the compare hashes them.
  68. pub(super) copies: Vec<Landed>,
  69. /// The bytes of them.
  70. pub(super) total: u64,
  71. /// Of each: the piece, and the hash the last flight that may have
  72. /// written it ended with.
  73. of: Vec<(Piece, Option<u32>)>,
  74. /// Of what is landed, the piece (in `copies`) it is of.
  75. within: Vec<usize>,
  76. /// Of each piece: 0 not looked at yet, 1 as that flight ended with, 2
  77. /// not so.
  78. found: Vec<AtomicU8>,
  79. }
  80. impl Check {
  81. /// For `landed`, parts of pieces that `plans` may have written, whose
  82. /// compares' results are in `differs`: the parts are given their places
  83. /// in the pieces that come down.
  84. pub(super) fn new<'a>(plans: impl Iterator<Item = &'a CardPlan>, differs: &[u32], landed: &mut [Landed]) -> Check {
  85. let mut index: HashMap<Piece, usize> = HashMap::new();
  86. let (mut copies, mut of, mut within, mut total) = (Vec::new(), Vec::new(), Vec::new(), 0u64);
  87. for (shadow, lo, _, at) in landed {
  88. let number = shadow.card_piece_of(*lo);
  89. let piece = (shadow.id(), number);
  90. let i = *index.entry(piece).or_insert_with(|| {
  91. let (from, to) = shadow.card_hashed(number);
  92. copies.push((shadow.clone(), from, to, total));
  93. of.push((piece, None));
  94. total += (to - from) as u64;
  95. copies.len() - 1
  96. });
  97. *at = copies[i].3 + (*lo - copies[i].1) as u64;
  98. within.push(i);
  99. }
  100. // (The last flight's stands.)
  101. for r in plans.flat_map(|plan| &plan.ranges).filter(|r| r.compared && !r.picked) {
  102. for p in 0..r.span.pieces {
  103. if let Some(&i) = index.get(&(r.shadow.id(), r.span.first + p))
  104. && let Some(&d) = differs.get((r.at + p) as usize)
  105. {
  106. of[i].1 = Some(folded(d));
  107. }
  108. }
  109. }
  110. let found = of.iter().map(|_| AtomicU8::new(0)).collect();
  111. Check { copies, total, of, within, found }
  112. }
  113. /// Looks at the piece that part `i` of what is landed is of, if none of
  114. /// its parts was looked at: on the thread that lands it, just before, so
  115. /// that its bytes are near.
  116. ///
  117. /// # Safety
  118. /// What was fetched is at `data`, and stays as it is during the call.
  119. pub(super) unsafe fn look(&self, i: usize, data: usize) {
  120. let i = self.within[i];
  121. if self.found[i].load(Ordering::Relaxed) != 0 {
  122. return;
  123. }
  124. let Some(hash) = self.of[i].1 else {
  125. return;
  126. };
  127. let (_, from, to, at) = &self.copies[i];
  128. // SAFETY: the caller's.
  129. let bytes = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, to - from) };
  130. self.found[i].store(if self::hash(bytes) == hash { 1 } else { 2 }, Ordering::Relaxed);
  131. }
  132. /// All is landed: what was found is kept for later flights.
  133. pub(super) fn done(&self, suspects: &mut Suspects) {
  134. for ((piece, _), found) in self.of.iter().zip(&self.found) {
  135. match found.load(Ordering::Relaxed) {
  136. // Not compared on the card: fetched by every flight.
  137. 0 => {}
  138. found => suspects.fetched(*piece, found == 1),
  139. }
  140. }
  141. }
  142. }
  143. /// Of a result of the compare: whether the piece differs.
  144. pub(super) fn flagged(result: u32) -> bool {
  145. result & 1 != 0
  146. }
  147. /// Of a result of the compare: the piece's hash, 31 bits of it.
  148. pub(super) fn folded(result: u32) -> u32 {
  149. result >> 1
  150. }
  151. /// The hash the compare on the card ([`CARD_COMPARE`]) makes of a piece
  152. /// that holds `bytes` (a multiple of 16 of them), as [`folded`].
  153. pub(super) fn hash(bytes: &[u8]) -> u32 {
  154. #[cfg(target_arch = "x86_64")]
  155. if std::is_x86_feature_detected!("avx2") {
  156. // SAFETY: the feature is there.
  157. return unsafe { hash_avx2(bytes) };
  158. }
  159. hash_plain(bytes)
  160. }
  161. const MUL: [u32; 4] = [0x0100_0193, 0x9E37_79B1, 0x85EB_CA77, 0xC2B2_AE3D];
  162. const SEED: [u32; 4] = [0x9E37_79B9, 0x85EB_CA6B, 0xC2B2_AE35, 0x27D4_EB2F];
  163. fn step(h: &mut [u32; 4], with: [u32; 4]) {
  164. let x: [u32; 4] = std::array::from_fn(|i| (h[i] ^ with[i]).wrapping_mul(MUL[i]));
  165. *h = std::array::from_fn(|i| x[(i + 1) % 4] ^ (x[i] >> 15));
  166. }
  167. /// The 64 threads' hashes as one, folded to 31 bits.
  168. fn finish(parts: &[[u32; 4]; 64]) -> u32 {
  169. let mut h = parts[0];
  170. for part in &parts[1..] {
  171. step(&mut h, *part);
  172. }
  173. let f = h[0] ^ h[1].wrapping_mul(3) ^ h[2].wrapping_mul(5) ^ h[3].wrapping_mul(7);
  174. f & 0x7FFF_FFFF
  175. }
  176. fn seeds() -> [[u32; 4]; 64] {
  177. std::array::from_fn(|thread| SEED.map(|s| s.wrapping_add(thread as u32)))
  178. }
  179. fn tail(parts: &mut [[u32; 4]; 64], bytes: &[u8]) {
  180. for (thread, chunk) in bytes.chunks_exact(16).enumerate() {
  181. let with = std::array::from_fn(|i| u32::from_le_bytes([chunk[i * 4], chunk[i * 4 + 1], chunk[i * 4 + 2], chunk[i * 4 + 3]]));
  182. step(&mut parts[thread], with);
  183. }
  184. }
  185. fn hash_plain(bytes: &[u8]) -> u32 {
  186. let mut parts = seeds();
  187. for row in bytes.chunks(1024) {
  188. tail(&mut parts, row);
  189. }
  190. finish(&parts)
  191. }
  192. #[cfg(target_arch = "x86_64")]
  193. #[target_feature(enable = "avx2")]
  194. fn hash_avx2(bytes: &[u8]) -> u32 {
  195. use std::arch::x86_64::*;
  196. let mut parts = seeds();
  197. let rows = bytes.chunks_exact(1024);
  198. let rest = rows.remainder();
  199. let mul = _mm256_setr_epi32(
  200. MUL[0] as i32, MUL[1] as i32, MUL[2] as i32, MUL[3] as i32, MUL[0] as i32, MUL[1] as i32, MUL[2] as i32, MUL[3] as i32,
  201. );
  202. let state = parts.as_mut_ptr().cast::<__m256i>();
  203. for row in rows {
  204. let from = row.as_ptr().cast::<__m256i>();
  205. for k in 0..32 {
  206. // SAFETY: two threads' hashes of 16 bytes each, and their 32 of
  207. // the row's 1,024 bytes.
  208. unsafe {
  209. let h = _mm256_xor_si256(_mm256_loadu_si256(state.add(k)), _mm256_loadu_si256(from.add(k)));
  210. let x = _mm256_mullo_epi32(h, mul);
  211. // y, z, w, x of each.
  212. let turned = _mm256_shuffle_epi32::<0b00_11_10_01>(x);
  213. _mm256_storeu_si256(state.add(k), _mm256_xor_si256(turned, _mm256_srli_epi32::<15>(x)));
  214. }
  215. }
  216. }
  217. tail(&mut parts, rest);
  218. finish(&parts)
  219. }
  220. #[cfg(test)]
  221. mod tests {
  222. use super::*;
  223. #[test]
  224. fn the_wide_hash_is_the_plain_one() {
  225. let bytes: Vec<u8> = (0..65_536u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect();
  226. for n in [0usize, 16, 32, 1008, 1024, 1040, 5000 & !15, 65_536] {
  227. assert_eq!(hash(&bytes[..n]), hash_plain(&bytes[..n]), "{n} bytes");
  228. }
  229. let mut other = bytes.clone();
  230. other[40_000] ^= 1;
  231. assert_ne!(hash(&bytes), hash(&other));
  232. }
  233. /// A model of one piece. The card runs flights in order; each writes the
  234. /// piece several times and its compare flags it if it ends otherwise
  235. /// than the flight before. Each landing fetches what is wanted, on a
  236. /// queue beside the drawing one: the fetch sees the piece as it is while
  237. /// a later flight is at some step. Returns what the CPU's side holds in
  238. /// the end, and the fetches.
  239. fn landed(flights: &[&[u32]], seen: &[(usize, usize)], check: bool) -> (u32, u32) {
  240. let piece: Piece = (1, 0);
  241. let mut suspects = Suspects::default();
  242. let (mut held, mut ended, mut fetches) = (0, 0, 0);
  243. for (f, steps) in flights.iter().enumerate() {
  244. let before = ended;
  245. ended = *steps.last().expect("a step");
  246. let flagged = ended != before;
  247. if if check { !suspects.wanted(piece, flagged) } else { !flagged } {
  248. continue;
  249. }
  250. fetches += 1;
  251. // While flight `at` is after its step `step`.
  252. let (at, step) = seen[f];
  253. assert!(at >= f);
  254. held = flights[at][step];
  255. suspects.fetched(piece, held == ended);
  256. }
  257. (held, fetches)
  258. }
  259. /// A counter that each flight clears and counts up to the same: the
  260. /// first flight's fetch sees it cleared by the second, whose compare
  261. /// flags nothing.
  262. #[test]
  263. fn a_piece_caught_in_between_is_fetched_again() {
  264. let count: &[u32] = &[0, 3, 5];
  265. // The first is fetched while the second has cleared it.
  266. assert_eq!(landed(&[count, count], &[(1, 0), (1, 2)], false), (0, 1), "the CPU's side keeps what was in between");
  267. assert_eq!(landed(&[count, count], &[(1, 0), (1, 2)], true), (5, 2));
  268. // And again, while the third was at it; the fourth finds it whole.
  269. let four = [count; 4];
  270. assert_eq!(landed(&four, &[(1, 0), (2, 1), (3, 0), (3, 2)], true), (5, 4));
  271. // Fetched whole: no more fetches than without the check.
  272. assert_eq!(landed(&four, &[(0, 2), (1, 2), (2, 2), (3, 2)], true), (5, 1));
  273. assert_eq!(landed(&four, &[(0, 2), (1, 2), (2, 2), (3, 2)], false), (5, 1));
  274. }
  275. /// What the hash costs (ignored: a measurement): pieces that just came
  276. /// down, hashed alone, compared with what the CPU's side holds (as the
  277. /// merge begins), and both.
  278. #[test]
  279. #[ignore]
  280. fn hash_costs() {
  281. let (bytes, held) = (vec![0x5Au8; 96 << 20], vec![0x5Au8; 96 << 20]);
  282. let pieces = || bytes.chunks(64 << 10).zip(held.chunks(64 << 10));
  283. let compare = |a: &[u8], b: &[u8]| a.chunks(4096).zip(b.chunks(4096)).filter(|(a, b)| a != b).count() as u32;
  284. for _ in 0..5 {
  285. let mut all = 0u32;
  286. let mut time = |f: &dyn Fn(&[u8], &[u8]) -> u32| {
  287. let t = std::time::Instant::now();
  288. for (a, b) in pieces() {
  289. all ^= f(a, b);
  290. }
  291. t.elapsed().as_secs_f64() * 1e3
  292. };
  293. let (hashed, compared, both) = (
  294. time(&|a, _| hash(a)),
  295. time(&compare),
  296. time(&|a, b| hash(a) ^ compare(a, b)),
  297. );
  298. println!("96 MB: hashed {hashed:.2} ms, compared {compared:.2} ms, both {both:.2} ms ({all:#x})");
  299. }
  300. }
  301. }