land.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. //! What shaders wrote goes into title memory on a few threads
  2. //! (`VICTORY_LAND`, on by default; `=0` merges piece by piece on the thread
  3. //! that lands flights, as before).
  4. //!
  5. //! The relay's thread (`crate::host::relay`) was 58-60 ms of a 104 ms frame
  6. //! landing (run record-1): some 1,500 pieces of 64 KiB, 98 MB, fetched from
  7. //! copies in the card's memory, and each of them searched from both ends,
  8. //! cleared room for, read from title memory, copied, merged and compared
  9. //! again while it was put, one after the other; a lock and a protection
  10. //! call to open the guard of each, and the kernel's fault on the first
  11. //! write to each 4 KiB page of memory just made writable again.
  12. //!
  13. //! Here a piece is merged in one pass ([`crate::safecopy::merge`]): what
  14. //! the card holds is compared with what it held 32 bytes at a time, title
  15. //! memory is read only where they differ, just before the dwords that
  16. //! change are stored. The pieces of a landing are cut into jobs for a few
  17. //! threads kept for it ([`Pool`]).
  18. //!
  19. //! What stays in order: pieces in the same 64 KiB of title memory are in
  20. //! one job, in the order they were given (two copies may hold the same
  21. //! title memory); a landing's copies in the card's memory come before its
  22. //! other copies; a landing is done, whole, before the title is told
  23. //! anything and before the next one starts (`Host::relay_land`).
  24. //!
  25. //! With `VICTORY_LAND_BESIDE` (on by default) title memory that is a view of
  26. //! the title's physical pages is written through a view of our own of the
  27. //! same pages ([`crate::inplace::beside`]). The guards (`crate::watch`) are
  28. //! read-only title views: they stay as they are, no protection changes, and
  29. //! [`crate::watch::landed_beside`] notes the blocks written afterwards, so
  30. //! that the next refresh takes them as before.
  31. use std::sync::atomic::{AtomicU64, Ordering};
  32. use std::sync::{Condvar, Mutex, MutexGuard, OnceLock};
  33. /// The unit pieces are cut in (of title memory), and the guards' blocks.
  34. pub(crate) const BLOCK: usize = 64 << 10;
  35. /// The unit title memory is there or not in.
  36. const PAGE: usize = 4096;
  37. /// About this many bytes to a job.
  38. const JOB: usize = 256 << 10;
  39. /// See the file.
  40. pub(crate) fn on() -> bool {
  41. static ON: OnceLock<bool> = OnceLock::new();
  42. *ON.get_or_init(|| {
  43. std::env::var_os("VICTORY_LAND").is_none_or(|v| v != "0") && crate::safecopy::on() && crate::shadow::exact_back()
  44. })
  45. }
  46. /// How many threads land, the relay's own counted (`VICTORY_LAND_THREADS`).
  47. fn threads() -> usize {
  48. static THREADS: OnceLock<usize> = OnceLock::new();
  49. *THREADS.get_or_init(|| {
  50. let asked = std::env::var("VICTORY_LAND_THREADS").ok().and_then(|v| v.trim().parse().ok());
  51. asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(2, |n| n.get() / 4).clamp(1, 4)).clamp(1, 16)
  52. })
  53. }
  54. /// Whether views of the title's pages are written through one of ours.
  55. fn beside_on() -> bool {
  56. static ON: OnceLock<bool> = OnceLock::new();
  57. *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_BESIDE").is_none_or(|v| v != "0"))
  58. }
  59. /// Whether pieces an earlier fetch holds as they are now are left out
  60. /// ([`Had`]; `VICTORY_LAND_SKIP=1`, off by default: counted either way).
  61. pub(crate) fn skip_on() -> bool {
  62. static ON: OnceLock<bool> = OnceLock::new();
  63. *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_SKIP").is_some_and(|v| v == "1"))
  64. }
  65. /// Since the last frame-rate line; microseconds first.
  66. pub(crate) mod stat {
  67. /// Which pieces to fetch; their list recorded and sent.
  68. pub(crate) const GATHER: usize = 0;
  69. /// Looking for what shaders wrote to copies in the PC's memory, the part
  70. /// done while the fetch was on its way.
  71. pub(crate) const SCAN_BESIDE: usize = 1;
  72. /// The same, with nothing else to wait for.
  73. pub(crate) const SCAN: usize = 2;
  74. /// Merging what was fetched: until the last job is done, and the jobs'
  75. /// time on all threads.
  76. pub(crate) const CARD: usize = 3;
  77. pub(crate) const CARD_ALL: usize = 4;
  78. /// Merging what the scan found.
  79. pub(crate) const BACK: usize = 5;
  80. pub(crate) const BACK_ALL: usize = 6;
  81. /// In the jobs: waiting for the lock against the title's bytes going in.
  82. pub(crate) const LOCK: usize = 7;
  83. /// In the jobs: guards opened before a write, or noted after one.
  84. pub(crate) const NOTES: usize = 8;
  85. /// The flights' ranges done with; reading back, resets; what the title
  86. /// is told; the rest (the line's account).
  87. pub(crate) const DONE: usize = 9;
  88. pub(crate) const READ_BACKS: usize = 10;
  89. pub(crate) const TOLD: usize = 11;
  90. pub(crate) const REST: usize = 12;
  91. /// Counts: pieces merged, those with a new byte, their 4 KiB pages,
  92. /// those with a new byte, blocks of 32 bytes with a new byte, dwords put.
  93. pub(crate) const PIECES: usize = 13;
  94. pub(crate) const NEW_PIECES: usize = 14;
  95. pub(crate) const PAGES: usize = 15;
  96. pub(crate) const NEW_PAGES: usize = 16;
  97. pub(crate) const NEW_BLOCKS: usize = 17;
  98. pub(crate) const DWORDS: usize = 18;
  99. /// Pieces put through a view of ours, through the title's; pages where
  100. /// title memory was not there.
  101. pub(crate) const BESIDE: usize = 19;
  102. pub(crate) const DIRECT: usize = 20;
  103. pub(crate) const MISSING: usize = 21;
  104. /// Bytes asked for twice in a landing (fetched once); pieces and bytes
  105. /// an earlier fetch held already.
  106. pub(crate) const TWICE: usize = 22;
  107. pub(crate) const HAD: usize = 23;
  108. pub(crate) const HAD_BYTES: usize = 24;
  109. /// Jobs.
  110. pub(crate) const JOBS: usize = 25;
  111. pub(crate) const COUNT: usize = 26;
  112. }
  113. static STATS: [AtomicU64; stat::COUNT] = [const { AtomicU64::new(0) }; stat::COUNT];
  114. pub(crate) fn count(which: usize, n: u64) {
  115. STATS[which].fetch_add(n, Ordering::Relaxed);
  116. }
  117. /// Adds the microseconds since `from` to `which`; now.
  118. pub(crate) fn spent(which: usize, from: std::time::Instant) -> std::time::Instant {
  119. let now = std::time::Instant::now();
  120. count(which, (now - from).as_micros() as u64);
  121. now
  122. }
  123. /// For the frame-rate line: where landing went, per frame.
  124. pub(crate) fn log(frames: f64) {
  125. let s: Vec<f64> = STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  126. if s[stat::PIECES] == 0.0 && s[stat::REST] == 0.0 {
  127. return;
  128. }
  129. let ms = |i: usize| s[i] / 1000.0;
  130. let mb = |v: f64| v / (1 << 20) as f64;
  131. tracing::info!(
  132. "landing per frame (VICTORY_LAND={}, {} threads): which pieces to fetch {:.2} ms, then the fetches (the relay's line); \
  133. looking through copies in the PC's memory {:.2} ms beside them and {:.2} ms more; merging what was fetched {:.2} ms \
  134. ({:.2} ms on all threads, {:.0} jobs), merging the others {:.2} ms ({:.2} on all threads); of the threads' time \
  135. {:.2} ms waiting for the title's bytes going in, {:.2} ms opening or noting guards; then ranges done with {:.2} ms, \
  136. read-backs and lists {:.2}, the title told {:.2}, the rest {:.2}",
  137. u8::from(on()),
  138. threads(),
  139. ms(stat::GATHER),
  140. ms(stat::SCAN_BESIDE),
  141. ms(stat::SCAN),
  142. ms(stat::CARD),
  143. ms(stat::CARD_ALL),
  144. s[stat::JOBS],
  145. ms(stat::BACK),
  146. ms(stat::BACK_ALL),
  147. ms(stat::LOCK),
  148. ms(stat::NOTES),
  149. ms(stat::DONE),
  150. ms(stat::READ_BACKS),
  151. ms(stat::TOLD),
  152. ms(stat::REST),
  153. );
  154. tracing::info!(
  155. "landed per frame: {:.0} pieces, {:.0} with a new byte; of their {:.0} pages of 4 KiB {:.0} with a new byte ({:.1} MB), \
  156. {:.1} MB in blocks of 32 bytes with one, {:.2} MB put as dwords; {:.0} pieces through a view of ours \
  157. (VICTORY_LAND_BESIDE={}), {:.0} through the title's; {:.0} pages not there; asked for twice in a landing {:.1} MB; \
  158. held already by an earlier fetch {:.0} pieces {:.1} MB (VICTORY_LAND_SKIP={})",
  159. s[stat::PIECES],
  160. s[stat::NEW_PIECES],
  161. s[stat::PAGES],
  162. s[stat::NEW_PAGES],
  163. mb(s[stat::NEW_PAGES] * PAGE as f64),
  164. mb(s[stat::NEW_BLOCKS] * 32.0),
  165. mb(s[stat::DWORDS] * 4.0),
  166. s[stat::BESIDE],
  167. u8::from(beside_on()),
  168. s[stat::DIRECT],
  169. s[stat::MISSING],
  170. mb(s[stat::TWICE]),
  171. s[stat::HAD],
  172. mb(s[stat::HAD_BYTES]),
  173. u8::from(skip_on()),
  174. );
  175. }
  176. /// Threads kept for landing, and the work they are at.
  177. struct Pool {
  178. state: Mutex<State>,
  179. more: Condvar,
  180. idle: Condvar,
  181. /// One batch at a time.
  182. turn: Mutex<()>,
  183. threads: usize,
  184. }
  185. struct State {
  186. /// What to do with each number below `count`.
  187. work: Option<Work>,
  188. next: usize,
  189. count: usize,
  190. /// Helpers inside a call.
  191. running: usize,
  192. panicked: bool,
  193. }
  194. #[derive(Clone, Copy)]
  195. struct Work(*const (dyn Fn(usize) + Sync));
  196. // SAFETY: the closure may be called from any thread (`Sync`), and
  197. // `Pool::each` keeps it alive until no helper is inside a call.
  198. unsafe impl Send for Work {}
  199. impl Pool {
  200. fn state(&self) -> MutexGuard<'_, State> {
  201. self.state.lock().unwrap_or_else(|e| e.into_inner())
  202. }
  203. fn new(threads: usize) -> &'static Pool {
  204. let pool: &'static Pool = Box::leak(Box::new(Pool {
  205. state: Mutex::new(State { work: None, next: 0, count: 0, running: 0, panicked: false }),
  206. more: Condvar::new(),
  207. idle: Condvar::new(),
  208. turn: Mutex::new(()),
  209. threads,
  210. }));
  211. for i in 1..threads {
  212. // (A helper that is not there is only missed.)
  213. let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || pool.help());
  214. }
  215. pool
  216. }
  217. fn help(&self) {
  218. let mut state = self.state();
  219. loop {
  220. let Some((work, i)) = take(&mut state) else {
  221. state = self.more.wait(state).unwrap_or_else(|e| e.into_inner());
  222. continue;
  223. };
  224. state.running += 1;
  225. drop(state);
  226. // SAFETY: counted in `running`, so `each` has not returned.
  227. let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { (*work.0)(i) }));
  228. state = self.state();
  229. state.running -= 1;
  230. state.panicked |= ran.is_err();
  231. if state.running == 0 {
  232. self.idle.notify_all();
  233. }
  234. }
  235. }
  236. /// Calls `f` with every number below `count`, on the pool's threads and
  237. /// this one, and returns when every call has.
  238. fn each(&self, count: usize, f: &(dyn Fn(usize) + Sync)) {
  239. if count < 2 || self.threads < 2 {
  240. (0..count).for_each(f);
  241. return;
  242. }
  243. let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner());
  244. // SAFETY: the lifetime is left out only until this call returns, and
  245. // it does not before no helper is inside `f` and none can enter.
  246. let work = Work(unsafe { std::mem::transmute::<*const (dyn Fn(usize) + Sync + '_), *const (dyn Fn(usize) + Sync + 'static)>(f) });
  247. let mut state = self.state();
  248. (state.work, state.next, state.count, state.panicked) = (Some(work), 0, count, false);
  249. drop(state);
  250. if count > self.threads {
  251. self.more.notify_all();
  252. } else {
  253. (1..count).for_each(|_| self.more.notify_one());
  254. }
  255. let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
  256. loop {
  257. let Some((_, i)) = take(&mut self.state()) else { break };
  258. f(i);
  259. }
  260. }));
  261. let mut state = self.state();
  262. // (After a panic here: nothing more is begun.)
  263. state.work = None;
  264. while state.running > 0 {
  265. state = self.idle.wait(state).unwrap_or_else(|e| e.into_inner());
  266. }
  267. let panicked = state.panicked;
  268. drop(state);
  269. if let Err(panic) = ran {
  270. std::panic::resume_unwind(panic);
  271. }
  272. assert!(!panicked, "a job of landing panicked");
  273. }
  274. }
  275. /// The next number of the batch, if there is one.
  276. fn take(state: &mut State) -> Option<(Work, usize)> {
  277. let work = state.work?;
  278. if state.next >= state.count {
  279. return None;
  280. }
  281. state.next += 1;
  282. Some((work, state.next - 1))
  283. }
  284. /// [`Pool::each`] on the threads kept for landing.
  285. pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) {
  286. static POOL: OnceLock<&'static Pool> = OnceLock::new();
  287. POOL.get_or_init(|| Pool::new(threads())).each(count, f);
  288. }
  289. /// A piece to land: the copy's number, the title address, its bytes.
  290. pub(crate) type Piece = (u64, usize, usize);
  291. /// `pieces` in the order they are landed: by the 64 KiB block of title
  292. /// memory they lie in, those in one block in the order given (each is
  293. /// within one block). Where one copy alone has pieces in a block, those
  294. /// that overlap or touch are one piece: a landing's flights declare parts
  295. /// of the same memory, and what overlapped came down and was merged twice.
  296. /// Each with the number of the piece given that it begins with.
  297. pub(crate) fn ordered(pieces: &[Piece]) -> Vec<(usize, usize, usize)> {
  298. let mut order: Vec<usize> = (0..pieces.len()).collect();
  299. order.sort_by_key(|&i| pieces[i].1 / BLOCK);
  300. let mut out: Vec<(usize, usize, usize)> = Vec::with_capacity(order.len());
  301. for group in order.chunk_by(|&a, &b| pieces[a].1 / BLOCK == pieces[b].1 / BLOCK) {
  302. let alone = group.len() > 1 && group.iter().all(|&i| pieces[i].0 == pieces[group[0]].0);
  303. if !alone {
  304. out.extend(group.iter().map(|&i| (i, pieces[i].1, pieces[i].2)));
  305. continue;
  306. }
  307. let mut sorted = group.to_vec();
  308. sorted.sort_by_key(|&i| pieces[i].1);
  309. let begun = out.len();
  310. for i in sorted {
  311. let (_, at, len) = pieces[i];
  312. match out[begun..].last_mut() {
  313. Some(last) if at <= last.1 + last.2 => {
  314. let end = (last.1 + last.2).max(at + len);
  315. count(stat::TWICE, (last.2 + len - (end - last.1)) as u64);
  316. last.2 = end - last.1;
  317. }
  318. _ => out.push((i, at, len)),
  319. }
  320. }
  321. }
  322. out
  323. }
  324. /// Pieces (title address, bytes; in [`ordered`]'s order) as jobs: runs of
  325. /// about [`JOB`] bytes that end where a block ends.
  326. pub(crate) fn jobs(pieces: &[(usize, usize)]) -> Vec<std::ops::Range<usize>> {
  327. let mut out: Vec<std::ops::Range<usize>> = Vec::new();
  328. let (mut from, mut bytes) = (0, 0);
  329. for (i, &(at, len)) in pieces.iter().enumerate() {
  330. let new_block = i == 0 || pieces[i - 1].0 / BLOCK != at / BLOCK;
  331. if bytes >= JOB && new_block {
  332. out.push(from..i);
  333. (from, bytes) = (i, 0);
  334. }
  335. bytes += len;
  336. }
  337. if from < pieces.len() {
  338. out.push(from..pieces.len());
  339. }
  340. out
  341. }
  342. /// What earlier fetches brought, for as long as a flight they ran behind
  343. /// has not landed: per fetch, the value the host's fence had been given
  344. /// behind the last flight sent before it, and by copy (its number) and
  345. /// piece the offsets it brought.
  346. ///
  347. /// A fetch on the drawing queue runs behind everything sent before it, so
  348. /// it brings what those flights' shaders wrote too, and the merge of it put
  349. /// that into title memory. Their own landings flag the same pieces and
  350. /// fetched them again, to find every byte merged. A piece that a fetch held
  351. /// whole, behind the flight that flags it, has nothing more of that flight.
  352. /// (Bytes left out of that merge, the title's that went up behind the
  353. /// fetch, went up behind that flight too, and stand over what it wrote.)
  354. #[derive(Default)]
  355. pub(crate) struct Had(Vec<(u64, std::collections::HashMap<(u64, usize), (usize, usize)>)>);
  356. impl Had {
  357. /// Flights from the one behind which `fence` is signalled on are landed
  358. /// next: what is of no use to them is dropped.
  359. pub(crate) fn landing(&mut self, fence: u64) {
  360. self.0.retain(|had| had.0 >= fence);
  361. }
  362. /// A fetch that ran behind every flight up to `fence` brought (copy,
  363. /// title address, bytes) `pieces`. They are merged before the next ask.
  364. pub(crate) fn fetched(&mut self, fence: u64, pieces: impl Iterator<Item = Piece>) {
  365. let mut all = std::collections::HashMap::new();
  366. for (copy, at, len) in pieces {
  367. // (Two parts of a block that do not touch: the longer one.)
  368. let had = all.entry((copy, at / BLOCK)).or_insert((at, at + len));
  369. if len > had.1 - had.0 {
  370. *had = (at, at + len);
  371. }
  372. }
  373. self.0.push((fence, all));
  374. }
  375. /// Whether a fetch behind the flight of `fence` brought all of the
  376. /// piece.
  377. pub(crate) fn holds(&self, fence: u64, (copy, at, len): Piece) -> bool {
  378. self.0.iter().any(|(behind, all)| {
  379. *behind >= fence && all.get(&(copy, at / BLOCK)).is_some_and(|had| had.0 <= at && at + len <= had.1)
  380. })
  381. }
  382. }
  383. /// What a job wrote beside the guards, to be noted ([`Notes::flush`]).
  384. #[derive(Default)]
  385. pub(crate) struct Notes {
  386. /// Pages of 4 KiB, by number.
  387. pages: Vec<usize>,
  388. /// Per piece, from the first such page to the last: address, bytes.
  389. spans: Vec<(usize, usize)>,
  390. }
  391. impl Notes {
  392. /// At the end of a job: what it wrote beside the guards is noted.
  393. pub(crate) fn flush(&mut self) {
  394. if self.pages.is_empty() {
  395. return;
  396. }
  397. let noting = std::time::Instant::now();
  398. crate::watch::landed_beside(&self.pages, &self.spans);
  399. self.pages.clear();
  400. self.spans.clear();
  401. spent(stat::NOTES, noting);
  402. }
  403. }
  404. /// Lands one piece: `parts` (offsets from and to) of the bytes at `now`,
  405. /// which the card wrote, go into title memory from `title` on and into
  406. /// `held` ([`crate::safecopy::merge`] says how, and what `take` is). The
  407. /// piece lies in one 64 KiB block of title memory. Returns the bytes put.
  408. ///
  409. /// # Safety
  410. /// `now` and `held` are ours from 0 to the last part's end, and nothing but
  411. /// the card writes `now` there, nothing but this call `held`.
  412. pub(crate) unsafe fn piece(
  413. title: usize,
  414. now: *const u8,
  415. held: *mut u8,
  416. parts: &[(usize, usize)],
  417. take: bool,
  418. notes: &mut Notes,
  419. ) -> u64 {
  420. // SAFETY: the caller's.
  421. unsafe { piece_at(title, now, held, parts, take, notes, beside_on()) }
  422. }
  423. /// [`piece`], and whether a view of ours is looked for.
  424. ///
  425. /// # Safety
  426. /// [`piece`]'s.
  427. unsafe fn piece_at(
  428. title: usize,
  429. now: *const u8,
  430. held: *mut u8,
  431. parts: &[(usize, usize)],
  432. take: bool,
  433. notes: &mut Notes,
  434. beside: bool,
  435. ) -> u64 {
  436. let Some(end) = parts.last().map(|p| p.1) else {
  437. return 0;
  438. };
  439. // From here until the piece is put the runtime changes no mapping: our
  440. // view's address stays where the title sees `title`. Not waited for: if
  441. // a change is under way, the title's own address does.
  442. let reading = beside.then(crate::watch::title_memory_reading_now).flatten();
  443. let beside = reading.as_ref().and_then(|_| crate::inplace::beside(title, end));
  444. count(stat::PIECES, 1);
  445. count(if beside.is_some() { stat::BESIDE } else { stat::DIRECT }, 1);
  446. // The pages that differ, before any is written: none, and the guard
  447. // stays; else it is opened once for the piece.
  448. let mut differing = [true; BLOCK / PAGE + 1];
  449. let base = title / PAGE;
  450. if beside.is_none() {
  451. drop(reading);
  452. differing.fill(false);
  453. for_pages(title, parts, |from, n| {
  454. // SAFETY: the caller's.
  455. if unsafe { crate::safecopy::differ(now.add(from), held.add(from), n) } {
  456. differing[(title + from) / PAGE - base] = true;
  457. }
  458. });
  459. let Some(first) = differing.iter().position(|&d| d) else {
  460. for_pages(title, parts, |_, _| count(stat::PAGES, 1));
  461. return 0;
  462. };
  463. let last = differing.iter().rposition(|&d| d).unwrap_or(first);
  464. let (from, to) = (((base + first) * PAGE).max(title), ((base + last + 1) * PAGE).min(title + end));
  465. let opening = std::time::Instant::now();
  466. crate::watch::landing(from, to - from);
  467. spent(stat::NOTES, opening);
  468. }
  469. let into = beside.unwrap_or(title);
  470. let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0);
  471. let mut span: Option<(usize, usize)> = None;
  472. for_pages(title, parts, |from, n| {
  473. pages += 1;
  474. if !differing[(title + from) / PAGE - base] {
  475. return;
  476. }
  477. // SAFETY: the caller's; title memory, by an address that shows it
  478. // (`beside`) or the title's own.
  479. let done = unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) };
  480. blocks += done.new;
  481. dwords += done.dwords;
  482. missing += u64::from(!done.there);
  483. if done.new > 0 {
  484. new_pages += 1;
  485. if beside.is_some() {
  486. let page = (title + from) / PAGE;
  487. // (Two parts in one page.)
  488. if notes.pages.last() != Some(&page) {
  489. notes.pages.push(page);
  490. }
  491. let s = span.get_or_insert((title + from, title + from + n));
  492. s.1 = title + from + n;
  493. }
  494. }
  495. });
  496. if let Some((from, to)) = span {
  497. notes.spans.push((from, to - from));
  498. }
  499. count(stat::NEW_PIECES, u64::from(new_pages > 0));
  500. count(stat::PAGES, pages);
  501. count(stat::NEW_PAGES, new_pages);
  502. count(stat::NEW_BLOCKS, blocks);
  503. count(stat::DWORDS, dwords);
  504. count(stat::MISSING, missing);
  505. crate::shadow::PUT[0].fetch_add(u64::from(dwords > 0), Ordering::Relaxed);
  506. crate::shadow::PUT[2].fetch_add(dwords * 4, Ordering::Relaxed);
  507. dwords * 4
  508. }
  509. /// `parts` of a piece that begins at `title`, cut where 4 KiB pages of title
  510. /// memory end: offset and bytes.
  511. fn for_pages(title: usize, parts: &[(usize, usize)], mut f: impl FnMut(usize, usize)) {
  512. for &(from, to) in parts {
  513. let mut at = from;
  514. while at < to {
  515. let n = (PAGE - (title + at) % PAGE).min(to - at);
  516. f(at, n);
  517. at += n;
  518. }
  519. }
  520. }
  521. #[cfg(test)]
  522. mod tests;