gpu: incremental HeapRanges spans, chunked wide_each refreshes, and zero-alloc prelude/front_spans

This commit is contained in:
theme613 committed 2026-11-28 16:07:21 +08:00
1 parent 6f34121d31
commit 8503191734
3 files changed
+361 -159

No files matched your search

+166 -54
View File
@@ -715,49 +715,162 @@ fn heap_spread() -> bool {
} }
/// The host copy and range the buffer view of each of a heap's slots reads /// The host copy and range the buffer view of each of a heap's slots reads
/// ([`State::heap_buffers`]), by slot. /// ([`State::heap_buffers`]), by slot, with incremental per-copy spans and
#[derive(Default)] /// active-slot buckets partitioned by `slot % HEAP_ROUND`.
struct HeapRanges<T>(Vec<Option<(T, u64, u64)>>); struct HeapRanges<T> {
slots: Vec<Option<(std::sync::Arc<T>, u64, u64)>>,
in_part: Vec<u64>,
by_part: [Vec<u32>; HEAP_ROUND as usize],
spans: crate::host::ByCopy<(std::sync::Arc<T>, u64, u64)>,
spans_dirty: bool,
views: u32,
}
impl<T> Default for HeapRanges<T> {
fn default() -> Self {
Self {
slots: Vec::new(),
in_part: Vec::new(),
by_part: std::array::from_fn(|_| Vec::new()),
spans: Default::default(),
spans_dirty: false,
views: 0,
}
}
}
/// Descriptor-derived references belong to the heap that produced them. /// Descriptor-derived references belong to the heap that produced them.
pub(crate) struct BufferSweep { pub(crate) struct BufferSweep {
passes: u64, passes: u64,
ranges: HeapRanges<std::sync::Arc<crate::shadow::Shadow>>, ranges: HeapRanges<crate::shadow::Shadow>,
// Last refresh frame and covered interval for throttled, unwatched copies. // Last refresh frame and covered interval for throttled, unwatched copies.
unwatched: std::collections::HashMap<u64, (u64, u64, u64)>, unwatched: std::collections::HashMap<u64, (u64, u64, u64)>,
} }
impl Default for BufferSweep { impl Default for BufferSweep {
fn default() -> Self { fn default() -> Self {
Self { passes: 0, ranges: HeapRanges(Vec::new()), unwatched: Default::default() } Self { passes: 0, ranges: HeapRanges::default(), unwatched: Default::default() }
} }
} }
impl<T> HeapRanges<T> { impl<T> HeapRanges<T> {
fn set(&mut self, slot: u32, range: Option<(T, u64, u64)>) { fn clear(&mut self) {
let slot = slot as usize; self.slots.clear();
if range.is_none() && slot >= self.0.len() { self.in_part.clear();
return; for part in &mut self.by_part {
part.clear();
} }
if slot >= self.0.len() { self.spans.clear();
self.0.resize_with(slot + 1, || None); self.spans_dirty = false;
} self.views = 0;
self.0[slot] = range;
} }
/// Forgets the slots of one of `parts` parts fn set(&mut self, slot: u32, range: Option<(std::sync::Arc<T>, u64, u64)>) {
/// (`HostHeap::buffer_slots_of`). use std::sync::Arc;
fn forget_part(&mut self, part: u32, parts: u32) { let idx = slot as usize;
self.0.iter_mut().skip(part as usize).step_by(parts as usize).for_each(|r| *r = None); match (self.slots.get(idx).and_then(Option::as_ref), range.as_ref()) {
(None, None) => return,
(Some((os, of, ot)), Some((ns, nf, nt)))
if Arc::ptr_eq(os, ns) && *of == *nf && *ot == *nt =>
{
return;
}
_ => {}
}
if idx >= self.slots.len() {
self.slots.resize_with(idx + 1, || None);
}
let old = std::mem::replace(&mut self.slots[idx], range);
if let Some((os, of, ot)) = old {
self.views -= 1;
if !self.spans_dirty {
let old_key = Arc::as_ptr(&os) as usize;
if let Some(&(_, min_from, max_to)) = self.spans.get(&old_key) {
let shrunk = match &self.slots[idx] {
Some((ns, nf, nt)) if Arc::ptr_eq(&os, ns) => {
(of <= min_from && *nf > of) || (ot >= max_to && *nt < ot)
}
_ => of <= min_from || ot >= max_to,
};
if shrunk {
self.spans_dirty = true;
}
}
}
}
if let Some((ns, nf, nt)) = &self.slots[idx] {
self.views += 1;
let word = idx / 64;
let bit = 1u64 << (idx % 64);
if word >= self.in_part.len() {
self.in_part.resize(word + 1, 0);
}
if self.in_part[word] & bit == 0 {
self.in_part[word] |= bit;
self.by_part[idx % HEAP_ROUND as usize].push(slot);
}
if !self.spans_dirty {
let key = Arc::as_ptr(ns) as usize;
let span = self.spans.entry(key).or_insert_with(|| (ns.clone(), *nf, *nt));
span.1 = span.1.min(*nf);
span.2 = span.2.max(*nt);
}
}
} }
fn ranges(&self) -> impl Iterator<Item = &(T, u64, u64)> { /// Removes slots in `part` that are no longer live buffer slots without
self.0.iter().flatten() /// churning slots that stay unchanged.
fn prune_part(&mut self, part: u32, mut is_live: impl FnMut(u32) -> bool) {
let part_idx = part as usize;
let mut list = std::mem::take(&mut self.by_part[part_idx]);
let mut i = 0;
while i < list.len() {
let slot = list[i];
let idx = slot as usize;
let occupied = self.slots.get(idx).is_some_and(Option::is_some);
if !occupied || !is_live(slot) {
if occupied {
self.set(slot, None);
}
let word = idx / 64;
if let Some(bits) = self.in_part.get_mut(word) {
*bits &= !(1u64 << (idx % 64));
}
list.swap_remove(i);
} else {
i += 1;
}
}
self.by_part[part_idx] = list;
}
fn spans(&mut self) -> &crate::host::ByCopy<(std::sync::Arc<T>, u64, u64)> {
if self.spans_dirty {
self.spans.clear();
for part in &self.by_part {
for &slot in part {
if let Some((shadow, from, to)) = self.slots.get(slot as usize).and_then(Option::as_ref) {
let key = std::sync::Arc::as_ptr(shadow) as usize;
let span = self.spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to));
span.1 = span.1.min(*from);
span.2 = span.2.max(*to);
}
}
}
self.spans_dirty = false;
}
&self.spans
}
#[cfg(test)]
fn ranges(&self) -> impl Iterator<Item = &(std::sync::Arc<T>, u64, u64)> {
self.slots.iter().flatten()
} }
} }
#[cfg(test)] #[cfg(test)]
mod heap_range_tests { mod heap_range_tests {
use std::sync::Arc;
use super::{HEAP_ROUND, HeapRanges}; use super::{HEAP_ROUND, HeapRanges};
/// Round by round every slot is looked at again once, whatever was /// Round by round every slot is looked at again once, whatever was
@@ -765,25 +878,25 @@ mod heap_range_tests {
#[test] #[test]
fn every_slot_is_looked_at_again_in_a_round() { fn every_slot_is_looked_at_again_in_a_round() {
const SLOTS: u32 = 1000; const SLOTS: u32 = 1000;
let mut ranges = HeapRanges(Vec::new()); let copy = Arc::new(());
let mut ranges = HeapRanges::default();
ranges.set(7, None); ranges.set(7, None);
assert_eq!(ranges.ranges().count(), 0); assert_eq!(ranges.views, 0);
for slot in (0..SLOTS).step_by(3) { for slot in (0..SLOTS).step_by(3) {
ranges.set(slot, Some(((), 0, 1))); ranges.set(slot, Some((copy.clone(), 0, 1)));
} }
let parts = HEAP_ROUND as u32; let parts = HEAP_ROUND as u32;
for pass in 1..=HEAP_ROUND { for pass in 1..=HEAP_ROUND {
let part = (pass % HEAP_ROUND) as u32; let part = (pass % HEAP_ROUND) as u32;
ranges.forget_part(part, parts); ranges.prune_part(part, |s| s % 3 == 0);
for slot in (0..SLOTS).step_by(3).filter(|slot| slot % parts == part) { for slot in (0..SLOTS).step_by(3).filter(|slot| slot % parts == part) {
assert!(ranges.0[slot as usize].is_none(), "slot {slot} not forgotten"); ranges.set(slot, Some((copy.clone(), pass, pass + 1)));
ranges.set(slot, Some(((), pass, pass)));
} }
assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize); assert_eq!(ranges.views as usize, SLOTS.div_ceil(3) as usize);
} }
assert!(ranges.ranges().all(|r| r.1 != 0), "a slot not looked at in a round"); assert!(ranges.ranges().all(|r| r.1 != 0), "a slot not looked at in a round");
ranges.set(3, None); ranges.set(3, None);
assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize - 1); assert_eq!(ranges.views as usize, SLOTS.div_ceil(3) as usize - 1);
} }
/// The spans of 4,400 copies from the ranges of 72,000 slots, as a pass /// The spans of 4,400 copies from the ranges of 72,000 slots, as a pass
@@ -793,9 +906,8 @@ mod heap_range_tests {
#[ignore] #[ignore]
fn spans_of_a_pass() { fn spans_of_a_pass() {
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc;
let copies: Vec<Arc<u64>> = (0..4400).map(Arc::new).collect(); let copies: Vec<Arc<u64>> = (0..4400).map(Arc::new).collect();
let (mut table, mut slots) = (HashMap::new(), HeapRanges(Vec::new())); let (mut table, mut slots) = (HashMap::new(), HeapRanges::default());
for slot in 0..72_000u32 { for slot in 0..72_000u32 {
let copy = &copies[slot as usize * 7919 % 4400]; let copy = &copies[slot as usize * 7919 % 4400];
table.insert(slot, (copy.clone(), u64::from(slot), u64::from(slot) + 64)); table.insert(slot, (copy.clone(), u64::from(slot), u64::from(slot) + 64));
@@ -1174,13 +1286,13 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
let changed = host.buffer_changes(); let changed = host.buffer_changes();
let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()); let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread());
let slots = if all { let slots = if all {
ranges.0.clear(); ranges.clear();
host.buffer_slots() host.buffer_slots()
} else if heap_spread() { } else if heap_spread() {
// The written ones, and this pass's part of the others. // The written ones, and this pass's part of the others.
let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32); let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32);
ranges.forget_part(part, parts);
let mut slots = host.buffer_slots_of(part, parts); let mut slots = host.buffer_slots_of(part, parts);
ranges.prune_part(part, |s| slots.binary_search(&s).is_ok());
slots.extend(changed); slots.extend(changed);
slots slots
} else { } else {
@@ -1256,16 +1368,10 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
} }
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
let looked = std::time::Instant::now(); let looked = std::time::Instant::now();
// Per host copy, the span its picked views cover. // Per host copy, the span its picked views cover (maintained incrementally).
let mut spans: crate::host::ByCopy<(std::sync::Arc<crate::shadow::Shadow>, u64, u64)> = Default::default(); let views = ranges.views;
let mut views = 0u32; let spans = ranges.spans();
for (shadow, from, to) in ranges.ranges() { let copies_len = spans.len();
views += 1;
let key = std::sync::Arc::as_ptr(shadow) as usize;
let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to));
span.1 = span.1.min(*from);
span.2 = span.2.max(*to);
}
let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum();
// Memory that is not write-watched is copied whole by every refresh. // Memory that is not write-watched is copied whole by every refresh.
// It was once refreshed only every 120 frames (unmapped pages read // It was once refreshed only every 120 frames (unmapped pages read
@@ -1279,21 +1385,27 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
std::env::var("VICTORY_UNWATCHED_FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(1) std::env::var("VICTORY_UNWATCHED_FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(1)
}); });
let mut found = Vec::with_capacity(spans.len()); let mut found = Vec::with_capacity(spans.len());
let mut next_unwatched = std::collections::HashMap::new(); if every > 1 {
for (shadow, from, to) in spans.values() { let mut next_unwatched = std::collections::HashMap::new();
if every > 1 && shadow.unwatched() { for (shadow, from, to) in spans.values() {
let id = shadow.id(); if shadow.unwatched() {
if let Some(&(last, low, high)) = unwatched.get(&id) let id = shadow.id();
&& frame >= last && frame - last < every && low <= *from && *to <= high if let Some(&(last, low, high)) = unwatched.get(&id)
{ && frame >= last && frame - last < every && low <= *from && *to <= high
next_unwatched.insert(id, (last, low, high)); {
continue; next_unwatched.insert(id, (last, low, high));
continue;
}
next_unwatched.insert(id, (frame, *from, *to));
} }
next_unwatched.insert(id, (frame, *from, *to)); found.push((shadow.clone(), *from, (*to).min(*from + shadow.left(*from))));
}
*unwatched = next_unwatched;
} else {
for (shadow, from, to) in spans.values() {
found.push((shadow.clone(), *from, (*to).min(*from + shadow.left(*from))));
} }
found.push((shadow.clone(), *from, (*to).min(*from + shadow.left(*from))));
} }
*unwatched = next_unwatched;
drop(kept); drop(kept);
#[cfg(feature = "diagnostics")] #[cfg(feature = "diagnostics")]
let refreshed = std::time::Instant::now(); let refreshed = std::time::Instant::now();
@@ -1310,7 +1422,7 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
tracing::info!( tracing::info!(
slots = slots.len(), slots = slots.len(),
views, views,
copies = spans.len(), copies = copies_len,
mb = bytes >> 20, mb = bytes >> 20,
ms = started.elapsed().as_millis(), ms = started.elapsed().as_millis(),
"buffer views of the heap made ready for shaders that pick them by index" "buffer views of the heap made ready for shaders that pick them by index"
+161 -105
View File
@@ -7362,97 +7362,115 @@ impl HostList {
const COPY_SOURCE: u32 = 0x800; const COPY_SOURCE: u32 = 0x800;
let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32); let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
// The copies (depth texture, twin, whether into the twin); the
// sides are then as this list leaves them.
let mut syncs = Vec::new();
let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner());
for u in twins.values() { // Fast path (~95% of lists): no depth-twin syncs and no prelude
let real = u.twin.behind.load(Ordering::Relaxed); // texture uploads, so avoid allocating sync/aliasing/copying HashMap.
let mut behind = [real & 1 != 0, real & 2 != 0]; let (syncs, to_copy, aliasing, barriers) = if twins.is_empty() && uploads.is_empty() {
for side in [0, 1] { drop(twins);
if u.needs[side] && behind[side] { let mut barriers = Vec::new();
syncs.push((u.depth.clone(), u.twin.clone(), side == 1)); for (_, (first, last, copy)) in states.iter() {
behind = [false; 2]; let real = copy.state.swap(*last, Ordering::Relaxed);
if real != *first {
barriers.push(transition(&copy.texture, host_state(real), host_state(*first)));
} }
} }
let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side])); if barriers.is_empty() {
let left = u32::from(left[0]) | (u32::from(left[1]) << 1); return None;
u.twin.behind.store(left, Ordering::Relaxed); }
} (Vec::new(), Vec::new(), Vec::new(), barriers)
drop(twins); } else {
// A copy runs with its textures in the copy states: each moves // The copies (depth texture, twin, whether into the twin); the
// there from its real state, and from there to the state the list // sides are then as this list leaves them.
// starts with (back to its real state if the list does not use it). let mut syncs = Vec::new();
let mut to_copy = Vec::new(); for u in twins.values() {
let mut barriers = Vec::new(); let real = u.twin.behind.load(Ordering::Relaxed);
let mut copying = std::collections::HashMap::new(); let mut behind = [real & 1 != 0, real & 2 != 0];
for (depth, twin, colour) in &syncs { for side in [0, 1] {
let (from, to) = if *colour { if u.needs[side] && behind[side] {
(depth, &twin.colour) syncs.push((u.depth.clone(), u.twin.clone(), side == 1));
} else { behind = [false; 2];
(&twin.colour, depth) }
}; }
for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] { let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side]));
let key = std::sync::Arc::as_ptr(texture) as usize; let left = u32::from(left[0]) | (u32::from(left[1]) << 1);
let real = texture.state.load(Ordering::Relaxed); u.twin.behind.store(left, Ordering::Relaxed);
copying.insert(key, state); }
if real != state { drop(twins);
to_copy.push(transition( // A copy runs with its textures in the copy states: each moves
&texture.texture, // there from its real state, and from there to the state the list
host_state(real), // starts with (back to its real state if the list does not use it).
host_state(state), let mut to_copy = Vec::new();
)); let mut barriers = Vec::new();
if !states.contains_key(&key) { let mut copying: ByCopy<u32> = ByCopy::default();
barriers.push(transition( for (depth, twin, colour) in &syncs {
let (from, to) = if *colour {
(depth, &twin.colour)
} else {
(&twin.colour, depth)
};
for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] {
let key = std::sync::Arc::as_ptr(texture) as usize;
let real = texture.state.load(Ordering::Relaxed);
copying.insert(key, state);
if real != state {
to_copy.push(transition(
&texture.texture, &texture.texture,
host_state(state),
host_state(real), host_state(real),
host_state(state),
)); ));
if !states.contains_key(&key) {
barriers.push(transition(
&texture.texture,
host_state(state),
host_state(real),
));
}
} }
} }
} }
} // The uploads decided at submission: each host copy to the copy
// The uploads decided at submission: each host copy to the copy // destination state, and from there to the state the list starts
// destination state, and from there to the state the list starts // with (back to its real state if the list does not use it).
// with (back to its real state if the list does not use it). let mut aliasing = Vec::new();
let mut aliasing = Vec::new(); for (upload, first_upload) in uploads {
for (upload, first_upload) in uploads { let copy = &upload.copy;
let copy = &upload.copy; let key = std::sync::Arc::as_ptr(copy) as usize;
let key = std::sync::Arc::as_ptr(copy) as usize; // A texture cut from a block may lie where another did: what the
// A texture cut from a block may lie where another did: what the // card holds of that one is done with before the first upload
// card holds of that one is done with before the first upload // into this one.
// into this one. if crate::pool::on() && *first_upload {
if crate::pool::on() && *first_upload { aliasing.push(D3D12_RESOURCE_BARRIER {
aliasing.push(D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 {
Anonymous: D3D12_RESOURCE_BARRIER_0 { Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { pResourceBefore: std::mem::ManuallyDrop::new(None),
pResourceBefore: std::mem::ManuallyDrop::new(None), // SAFETY: a borrowed pointer the barrier never releases.
// SAFETY: a borrowed pointer the barrier never releases. pResourceAfter: unsafe { std::mem::transmute_copy(&copy.texture) },
pResourceAfter: unsafe { std::mem::transmute_copy(&copy.texture) }, }),
}), },
}, });
});
}
let real = copying.get(&key).copied().unwrap_or_else(|| copy.state.load(Ordering::Relaxed));
if real != COPY_DEST {
to_copy.push(transition(&copy.texture, host_state(real), host_state(COPY_DEST)));
if !states.contains_key(&key) {
barriers.push(transition(&copy.texture, host_state(COPY_DEST), host_state(real)));
} }
let real = copying.get(&key).copied().unwrap_or_else(|| copy.state.load(Ordering::Relaxed));
if real != COPY_DEST {
to_copy.push(transition(&copy.texture, host_state(real), host_state(COPY_DEST)));
if !states.contains_key(&key) {
barriers.push(transition(&copy.texture, host_state(COPY_DEST), host_state(real)));
}
}
copying.insert(key, COPY_DEST);
} }
copying.insert(key, COPY_DEST); barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
} let real = copy.state.swap(*last, Ordering::Relaxed);
barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| { let real = if copying.is_empty() { real } else { copying.get(key).copied().unwrap_or(real) };
let real = copy.state.swap(*last, Ordering::Relaxed); (real != *first)
let real = copying.get(key).copied().unwrap_or(real); .then(|| transition(&copy.texture, host_state(real), host_state(*first)))
(real != *first) }));
.then(|| transition(&copy.texture, host_state(real), host_state(*first))) if barriers.is_empty() && syncs.is_empty() && uploads.is_empty() {
})); return None;
if barriers.is_empty() && syncs.is_empty() && uploads.is_empty() { }
return None; (syncs, to_copy, aliasing, barriers)
} };
let mut held = self.prelude.lock().unwrap_or_else(|e| e.into_inner()); let mut held = self.prelude.lock().unwrap_or_else(|e| e.into_inner());
if held.is_none() { if held.is_none() {
let kept = if prelude_pool() { PRELUDES.lock().unwrap_or_else(|e| e.into_inner()).pop() } else { None }; let kept = if prelude_pool() { PRELUDES.lock().unwrap_or_else(|e| e.into_inner()).pop() } else { None };
@@ -8578,6 +8596,9 @@ struct Batch {
/// [`Batch::refresh_front`]'s walk over the steps. /// [`Batch::refresh_front`]'s walk over the steps.
ranges: Vec<(usize, usize)>, ranges: Vec<(usize, usize)>,
touches: Vec<Touch>, touches: Vec<Touch>,
front_at: ByCopy<usize>,
front_spans_buf: Vec<(usize, usize, usize)>,
front_given: Vec<u32>,
} }
thread_local! { thread_local! {
@@ -8624,12 +8645,15 @@ fn refresh_front() -> bool {
/// What a part refreshes of a copy it has given to its shaders stays where it /// What a part refreshes of a copy it has given to its shaders stays where it
/// stands: around what they write. What a later part refreshes is the /// stands: around what they write. What a later part refreshes is the
/// title's bytes of before either. /// title's bytes of before either.
fn front_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> { fn front_spans_into(
let mut at: ByCopy<usize> = ByCopy::default(); steps: impl Iterator<Item = Touch>,
// (Copy, from, to), in the order they come, and the part that gave it to at: &mut ByCopy<usize>,
// shaders last. spans: &mut Vec<(usize, usize, usize)>,
let mut spans: Vec<(usize, usize, usize)> = Vec::new(); given: &mut Vec<u32>,
let mut given: Vec<u32> = Vec::new(); ) {
at.clear();
spans.clear();
given.clear();
let (mut part, mut last) = (1, usize::MAX); let (mut part, mut last) = (1, usize::MAX);
for step in steps { for step in steps {
match step { match step {
@@ -8663,6 +8687,12 @@ fn front_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)>
} }
} }
spans.retain(|s| s.1 < s.2); spans.retain(|s| s.1 < s.2);
}
#[cfg(test)]
fn front_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> {
let (mut at, mut spans, mut given) = (ByCopy::default(), Vec::new(), Vec::new());
front_spans_into(steps, &mut at, &mut spans, &mut given);
spans spans
} }
@@ -8828,6 +8858,9 @@ impl Batch {
self.spans_at.clear(); self.spans_at.clear();
self.ranges.clear(); self.ranges.clear();
self.touches.clear(); self.touches.clear();
self.front_at.clear();
self.front_spans_buf.clear();
self.front_given.clear();
SPARE_BATCH.set(Some(self)); SPARE_BATCH.set(Some(self));
} }
@@ -8983,10 +9016,16 @@ impl Batch {
} }
} }
} }
let found = front_spans(self.touches.drain(..)); front_spans_into(
let spans: Vec<_> = found self.touches.drain(..),
.into_iter() &mut self.front_at,
.filter_map(|(key, from, to)| Some((self.spans.get(*self.spans_at.get(&key)?)?.0.clone(), from, to))) &mut self.front_spans_buf,
&mut self.front_given,
);
let spans: Vec<_> = self
.front_spans_buf
.iter()
.filter_map(|&(key, from, to)| Some((self.spans.get(*self.spans_at.get(&key)?)?.0.clone(), from, to)))
.collect(); .collect();
self.front = true; self.front = true;
for (shadow, from, to) in &spans { for (shadow, from, to) in &spans {
@@ -9013,18 +9052,28 @@ impl Batch {
crate::watch::ask_ahead(&ranges); crate::watch::ask_ahead(&ranges);
} }
FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed); FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed);
crate::shadow::wide_each(spans.len() + due.len(), move |i| { const SPAN_CHUNK: usize = 32;
// The textures first: they are the longer pieces. let span_chunks = spans.len().div_ceil(SPAN_CHUNK);
let Some(i) = i.checked_sub(due.len()) else { let due_len = due.len();
crate::shadow::wide_each(due_len + span_chunks, move |i| {
// The textures first (1 by 1): they are the longer pieces.
let Some(chunk_idx) = i.checked_sub(due_len) else {
due[i].refresh(); due[i].refresh();
return; return;
}; };
let (shadow, from, to) = &spans[i]; let start = chunk_idx * SPAN_CHUNK;
if many && shadow.nothing_new(*from, *to - *from) { let end = (start + SPAN_CHUNK).min(spans.len());
FLUSHES[2].fetch_add(1, Ordering::Relaxed); let mut skipped = 0u64;
return; for (shadow, from, to) in &spans[start..end] {
if many && shadow.nothing_new(*from, *to - *from) {
skipped += 1;
continue;
}
Self::update(shadow, *from, *to);
}
if skipped > 0 {
FLUSHES[2].fetch_add(skipped, Ordering::Relaxed);
} }
Self::update(shadow, *from, *to);
}); });
if ahead { if ahead {
crate::watch::ask_ahead_done(); crate::watch::ask_ahead_done();
@@ -9176,15 +9225,22 @@ impl Batch {
let before = PREPARING[0].load(Ordering::Relaxed); let before = PREPARING[0].load(Ordering::Relaxed);
FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed); FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed);
if light { if light {
// A number to a free thread, not a job to each copy. // Chunked work-stealing avoids per-item atomic contention.
let refreshes = std::mem::take(&mut self.refreshes); let refreshes = std::mem::take(&mut self.refreshes);
crate::shadow::wide_each(refreshes.len(), move |i| { let many = refreshes.len() > FEW;
let (shadow, from, to) = &refreshes[i]; let chunk = if many { 32 } else { 1 };
if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) { crate::shadow::wide_each_chunked(refreshes.len(), chunk, move |range| {
FLUSHES[2].fetch_add(1, Ordering::Relaxed); let mut skipped = 0u64;
return; for (shadow, from, to) in &refreshes[range] {
if many && shadow.nothing_new(*from, *to - *from) {
skipped += 1;
continue;
}
Self::update(shadow, *from, *to);
}
if skipped > 0 {
FLUSHES[2].fetch_add(skipped, Ordering::Relaxed);
} }
Self::update(shadow, *from, *to);
}); });
} else { } else {
let jobs: Vec<Box<dyn FnOnce() + Send>> = self let jobs: Vec<Box<dyn FnOnce() + Send>> = self
+34
View File
@@ -1843,6 +1843,40 @@ pub(crate) fn wide_each(n: usize, work: impl Fn(usize) + Send + Sync + 'static)
wide(jobs); wide(jobs);
} }
/// As [`wide_each`], but hands out contiguous slices of up to `chunk` indices
/// per atomic claim to eliminate cross-core cache-line bouncing on thousands
/// of lightweight items (e.g. unchanged copy checks).
pub(crate) fn wide_each_chunked(
n: usize,
chunk: usize,
work: impl Fn(std::ops::Range<usize>) + Send + Sync + 'static,
) {
let chunk = chunk.max(1);
let chunks = n.div_ceil(chunk);
if chunks == 0 {
return;
}
let next = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let work = Arc::new(work);
let threads = (wide_threads() + 1).min(chunks);
let jobs = (0..threads)
.map(|_| {
let (next, work) = (next.clone(), work.clone());
Box::new(move || {
loop {
let c = next.fetch_add(1, Ordering::Relaxed);
let start = c.saturating_mul(chunk);
if start >= n {
break;
}
work(start..(start + chunk).min(n));
}
}) as Job
})
.collect();
wide(jobs);
}
/// About this many bytes to a piece of work for [`wide`]. /// About this many bytes to a piece of work for [`wide`].
const WIDE_JOB: usize = 1 << 20; const WIDE_JOB: usize = 1 << 20;