diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 53e0a6656..57b51c975 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -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 diff --git a/crates/metal2vulkan-rt/src/buffer.rs b/crates/metal2vulkan-rt/src/buffer.rs index 548c86688..a44dce247 100644 --- a/crates/metal2vulkan-rt/src/buffer.rs +++ b/crates/metal2vulkan-rt/src/buffer.rs @@ -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 => { diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 027a650c8..79e779524 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -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 diff --git a/crates/metal2vulkan-rt/src/memory.rs b/crates/metal2vulkan-rt/src/memory.rs index a3e7b2a7f..a3ee4a886 100644 --- a/crates/metal2vulkan-rt/src/memory.rs +++ b/crates/metal2vulkan-rt/src/memory.rs @@ -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, } +/// 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) { 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(); diff --git a/crates/metal2vulkan-rt/src/tests/memory.rs b/crates/metal2vulkan-rt/src/tests/memory.rs index 21c06d113..7a8f751e8 100644 --- a/crates/metal2vulkan-rt/src/tests/memory.rs +++ b/crates/metal2vulkan-rt/src/tests/memory.rs @@ -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, diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index 4e089b83e..4b9845e16 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -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), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 70de0be1a..98de8f1f8 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -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