Merge branch 'local/next' into day/faults

This commit is contained in:
local committed 2026-11-25 15:31:33 -06:00
commit b46de36de6
12 files changed
+464 -126

No files matched your search

+10 -1
View File
@@ -39,7 +39,10 @@ fn fast_of(sets: &[(u32, u8)]) -> Vec<u32> {
}
/// `VICTORY_FAST_CORES`: 0: no thread asks; 1: the threads a frame waits for
/// one by one; 2 (the default): the threads they share their work with too.
/// one by one; 2 (the default): the threads they share their work with too;
/// 3: those that work beside the rest as well (lists translated, descriptors
/// made): more threads by then than the fast cores run at a time, while the
/// slow ones stood idle.
fn stage() -> u32 {
static STAGE: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
*STAGE.get_or_init(|| std::env::var("VICTORY_FAST_CORES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2))
@@ -60,6 +63,12 @@ pub(crate) fn keep_helper_on_fast_cores(what: &str) {
ask(what, 2);
}
/// [`keep_on_fast_cores`] for one of many threads whose work is ahead of what
/// a frame waits for.
pub(crate) fn keep_many_on_fast_cores(what: &str) {
ask(what, 3);
}
fn ask(what: &str, from: u32) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets};
if stage() < from {
+32 -3
View File
@@ -304,6 +304,7 @@ pub(crate) fn sync_heaps() {
let (mut views, mut bytes) = (0u64, 0u64);
let mut spent = [0u64; 4];
let since = |at: std::time::Instant| at.elapsed().as_nanos() as u64;
let mut kinds = [0u64; 6];
let mut page_bytes: Vec<u8> = Vec::new();
let mut changed: Vec<u32> = Vec::new();
let mut wait: Vec<u32> = Vec::new();
@@ -325,7 +326,7 @@ pub(crate) fn sync_heaps() {
// since: a shader may pick them by index.
let before = host.copied_before(frame);
let of_tables = std::sync::atomic::AtomicU64::new(0);
crate::land::each_view(before.len().div_ceil(SYNC_AT_A_TIME), &|n| {
crate::land::each_view(true, before.len().div_ceil(SYNC_AT_A_TIME), &|n| {
for &index in before.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() {
if host.copied_tabled(index, frame) {
of_tables.fetch_add(1, Relaxed);
@@ -337,6 +338,7 @@ pub(crate) fn sync_heaps() {
let of_tables = of_tables.into_inner();
tabled += of_tables;
mirrored += before.len() as u64 - of_tables;
kinds[4] += before.len() as u64 - of_tables;
// Those of the changed pages, made together at the end.
let mut make: Vec<u32> = Vec::new();
let began = std::time::Instant::now();
@@ -401,13 +403,23 @@ pub(crate) fn sync_heaps() {
}
make.push(index);
mirrored += 1;
kinds[if heap.samplers() {
3
} else if word(0) != VIEW_TAG {
0
} else if word(2) >> KIND_SHIFT == 0 {
1
} else {
2
}] += 1;
kinds[5] += u64::from(!heap.samplers() && host.near_tabled(index, frame));
}
}
page += crate::watch::PAGE;
}
}
let began = std::time::Instant::now();
crate::land::each_view(make.len().div_ceil(SYNC_AT_A_TIME), &|n| {
crate::land::each_view(true, make.len().div_ceil(SYNC_AT_A_TIME), &|n| {
for &index in make.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() {
host.mirror(index, start + u64::from(index) * step, false);
}
@@ -426,8 +438,16 @@ pub(crate) fn sync_heaps() {
for (count, n) in SYNC_SPLIT.iter().zip([views, bytes, taking, reading, comparing, making]) {
count.fetch_add(n, Relaxed);
}
for (count, n) in SYNCED_KINDS.iter().zip(kinds) {
count.fetch_add(n, Relaxed);
}
}
/// Of those mirrored, since the last frame line: no view, a view of an object,
/// another, a sampler; waited and no draw came; next to a slot of a table's.
#[cfg(windows)]
static SYNCED_KINDS: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
/// Records [`sync_heaps`] gives a thread at a time.
#[cfg(windows)]
const SYNC_AT_A_TIME: usize = 256;
@@ -462,13 +482,16 @@ 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, 5].map(|i| SYNC_SPLIT[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64);
let kinds = [0, 1, 2, 3, 4, 5].map(|i| SYNCED_KINDS[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames);
if pages == 0 {
return;
}
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 \
draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for); {:.1} of the pages guarded views, {:.1} MB read; {:.2} ms asking, {:.2} reading, {:.2} comparing, {:.2} making",
draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for); of the mirrored \
{:.0} no views, {:.0} of objects, {:.0} others, {:.0} samplers, {:.0} that waited and no draw came, {:.0} near a table's slot; \
{:.1} of the pages guarded views, {:.1} MB read; {:.2} ms asking, {:.2} reading, {:.2} comparing, {:.2} making",
pages as f64 / frames,
looked as f64 / frames,
mirrored as f64 / frames,
@@ -476,6 +499,12 @@ pub(crate) fn sync_line(frames: f64) {
later as f64 / frames,
micros as f64 / 1000.0 / frames,
waited as f64 / 1000.0 / frames,
kinds[0],
kinds[1],
kinds[2],
kinds[3],
kinds[4],
kinds[5],
split[0] / frames,
split[1] / (1 << 20) as f64 / frames,
split[2] / 1e6 / frames,
+89 -17
View File
@@ -13,6 +13,65 @@ use windows::Win32::Graphics::Dxgi::Common::*;
use super::{VIEW_TAG, View, view_at};
use crate::host::host;
/// A set of a heap's slots, a bit for each: no lock (a pass that went through
/// a set of 70,000 under its lock kept everyone who writes slots waiting for
/// 5 ms of a frame, timeline thin-6).
struct Slots(Vec<std::sync::atomic::AtomicU64>);
impl Slots {
fn new(count: usize) -> Self {
let mut bits = Vec::new();
bits.resize_with(count.div_ceil(64), Default::default);
Slots(bits)
}
fn put(&self, slot: u32) {
if let Some(bits) = self.0.get(slot as usize / 64) {
bits.fetch_or(1 << (slot % 64), std::sync::atomic::Ordering::AcqRel);
}
}
/// Whether it was there.
fn remove(&self, slot: u32) -> bool {
use std::sync::atomic::Ordering::{AcqRel, Acquire};
let bit = 1 << (slot % 64);
self.0.get(slot as usize / 64).is_some_and(|bits| {
bits.load(Acquire) & bit != 0 && bits.fetch_and(!bit, AcqRel) & bit != 0
})
}
fn of(n: usize, mut bits: u64, out: &mut Vec<u32>, which: &impl Fn(u32) -> bool) {
while bits != 0 {
let slot = n as u32 * 64 + bits.trailing_zeros();
bits &= bits - 1;
if which(slot) {
out.push(slot);
}
}
}
/// Those that `which` says, in order.
fn all(&self, which: impl Fn(u32) -> bool) -> Vec<u32> {
let mut out = Vec::new();
for (n, bits) in self.0.iter().enumerate() {
Self::of(n, bits.load(std::sync::atomic::Ordering::Acquire), &mut out, &which);
}
out
}
/// All of them, and none is left.
fn take(&self) -> Vec<u32> {
use std::sync::atomic::Ordering::{AcqRel, Acquire};
let mut out = Vec::new();
for (n, bits) in self.0.iter().enumerate() {
if bits.load(Acquire) != 0 {
Self::of(n, bits.swap(0, AcqRel), &mut out, &|_| true);
}
}
out
}
}
/// The record each slot of a heap was last made from, and a lock for every
/// few hundredth of the slots: whoever makes a slot holds its lock, and no
/// other.
@@ -123,10 +182,10 @@ pub(crate) struct HostHeap {
/// (and its memory a host copy) only when something reads it: a draw
/// through a table, or [`HostHeap::buffer_slots`] for shaders that pick
/// buffers from the whole heap.
buffers: Mutex<std::collections::BTreeSet<u32>>,
buffers: Slots,
/// Of those and of the slots that left the set: the ones written since
/// [`HostHeap::buffer_changes`] last took them.
changed: Mutex<std::collections::HashSet<u32>>,
changed: Slots,
/// Title slots holding a view of a texture the title may fill itself (a
/// placed texture, a texture object), with the frame from which they
/// are due: such a texture is uploaded when a draw reads it through a
@@ -1487,8 +1546,8 @@ impl HostHeap {
free: std::sync::atomic::AtomicU32::new(extra),
too_long: std::sync::atomic::AtomicU32::new(u32::MAX),
strides,
buffers: Mutex::default(),
changed: Mutex::default(),
buffers: Slots::new(count as usize),
changed: Slots::new(count as usize),
textures: Mutex::default(),
tabled: (0..if sampler { 0 } else { count })
.map(|_| std::sync::atomic::AtomicU32::new(0))
@@ -2351,22 +2410,19 @@ impl HostHeap {
/// The title slots that hold buffer views.
pub(crate) fn buffer_slots(&self) -> Vec<u32> {
let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
buffers.iter().copied().collect()
self.buffers.all(|_| true)
}
/// Of [`HostHeap::buffer_slots`], those of one of `parts` parts: every
/// slot is in the same part each time.
pub(crate) fn buffer_slots_of(&self, part: u32, parts: u32) -> Vec<u32> {
let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
buffers.iter().copied().filter(|slot| slot % parts == part).collect()
self.buffers.all(|slot| slot % parts == part)
}
/// The title slots whose buffer view was written, or went, since the
/// last call.
pub(crate) fn buffer_changes(&self) -> Vec<u32> {
let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner());
std::mem::take(&mut *changed).into_iter().collect()
self.changed.take()
}
/// Records what title slot `index` now holds for shaders that pick
@@ -2455,18 +2511,14 @@ impl HostHeap {
// dword, either value is one the slot had).
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) };
}
let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
let was = if stride.is_some() {
buffers.insert(index);
self.buffers.put(index);
true
} else {
buffers.remove(&index)
self.buffers.remove(index)
};
if was {
self.changed
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(index);
self.changed.put(index);
}
stale
}
@@ -2889,6 +2941,13 @@ impl HostHeap {
stamp != 0 && now.wrapping_sub(stamp) & !TABLED_READ <= COPIED_FRAMES
}
/// Whether a slot within 64 of `index` is a table's lately (counted for
/// the log: such a slot is likely one of a table not read yet).
pub(crate) fn near_tabled(&self, index: u32, frame: u64) -> bool {
let first = index & !63;
(first..first + 64).any(|i| i < self.count && self.copied_tabled(i, frame))
}
/// New records the title copied into slots `slots` in `frame` wait for
/// the draw that may read them through a table.
pub(crate) fn copied_wait(&self, frame: u64, slots: Vec<u32>) {
@@ -5267,6 +5326,19 @@ mod tests {
assert_eq!(slots(u64::MAX), [2]);
}
#[test]
fn a_set_of_slots_holds_what_was_put_in() {
let set = Slots::new(200);
for slot in [199, 0, 64, 63, 130, 64] {
set.put(slot);
}
assert_eq!(set.all(|_| true), [0, 63, 64, 130, 199]);
assert_eq!(set.all(|slot| slot % 2 == 0), [0, 64, 130]);
assert!(set.remove(64) && !set.remove(64) && !set.remove(5));
assert_eq!(set.take(), [0, 63, 130, 199]);
assert!(set.take().is_empty());
}
/// A slot a draw read through a table leaves the queue; the title's
/// next write of it waits for its draw, and is due after the grace
/// frames if none reads it.
+1 -1
View File
@@ -806,7 +806,7 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
const AT_A_TIME: usize = 256;
let parts: Vec<&[u32]> = slots.chunks(AT_A_TIME).collect();
let found: Vec<std::sync::OnceLock<Vec<_>>> = parts.iter().map(|_| Default::default()).collect();
crate::land::each_view(parts.len(), &|n| {
crate::land::each_view(false, parts.len(), &|n| {
let looked: Vec<_> = parts[n].iter().map(|&index| (index, look(index))).collect();
// (After each piece while the device lives: a cheap query.)
if alive
+22 -4
View File
@@ -186,6 +186,9 @@ pub(super) struct Own {
copies: Vec<Copy>,
}
/// Runs whose pairs are one piece of work.
const RUNS_AT_A_TIME: usize = 4096;
/// Takes what `dirty` sends up out of the CPU sides.
pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)]) -> Option<Own> {
let began = std::time::Instant::now();
@@ -210,15 +213,29 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us
}
let memory = memory(host, at)?;
let mut moves: Vec<(usize, usize, usize)> = Vec::new();
let mut work: Vec<(usize, &[(usize, usize)], usize)> = Vec::new();
for ((shadow, ranges), copy) in dirty.iter().zip(&copies) {
let from = shadow.card_data() as usize;
moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n)));
let mut to = (memory.data + copy.pairs.0 as usize) as *mut [u32; 2];
// (80,000 runs of some words a frame: in pieces of work.)
let mut to = memory.data + copy.pairs.0 as usize;
for ranges in ranges.chunks(RUNS_AT_A_TIME) {
let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum();
if words > 0 {
work.push((from, ranges, to));
to += words * 8;
}
}
}
let one = |i: usize| {
let (from, ranges, to) = work[i];
let mut to = to as *mut [u32; 2];
for &(a, b) in ranges.iter().filter(|r| short(r)) {
for offset in (a..b).step_by(4) {
// SAFETY: inside the copy's mapping (its CPU side, which
// this thread alone writes in these ranges) and inside the
// memory, which has room for every pair.
// the thread that asked, and waits, alone writes in these
// ranges) and inside the memory, which has room for every
// pair, a piece of work's behind the last one's.
unsafe {
let word = ((from + offset) as *const u32).read_unaligned();
to.write([offset as u32, word]);
@@ -226,7 +243,8 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us
}
}
}
}
};
crate::land::each_under(work.len(), &one);
STATS[0].fetch_add(moves.iter().map(|m| m.2 as u64).sum(), Ordering::Relaxed);
STATS[1].fetch_add(moves.len() as u64, Ordering::Relaxed);
STATS[2].fetch_add(copies.iter().map(|c| u64::from(c.pairs.1)).sum(), Ordering::Relaxed);
+7 -1
View File
@@ -24,9 +24,15 @@ static MOVED: Mutex<Option<HashMap<(u64, u64), Moved>>> = Mutex::new(None);
pub(super) fn moved(way: usize, span: (u64, u64), ranges: impl Iterator<Item = (usize, usize)>) {
let mut all = MOVED.lock().unwrap_or_else(|e| e.into_inner());
let m = all.get_or_insert_with(Default::default).entry(span).or_default();
// (Thousands of runs lie in one piece, one after the other.)
let mut last = u32::MAX;
for (from, to) in ranges.filter(|r| r.0 < r.1) {
m.bytes[way] += (to - from) as u64;
m.pieces[way].extend((from >> 16) as u32..=((to - 1) >> 16) as u32);
let (first, end) = ((from >> 16) as u32, ((to - 1) >> 16) as u32);
if (first, end) != (last, last) {
m.pieces[way].extend(first..=end);
}
last = end;
}
}
+25 -7
View File
@@ -238,7 +238,11 @@ impl Pool {
for i in 1..threads {
// (A helper that is not there is only missed.)
let _ = std::thread::Builder::new().name(format!("{name}-{i}")).spawn(move || {
crate::cores::keep_helper_on_fast_cores(name);
if name == "victory-land" {
crate::cores::keep_helper_on_fast_cores(name);
} else {
crate::cores::keep_many_on_fast_cores(name);
}
pool.help()
});
}
@@ -324,18 +328,32 @@ pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) {
POOL.get_or_init(|| Pool::new("victory-land", threads())).each(count, f);
}
/// Calls `f` with every number below `count`, on this thread and on threads
/// kept for making descriptors (`VICTORY_VIEW_THREADS`, 5 with this one; 1:
/// on this one alone).
pub(crate) fn each_view(count: usize, f: &(dyn Fn(usize) + Sync)) {
/// [`Pool::each`] on threads kept for the title's bytes under flights' writes
/// (`VICTORY_UNDER_THREADS`, 6 with this one).
pub(crate) fn each_under(count: usize, f: &(dyn Fn(usize) + Sync)) {
static POOL: OnceLock<&'static Pool> = OnceLock::new();
POOL.get_or_init(|| {
let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(5usize);
Pool::new("victory-views", threads.clamp(1, 16))
let threads = std::env::var("VICTORY_UNDER_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(6usize);
Pool::new("victory-under", threads.clamp(1, 16))
})
.each(count, f);
}
/// Calls `f` with every number below `count`, on this thread and on threads
/// kept for making descriptors (`VICTORY_VIEW_THREADS`, 4 with this one; 1:
/// on this one alone). Those for `records`, the heaps' records copied as
/// bytes, are others than those for the views picked by index: submissions
/// wait for the first, lists for the second, and each kept the other waiting.
pub(crate) fn each_view(records: bool, count: usize, f: &(dyn Fn(usize) + Sync)) {
static POOLS: [OnceLock<&'static Pool>; 2] = [const { OnceLock::new() }; 2];
POOLS[usize::from(records)]
.get_or_init(|| {
let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4usize);
Pool::new(if records { "victory-records" } else { "victory-views" }, threads.clamp(1, 16))
})
.each(count, f);
}
/// A piece to land: the copy's number, the title address, its bytes.
pub(crate) type Piece = (u64, usize, usize);
+1 -1
View File
@@ -303,7 +303,7 @@ fn start() {
let threads = std::env::var("VICTORY_THIN_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8usize).clamp(1, 32);
for i in 0..threads {
let worker = move || {
crate::cores::keep_helper_on_fast_cores("victory-list");
crate::cores::keep_many_on_fast_cores("victory-list");
crate::queue::no_drain_here();
loop {
let recording = {
+9 -3
View File
@@ -797,8 +797,14 @@ impl Memory {
const SIZES: usize = usize::MAX - (9 << 33);
/// Whether a submission that asks for the sizes of structures is waited for,
/// and landed, before the title goes on (`VICTORY_BVH_SIZES_WAIT=0`: it is
/// not).
/// and landed, before the title goes on (`VICTORY_BVH_SIZES_WAIT=1`; off).
///
/// Off: it does not help. In run light-15, with it, 33 of 154 copies had the
/// slot's old size still (all of them recorded one frame after the size was
/// asked for) against 53 of 230 in light-11, 48 of 275 dynamic structures
/// were good, and the title asks in every frame, so every frame waits (109 ms
/// against 90). The title reads the slot before our submission of the asking
/// list is through, or reads it for another purpose; not known.
///
/// The title asks for a new structure's compacted size (a program of one
/// thread stores it into a small buffer), reads it a frame or two later
@@ -810,7 +816,7 @@ const SIZES: usize = usize::MAX - (9 << 33);
/// the right size.
fn sizes_wait() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_SIZES_WAIT").is_none_or(|v| v != "0"))
*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_SIZES_WAIT").is_some_and(|v| v == "1"))
}
/// Whether a dispatch of the builder is its program of a structure's size:
+1 -5
View File
@@ -788,11 +788,7 @@ impl Player {
let m = moves.entry(format!("{seen:?}")).or_insert((0u32, 0u64));
*m = (m.0 + 1, m.1 + r.desc.width);
}
let mut desc = gpu::to_desc(&r.desc);
// (Heaps are made without what let others open them.)
if matches!(r.place, Place::Placed { .. }) {
desc.Flags &= !D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER;
}
let desc = gpu::to_desc(&r.desc);
let mut made: Option<ID3D12Resource> = None;
let clear: Option<D3D12_CLEAR_VALUE> = r.clear.map(|c| {
// SAFETY: 20 bytes that were a clear value.
+250 -74
View File
@@ -742,7 +742,7 @@ fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
/// so a piece that held several ranges was hashed once for each.
pub(crate) fn joined_piece_runs(mut runs: Vec<CardSpan>) -> Vec<CardSpan> {
runs.sort_unstable_by_key(|r| r.first);
let mut out: Vec<CardSpan> = Vec::with_capacity(runs.len());
let mut out: Vec<CardSpan> = Vec::new();
for run in runs {
match out.last_mut() {
Some(last) if run.first <= last.first + last.pieces => {
@@ -1444,6 +1444,25 @@ type Job = Box<dyn FnOnce() + Send>;
struct Workers {
jobs: Mutex<std::collections::VecDeque<Job>>,
more: std::sync::Condvar,
/// How many jobs there are, for [`spin`].
there: std::sync::atomic::AtomicUsize,
}
/// Waits awake until `there` says so, `VICTORY_WIDE_SPIN` microseconds at
/// most (0, the default: not at all): asleep, a thread is woken in 50 us and
/// more, 95 times a frame.
fn spin(there: impl Fn() -> bool) {
static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let most = *MOST.get_or_init(|| std::env::var("VICTORY_WIDE_SPIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0));
if most == 0 {
return;
}
let began = std::time::Instant::now();
while !there() && (began.elapsed().as_micros() as u64) < most {
for _ in 0..16 {
std::hint::spin_loop();
}
}
}
/// How many threads are kept for [`wide`].
@@ -1457,6 +1476,7 @@ fn workers() -> &'static Workers {
let workers = WORKERS.get_or_init(|| Workers {
jobs: Mutex::new(std::collections::VecDeque::new()),
more: std::sync::Condvar::new(),
there: std::sync::atomic::AtomicUsize::new(0),
});
STARTED.call_once(|| {
for i in 0..wide_threads() {
@@ -1465,9 +1485,13 @@ fn workers() -> &'static Workers {
let workers = WORKERS.get().expect("made above");
loop {
let job = {
// A little while awake first: the next work comes
// within microseconds more often than not.
spin(|| workers.there.load(Ordering::Acquire) > 0);
let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(job) = jobs.pop_front() {
workers.there.fetch_sub(1, Ordering::AcqRel);
break job;
}
jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner());
@@ -1498,6 +1522,7 @@ fn wide(jobs: Vec<Job>) {
let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
for job in jobs {
let left = left.clone();
workers.there.fetch_add(1, Ordering::AcqRel);
queue.push_back(Box::new(move || {
job();
let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner());
@@ -1512,10 +1537,14 @@ fn wide(jobs: Vec<Job>) {
loop {
let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front();
match job {
Some(job) => job(),
Some(job) => {
workers.there.fetch_sub(1, Ordering::AcqRel);
job()
}
None => break,
}
}
spin(|| left.0.try_lock().is_ok_and(|n| *n == 0));
let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner());
while *n > 0 {
n = left.1.wait(n).unwrap_or_else(|e| e.into_inner());
@@ -2059,6 +2088,68 @@ fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize,
runs
}
/// [`dword_runs`] with no gap, the fast way where it can be: a frame compares
/// 12 MB this way and finds 80,000 runs.
fn word_runs(at: usize, title: &[u8], held: &[u8]) -> Vec<(usize, usize)> {
#[cfg(target_arch = "x86_64")]
if at % 4 == 0 && title.len() % 4 == 0 && title.len() == held.len() && std::arch::is_x86_feature_detected!("avx2") {
// SAFETY: the processor has AVX2, and the lengths are the same.
return unsafe { word_runs_avx2(title, held) };
}
dword_runs(at, title, held, 0)
}
/// # Safety
/// AVX2, and two slices of one length, whole words.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn word_runs_avx2(title: &[u8], held: &[u8]) -> Vec<(usize, usize)> {
use std::arch::x86_64::*;
let mut runs: Vec<(usize, usize)> = Vec::new();
let mut push = |from: usize, len: usize| match runs.last_mut() {
Some((a, n)) if *a + *n == from => *n += len,
_ => runs.push((from, len)),
};
let n = title.len();
let mut i = 0;
while i + 256 <= n {
let mut differ = 0u64;
for k in 0..8 {
// SAFETY: inside both slices (`i + 256 <= n`).
let same = unsafe {
_mm256_cmpeq_epi32(
_mm256_loadu_si256(title.as_ptr().add(i + 32 * k).cast()),
_mm256_loadu_si256(held.as_ptr().add(i + 32 * k).cast()),
)
};
differ |= u64::from(!_mm256_movemask_ps(_mm256_castsi256_ps(same)) as u8) << (8 * k);
}
while differ != 0 {
let first = differ.trailing_zeros();
let count = (differ >> first).trailing_ones();
push(i + 4 * first as usize, 4 * count as usize);
if first + count >= 64 {
break;
}
differ &= u64::MAX << (first + count);
}
i += 256;
}
while i + 4 <= n {
if title[i..i + 4] != held[i..i + 4] {
push(i, 4);
}
i += 4;
}
runs
}
/// Whether the pages of [`Shadow::merge_under_writes`] are compared on several
/// threads (`VICTORY_UNDER_WIDE=0`: on the submitting one).
fn under_wide() -> bool {
crate::toggled!("VICTORY_UNDER_WIDE")
}
/// What shaders wrote goes into title memory from `at` on: `title` is what
/// was read there, `merged` the same with their bytes put in. Only the
/// dwords that differ are written. The whole stretch from the first changed
@@ -2140,7 +2231,7 @@ pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, ti
#[cfg(test)]
mod merge_tests {
use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed};
use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed, word_runs};
/// A piece put back takes the GPU's bytes where the copy changed and
/// the title's everywhere else, reads and writes title memory only from
@@ -2311,6 +2402,31 @@ mod merge_tests {
println!("64 KiB that are the same: {:.1} us by eights, {:.1} us now", best(&eights), best(&runs));
}
#[test]
fn word_runs_are_the_dword_runs() {
let mut seed = 7u32;
let mut random = move || {
seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
seed >> 8
};
for round in 0..200 {
let n = 4 * (random() as usize % 400);
let was: Vec<u8> = (0..n).map(|_| random() as u8).collect();
let mut now = was.clone();
for _ in 0..random() % 200 {
if n == 0 {
break;
}
let at = random() as usize % n;
let len = (random() as usize % 24).min(n - at);
for b in &mut now[at..at + len] {
*b = random() as u8;
}
}
assert_eq!(word_runs(0x1000, &now, &was), dword_runs(0x1000, &now, &was, 0), "round {round}");
}
}
#[test]
fn changed_runs_are_exactly_the_bytes_that_differ() {
let was: Vec<u8> = (0..300u32).map(|i| (i * 13 + 5) as u8).collect();
@@ -3377,7 +3493,6 @@ impl Shadow {
// copy in the PC's memory in the snapshot.
let busy = if crate::watch::light() { joined(busy) } else { busy };
let base = start / PAGE;
let mut title = vec![0u8; PAGE];
for (a, e) in busy {
// As the refresh itself asks (`update_free`): the journal if
// the submission's asking covered the range, else the kernel,
@@ -3393,89 +3508,150 @@ impl Shadow {
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
stale_pages_in(base, &copied, a, e, &written)
};
for page in stale {
let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e));
if lo >= hi {
if stale.is_empty() {
continue;
}
// The lock of the copy's reference (the snapshot, or the
// CPU's side of a copy in the card's memory), from before
// title memory is read until the title's bytes are in: with
// the copy-back on its own thread ([`relay`]) that thread
// puts what the card wrote into title memory and into the
// reference under the same lock, and a page read before
// such a merge and compared after it would take the card's
// bytes for the title's.
let merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
let held = if self.card.is_some() {
self.data as usize
} else {
before.as_mut().map_or(0, |snapshot| snapshot.as_mut_ptr() as usize)
};
if held == 0 {
note_stale(3);
return true;
}
// A page's part in the range, compared and put in: the runs it
// changed; none for a page that is not there (left as it is, and
// looked at again next time) or that had too many.
type Done = Option<Vec<(usize, usize)>>;
let left = std::sync::atomic::AtomicI64::new(*runs_left as i64);
let over = std::sync::atomic::AtomicBool::new(false);
let done: Vec<Mutex<Done>> = stale.iter().map(|_| Mutex::new(None)).collect();
let page_of = |i: usize| -> (usize, usize) { ((stale[i] * PAGE).max(a), ((stale[i] + 1) * PAGE).min(e)) };
let one = |i: usize| {
let (lo, hi) = page_of(i);
if lo < hi && !over.load(Ordering::Relaxed) {
// SAFETY: the reference holds the copy's bytes at the
// copy's offsets, and these are in a declared range; the
// locks held above keep out what else writes them, and
// no two pages are the same.
let runs = unsafe { self.merge_page_under_writes(lo, hi - lo, held as *mut u8, &left) };
match runs {
Ok(runs) => *done[i].lock().unwrap_or_else(|e| e.into_inner()) = runs,
Err(()) => over.store(true, Ordering::Relaxed),
}
}
};
// (Not on the threads of `wide`: the thread that waits there
// takes whatever work comes, and a landing's takes the lock.)
if stale.len() > 2 && under_wide() {
crate::land::each_under(stale.len(), &one);
} else {
(0..stale.len()).for_each(one);
}
*runs_left = left.into_inner().max(0) as usize;
let mut taken = Vec::new();
for (i, runs) in done.into_iter().enumerate() {
let Some(runs) = runs.into_inner().unwrap_or_else(|e| e.into_inner()) else {
continue;
}
let n = hi - lo;
let title = &mut title[..n];
// The lock of the copy's reference (the snapshot, or the
// CPU's side of a copy in the card's memory), from before
// title memory is read until the title's bytes are in: with
// the copy-back on its own thread ([`relay`]) that thread
// puts what the card wrote into title memory and into the
// reference under the same lock, and a page read before
// such a merge and compared after it would take the card's
// bytes for the title's.
let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
// A page that is not there is left as it is, and looked at
// again next time.
if !crate::host::read_into(lo as *const u8, title) {
continue;
}
MERGED[0].fetch_add(1, Ordering::Relaxed);
let at = lo - start;
if self.card.is_some() {
// SAFETY: inside the mapping of the copy's CPU side,
// which only the submitting thread writes.
let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
// Whole words go up as pairs, all of them in one
// dispatch: only what is a copy of its own counts.
let runs = if crate::host::words_under() { dword_runs(lo, title, held, 0) } else { changed_runs(title, held) };
let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m);
let copies = runs.iter().filter(own).count();
if copies > *runs_left {
note_stale(2);
return true;
}
*runs_left -= copies;
let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec());
for &(r, m) in &runs {
held[r..r + m].copy_from_slice(&title[r..r + m]);
MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
}
MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m)));
if let Some(was) = was {
crate::host::upcheck::note(self.id, at, &was, held);
}
} else {
let Some(snapshot) = before.as_mut() else {
note_stale(3);
return true;
};
// SAFETY: the snapshot's allocation holds the copy's
// bytes at the copy's offsets (`writing`), and these
// are in a declared range.
let held = unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) };
for (r, m) in changed_runs(title, held) {
// SAFETY: inside the copy's mapping. The card may be
// writing the copy beside these bytes; they are
// written here and nothing around them.
unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) };
held[r..r + m].copy_from_slice(&title[r..r + m]);
MERGED[1].fetch_add(1, Ordering::Relaxed);
MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
}
}
drop(before);
drop(_merging);
};
let (lo, hi) = ((stale[i] * PAGE).max(a), ((stale[i] + 1) * PAGE).min(e));
MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
MERGED[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed);
self.card_changed_runs(runs.into_iter().map(|(r, m)| (lo - start + r, lo - start + r + m)));
// Taken, if the range holds all of the page that is in the
// copy; else the rest of it is the refresh's, which notes
// only whole pages, and the page is looked at again.
if (page * PAGE).max(start) >= a && ((page + 1) * PAGE).min(end) <= e {
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
if lo < hi && (stale[i] * PAGE).max(start) >= a && ((stale[i] + 1) * PAGE).min(end) <= e {
taken.push(stale[i]);
}
}
drop(before);
drop(merging);
{
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
for page in taken {
if let Some(at) = copied.get_mut(page - base) {
*at = now;
}
}
}
if over.into_inner() {
note_stale(2);
return true;
}
}
false
}
/// Of [`Shadow::merge_under_writes`]: title memory `[lo, lo + n)`, in one
/// page, compared with the reference, which begins at `held`, and put in.
/// The runs that changed, none if it cannot be read, and an error if
/// there were more to copy one by one than `left`.
///
/// # Safety
/// The reference holds the copy's length, and nothing else writes these
/// bytes of it during the call.
unsafe fn merge_page_under_writes(
&self,
lo: usize,
n: usize,
held: *mut u8,
left: &std::sync::atomic::AtomicI64,
) -> Result<Option<Vec<(usize, usize)>>, ()> {
thread_local! {
static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
TITLE.with_borrow_mut(|title| {
title.resize(PAGE, 0);
let title = &mut title[..n];
if !crate::host::read_into(lo as *const u8, title) {
return Ok(None);
}
MERGED[0].fetch_add(1, Ordering::Relaxed);
let at = lo - self.start as usize;
// SAFETY: the caller's.
let held = unsafe { std::slice::from_raw_parts_mut(held.add(at), n) };
if self.card.is_some() {
// Whole words go up as pairs, all of them in one
// dispatch: only what is a copy of its own counts.
let runs = if crate::host::words_under() { word_runs(lo, title, held) } else { changed_runs(title, held) };
let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m);
let copies = runs.iter().filter(own).count() as i64;
if copies > 0 && left.fetch_sub(copies, Ordering::Relaxed) < copies {
return Err(());
}
let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec());
for &(r, m) in &runs {
held[r..r + m].copy_from_slice(&title[r..r + m]);
}
if let Some(was) = was {
crate::host::upcheck::note(self.id, at, &was, held);
}
return Ok(Some(runs));
}
let runs = changed_runs(title, held);
for &(r, m) in &runs {
// SAFETY: inside the copy's mapping. The card may be
// writing the copy beside these bytes; they are
// written here and nothing around them.
unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) };
held[r..r + m].copy_from_slice(&title[r..r + m]);
}
Ok(Some(runs))
})
}
/// At submission: copies what changed of `[address, address + len)`
/// since it was last copied (all of it if the memory is not
/// write-watched). Returns the bytes copied.