rt: the block-maker thread waits out the submits inside the driver after each memory call

What: after each of its vkAllocateMemory and vkFreeMemory calls, the block-maker thread
(memory::run, and each class's first unit in the device's making) waits until every
vkQueueSubmit2 call of rt's that was inside the driver as its call returned has returned;
with none inside it goes straight on. Every device, no query, no switch. Takes that allocate
on a consumer's thread make their one call with no wait. Unit lengths unchanged.

How: a new SubmitCalls (submit_calls.rs) counts each vkQueueSubmit2 in just before the call
and out as its guard drops after it, under a mutex held for an add; it wakes a waiter only
while one waits, so the submit thread never waits on the maker. The maker reads the count in
at its call's return and blocks on a condvar until that many returned. The thread-local that
marked the maker thread (ON_MAKER) now holds the device's SubmitCalls; memory::allocate and a
new memory::free (every free the maker makes: idle and own frees, and its make-failure and
race frees in fill, ring and staging) call passed() after the driver call. The
submissions-during-frees flag moved from the pool into SubmitCalls and now covers the
vkFreeMemory call alone, so the wait after a free is not counted as part of it (it also
covers every maker free, not only idle ones; the metric's doc says so). New metrics
maker_memory_calls, maker_yields, maker_yield_nanos (api_signatures blessed; the replay
player prints them). README: the NVIDIA hold known gap says what rt does now and what remains
(a single call still holds a submit for its own length).

Why: NVIDIA 620.70.06 holds a submit while another thread is inside vkAllocateMemory or
vkFreeMemory, and holds it through calls made back to back (rtsweep's standalone program on
the RTX 3090: giving back 1 GiB in 64 MiB frees back to back held the worst submit 216 ms,
with this wait 72 ms, 0.90-0.96 of the longest single call; on a quiet queue it adds no
wait). The planner ruled this form (a1).

Verified: see the lane's check jobs (GPU-free ordering tests in tests::maker_yield, the
device test on lavapipe and the RTX 3090, clippy plain and --cfg m2v_gpu, rustdoc).
This commit is contained in:
Anees Iqbal committed 2026-11-20 03:23:04 -08:00
1 parent 07710bf5ca
commit ef875741cc
15 files changed
+531 -76

No files matched your search

+19 -7
View File
@@ -869,15 +869,27 @@ planes' first use, so `Surface::wait_until_ready()` returns at once.
about 1.1 ms per MiB and holds any submit of the same process for its length; on an internal
NVIDIA card the same free takes about 0.5 ms per 16 MiB. rt frees one idle allocation at a time,
at its idle age, whatever the queues are doing. `Metrics::allocations_freed` counts the frees,
and `Metrics::submissions_during_frees` the submits made while one was in progress.
and `Metrics::submissions_during_frees` the submits made while one of the block-maker thread's
frees was in progress.
- NVIDIA's Linux driver holds a submit made while another thread is inside `vkAllocateMemory` or
`vkFreeMemory` until that call returns, device-local memory included, and calls made back to
back hold it through all of them. In a 336-second guest walk on an RTX 3090 (driver
620.70.06, rt at 7096fa7de3), every submit of 5 ms or more overlapped such calls on other
threads for 97 to 100% of its length: a 64 MiB Shared allocation made inside a take held one
submit for 14.2 ms; frees of imported blocks, 0.4 to 2.9 ms each and 52 in one second, held four
submits for 5.2 to 6.9 ms; and the pool's trim after the workload, five 64 MiB frees of 7.7 to
13.9 ms made back to back, held one submit for 48.7 ms. A take that leaves its class no wholly
back hold it through all of them. So after each of its allocations and frees the block-maker
thread waits until every `vkQueueSubmit2` call of rt's that was inside the driver as its call
returned has returned, and with none inside it goes straight on: a submit waits out at most one
of its calls, the one it met. `Metrics::maker_memory_calls` counts those calls,
`maker_yields` the ones after which it waited, and `maker_yield_nanos` the time. A single call
still holds a submit for its own length, and a take that allocates on the consumer's thread
makes its one call with no wait. In a standalone program on an RTX 3090 (driver 620.70.06),
giving back 1 GiB of Shared memory in 64 MiB frees made back to back held the worst submit for
216 ms, and with this wait after each free for 72 ms; from 2 to 64 MiB units the worst hold
with the wait was 0.90 to 0.96 times the longest single free, and with no submit made the wait
added nothing. In a 336-second guest walk on an RTX 3090 (driver 620.70.06, rt at 7096fa7de3,
whose block-maker thread made its calls back to back), every submit of 5 ms or more overlapped
such calls on other threads for 97 to 100% of its length: a 64 MiB Shared allocation made inside
a take held one submit for 14.2 ms; frees of imported blocks, 0.4 to 2.9 ms each and 52 in one
second, held four submits for 5.2 to 6.9 ms; and the pool's trim after the workload, five 64 MiB
frees of 7.7 to 13.9 ms made back to back, held one submit for 48.7 ms. A take that leaves its
class no wholly
free unit also sets the block-maker making the class's next allocation at once, so the take's
own first submission can wait out that allocation: on the same card (rt at ac1896537f) a
16 MiB Private allocation of 661 µs held the next submit for 603 µs, and on an RTX 2080 one of
+36 -3
View File
@@ -384,6 +384,9 @@ struct Atomics {
site_longest: [Mutex<Longest>; SITES],
maker_waits: AtomicU64,
maker_wait_max_nanos: AtomicU64,
maker_memory_calls: AtomicU64,
maker_yields: AtomicU64,
maker_yield_nanos: AtomicU64,
dispatches_without_effects: AtomicU64,
shared_long_reuses: AtomicU64,
private_long_reuses: AtomicU64,
@@ -749,6 +752,18 @@ impl Counters {
a.maker_wait_max_nanos.fetch_max(nanos, Relaxed);
}
/// A `vkAllocateMemory` or `vkFreeMemory` made ahead of need, after which the thread waited
/// `waited` nanoseconds for the submit calls inside the driver as it returned, `None` where
/// none was ([`Metrics::maker_memory_calls`]).
pub(crate) fn maker_memory_call(&self, waited: Option<u64>) {
let a = &self.atomics;
a.maker_memory_calls.fetch_add(1, Relaxed);
if let Some(nanos) = waited {
a.maker_yields.fetch_add(1, Relaxed);
a.maker_yield_nanos.fetch_add(nanos, Relaxed);
}
}
/// A `vkAllocateMemory` of `bytes` that took `nanos` nanoseconds at `site`, on a thread of the
/// consumer's ([`Metrics::texture_allocations`] and the other sites').
pub(crate) fn site_allocation(&self, site: Site, bytes: u64, nanos: u64) {
@@ -1082,6 +1097,9 @@ impl Counters {
private_take_allocations: site(Site::PrivateTake),
maker_waits: a.maker_waits.load(Relaxed),
maker_wait_max_nanos: a.maker_wait_max_nanos.load(Relaxed),
maker_memory_calls: a.maker_memory_calls.load(Relaxed),
maker_yields: a.maker_yields.load(Relaxed),
maker_yield_nanos: a.maker_yield_nanos.load(Relaxed),
shared_long_reuses: a.shared_long_reuses.load(Relaxed),
private_long_reuses: a.private_long_reuses.load(Relaxed),
allocations_mapped: a.allocations_mapped.load(Relaxed),
@@ -1403,6 +1421,20 @@ pub struct Metrics {
/// The longest of those waits, in nanoseconds of [`host_time`](crate::host_time); a maximum
/// since the device was made, so the difference of two reads does not apply to it.
pub maker_wait_max_nanos: u64,
/// `vkAllocateMemory` and `vkFreeMemory` calls made ahead of need, off the consumer's calls:
/// the block-maker thread's (the runtime's fixed-size internals, the pool's units, and the
/// frees of idle allocations and of the imported and exported blocks given back), and each
/// class's first allocation in the device's making. A driver may hold a submit made during
/// such a call until it returns, and through calls made back to back, so after each one the
/// thread waits until every one of the runtime's `vkQueueSubmit2` calls that was inside the
/// driver as it returned has returned: a submit waits out at most one of these calls.
pub maker_memory_calls: u64,
/// Of [`maker_memory_calls`](Self::maker_memory_calls), those after which a
/// `vkQueueSubmit2` call was inside the driver, which the thread waited for; after the others
/// it went straight on.
pub maker_yields: u64,
/// The nanoseconds of [`host_time`](crate::host_time) those waits took, in total.
pub maker_yield_nanos: u64,
/// Shared takes carved from a long allocation, one a take longer than the 16 MiB unit made for
/// itself, after that take: a take of the same length, which a long allocation alone serves.
pub shared_long_reuses: u64,
@@ -1527,9 +1559,10 @@ pub struct Metrics {
/// Idle allocations the block-maker thread freed: one at a time, each once it had been idle,
/// holding no live block, for 250 ms, whatever the device's queues were doing.
pub allocations_freed: u64,
/// Submissions made while the block-maker thread was inside an idle allocation's
/// `vkFreeMemory`. A driver may hold such a submission until the free returns: on the NVIDIA
/// cards measured in Thunderbolt enclosures, about 1.1 ms per MiB of host-visible memory.
/// Submissions made while the block-maker thread was inside one of its `vkFreeMemory` calls:
/// an idle allocation's, an imported or exported block's given back, or one it made and could
/// not use. A driver may hold such a submission until the free returns: on the NVIDIA cards
/// measured in Thunderbolt enclosures, about 1.1 ms per MiB of host-visible memory.
pub submissions_during_frees: u64,
/// The frees of [`allocations_freed`](Self::allocations_freed) by how long each allocation had
/// been idle when its free began, in buckets of under 250 ms (a spilled allocation that
+6
View File
@@ -24,6 +24,7 @@ use crate::record::Recorders;
use crate::ring::Ring;
use crate::sampler::{Constexpr, SamplerTable};
use crate::submit::{self, Work};
use crate::submit_calls::SubmitCalls;
use crate::times::{StampPools, Ticks};
use ash::vk;
use metal2vulkan::device::{
@@ -314,6 +315,9 @@ pub(crate) struct Core {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) hold_completions: std::sync::RwLock<()>,
pub(crate) pool: Pool,
/// The runtime's `vkQueueSubmit2` calls inside the driver, which the block-maker thread waits
/// out after each of its memory calls.
pub(crate) submit_calls: Arc<SubmitCalls>,
/// What the device imports (`Device::import_dma_buf` on Unix, [`Device::import_host_memory`]).
pub(crate) imports: Imports,
/// What the device exports ([`Device::new_exported_block`]).
@@ -693,6 +697,7 @@ impl Device {
granularity,
alignment,
);
let submit_calls = Arc::new(SubmitCalls::new(counters.clone()));
let live = instance.teardowns().live();
let core = Arc::new(Core {
instance,
@@ -731,6 +736,7 @@ impl Device {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
hold_completions: std::sync::RwLock::new(()),
pool,
submit_calls,
imports,
exports,
claims: Mutex::new(HashMap::new()),
+1 -1
View File
@@ -256,7 +256,7 @@ impl Filler {
unsafe {
device.destroy_buffer(self.zeros, None);
if allocated {
device.free_memory(self.zeros_memory, None);
memory::free(device, self.zeros_memory);
}
}
allocated
+1
View File
@@ -53,6 +53,7 @@ mod sampler;
mod shadow;
mod staging;
mod submit;
mod submit_calls;
mod surface;
#[cfg(test)]
mod tests;
+61 -50
View File
@@ -11,10 +11,11 @@ use crate::device::{lock, Core};
use crate::error::{Error, Limit};
use crate::floor;
use crate::places::Ranges;
use crate::submit_calls::SubmitCalls;
use ash::vk;
use std::cell::RefCell;
use std::collections::{HashSet, VecDeque};
use std::ptr::NonNull;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
@@ -547,12 +548,6 @@ pub(crate) struct Pool {
/// The alignment of a buffer of the pool's usage, which Vulkan holds the same for every such
/// buffer.
alignment: u64,
/// Whether the block-maker thread is in an idle allocation's `vkFreeMemory`.
freeing: 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)))]
hold_frees: Mutex<bool>,
/// For the device tests: each idle allocation the block-maker thread freed, as when it became
/// idle, when its free began and when it ended, in nanoseconds of
/// [`host_time`](crate::host_time).
@@ -653,10 +648,49 @@ struct State {
}
thread_local! {
/// Whether this thread makes allocations ahead of need: the block-maker thread ([`run`]), its
/// internals among them, or the device's making while it makes the first allocations
/// ([`stock`]). For the allocation-time metrics.
static ON_MAKER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Where this thread makes memory ahead of need, its device's submit calls: on the block-maker
/// thread ([`run`]), its internals among what it makes, and in the device's making while it
/// makes the first allocations ([`stock`]). Each of its allocations and frees waits them out
/// after it ([`passed`]), and its allocations' times count apart from the consumer's.
static MAKER: RefCell<Option<Arc<SubmitCalls>>> = const { RefCell::new(None) };
}
/// Makes this thread one that makes memory ahead of need for the device whose submit calls are
/// `calls` ([`MAKER`]); `None` makes it one that does not.
pub(crate) fn make_ahead_here(calls: Option<Arc<SubmitCalls>>) {
MAKER.set(calls);
}
/// Whether this thread makes memory ahead of need ([`MAKER`]).
fn on_maker() -> bool {
MAKER.with_borrow(Option::is_some)
}
/// After each `vkAllocateMemory` and `vkFreeMemory` call, as it returned: on a thread that makes
/// memory ahead of need, waits until every submit call of its device that was inside the driver
/// then has returned ([`SubmitCalls::wait_out`]), so a driver that holds a submit through memory
/// calls made back to back holds it through this one alone. On every other thread nothing.
pub(crate) fn passed() {
MAKER.with_borrow(|maker| {
if let Some(calls) = maker {
calls.wait_out();
}
});
}
/// `vkFreeMemory` of `memory`, the form of every free the block-maker thread makes: there,
/// marked for the submissions made during it ([`SubmitCalls::freeing`]), and then [`passed`].
///
/// # Safety
///
/// As `vkFreeMemory`: `memory` is `device`'s, and nothing uses it.
pub(crate) unsafe fn free(device: &ash::Device, memory: vk::DeviceMemory) {
MAKER.with_borrow(|maker| match maker {
// SAFETY: the caller's.
Some(calls) => calls.free(|| unsafe { device.free_memory(memory, None) }),
// SAFETY: the caller's.
None => unsafe { device.free_memory(memory, None) },
});
}
/// What a block is: a range of an allocation.
@@ -725,9 +759,6 @@ impl Pool {
counters,
granule: GRANULE.max(granularity.next_power_of_two()),
alignment,
freeing: 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)))]
frees: Mutex::new(Vec::new()),
}
@@ -754,14 +785,6 @@ impl Pool {
}
}
/// Whether the block-maker thread is in an idle allocation's `vkFreeMemory`, which a driver
/// may hold a submission made now for ([`Metrics::submissions_during_frees`]).
///
/// [`Metrics::submissions_during_frees`]: crate::Metrics::submissions_during_frees
pub(crate) fn freeing(&self) -> bool {
self.freeing.load(Relaxed)
}
/// For the device tests: whether the class holds a wholly free unit ([`State::whole`]), so
/// the block-maker thread makes nothing for it.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -794,13 +817,6 @@ impl Pool {
.collect()
}
/// For the device tests: holds each idle allocation's free, with [`freeing`](Self::freeing)
/// set, while `hold` is true.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn hold_frees(&self, hold: bool) {
*lock(&self.hold_frees) = hold;
}
/// For the device tests: each idle allocation the block-maker thread freed so far, as when
/// it became idle, when its free began and when it ended ([`host_time`](crate::host_time)).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -1302,7 +1318,7 @@ fn ahead(core: &Core, class: MemoryClass) -> Option<Allocation> {
/// the class's next take or give-back.
pub(crate) fn stock(core: &Core) {
// Made ahead of need, as the block-maker thread's are: counted with them.
ON_MAKER.set(true);
make_ahead_here(Some(Arc::clone(&core.submit_calls)));
for class in MemoryClass::ALL {
let made = ahead(core, class);
let mut state = core.pool.lock();
@@ -1312,7 +1328,7 @@ pub(crate) fn stock(core: &Core) {
}
core.pool.settle(&mut state, class);
}
ON_MAKER.set(false);
make_ahead_here(None);
}
/// The block-maker thread, until the device's teardown or a quiesce stops it. Off every caller's
@@ -1320,11 +1336,13 @@ pub(crate) fn stock(core: &Core) {
/// ones first of all; it frees each imported or exported block given back, then runs an import's
/// release; it makes an allocation of a class that holds no wholly free unit ([`State::whole`]),
/// having the consumer map it before it joins the pool; and it frees each allocation idle for
/// [`IDLE_AGE_NANOS`], after the consumer's unmap of it, one at a time. It sleeps until the next
/// change, or until the oldest idle allocation reaches the idle age. Stopped, it makes nothing
/// more: what is asked of it and not made, the calls that need it make.
/// [`IDLE_AGE_NANOS`], after the consumer's unmap of it, one at a time. After each of its
/// allocations and frees it waits out the submit calls inside the driver as the call returned
/// ([`passed`]). It sleeps until the next change, or until the oldest idle allocation reaches the
/// idle age. Stopped, it makes nothing more: what is asked of it and not made, the calls that need
/// it make.
pub(crate) fn run(core: Arc<Core>) {
ON_MAKER.set(true);
make_ahead_here(Some(Arc::clone(&core.submit_calls)));
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
if let MakerTest::Park(park) = &core.maker_test {
park.wait();
@@ -1485,7 +1503,8 @@ pub(crate) unsafe fn allocate_spilling(
/// `counters`' blocks gauge, refused with [`Limit::MemoryAllocations`] before the driver is called
/// where `max`, the device's `maxMemoryAllocationCount`, are live. Each free falls the gauge. The
/// call's time is counted on the block-maker thread or on the consumer's, and on the consumer's
/// at `site` too, where the call names one.
/// at `site` too, where the call names one. On the block-maker thread the call is then
/// [`passed`].
///
/// # Safety
///
@@ -1504,7 +1523,8 @@ pub(crate) unsafe fn allocate(
// SAFETY: the caller's.
let allocated = unsafe { device.allocate_memory(info, None) };
let nanos = crate::host_time().saturating_sub(start);
let maker = ON_MAKER.get();
passed();
let maker = on_maker();
counters.allocation_time(nanos, maker);
if let (false, Some(site)) = (maker, site) {
counters.site_allocation(site, info.allocation_size, nanos);
@@ -2193,10 +2213,8 @@ fn free_own(core: &Core, memory: &Memory, release: Option<Release>) {
core.counters.fall(Gauge::SurfaceBuffers);
return;
}
core.pool.freeing.store(true, Relaxed);
// SAFETY: as above; nothing else is bound to the memory.
unsafe { core.device.free_memory(memory.memory, None) };
core.pool.freeing.store(false, Relaxed);
unsafe { free(&core.device, memory.memory) };
core.counters.fall(Gauge::Blocks);
match memory.own {
Some(Own::Export(_)) => core.counters.fall(Gauge::Exports),
@@ -2214,23 +2232,16 @@ fn free_own(core: &Core, memory: &Memory, release: Option<Release>) {
/// On the block-maker thread: frees an allocation the idle rule took out, after the consumer's
/// unmap of it, and counts its idle time. The submissions made during its `vkFreeMemory` are
/// counted.
/// counted ([`free`]).
fn free_idle(core: &Core, allocation: Allocation) {
core.pool.unmap(allocation.id);
let pool = &core.pool;
let since = allocation.idle_since;
let began = crate::host_time();
core.counters.freed_idle(began.saturating_sub(since));
pool.freeing.store(true, Relaxed);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
while *lock(&pool.hold_frees) {
std::thread::sleep(Duration::from_millis(1));
}
free_allocation(core, allocation);
pool.freeing.store(false, Relaxed);
core.counters.count(Metric::AllocationsFreed);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
lock(&pool.frees).push((since, began, crate::host_time()));
lock(&core.pool.frees).push((since, began, crate::host_time()));
}
/// Frees an allocation and its buffer, whose blocks are all given back or gone with the device,
@@ -2240,7 +2251,7 @@ fn free_allocation(core: &Core, allocation: Allocation) {
// block holds it until it retires.
unsafe {
core.device.destroy_buffer(allocation.buffer, None);
core.device.free_memory(allocation.memory, None);
free(&core.device, allocation.memory);
}
core.counters.fall(Gauge::Blocks);
(core.counters).fall_by(allocation.class.allocation_gauge(), allocation.len);
+1 -1
View File
@@ -346,7 +346,7 @@ fn make(core: &Core) -> Result<(RingBlock, u64, Mapping), Error> {
// SAFETY: nothing uses the block.
unsafe {
device.destroy_buffer(block.buffer, None);
device.free_memory(block.memory, None);
memory::free(device, block.memory);
}
core.counters.fall(Gauge::Blocks);
Err(error)
+3 -3
View File
@@ -225,7 +225,7 @@ impl Region {
// SAFETY: the caller's; freeing the memory unmaps it.
unsafe {
core.device.destroy_buffer(self.buffer, None);
core.device.free_memory(self.memory, None);
memory::free(&core.device, self.memory);
}
core.counters.fall(Gauge::Blocks);
}
@@ -357,7 +357,7 @@ fn host_buffer(
// SAFETY: nothing uses them.
unsafe {
device.destroy_buffer(buffer, None);
device.free_memory(memory, None);
memory::free(device, memory);
}
core.counters.fall(Gauge::Blocks);
return Err(error);
@@ -368,7 +368,7 @@ fn host_buffer(
// SAFETY: nothing uses them.
unsafe {
device.destroy_buffer(buffer, None);
device.free_memory(memory, None);
memory::free(device, memory);
}
core.counters.fall(Gauge::Blocks);
return Err(Error::Vulkan {
+5 -1
View File
@@ -2075,7 +2075,7 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
}
if ok {
let queue = lock(&core.queues.runtime);
if core.pool.freeing() {
if core.submit_calls.freeing() {
core.counters.count(Metric::SubmissionsDuringFrees);
}
// A bind of an import over several dma-bufs since the last submission: this one waits for
@@ -2107,10 +2107,14 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
// read the metrics, before the call returns here.
core.counters.count(Metric::Submissions);
core.counters.submitted_infos(infos.len() as u64);
// Inside the driver from here until the call returns, for the block-maker thread's
// wait after its memory calls (`crate::submit_calls`).
let call = core.submit_calls.enter();
// SAFETY: every command buffer is executable and in no other pending submission;
// every wait is on a signal submitted earlier, and every signal raises its semaphore;
// the queue is held.
ok = unsafe { device.queue_submit2(*queue, &infos, vk::Fence::null()) }.is_ok();
drop(call);
if !ok {
break;
}
+144
View File
@@ -0,0 +1,144 @@
//! The runtime's `vkQueueSubmit2` calls inside the driver, as the block-maker thread's memory
//! calls meet them.
//!
//! A driver may hold a submit made while another thread is inside `vkAllocateMemory` or
//! `vkFreeMemory` until that call returns, and hold it through calls made back to back (NVIDIA's
//! Linux driver 620.70.06 does, device-local memory included). So after each of its allocations
//! and frees the block-maker thread waits until every submit call that had entered the driver
//! when its own call returned has come back ([`SubmitCalls::wait_out`]); where none was inside
//! the driver then, it goes on at once. A submit then waits out at most one of its calls, the
//! one it met. A submit never waits for the block-maker thread: its call counts itself in and out
//! under a lock held for an add, and wakes the thread only while it waits. A take that allocates
//! on the consumer's thread makes a single call, and waits for nothing.
use crate::counters::Counters;
use crate::device::lock;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
use std::sync::{Condvar, Mutex, PoisonError};
/// The device's submit calls inside the driver, and whether the block-maker thread is inside a
/// `vkFreeMemory`.
pub(crate) struct SubmitCalls {
calls: Mutex<Calls>,
/// Signalled as a call returns while a thread waits for one ([`Calls::waiting`]).
returned: Condvar,
/// Whether the block-maker thread is inside a `vkFreeMemory`, which a driver may hold a
/// submission made now for ([`Metrics::submissions_during_frees`]).
///
/// [`Metrics::submissions_during_frees`]: crate::Metrics::submissions_during_frees
freeing: AtomicBool,
/// The device's counters: the block-maker thread's calls and its waits.
counters: Counters,
/// For the device tests: while set, the block-maker thread waits inside each of its frees,
/// with [`freeing`](Self::freeing) set, before it calls `vkFreeMemory`.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
hold_frees: Mutex<bool>,
}
/// The submit calls counted in and out.
#[derive(Default)]
struct Calls {
/// The calls that entered the driver.
entered: u64,
/// The calls that returned from it.
returned: u64,
/// The threads waiting for [`returned`](Self::returned) to reach a count.
waiting: usize,
}
/// A submit call inside the driver: counted out as it drops, once the call returned.
pub(crate) struct InDriver<'a>(&'a SubmitCalls);
impl Drop for InDriver<'_> {
fn drop(&mut self) {
let calls = &self.0;
let mut counts = lock(&calls.calls);
counts.returned += 1;
if counts.waiting > 0 {
calls.returned.notify_all();
}
}
}
impl SubmitCalls {
/// None inside the driver, for a new device whose counters are `counters`.
pub(crate) fn new(counters: Counters) -> SubmitCalls {
SubmitCalls {
calls: Mutex::new(Calls::default()),
returned: Condvar::new(),
freeing: AtomicBool::new(false),
counters,
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
hold_frees: Mutex::new(false),
}
}
/// Counts in a `vkQueueSubmit2` call made at once after this: it is counted out as the
/// returned guard drops, after the call returned, whatever it returned.
pub(crate) fn enter(&self) -> InDriver<'_> {
lock(&self.calls).entered += 1;
InDriver(self)
}
/// On the block-maker thread, as one of its `vkAllocateMemory` or `vkFreeMemory` calls
/// returned: waits until every submit call counted in by now has returned, blocking, for no
/// longer than those calls take; with none inside the driver, it returns at once. The call is
/// counted in [`Metrics::maker_memory_calls`], and a wait in [`Metrics::maker_yields`] and
/// [`Metrics::maker_yield_nanos`].
///
/// [`Metrics::maker_memory_calls`]: crate::Metrics::maker_memory_calls
/// [`Metrics::maker_yields`]: crate::Metrics::maker_yields
/// [`Metrics::maker_yield_nanos`]: crate::Metrics::maker_yield_nanos
pub(crate) fn wait_out(&self) {
let mut counts = lock(&self.calls);
let entered = counts.entered;
if counts.returned >= entered {
drop(counts);
self.counters.maker_memory_call(None);
return;
}
let since = crate::host_time();
counts.waiting += 1;
while counts.returned < entered {
counts = (self.returned.wait(counts)).unwrap_or_else(PoisonError::into_inner);
}
counts.waiting -= 1;
drop(counts);
let nanos = crate::host_time().saturating_sub(since);
self.counters.maker_memory_call(Some(nanos));
}
/// On the block-maker thread: `free`, its `vkFreeMemory`, with
/// [`freeing`](Self::freeing) set for its length, then [`wait_out`](Self::wait_out).
pub(crate) fn free(&self, free: impl FnOnce()) {
self.freeing.store(true, Relaxed);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
while *lock(&self.hold_frees) {
std::thread::sleep(std::time::Duration::from_millis(1));
}
free();
self.freeing.store(false, Relaxed);
self.wait_out();
}
/// Whether the block-maker thread is inside a `vkFreeMemory`, which a driver may hold a
/// submission made now for ([`Metrics::submissions_during_frees`]).
///
/// [`Metrics::submissions_during_frees`]: crate::Metrics::submissions_during_frees
pub(crate) fn freeing(&self) -> bool {
self.freeing.load(Relaxed)
}
/// For the tests: the threads waiting for a submit call to return.
#[cfg(test)]
pub(crate) fn waiting(&self) -> usize {
lock(&self.calls).waiting
}
/// For the device tests: holds each of the block-maker thread's frees, with
/// [`freeing`](Self::freeing) set, while `hold` is true.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn hold_frees(&self, hold: bool) {
*lock(&self.hold_frees) = hold;
}
}
@@ -0,0 +1,236 @@
//! The block-maker thread's wait after each of its memory calls (`crate::submit_calls`), with a
//! submit call counted in standing in for one inside the driver. GPU-free: a submit call inside
//! the driver as the maker's call returned has returned before the maker's next call starts, and
//! one that entered after does not hold it; on a quiet queue the maker goes straight on; the
//! wait after a free is not part of the free; and a thread that makes no memory ahead of need
//! waits for nothing. Under a device cfg, on every device of the cfg's kind: the block-maker
//! thread's allocation of a class's next unit waits out a submit call inside the driver before
//! the unit joins the pool, a take's own allocation on the consumer's thread waits for nothing,
//! and an idle allocation's free on a quiet queue goes straight on, every gauge at zero after.
use crate::counters::Counters;
use crate::device::lock;
use crate::memory::{make_ahead_here, passed};
use crate::submit_calls::SubmitCalls;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
/// How long a stand-in submit call stays inside the driver once the maker waits for it.
const HOLD: Duration = Duration::from_millis(50);
/// Waits until `done`, for at most 10 seconds.
fn until(what: &str, done: impl Fn() -> bool) {
let deadline = Instant::now() + Duration::from_secs(10);
while !done() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
thread::sleep(Duration::from_millis(1));
}
}
/// Runs `body` on a thread that makes memory ahead of need for `calls`, as the block-maker
/// thread does, and waits for it to end, for at most 10 seconds.
fn on_maker(calls: &Arc<SubmitCalls>, body: impl FnOnce() + Send + 'static) {
let calls = Arc::clone(calls);
let (ended, end) = mpsc::channel();
thread::spawn(move || {
make_ahead_here(Some(calls));
body();
let _ = ended.send(());
});
end.recv_timeout(Duration::from_secs(10))
.expect("the maker's calls end");
}
/// The block-maker thread's counts in `counters`: its memory calls, the waits after them and
/// whether those waits took any time.
fn counts(counters: &Counters) -> (u64, u64, bool) {
let metrics = counters.metrics();
let waited = metrics.maker_yield_nanos > 0;
(metrics.maker_memory_calls, metrics.maker_yields, waited)
}
/// A submit call inside the driver as the maker's call returned has returned before the maker's
/// next call starts; a submit call that entered after the maker's call returned does not hold
/// it, and the wait lasts until the call it waits for returns.
#[test]
fn the_makers_next_call_starts_once_each_submit_inside_the_driver_as_its_call_returned_returned() {
let counters = Counters::new();
let calls = Arc::new(SubmitCalls::new(counters.clone()));
let log: Arc<Mutex<Vec<&str>>> = Arc::default();
let first = calls.enter();
let maker = {
let (calls, log) = (Arc::clone(&calls), Arc::clone(&log));
thread::spawn(move || {
make_ahead_here(Some(calls));
lock(&log).push("the maker's call returned");
passed();
lock(&log).push("the maker's next call starts");
})
};
until("the maker to wait or go on", || {
calls.waiting() == 1 || lock(&log).len() == 2
});
let second = calls.enter();
thread::sleep(HOLD);
lock(&log).push("the first submit call returned");
drop(first);
// The second is still inside the driver.
until("the maker's next call", || lock(&log).len() == 3);
maker.join().expect("the maker");
assert_eq!(
*lock(&log),
[
"the maker's call returned",
"the first submit call returned",
"the maker's next call starts",
]
);
drop(second);
let metrics = counters.metrics();
assert_eq!((metrics.maker_memory_calls, metrics.maker_yields), (1, 1));
assert!(
metrics.maker_yield_nanos >= HOLD.as_nanos() as u64,
"the wait lasted until the call returned: {} ns",
metrics.maker_yield_nanos
);
}
/// With no submit call inside the driver as its calls return, the maker goes straight on: a
/// submit call that entered and returned before holds nothing, and no wait is counted.
#[test]
fn on_a_quiet_queue_the_maker_goes_straight_on() {
let counters = Counters::new();
let calls = Arc::new(SubmitCalls::new(counters.clone()));
drop(calls.enter());
on_maker(&calls, || {
passed();
passed();
});
assert_eq!(counts(&counters), (2, 0, false));
}
/// A free is marked as one for its own length: the maker's wait after it, with a submit call
/// inside the driver, is not part of it.
#[test]
fn the_wait_after_a_free_is_not_part_of_the_free() {
let counters = Counters::new();
let calls = Arc::new(SubmitCalls::new(counters.clone()));
let inside = calls.enter();
let marked: Arc<Mutex<Option<bool>>> = Arc::default();
let maker = {
let (calls, marked) = (Arc::clone(&calls), Arc::clone(&marked));
thread::spawn(move || {
make_ahead_here(Some(Arc::clone(&calls)));
calls.free(|| *lock(&marked) = Some(calls.freeing()));
})
};
until("the maker to wait after its free", || calls.waiting() == 1);
assert!(
!calls.freeing(),
"the wait after the free is not marked as a free"
);
drop(inside);
maker.join().expect("the maker");
assert_eq!(*lock(&marked), Some(true), "the free is marked as one");
assert!(!calls.freeing());
assert_eq!(counts(&counters), (1, 1, true));
}
/// A thread that makes no memory ahead of need, a consumer's take among them, waits for nothing
/// after its calls, a submit call inside the driver or not, and counts none of them.
#[test]
fn a_thread_that_makes_nothing_ahead_waits_for_nothing() {
let counters = Counters::new();
let calls = Arc::new(SubmitCalls::new(counters.clone()));
let inside = calls.enter();
let (ended, end) = mpsc::channel();
thread::spawn(move || {
passed();
let _ = ended.send(());
});
end.recv_timeout(Duration::from_secs(10))
.expect("the call goes on with a submit call inside the driver");
drop(inside);
assert_eq!(counts(&counters), (0, 0, false));
}
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use super::HOLD;
use crate::tests::command::on_device::{each_device, within};
use crate::MemoryClass;
use std::thread;
/// With a submit call counted in as inside the driver, the block-maker thread's allocation of
/// the Shared unit a take used up waits it out before the unit joins the pool, while a take
/// that allocates on the consumer's thread goes straight on; with none inside, the free of
/// the idle allocation the take gives back waits for nothing.
#[test]
fn every_devices_block_maker_waits_out_a_submit_call_inside_the_driver() {
each_device("maker_yield", |name, _, device| {
let core = device.core();
let counters = device.counters();
within("both classes stocked", || {
core.pool.stocked(MemoryClass::Shared) && core.pool.stocked(MemoryClass::Private)
});
let made = counters.metrics();
// Each class's first unit in the device's making, and the zero source, the ring's
// first block and the staging region on the block-maker thread.
assert_eq!(
(made.maker_memory_calls, made.maker_yields),
(5, 0),
"{name}: the memory calls made ahead of need"
);
let len = MemoryClass::Shared.block_len();
let inside = core.submit_calls.enter();
let long = (device.take_block(MemoryClass::Private, 2 * len))
.unwrap_or_else(|error| panic!("{name}: a long take: {error}"));
let taken = counters.metrics();
assert_eq!(
(taken.consumer_allocations, taken.maker_memory_calls),
(made.consumer_allocations + 1, made.maker_memory_calls),
"{name}: the long take allocated on the consumer's thread, waiting for nothing"
);
let block = (device.take_block(MemoryClass::Shared, len))
.unwrap_or_else(|error| panic!("{name}: the Shared unit: {error}"));
within("the block-maker thread to wait", || {
core.submit_calls.waiting() == 1
});
thread::sleep(HOLD);
assert!(
core.submit_calls.waiting() == 1 && !core.pool.stocked(MemoryClass::Shared),
"{name}: the new unit waits for the submit call"
);
drop(inside);
within("the new Shared unit", || {
core.pool.stocked(MemoryClass::Shared)
});
let yielded = counters.metrics();
assert_eq!(
(yielded.maker_memory_calls, yielded.maker_yields),
(made.maker_memory_calls + 1, 1),
"{name}: the unit's allocation waited"
);
assert!(
yielded.maker_yield_nanos >= HOLD.as_nanos() as u64,
"{name}: the wait lasted until the submit call returned: {} ns",
yielded.maker_yield_nanos
);
device.release_block(block).expect("a release");
within("the idle unit's free", || core.pool.frees().len() == 1);
let freed = counters.metrics();
assert_eq!(
(freed.maker_memory_calls, freed.maker_yields),
(yielded.maker_memory_calls + 1, 1),
"{name}: the free on a quiet queue went straight on"
);
println!(
"maker_yield: {name}: calls {}, waits {} of {} ns",
freed.maker_memory_calls, freed.maker_yields, freed.maker_yield_nanos
);
device.release_block(long).expect("a release");
});
}
}
+11 -10
View File
@@ -1289,7 +1289,7 @@ mod on_device {
// The other three freed at their idle age, oldest first.
wait_until("three idle Shared allocations freed", || {
core.pool.frees().len() == 3 && !core.pool.freeing()
core.pool.frees().len() == 3 && !core.submit_calls.freeing()
});
assert_freed_at_the_idle_age(name, &core.pool.frees());
let unmapped = hook.unmapped();
@@ -1309,7 +1309,7 @@ mod on_device {
let released = crate::host_time();
device.release_block(again).expect("a release");
wait_until("the fourth freed", || {
core.pool.frees().len() == 4 && !core.pool.freeing()
core.pool.frees().len() == 4 && !core.submit_calls.freeing()
});
let frees = core.pool.frees();
assert!(
@@ -1324,7 +1324,7 @@ mod on_device {
device.release_block(small).expect("a release");
wait_until("the small block given back", || core.pool.holds(small_id));
wait_until("the small block's allocation freed", || {
core.pool.frees().len() == 5 && !core.pool.freeing()
core.pool.frees().len() == 5 && !core.submit_calls.freeing()
});
thread::sleep(Duration::from_nanos(2 * IDLE_AGE_NANOS));
assert_eq!(
@@ -1420,7 +1420,7 @@ mod on_device {
assert_eq!(whole(class), 4, "{name}: {class:?}: four wholly free units");
}
wait_until("six idle allocations freed", || {
core.pool.frees().len() == 6 && !core.pool.freeing()
core.pool.frees().len() == 6 && !core.submit_calls.freeing()
});
assert_freed_at_the_idle_age(name, &core.pool.frees());
thread::sleep(Duration::from_nanos(2 * IDLE_AGE_NANOS));
@@ -1489,7 +1489,7 @@ mod on_device {
let allocation = long.allocation;
device.release_block(long).expect("a release");
wait_until("the long allocation freed", || {
core.pool.frees().len() == 1 && !core.pool.freeing()
core.pool.frees().len() == 1 && !core.submit_calls.freeing()
});
let unmapped = hook.unmapped();
assert_eq!(
@@ -1595,7 +1595,8 @@ mod on_device {
let mut given = Vec::new();
let mut between = None;
let mut commits = 0;
let ended = |count: usize| core.pool.frees().len() == count && !core.pool.freeing();
let ended =
|count: usize| core.pool.frees().len() == count && !core.submit_calls.freeing();
while !(given.len() == 2 && ended(2)) {
assert!(
started.elapsed() < Duration::from_secs(120),
@@ -1651,18 +1652,18 @@ mod on_device {
.wait_until_completed()
.expect("a wait outside a scheduled handler");
};
core.pool.hold_frees(true);
core.submit_calls.hold_frees(true);
device.release_block(blocks.remove(0)).expect("a release");
wait_until("a free held open", || core.pool.freeing());
wait_until("a free held open", || core.submit_calls.freeing());
fill(&buffer);
assert_eq!(
counters.metrics().submissions_during_frees,
steady.submissions_during_frees + 1,
"{name}: the submission during the free"
);
core.pool.hold_frees(false);
core.submit_calls.hold_frees(false);
wait_until("the third freed", || {
core.pool.frees().len() == 3 && !core.pool.freeing()
core.pool.frees().len() == 3 && !core.submit_calls.freeing()
});
fill(&buffer);
assert_eq!(
+1
View File
@@ -37,6 +37,7 @@ mod linear_planes;
#[cfg(m2v_gpu)]
mod locks;
mod lowered;
mod maker_yield;
mod managed;
mod memory;
mod mipmaps;
@@ -2793,6 +2793,9 @@ impl Backend for NewRuntime {
metrics.consumer_allocation_nanos,
),
("maker_allocation_nanos", metrics.maker_allocation_nanos),
("maker_memory_calls", metrics.maker_memory_calls),
("maker_yields", metrics.maker_yields),
("maker_yield_nanos", metrics.maker_yield_nanos),
("allocations_freed", metrics.allocations_freed),
("submissions_during_frees", metrics.submissions_during_frees),
("idle_frees_under_250ms", metrics.idle_frees_by_age[0]),
@@ -2431,8 +2431,11 @@ field metal2vulkan-rt::Metrics.made_ahead_variant_nanos pub made_ahead_variant_n
field metal2vulkan-rt::Metrics.made_ahead_variants pub made_ahead_variants: u64
field metal2vulkan-rt::Metrics.maker_allocation_nanos pub maker_allocation_nanos: u64
field metal2vulkan-rt::Metrics.maker_makes pub maker_makes: Timed
field metal2vulkan-rt::Metrics.maker_memory_calls pub maker_memory_calls: u64
field metal2vulkan-rt::Metrics.maker_wait_max_nanos pub maker_wait_max_nanos: u64
field metal2vulkan-rt::Metrics.maker_waits pub maker_waits: u64
field metal2vulkan-rt::Metrics.maker_yield_nanos pub maker_yield_nanos: u64
field metal2vulkan-rt::Metrics.maker_yields pub maker_yields: u64
field metal2vulkan-rt::Metrics.managed_bytes_captured pub managed_bytes_captured: u64
field metal2vulkan-rt::Metrics.over_copies pub over_copies: u64
field metal2vulkan-rt::Metrics.over_copies_imported pub over_copies_imported: u64
Can't render this file because it is too large.