rt: the block-maker thread starts no zero step while a consumer memset runs

What: Device::new_buffer's memset of a zeroed Shared buffer's bytes now holds a guard
(Pool::fill). While any guard is held, the block-maker thread starts no zero step of a kept Shared
block. It waits, and the last memset to end wakes it, only where it held a step back: the thread
sets fill_held before it reads the count, and the memset reads fill_held after it leaves the count
(SeqCst on both), and the notify is under the pool's lock. A step that already runs ends first, at
most 256 KiB. Metrics::zero_steps_held counts the steps held back; the replay player prints it.

Why: the harness's create_64MiB row regressed on the 2080, from about 905 us to 1008.6 us (1.147 of
old's 879 us; entry's bisect, m3-max-49153). The harness keeps a second 64 MiB block live, as a
guest does, so the takes alternate:
- one take finds a block the block-maker thread zeroed whole (about 1 us);
- the next finds mark 0, and the consumer memsets all 64 MiB.
That memset took 2.0-2.2 ms against about 910 us alone, because the thread's 256 KiB steps on the
other kept block ran at the same time (about 15 GB/s) and both shared the memory bus. Entry's
controls ruled out the memory type and the write method: with no kept-block zeroing the row was
911 us, and with the steady loop started 600 ms after the warm-up's release it was 906 us.

Test: every_device_holds_its_zero_steps_while_a_consumer_memset_runs. With a fill guard held, a
Shared block written and given back is kept with mark 0, the thread holds its step back (counted),
and no byte is zeroed for 20 ms. Once the guard drops, the block is zeroed to its end. Without the
fix the steps run beside the guard: the held count never rises and the mark moves.

Verified: nothing yet; the check job, the device legs and the 2080's create_64MiB timing follow.
This commit is contained in:
Anees Iqbal committed 2026-11-18 18:41:17 -08:00
1 parent 42811160e2
commit 76c6f5d071
7 files changed
+116 -4

No files matched your search

+3 -1
View File
@@ -165,7 +165,9 @@ in its memory.
threads: each Shared allocation it makes ahead of need, whole, before any take lands in it
(each device's first one in its making), and each Shared block given back and kept, in steps of
256 KiB while it waits for a take of its length. A take waits at most for the step that runs and
answers the bytes zeroed so far, so a mark is any length up to the block's. Nothing else counts:
answers the bytes zeroed so far, so a mark is any length up to the block's. The thread starts no
step while a zeroed buffer's memset runs on the consumer's thread (below), so the two do not
share the memory bus (`Metrics::zero_steps_held` counts the steps held back). Nothing else counts:
not the driver, the memory type or a new allocation. A Private block's mark is 0, as is a block
of an allocation a take makes itself. The consumer writes the bytes inside the mark only
through a buffer it places over them, which lowers the mark to the buffer's offset; a zeroed
+3
View File
@@ -148,12 +148,15 @@ impl Device {
match contents {
Some(contents) => {
let start = from.max(clean);
// No zero step of the block-maker thread runs beside the memset.
let fill = self.core().pool.fill();
// SAFETY: `start..length` lies in the new buffer, whose range is in the block.
unsafe {
(contents.get().as_ptr())
.add(start as usize)
.write_bytes(0, (length - start) as usize)
};
drop(fill);
self.core().counters.zeroed(length - start);
}
None => {
+11
View File
@@ -235,6 +235,7 @@ struct Atomics {
allocation_zeroing_nanos: AtomicU64,
kept_bytes_zeroed: AtomicU64,
kept_zeroing_nanos: AtomicU64,
zero_steps_held: AtomicU64,
zeroed_bytes_taken: AtomicU64,
zeroed_bytes_freed: AtomicU64,
block_zero_fills: AtomicU64,
@@ -493,6 +494,11 @@ impl Counters {
a.allocation_zeroing_nanos.fetch_add(nanos, Relaxed);
}
/// A zero step held back for a consumer memset ([`Metrics::zero_steps_held`]).
pub(crate) fn zero_step_held(&self) {
self.atomics.zero_steps_held.fetch_add(1, Relaxed);
}
/// A step of a kept block zeroed, `bytes` in `nanos` ([`Metrics::kept_bytes_zeroed`]).
pub(crate) fn zeroed_kept(&self, bytes: u64, nanos: u64) {
let a = &self.atomics;
@@ -650,6 +656,7 @@ impl Counters {
allocation_zeroing_nanos: a.allocation_zeroing_nanos.load(Relaxed),
kept_bytes_zeroed: a.kept_bytes_zeroed.load(Relaxed),
kept_zeroing_nanos: a.kept_zeroing_nanos.load(Relaxed),
zero_steps_held: a.zero_steps_held.load(Relaxed),
zeroed_bytes_taken: a.zeroed_bytes_taken.load(Relaxed),
zeroed_bytes_freed: a.zeroed_bytes_freed.load(Relaxed),
block_zero_fills: a.block_zero_fills.load(Relaxed),
@@ -808,6 +815,10 @@ pub struct Metrics {
pub kept_bytes_zeroed: u64,
/// The nanoseconds of [`host_time`](crate::host_time) those steps took, in total.
pub kept_zeroing_nanos: u64,
/// Times the block-maker thread held a zero step back because a memset of Shared bytes ran
/// on the consumer's thread ([`Device::new_buffer`](crate::Device::new_buffer)'s zeroing): it
/// starts the step once the memset ends, so the two do not share the memory bus.
pub zero_steps_held: u64,
/// The zero marks of every take, summed: the bytes the takes found zeroed.
pub zeroed_bytes_taken: u64,
/// Bytes the runtime zeroed that an idle allocation's free gave back before any take found
+44 -3
View File
@@ -15,7 +15,7 @@ use crate::places::Ranges;
use ash::vk;
use std::collections::{HashSet, VecDeque};
use std::ptr::NonNull;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering::Relaxed, Ordering::SeqCst};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
@@ -367,6 +367,12 @@ pub(crate) struct Pool {
granule: u64,
/// Whether the block-maker thread is in an idle allocation's `vkFreeMemory`.
freeing: AtomicBool,
/// The consumer's memsets of Shared bytes that run ([`Pool::fill`]): the block-maker thread
/// starts no zero step while one does, so the two never share the memory bus.
fills: AtomicUsize,
/// The block-maker thread holds a zero step back for a memset that runs: the last memset to
/// end wakes it.
fill_held: AtomicBool,
/// For the device tests: while set, the block-maker thread waits inside each idle
/// allocation's free, with [`freeing`](Self::freeing) set, before it calls `vkFreeMemory`.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -424,6 +430,22 @@ struct State {
zero_budget: Option<u64>,
}
/// A consumer memset of Shared bytes that runs ([`Pool::fill`]).
pub(crate) struct Fill<'a>(&'a Pool);
impl Drop for Fill<'_> {
fn drop(&mut self) {
let pool = self.0;
// The block-maker thread sets `fill_held` before it reads `fills`, and this reads it after
// the memset left `fills`: one of the two sees the other. The notify is under the lock,
// so the thread is either before its read or waiting.
if pool.fills.fetch_sub(1, SeqCst) == 1 && pool.fill_held.load(SeqCst) {
let _state = pool.lock();
pool.changed.notify_all();
}
}
}
thread_local! {
/// Whether this thread makes allocations ahead of need: the block-maker thread ([`run`]), or
/// the device's making while it makes the first allocations ([`stock`]). For the
@@ -472,6 +494,8 @@ impl Pool {
counters,
granule: GRANULE.max(granularity.next_power_of_two()),
freeing: AtomicBool::new(false),
fills: AtomicUsize::new(0),
fill_held: AtomicBool::new(false),
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
hold_frees: Mutex::new(false),
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -848,6 +872,15 @@ impl Pool {
self.changed.notify_all();
}
/// A memset of Shared bytes on the consumer's thread begins
/// ([`Device::new_buffer`](crate::Device::new_buffer)'s zeroing): the block-maker thread
/// starts no zero step until the returned guard drops, so the memset does not share the memory
/// bus with one. A step that runs already ends first: at most [`ZERO_STEP`] bytes.
pub(crate) fn fill(&self) -> Fill<'_> {
self.fills.fetch_add(1, SeqCst);
Fill(self)
}
/// Stops the block-maker thread once it finishes what it is doing.
pub(crate) fn stop(&self) {
self.lock().stop = true;
@@ -1180,8 +1213,16 @@ pub(crate) fn run(core: Arc<Core>) {
continue;
}
// Last, the kept Shared blocks' bytes, the newest block first, a step at a time from its
// first byte, off the lock; none while a take waits for a step.
if let Some((id, at, len)) = state.zero_step() {
// first byte, off the lock; none while a take waits for a step, and none while a consumer
// memset runs ([`Pool::fill`]): the step waits for the memset's end.
let step = state.zero_step();
pool.fill_held.store(step.is_some(), SeqCst);
let held = step.is_some() && pool.fills.load(SeqCst) > 0;
if held {
core.counters.zero_step_held();
}
if let Some((id, at, len)) = step.filter(|_| !held) {
pool.fill_held.store(false, Relaxed);
state.zeroing = Some(id);
drop(state);
let start = crate::host_time();
@@ -1934,6 +1934,59 @@ mod on_device {
}
}
/// The block-maker thread starts no zero step while a memset of Shared bytes runs on the
/// consumer's thread, so the two never share the memory bus: with a memset held open
/// ([`Pool::fill`](crate::memory::Pool::fill)), a Shared block written and given back is kept
/// with its mark at 0, the thread holds its step back (counted) and zeroes nothing; once the
/// memset ends, the thread zeroes the block to its end.
#[test]
fn every_device_holds_its_zero_steps_while_a_consumer_memset_runs() {
const LEN: u64 = 4 << 20;
let instance = crate::tests::validation::instance(&[]);
let devices = devices_of_the_cfgs_kind(&instance);
assert!(!devices.is_empty(), "no device of this cfg's kind");
for (name, physical) in &devices {
let device = Device::new(physical, DeviceOptions::default())
.unwrap_or_else(|error| panic!("{name}: {error}"));
let core = device.core();
let counters = device.counters();
let block = (device.take_block(MemoryClass::Shared, LEN))
.unwrap_or_else(|error| panic!("{name}: a Shared block: {error}"));
let id = block.id;
bytes(&block).fill(0xCD);
let before = counters.metrics();
let fill = core.pool.fill();
device.release_block(block).expect("a release");
wait_until("the step held back", || {
counters.metrics().zero_steps_held > before.zero_steps_held
});
thread::sleep(Duration::from_millis(20));
assert_eq!(
(
core.pool.kept_zeroed(MemoryClass::Shared),
counters.metrics().kept_bytes_zeroed - before.kept_bytes_zeroed
),
(vec![(id, 0)], 0),
"{name}: no step beside the memset"
);
drop(fill);
wait_until("the block zeroed to its end", || {
core.pool.kept_zeroed(MemoryClass::Shared) == [(id, LEN)]
});
assert_eq!(
counters.metrics().kept_bytes_zeroed - before.kept_bytes_zeroed,
LEN,
"{name}: zeroed once the memset ended"
);
println!(
"memory: {name}: zero steps held {} times beside a memset",
counters.metrics().zero_steps_held - before.zero_steps_held
);
drop(device);
wait_until("the teardown", || counters.gauges() == Gauges::default());
}
}
/// The add kernel over `a`, `b` and `out`, committed on `queue` and waited for.
fn add_into(
name: &str,
@@ -2113,6 +2113,7 @@ impl Backend for NewRuntime {
("allocation_zeroing_nanos", metrics.allocation_zeroing_nanos),
("kept_bytes_zeroed", metrics.kept_bytes_zeroed),
("kept_zeroing_nanos", metrics.kept_zeroing_nanos),
("zero_steps_held", metrics.zero_steps_held),
("zeroed_bytes_taken", metrics.zeroed_bytes_taken),
("zeroed_bytes_freed", metrics.zeroed_bytes_freed),
("block_zero_fills", metrics.block_zero_fills),
@@ -2390,6 +2390,7 @@ field metal2vulkan-rt::Metrics.translations_loaded pub translations_loaded: u64
field metal2vulkan-rt::Metrics.untimed_command_buffers pub untimed_command_buffers: u64
field metal2vulkan-rt::Metrics.upload_waits pub upload_waits: u64
field metal2vulkan-rt::Metrics.waits_behind_counter pub waits_behind_counter: u64
field metal2vulkan-rt::Metrics.zero_steps_held pub zero_steps_held: u64
field metal2vulkan-rt::Metrics.zeroed_bytes_freed pub zeroed_bytes_freed: u64
field metal2vulkan-rt::Metrics.zeroed_bytes_taken pub zeroed_bytes_taken: u64
field metal2vulkan-rt::RawDevice.device pub device: &'a ash::Device
Can't render this file because it is too large.