diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index bd9f371..977903a 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -327,6 +327,7 @@ pub(crate) fn sync_heaps() { let mut spent = [0u64; 3]; let since = |at: std::time::Instant| at.elapsed().as_nanos() as u64; let mut kinds = [0u64; 5]; + let mut short = 0u64; let mut wait: Vec = Vec::new(); let frame = crate::frame::current(); let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); @@ -378,37 +379,62 @@ pub(crate) fn sync_heaps() { let began = std::time::Instant::now(); let copied = host.copied_begin(step as usize); let samplers = heap.samplers(); + let in_place = sync_in_place() && step == 32 && crate::safecopy::on(); let found: Vec> = parts.chunks(SYNC_PAGES).map(|_| Default::default()).collect(); crate::land::each_view(true, found.len(), &|n| { let mut out = SyncPart::default(); let mut page_bytes: Vec = Vec::new(); let mut changed: Vec = Vec::new(); + let mut bits: Vec = Vec::new(); for &(from, to) in parts.chunks(SYNC_PAGES).nth(n).unwrap_or_default() { - // The page's records are read through the kernel, into a - // copy: a page the title unmaps meanwhile fails the read - // where 2,048 reads in place would fault. - page_bytes.resize(to - from, 0); - if !crate::host::read_into(from as *const u8, &mut page_bytes) { - continue; - } - out.pages += 1; - out.views += u64::from(crate::watch::guarded(from, to)); - out.bytes += (to - from) as u64; let slots = changed_slots(from, to, start as usize, step, mirrored_count); // A record that straddles the range's ends is left // to the range that holds its first byte. let first = ((from - start as usize) as u64).div_ceil(step).max(slots.start); - let Some(records) = page_bytes.get((start + first * step) as usize - from..) else { - continue; + let lead = (start + first * step) as usize; + let records: &[u8] = if in_place { + // Read where they are, each record once, and compared + // as it is read (`host::Copied::changes_in_place`). + let count = (to.saturating_sub(lead) as u64 / step).min(slots.end.saturating_sub(first)); + changed.clear(); + // SAFETY: as below; title memory is read by a copy that + // fails where a page is not there. + let whole = + unsafe { copied.changes_in_place(first as u32, lead as *const u8, count as usize, &mut bits, &mut changed) }; + out.pages += 1; + out.views += u64::from(crate::watch::guarded(from, to)); + out.bytes += (to - from) as u64; + out.looked += count; + out.short += u64::from(!whole); + // What was read of the changed records is in the records + // last seen now. + // SAFETY: this part's records alone, which nothing else + // writes meanwhile. + unsafe { copied.seen(first as u32, count as usize) } + } else { + // The page's records are read through the kernel, into a + // copy: a page the title unmaps meanwhile fails the read + // where 2,048 reads in place would fault. + page_bytes.resize(to - from, 0); + if !crate::host::read_into(from as *const u8, &mut page_bytes) { + continue; + } + out.pages += 1; + out.views += u64::from(crate::watch::guarded(from, to)); + out.bytes += (to - from) as u64; + let Some(records) = page_bytes.get(lead.wrapping_sub(from)..) else { + continue; + }; + let count = (records.len() as u64 / step).min(slots.end.saturating_sub(first)); + out.looked += count; + // Only the records that are not the ones last seen + // there (`host::Copied::changes`). + changed.clear(); + // SAFETY: the parts are ranges of the heap apart from one + // another, and only records that lie whole in one are its. + unsafe { copied.changes(first as u32, &records[..(count * step) as usize], &mut changed) }; + records }; - let count = (records.len() as u64 / step).min(slots.end.saturating_sub(first)); - out.looked += count; - // Only the records that are not the ones last seen - // there (`host::Copied::changes`). - changed.clear(); - // SAFETY: the parts are ranges of the heap apart from one - // another, and only records that lie whole in one are its. - unsafe { copied.changes(first as u32, &records[..(count * step) as usize], &mut changed) }; for &index in &changed { let at = (u64::from(index) - first) as usize * step as usize; let word = |n: usize| { @@ -461,6 +487,7 @@ pub(crate) fn sync_heaps() { views += part.views; bytes += part.bytes; looked += part.looked; + short += part.short; tabled += part.tabled; kinds[0] += part.nothing; later += part.wait.len() as u64; @@ -495,6 +522,34 @@ pub(crate) fn sync_heaps() { for (count, n) in SYNCED_KINDS.iter().zip(kinds) { count.fetch_add(n, Relaxed); } + SYNC_SHORT.fetch_add(short, Relaxed); +} + +/// Pages [`sync_heaps`] read in place of which a part could not be read +/// ([`sync_in_place`]), since the last frame line. +#[cfg(windows)] +static SYNC_SHORT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether [`sync_heaps`] reads a changed page's records where they are, each +/// once, and compares each with the one last seen as it reads it, 32 bytes at +/// a time (`VICTORY_SYNC_IN_PLACE=1`; off by default: into a copy of the page +/// first, through the kernel, then compared, as before). +/// +/// Ported from Belobug/VIctory-Belobug-AMD 15ab94e (measured there: the copy +/// and the compare were each a pass over all of the page, 7.4 and 5.3 ms a +/// frame of the six threads for 35 MB, run heapsync-ab1; on by default there +/// since 8822ed4). Here the round's "reading and comparing" was 2.6-3.1 ms a +/// frame (release run 233354), and the submitting thread waits for the +/// round. A page the title unmaps meanwhile fails where the copy failed; the +/// records before the place are taken as they were read. +#[cfg(windows)] +fn sync_in_place() -> bool { + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_SYNC_IN_PLACE") { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SYNC_IN_PLACE").is_some_and(|v| v != "0")) } /// Of those mirrored, since the last frame line: no view, a view of an object, @@ -515,6 +570,8 @@ struct SyncPart { make: Vec, wait: Vec, kinds: [u64; 5], + /// Pages read in place not all there ([`SYNC_SHORT`]). + short: u64, } /// Pages [`sync_heaps`] gives a thread at a time. @@ -556,9 +613,17 @@ pub(crate) fn sync_line(frames: f64) { let [pages, looked, mirrored, micros, tabled, later, waited] = [0, 1, 2, 3, 4, 5, 6].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); let split = [0, 1, 2, 3, 4].map(|i| SYNC_SPLIT[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64); let kinds = [0, 1, 2, 3, 4].map(|i| SYNCED_KINDS[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames); + let short = SYNC_SHORT.swap(0, std::sync::atomic::Ordering::Relaxed); if pages == 0 { return; } + if sync_in_place() { + tracing::info!( + "the heaps' records read where they are (VICTORY_SYNC_IN_PLACE=1): {:.1} pages per frame, {short} of them not all \ + there since the last line", + pages as f64 / frames + ); + } tracing::info!( "descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \ {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.1} new ones of \ diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 456860a..347a86e 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -4713,6 +4713,48 @@ impl Copied<'_> { let last = unsafe { std::slice::from_raw_parts_mut(self.at.add(at), end - at) }; changed_records(last, &records[..end - at], self.step, first, out); } + + /// As [`Copied::changes`] for the `count` records of title memory at + /// `title` (slot `first` on), 32 bytes each, read where they are, each + /// once ([`crate::safecopy::changed`]); `bits` is room. False when a page + /// of them could not be read: those before it are done, the others + /// stay as last seen. + /// + /// # Safety + /// As [`Copied::changes`]; `title` is title memory (read by a copy that + /// fails where a page is not there). + pub(crate) unsafe fn changes_in_place(&self, first: u32, title: *const u8, count: usize, bits: &mut Vec, out: &mut Vec) -> bool { + let at = first as usize * self.step; + let count = count.min(self.len.saturating_sub(at) / 32); + if self.step != 32 || count == 0 { + return true; + } + bits.clear(); + bits.resize(count.div_ceil(64), 0); + // SAFETY: within the records held; the caller's slots alone. + let whole = unsafe { crate::safecopy::changed(title, self.at.add(at), count, bits) }; + for (n, &word) in bits.iter().enumerate() { + let mut word = word; + while word != 0 { + out.push(first + (n * 64) as u32 + word.trailing_zeros()); + word &= word - 1; + } + } + whole + } + + /// The `count` records last seen from slot `first` on (fewer where the + /// heap ends). + /// + /// # Safety + /// As [`Copied::changes`]: no other call beside this one has any of + /// these slots. + pub(crate) unsafe fn seen(&self, first: u32, count: usize) -> &[u8] { + let at = (first as usize * self.step).min(self.len); + let len = (count * self.step).min(self.len - at); + // SAFETY: within the records held; the caller's slots alone. + unsafe { std::slice::from_raw_parts(self.at.add(at), len) } + } } /// The records (`step` bytes each, the first is slot `first`) that differ diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index 66bb68a..244e825 100644 --- a/crates/victory-gpu/src/safecopy.rs +++ b/crates/victory-gpu/src/safecopy.rs @@ -134,6 +134,43 @@ std::arch::global_asm!( "mov qword ptr [rax + 8], r11", "mov rax, r9", "ret", + ".globl victory_safe_changed", + ".globl victory_safe_changed_at", + ".globl victory_safe_changed_after", + ".globl victory_safe_changed_failed", + // rcx title memory, rdx what was last seen there, r8 records of 32 + // bytes, r9 a bit per record (zeroed by the caller): each record of + // title memory is read once; where it differs from the one last seen it + // goes over that one, and then its bit is set. eax: whether all could + // be read (where one could not, those before it are done). + "victory_safe_changed:", + "xor r10d, r10d", + "test r8, r8", + "jz 3f", + "2:", + "victory_safe_changed_at:", + "vmovdqu ymm0, ymmword ptr [rcx]", + "victory_safe_changed_after:", + "vpcmpeqb ymm1, ymm0, ymmword ptr [rdx]", + "vpmovmskb eax, ymm1", + "cmp eax, -1", + "je 4f", + "vmovdqu ymmword ptr [rdx], ymm0", + "bts qword ptr [r9], r10", + "4:", + "add rcx, 32", + "add rdx, 32", + "inc r10", + "cmp r10, r8", + "jb 2b", + "3:", + "vzeroupper", + "mov eax, 1", + "ret", + "victory_safe_changed_failed:", + "vzeroupper", + "xor eax, eax", + "ret", ); unsafe extern "system" { @@ -149,6 +186,27 @@ unsafe extern "system" { fn victory_safe_merge_at(); fn victory_safe_merge_after(); fn victory_safe_merge_failed(); + fn victory_safe_changed(title: *const u8, seen: *mut u8, records: usize, bits: *mut u64) -> u32; + fn victory_safe_changed_at(); + fn victory_safe_changed_after(); + fn victory_safe_changed_failed(); +} + +/// The records of 32 bytes at `title` (`records` of them) that differ from +/// those in `seen`: each is read once, goes over the one in `seen`, and gets +/// its bit in `bits` (record n: bit n % 64 of word n / 64). False if a page +/// of title memory could not be read: then the records before it are done, +/// and the others are as they were. +/// +/// # Safety +/// `seen` holds `records * 32` bytes of ours that nothing else reads or +/// writes meanwhile, and `bits` at least `records.div_ceil(64)` words, all +/// 0; `title` is as [`copy`]'s source. [`on`] must have been asked. +pub(crate) unsafe fn changed(title: *const u8, seen: *mut u8, records: usize, bits: &mut [u64]) -> bool { + assert!(bits.len() >= records.div_ceil(64)); + // SAFETY: a fault reading title memory leaves through the failing exit + // ([`failing_exit`]); the rest is the caller's. + unsafe { victory_safe_changed(title, seen, records, bits.as_mut_ptr()) != 0 } } /// What [`merge`] did. @@ -354,6 +412,10 @@ pub(crate) fn failing_exit(at: usize) -> Option { if (from..to).contains(&at) { return Some(victory_safe_put_failed as *const () as usize); } + let (from, to) = (victory_safe_changed_at as *const () as usize, victory_safe_changed_after as *const () as usize); + if (from..to).contains(&at) { + return Some(victory_safe_changed_failed as *const () as usize); + } let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize); (from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize) } @@ -409,6 +471,47 @@ mod tests { } } + /// The records that differ get their bits and go over those last seen; + /// a page that is not there fails, with the records before it done. + #[test] + fn changed_records_are_found_and_taken() { + assert!(on()); + let pages = Pages::new(3 << 12); + pages.fill(); + let records: usize = (3 << 12) / 32; + // SAFETY: inside the allocation. + let title = unsafe { std::slice::from_raw_parts(pages.0, pages.1) }.to_vec(); + let mut seen = title.clone(); + let mut differ = Vec::new(); + for n in [0usize, 1, 63, 64, 65, 200, 383] { + seen[n * 32 + n % 32] ^= 0x11; + differ.push(n); + } + let mut bits = vec![0u64; records.div_ceil(64)]; + // SAFETY: inside the allocation; `seen` and `bits` are ours. + assert!(unsafe { changed(pages.0, seen.as_mut_ptr(), records, &mut bits) }); + let found: Vec = (0..records).filter(|n| bits[n / 64] >> (n % 64) & 1 != 0).collect(); + assert_eq!(found, differ); + assert_eq!(seen, title); + bits.fill(0); + // SAFETY: as above. + assert!(unsafe { changed(pages.0, seen.as_mut_ptr(), records, &mut bits) }); + assert!(bits.iter().all(|&b| b == 0)); + // The second page is not there: records 0 and 200 (on the third) differ. + for n in [0usize, 200] { + seen[n * 32] ^= 0x22; + } + // SAFETY: a page of our allocation. + unsafe { VirtualFree(pages.0.add(4096).cast(), 4096, MEM_DECOMMIT) }; + let mut bits = vec![0u64; records.div_ceil(64)]; + // SAFETY: as above; the page that is not there fails the call. + assert!(!unsafe { changed(pages.0, seen.as_mut_ptr(), records, &mut bits) }); + let found: Vec = (0..records).filter(|n| bits[n / 64] >> (n % 64) & 1 != 0).collect(); + assert_eq!(found, [0]); + assert_eq!(seen[..32], title[..32]); + assert_ne!(seen[200 * 32..201 * 32], title[200 * 32..201 * 32]); + } + /// The dwords that changed are stored, and no byte of any other, at /// every alignment and length; a page that is not there fails. #[test]