rt: the block-maker thread frees idle allocations one at a time, only in quiet gaps

The planner's ruling (free when quiet), replacing "free whenever the window lets go": a driver may
hold every submission of the process for the whole of a vkFreeMemory, and on the NVIDIA cards we
measured in Thunderbolt enclosures freeing host-visible memory takes about 1.1 ms per MiB (15-17 ms
for one 16 MiB allocation), where an internal NVIDIA card frees 16 MiB in about 0.5 ms (store lane
and planner rows). Under the 10 s window a give-back freed every surplus allocation at once, back
to back, beside the guest's submissions.

What changed:
- The idle rule (which allocations are surplus: the window's peak, the cap, the reserve) is as it
  was. It now answers one allocation at a time (Rule::Free), and the block-maker thread frees it
  only once no commit or submission has come on any of the device's queues for 20 ms
  (QUIET_NANOS), then looks again. CommandBuffer::commit and the submit thread's vkQueueSubmit2
  stamp the pool (one atomic fetch_max of host_time, nothing else on those paths).
- The rule runs on the block-maker thread's own time too: it sleeps until the next change, the
  end of the quiet time where it has an allocation to free, or the second the window's peak can
  fall where it keeps idle allocations. So a program that goes quiet gives its idle allocations
  back without a call of its own (before, the rule ran only on a take or give-back).
- A spilled allocation that empties retires: no take lands in it, its bytes are not free bytes,
  and it is the rule's next to free, through the same quiet path (it was freed at once).
- Metrics::allocations_freed counts the frees; Metrics::submissions_during_frees counts the
  submissions made while the thread was inside a free's vkFreeMemory. The replay's per-frame
  counters carry both.
- README: the idle paragraph, and a known gap of memory blocks in the planner's wording.
  release_block's doc. api_signatures gains the two fields.

Tests:
- every_device_frees_idle_allocations_as_the_window_s_peak_falls: the three oldest freed one at
  a time when the clock passes the window, and the fourth freed five seconds later with no take
  or give-back (the timer path); four frees counted.
- every_device_frees_idle_allocations_in_quiet_gaps: command buffers committed every 2 ms while
  four idle allocations are surplus; every free begins at least 20 ms after the last commit before
  it (checked against the test thread's own commit times, whatever its gaps); the four are freed
  once the commits stop. Then a free held open: a submission during it is counted, one after it
  is not.
- The spill test exercises the retiring path (it failed while a newly made spilled allocation was
  taken for an emptied one: 3090, 2080, RX 550 in m3-max-44872/44873/44874; fixed).

Verified at d7918e27fa (this commit's code on a6520161e8; the tree here is the same diff applied on
development 61f2799088): check m3-max-44879 (clippy all-features, --cfg m2v_gpu, rt under
--cfg m2v_cpu_icd, translator no-feature; rt and harness suites); legs 3090 m3-max-44882,
2080 44883, RX 550 44884, lavapipe 44885: 174/174 each. The old runtime and the translator are
untouched.
This commit is contained in:
Anees Iqbal committed 2026-11-18 00:20:41 -08:00
1 parent 61f2799088
commit 0280c19285
9 files changed
+401 -91

No files matched your search

+14 -4
View File
@@ -137,10 +137,12 @@ in its memory.
while their bytes and those of its allocations in use stay at or under the most bytes it had in
use over the last 10 seconds, and within an eighth of the heap of the class's memory type; past
that it frees the oldest, after `BlockMappings::unmap` of each block kept in them, except those
the class's free bytes need to stay at 8 MiB or more. The rule runs as blocks are taken and given
back, never on a timer: a program that goes quiet keeps its idle allocations until its next take
or release, or until the device is torn down. `Gauges::shared_idle_bytes` and
`Gauges::private_idle_bytes` count the idle bytes. Once the last handle is gone the block's
the class's free bytes need to stay at 8 MiB or more. The block-maker thread frees them one at a
time, and only once no commit or submission has come on any of the device's queues for 20 ms,
looking again after each free: a program that goes quiet gives its idle allocations back
without a call of its own, and a busy one at its next quiet gap. `Metrics::allocations_freed`
counts the frees. `Gauges::shared_idle_bytes` and `Gauges::private_idle_bytes` count the idle
bytes. Once the last handle is gone the block's
number names nothing
(`Error::NoSuchBlock`), and numbers are never reused during the device's life. The device's
teardown frees every block still claimed, after the consumer's `BlockMappings::unmap` returned
@@ -192,6 +194,14 @@ teardown, on the thread that tears down, after the runtime's other threads are j
into the runtime. Blocks the consumer never took are freed without it, and so is every block freed
after a quiesce.
### Known gaps of memory blocks
- On the NVIDIA cards we measured in Thunderbolt enclosures, freeing host-visible memory takes
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 block at a time and only
after 20 ms with no commit. `Metrics::allocations_freed` counts the frees, and
`Metrics::submissions_during_frees` the submits made while one was in progress.
## Set 1 and index grants
Shaders reach textures and samplers by index (`docs/RESOURCE-ID.md`). Every pipeline takes set 1,
+2
View File
@@ -404,6 +404,8 @@ impl CommandBuffer {
// the reaper, never in this call.
let core = self.building(|building| Ok(Arc::clone(building.device.core())))?;
let began = crate::host_time();
// The device is not quiet: the pool frees no idle allocation for a while.
core.pool.worked(began);
let mut work = core.work.lock();
core.counters
.commit_lock_wait(crate::host_time().saturating_sub(began));
+17
View File
@@ -39,6 +39,10 @@ pub(crate) enum Metric {
ForcedFlushesAcrossQueues,
/// [`Metrics::over_copies`].
OverCopies,
/// [`Metrics::allocations_freed`].
AllocationsFreed,
/// [`Metrics::submissions_during_frees`].
SubmissionsDuringFrees,
}
/// A gauge the runtime moves.
@@ -120,6 +124,8 @@ struct Atomics {
lone_submissions_across_queues: AtomicU64,
forced_flushes_across_queues: AtomicU64,
over_copies: AtomicU64,
allocations_freed: AtomicU64,
submissions_during_frees: AtomicU64,
buffers: AtomicU64,
textures: AtomicU64,
samplers: AtomicU64,
@@ -172,6 +178,8 @@ impl Counters {
Metric::LoneSubmissionsAcrossQueues => &a.lone_submissions_across_queues,
Metric::ForcedFlushesAcrossQueues => &a.forced_flushes_across_queues,
Metric::OverCopies => &a.over_copies,
Metric::AllocationsFreed => &a.allocations_freed,
Metric::SubmissionsDuringFrees => &a.submissions_during_frees,
};
atomic.fetch_add(1, Relaxed);
}
@@ -339,6 +347,8 @@ impl Counters {
lone_submissions_across_queues: a.lone_submissions_across_queues.load(Relaxed),
forced_flushes_across_queues: a.forced_flushes_across_queues.load(Relaxed),
over_copies: a.over_copies.load(Relaxed),
allocations_freed: a.allocations_freed.load(Relaxed),
submissions_during_frees: a.submissions_during_frees.load(Relaxed),
}
}
@@ -478,6 +488,13 @@ pub struct Metrics {
/// buffer's bytes into the image, in the upload that leads a submission or after a command
/// wrote the buffer, and the image back into the buffer after a command wrote the texture.
pub over_copies: u64,
/// Idle allocations the block-maker thread freed: one at a time, each once no commit or
/// submission had come on any of the device's queues for 20 ms.
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.
pub submissions_during_frees: u64,
}
/// No Metal counterpart: the live count of each kind of resource. Every one is zero once the
+4 -3
View File
@@ -640,9 +640,10 @@ impl Device {
/// in use: the device keeps a class's idle allocations while their bytes and those of its
/// allocations in use stay at or under the most bytes it had in use over the last 10 seconds,
/// and within an eighth of its memory type's heap, and frees the oldest past that, after
/// [`BlockMappings::unmap`] of each block kept in it.
/// The rule runs as blocks are taken and given back, never on a timer: a program that goes
/// quiet keeps its idle allocations until its next take or release.
/// [`BlockMappings::unmap`] of each block kept in it. It frees them one at a time, on the
/// block-maker thread, and only once no commit or submission has come on any of the device's
/// queues for 20 ms: a program that goes quiet gives its idle allocations back without a call
/// of its own.
///
/// Err: [`Refusal::OtherDevice`] for another device's block, whose handle is dropped all the
/// same.
+203 -56
View File
@@ -12,6 +12,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::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
@@ -36,6 +37,12 @@ impl Peaks {
pub(crate) fn most(&self) -> u64 {
self.0.iter().map(|&(_, bytes)| bytes).max().unwrap_or(0)
}
/// The second the oldest second recorded leaves the window, where one is recorded: until
/// then, [`most`](Self::most) does not fall.
pub(crate) fn falls(&self) -> Option<u64> {
(self.0.front()).map(|&(second, _)| second + WINDOW_SECS)
}
}
/// How many of a class's idle allocations of `idle` bytes, the oldest first, the idle rule frees:
@@ -89,6 +96,16 @@ const BASE_ALIGN: u64 = 2 << 20;
/// whatever room they leave in it.
const WINDOW_SECS: u64 = 10;
/// How long the device stays quiet, with no commit and no submission on any of its queues, before
/// the block-maker thread frees an idle allocation, in nanoseconds of
/// [`host_time`](crate::host_time): 20 ms. A driver may hold the process's submissions for the
/// whole of a `vkFreeMemory`: on the NVIDIA cards measured in Thunderbolt enclosures, freeing
/// host-visible memory takes about 1.1 ms per MiB and holds any submission for its length, where
/// an internal NVIDIA card frees 16 MiB in about 0.5 ms. So the thread frees one allocation at a
/// time, only in such a gap, and looks again after each; a submission that arrives during a free
/// waits for the rest of it.
const QUIET_NANOS: u64 = 20_000_000;
/// The share of the heap of a class's memory type its idle allocations stay within, whatever the
/// window holds: an eighth.
const IDLE_SHARE: u64 = 8;
@@ -315,6 +332,10 @@ struct Allocation {
/// When its last live block came back, in the pool's give-backs: the oldest idle allocation
/// is freed first.
emptied: u64,
/// A spilled allocation whose last block came back: no take lands in it, its bytes are not
/// the class's free bytes, and the idle rule frees it next, so the next allocation tries
/// device-local memory again.
retiring: bool,
}
/// The pool: every allocation of each class, and the blocks given back and kept for a take of
@@ -331,9 +352,10 @@ struct Allocation {
/// The idle rule never frees an allocation that the class's free bytes need to stay at or above
/// [`MAKE_BELOW`], so it does not free what the block-maker thread would make again.
///
/// The idle rule runs as a block is taken or given back, never on a timer: a program that goes
/// quiet keeps its idle allocations until its next take or release, or until the device is torn
/// down.
/// The idle rule runs on the block-maker thread as a block is taken or given back, and again when
/// the window's peak can fall or the device has been quiet for [`QUIET_NANOS`]: an idle
/// allocation it takes out is freed in a quiet gap, one at a time, so a program that goes quiet
/// gives its idle allocations back without a call of its own.
pub(crate) struct Pool {
state: Mutex<State>,
/// Signalled whenever the state changes, for the block-maker thread and for takers waiting
@@ -349,6 +371,19 @@ pub(crate) struct Pool {
granule: u64,
/// The idle rule's clock: seconds since the pool was made.
clock: Clock,
/// The [`host_time`](crate::host_time) of the last commit or submission on any of the
/// device's queues ([`Pool::worked`]).
worked: AtomicU64,
/// 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: the [`host_time`](crate::host_time) at which the block-maker thread
/// found the device quiet, for each idle allocation it freed.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
quiet_frees: Mutex<Vec<u64>>,
}
/// The idle rule's clock, which the device tests move on.
@@ -367,12 +402,33 @@ impl Clock {
}
}
fn seconds(&self) -> u64 {
fn elapsed(&self) -> Duration {
let elapsed: Duration = self.origin.elapsed();
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
let elapsed = elapsed + *lock(&self.skew);
elapsed.as_secs()
elapsed
}
fn seconds(&self) -> u64 {
self.elapsed().as_secs()
}
/// How long until the clock reads `second`.
fn until(&self, second: u64) -> Duration {
Duration::from_secs(second).saturating_sub(self.elapsed())
}
}
/// What the idle rule asks of a class.
enum Rule {
/// No idle allocation that the rule weighs.
Keep,
/// Idle allocations that the window's peak holds, until the pool's clock reads this second
/// at the latest.
KeepUntil(u64),
/// The allocation to free next: a retiring one, else the oldest idle one past the
/// window's peak or the class's cap.
Free(vk::DeviceMemory),
}
struct State {
@@ -451,6 +507,12 @@ impl Pool {
caps: heaps.map(|heap| heap / IDLE_SHARE),
granule: GRANULE.max(granularity.next_power_of_two()),
clock: Clock::new(),
worked: AtomicU64::new(0),
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)))]
quiet_frees: Mutex::new(Vec::new()),
}
}
@@ -464,6 +526,38 @@ impl Pool {
.unwrap_or_else(PoisonError::into_inner)
}
fn wait_for<'a>(
&self,
state: MutexGuard<'a, State>,
timeout: Duration,
) -> MutexGuard<'a, State> {
match self.changed.wait_timeout(state, timeout) {
Ok((state, _)) => state,
Err(poisoned) => poisoned.into_inner().0,
}
}
/// A commit or submission at `now` ([`host_time`](crate::host_time)) on one of the device's
/// queues: the block-maker thread frees no idle allocation until [`QUIET_NANOS`] after it.
pub(crate) fn worked(&self, now: u64) {
self.worked.fetch_max(now, Relaxed);
}
/// How long until the device has been quiet for [`QUIET_NANOS`] at `now`
/// ([`host_time`](crate::host_time)): zero once it has.
fn quiet_in(&self, now: u64) -> Duration {
let quiet = self.worked.load(Relaxed).saturating_add(QUIET_NANOS);
Duration::from_nanos(quiet.saturating_sub(now))
}
/// 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's free bytes are at least [`MAKE_BELOW`], so the
/// block-maker thread makes nothing for it (an allocation it made is counted once its fill's
/// submission completed).
@@ -478,10 +572,27 @@ impl Pool {
self.lock().kept[class.index()].len()
}
/// For the device tests: moves the idle rule's clock on by `by`.
/// For the device tests: moves the idle rule's clock on by `by`, and wakes the block-maker
/// thread to run the rule.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn advance_clock(&self, by: Duration) {
*lock(&self.clock.skew) += by;
let _state = self.lock();
self.changed.notify_all();
}
/// 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: the [`host_time`](crate::host_time) at which the block-maker thread
/// found the device quiet, for each idle allocation it freed so far.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn quiet_frees(&self) -> Vec<u64> {
lock(&self.quiet_frees).clone()
}
/// The length and alignment of a block for a take of `len` bytes: its buffer's size rounded
@@ -662,15 +773,19 @@ impl Pool {
state.idle_bytes[index] = idle;
}
/// The idle rule for `class`: takes out its oldest idle allocations while their bytes pass the
/// most bytes the class had in use over the last [`WINDOW_SECS`] seconds less its bytes in use
/// now, or the class's cap; each with its kept blocks, for the caller to free without the
/// lock. The newest idle allocations with free bytes that the class's free bytes need to reach
/// [`MAKE_BELOW`] are its reserve: the rule neither counts nor frees them.
fn trim(&self, state: &mut State, class: MemoryClass) -> Vec<(Allocation, Vec<Memory>)> {
/// The idle rule for `class`: its next allocation to free is a retiring one, a spilled one that
/// emptied, so the next allocation tries device-local memory again; else the oldest idle one
/// while the idle allocations' bytes pass the most bytes the class had in use over the last
/// [`WINDOW_SECS`] seconds less its bytes in use now, or the class's cap. The newest idle
/// allocations with free bytes that the class's free bytes need to reach [`MAKE_BELOW`] are
/// its reserve: the rule neither counts nor frees them.
fn rule(&self, state: &mut State, class: MemoryClass) -> Rule {
let index = class.index();
state.note(class, self.clock.seconds());
let allocations = &state.allocations[index];
if let Some(retiring) = (allocations.iter()).find(|allocation| allocation.retiring) {
return Rule::Free(retiring.memory);
}
let mut free: u64 = (allocations.iter())
.filter(|allocation| allocation.live > 0)
.map(|allocation| allocation.free.bytes())
@@ -692,13 +807,16 @@ impl Pool {
});
idle.reverse();
let lens: Vec<u64> = idle.iter().map(|&(_, _, len, _)| len).collect();
let peak = state.peaks[index].most();
let surplus = surplus(&lens, peak, state.in_use(class), self.caps[index]);
let gone = (idle.iter().take(surplus))
.filter_map(|&(_, memory, ..)| state.take_out(class, memory))
.collect();
self.settle(state, class);
gone
let peaks = &state.peaks[index];
match idle.first() {
Some(&(_, memory, ..))
if surplus(&lens, peaks.most(), state.in_use(class), self.caps[index]) > 0 =>
{
Rule::Free(memory)
}
Some(_) => peaks.falls().map_or(Rule::Keep, Rule::KeepUntil),
None => Rule::Keep,
}
}
/// Records a block as handed to the consumer, so that its hook runs before its bytes are
@@ -766,9 +884,10 @@ impl State {
self.unkeep[class.index()]
}
/// The bytes of the free ranges of the class's allocations.
/// The bytes of the free ranges of the class's allocations, but those retiring.
fn free(&self, class: MemoryClass) -> u64 {
(self.allocations[class.index()].iter())
.filter(|allocation| !allocation.retiring)
.map(|allocation| allocation.free.bytes())
.sum()
}
@@ -779,9 +898,12 @@ impl State {
}
/// Reserves `len` bytes at a multiple of `align` in the first allocation of `class` with such
/// a free range, counting a block live there.
/// a free range, counting a block live there; none in a retiring one.
fn fit(&mut self, class: MemoryClass, len: u64, align: u64) -> Option<Carve> {
(self.allocations[class.index()].iter_mut()).find_map(|allocation| {
if allocation.retiring {
return None;
}
let base = allocation.free.take(len, align)?;
allocation.live += 1;
Some(allocation.carve(base))
@@ -887,9 +1009,12 @@ pub(crate) fn stock(core: &Core) {
/// The block-maker thread, until the device's teardown stops it. Off every caller's path, in
/// order: it gives a class's kept blocks' bytes back to their allocations where a take asked,
/// after the consumer's hook; it keeps each block given back for a take of its length (or gives
/// its bytes back, after the hook, where its allocation spilled), then
/// runs the class's idle rule, freeing what it takes out after the hook of each kept block in it;
/// and it makes an allocation of a class whose free bytes are fewer than [`MAKE_BELOW`].
/// its bytes back, after the hook, where its allocation spilled); it makes an allocation of a
/// class whose free bytes are fewer than [`MAKE_BELOW`]; and once the device has been quiet for
/// [`QUIET_NANOS`], it frees the next allocation the idle rule takes out, after the hook of each
/// kept block in it, one at a time. It sleeps until the next change, the end of the quiet time
/// where the rule has an allocation to free, or the second the window's peak can fall where it
/// keeps idle allocations.
pub(crate) fn run(core: Arc<Core>) {
ON_MAKER.set(true);
let pool = &core.pool;
@@ -920,8 +1045,8 @@ pub(crate) fn run(core: Arc<Core>) {
if let Some(memory) = state.returned.pop_front() {
drop(state);
// A block of a spilled allocation is not kept: its bytes go back to its allocation,
// and a spilled allocation that empties is freed, so the next tries device-local
// memory again.
// and a spilled allocation that empties is the idle rule's next to free, so the next
// tries device-local memory again.
let kept = !memory.spilled;
if !kept {
retire(&core, &memory);
@@ -933,7 +1058,6 @@ pub(crate) fn run(core: Arc<Core>) {
state.give_backs += 1;
state.failed[class.index()] = false;
let emptied = state.give_backs;
let mut spilled = None;
if let Some(allocation) = state.find(class, memory.memory) {
allocation.live -= 1;
if !kept {
@@ -941,40 +1065,14 @@ pub(crate) fn run(core: Arc<Core>) {
}
if allocation.live == 0 {
allocation.emptied = emptied;
spilled = allocation.spilled.then_some(allocation.memory);
allocation.retiring = allocation.spilled;
}
}
if kept {
state.kept[class.index()].push(memory);
}
let mut gone = pool.trim(&mut state, class);
if let Some(spilled) = spilled.and_then(|memory| state.take_out(class, memory)) {
gone.push(spilled);
pool.settle(&mut state, class);
}
pool.settle(&mut state, class);
pool.changed.notify_all();
drop(state);
for (allocation, kept) in gone {
for memory in &kept {
retire(&core, memory);
}
free_allocation(&core, allocation);
}
state = pool.lock();
continue;
}
let gone: Vec<(Allocation, Vec<Memory>)> = (MemoryClass::ALL.into_iter())
.flat_map(|class| pool.trim(&mut state, class))
.collect();
if !gone.is_empty() {
drop(state);
for (allocation, kept) in gone {
for memory in &kept {
retire(&core, memory);
}
free_allocation(&core, allocation);
}
state = pool.lock();
continue;
}
let wanted = (MemoryClass::ALL.into_iter())
@@ -995,7 +1093,37 @@ pub(crate) fn run(core: Arc<Core>) {
pool.changed.notify_all();
continue;
}
state = pool.wait(state);
// The idle rule, both classes: the next allocation to free, once the device is quiet.
let quiet = crate::host_time();
let quiet_in = pool.quiet_in(quiet);
let mut wake: Option<Duration> = None;
let mut gone = None;
for class in MemoryClass::ALL {
let due = match pool.rule(&mut state, class) {
Rule::Free(memory) if quiet_in.is_zero() => {
gone = state.take_out(class, memory);
pool.settle(&mut state, class);
break;
}
Rule::Free(_) => quiet_in,
Rule::KeepUntil(second) => pool.clock.until(second),
Rule::Keep => continue,
};
wake = Some(wake.map_or(due, |wake| wake.min(due)));
}
if let Some((allocation, kept)) = gone {
pool.changed.notify_all();
drop(state);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
lock(&pool.quiet_frees).push(quiet);
free_idle(&core, allocation, &kept);
state = pool.lock();
continue;
}
state = match wake {
Some(timeout) => pool.wait_for(state, timeout),
None => pool.wait(state),
};
}
}
@@ -1120,6 +1248,7 @@ fn make_allocation(core: &Core, class: MemoryClass, len: u64) -> Result<Allocati
free: Ranges::new(len),
live: 0,
emptied: 0,
retiring: false,
};
if class == MemoryClass::Shared {
// SAFETY: the memory type is host-visible, and the memory is not mapped.
@@ -1192,6 +1321,24 @@ fn retire(core: &Core, memory: &Memory) {
unsafe { core.device.destroy_buffer(memory.buffer, None) };
}
/// On the block-maker thread: frees an allocation the idle rule took out once the device was
/// quiet, after the hook of each block kept in it. The submissions made during its
/// `vkFreeMemory` are counted.
fn free_idle(core: &Core, allocation: Allocation, kept: &[Memory]) {
for memory in kept {
retire(core, memory);
}
let pool = &core.pool;
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);
}
/// Frees an allocation, whose blocks are all retired. Freeing the memory also unmaps it.
fn free_allocation(core: &Core, allocation: Allocation) {
// SAFETY: no buffer is bound to it any more, and no GPU work uses it.
+4
View File
@@ -1502,6 +1502,10 @@ fn submit(core: &Core, value: u64, upload: Option<Upload>, batch: Batch) {
.collect();
if ok {
let queue = lock(&core.queues.runtime);
core.pool.worked(crate::host_time());
if core.pool.freeing() {
core.counters.count(Metric::SubmissionsDuringFrees);
}
// 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.
+153 -28
View File
@@ -1053,11 +1053,13 @@ mod on_device {
/// Idle allocations follow the window's peak down: four Shared blocks of 16 MiB taken beside
/// a small one, each with an allocation of its own, and given back are kept, their
/// allocations idle, while the most bytes in use over the last 10 seconds hold them, through a
/// Private take and give-back 5 seconds on. Once the clock has moved 11 seconds, the small
/// block's give-back leaves its allocation in the window, and its allocation is the reserve
/// that keeps 8 MiB free: the three oldest idle allocations are freed after the hook of the
/// block kept in each, on the block-maker thread. 11 seconds later, with the Shared class
/// quiet, the next Private take and give-back frees the fourth; the reserve stays.
/// Private take and give-back and the small block's give-back 5 seconds on. Once the clock has
/// moved 11 seconds, the small block's allocation is the reserve that keeps 8 MiB free, and the
/// window holds one allocation more than the bytes in use: the three oldest idle allocations
/// are freed, one at a time, after the hook of the block kept in each, on the block-maker
/// thread. Five seconds later, with no take or give-back, the window's peak falls to nothing
/// and the fourth is freed; the reserve stays. Nothing commits, so the device is quiet
/// throughout.
#[test]
fn every_device_frees_idle_allocations_as_the_window_s_peak_falls() {
let instance = Instance::new(&[]).expect("an instance at the floor");
@@ -1079,8 +1081,7 @@ mod on_device {
.collect();
let four: Vec<u32> = taken.iter().map(|block| block.id.get()).collect();
let mut handed: Vec<BlockId> = taken.iter().map(|block| block.id).collect();
let small_id = small.id;
handed.push(small_id);
handed.push(small.id);
for block in taken {
device.release_block(block).expect("a release");
}
@@ -1091,29 +1092,29 @@ mod on_device {
"{name}: four idle allocations"
);
// Five seconds on, a Private take and give-back runs the rule for both classes: the
// Five seconds on, a Private take and give-back, and the small block's give-back: the
// window still holds the four.
core.pool.advance_clock(Duration::from_secs(5));
let nudge = (device.take_block(MemoryClass::Private, 1))
.unwrap_or_else(|error| panic!("{name}: a Private block: {error}"));
let nudge_id = nudge.id;
handed.push(nudge_id);
handed.push(nudge.id);
device.release_block(nudge).expect("a release");
wait_until("the Private block kept", || {
device.release_block(small).expect("a release");
wait_until("the Private and small blocks kept", || {
core.pool.kept(MemoryClass::Private) == 1
&& core.pool.kept(MemoryClass::Shared) == 5
});
assert_eq!(
(counters.gauges().shared_idle_bytes, hook.unmapped().len()),
(4 * len, 0),
"{name}: the four within the window"
(5 * len, 0),
"{name}: the four and the small block's within the window"
);
// Eleven seconds on: the small block's give-back frees the three oldest. The gauge of
// allocations falls after each one's free, which follows its kept block's hook and
// the idle gauge's fall: once it reads the zero source, the reserve, the fourth and
// the Private allocation, the three hooks and the idle gauge are final.
// Eleven seconds on: the three oldest are freed. The gauge of allocations falls after
// each one's free, which follows its kept block's hook and the idle gauge's fall: once
// it reads the zero source, the reserve, the fourth and the Private allocation, the
// three hooks and the idle gauge are final.
core.pool.advance_clock(Duration::from_secs(6));
device.release_block(small).expect("a release");
wait_until("three idle Shared allocations freed", || {
counters.gauges().blocks == ZERO_SOURCE + 3
});
@@ -1128,23 +1129,24 @@ mod on_device {
assert_eq!(unmapped.first, None, "{name}: no block recorded");
}
// Eleven seconds later, the Shared class quiet: a Private take of the kept block's
// length and its give-back free the fourth.
core.pool.advance_clock(Duration::from_secs(11));
let again = (device.take_block(MemoryClass::Private, 1))
.unwrap_or_else(|error| panic!("{name}: a Private block: {error}"));
assert_eq!(again.id, nudge_id, "{name}: the kept Private block");
device.release_block(again).expect("a release");
wait_until("the fourth freed", || hook.unmapped().len() == 4);
wait_until("the idle gauge", || {
counters.gauges().shared_idle_bytes == len
// Five seconds later, with no take or give-back: the window's peak is gone, and the
// fourth is freed.
core.pool.advance_clock(Duration::from_secs(5));
wait_until("the fourth freed", || {
counters.gauges().blocks == ZERO_SOURCE + 2
});
assert_eq!(
(hook.unmapped().len(), counters.gauges().shared_idle_bytes),
(4, len),
"{name}: the fourth unmapped, the reserve idle"
);
assert_eq!(hook.unmapped()[3].block, four[3], "{name}: the fourth");
assert_eq!(
core.pool.kept(MemoryClass::Shared),
1,
"{name}: the small block, kept in the reserve"
);
assert_eq!(counters.metrics().allocations_freed, 4, "{name}: the frees");
drop(device);
assert_eq!(
counters.gauges(),
@@ -1159,6 +1161,129 @@ mod on_device {
}
}
/// Idle allocations are freed only in quiet gaps, and a submission during a free is counted.
/// Four Shared blocks of 16 MiB are given back while command buffers are committed every
/// 2 ms; the clock moves past the window, so the idle rule frees all four but the reserve, yet
/// every free begins at least 20 ms after the last commit before it, whatever the test
/// thread's own gaps were. Once the commits stop, the idle allocations are freed. Then the
/// free of one of two more idle allocations is held open: a command buffer committed with a
/// fill during it is counted as a submission during a free, and one committed once both are
/// freed is not.
#[test]
fn every_device_frees_idle_allocations_in_quiet_gaps() {
const QUIET: u64 = 20_000_000;
let instance = Instance::new(&[]).expect("an instance at the floor");
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 queue = device.new_command_queue(1).expect("a queue");
let len = MemoryClass::Shared.block_len();
let commit = || {
let command_buffer = queue.command_buffer().expect("a command buffer");
let before = crate::host_time();
command_buffer.commit().expect("a commit");
(before, crate::host_time())
};
let give_back = |count: usize| {
let taken: Vec<Block> = (0..count)
.map(|_| {
(device.take_block(MemoryClass::Shared, len))
.unwrap_or_else(|error| panic!("{name}: a block: {error}"))
})
.collect();
for block in taken {
device.release_block(block).expect("a release");
}
wait_until("the blocks kept", || {
core.pool.kept(MemoryClass::Shared) == count
});
};
give_back(4);
let mut commits = vec![commit()];
// Commits every 2 ms, the four idle allocations past the window from the third on.
for step in 0..150 {
if step == 2 {
core.pool.advance_clock(Duration::from_secs(11));
}
thread::sleep(Duration::from_millis(2));
commits.push(commit());
}
let busy_frees = counters.metrics().allocations_freed;
// The count rises once each free has returned.
wait_until("the idle allocations freed once quiet", || {
counters.metrics().allocations_freed == 4 && !core.pool.freeing()
});
let quiet_frees = core.pool.quiet_frees();
for (index, &quiet) in quiet_frees.iter().enumerate() {
for &(before, after) in &commits {
assert!(
after > quiet || before + QUIET <= quiet,
"{name}: free {index} began {} us after a commit",
quiet.saturating_sub(before) / 1000
);
}
}
let gaps = (commits.windows(2))
.filter(|pair| pair[1].0 - pair[0].1 >= QUIET)
.count();
println!(
"memory: {name}: {} frees in quiet gaps, {busy_frees} of them while the test \
committed, with {gaps} gaps of 20 ms or more between its commits",
quiet_frees.len()
);
// A free held open: a submission during it is counted, one after it is not.
let target = (device.take_block(MemoryClass::Shared, 4096))
.unwrap_or_else(|error| panic!("{name}: a block: {error}"));
let buffer = (device.new_buffer(target.id, 0, 256, None)).expect("a buffer");
let fill = |buffer: &crate::Buffer| {
let command_buffer = queue.command_buffer().expect("a command buffer");
let to = vk_buffer(&device, target.id);
command_buffer
.record_for_test(&[buffer], |device, command| {
// SAFETY: the command buffer is recording; the block is held.
unsafe { device.cmd_fill_buffer(command, to, 0, 256, 7) };
})
.expect("a fill");
command_buffer.commit().expect("a commit");
command_buffer.wait_until_completed();
};
let freed = counters.metrics().allocations_freed;
core.pool.hold_frees(true);
give_back(2);
core.pool.advance_clock(Duration::from_secs(11));
wait_until("a free held open", || core.pool.freeing());
fill(&buffer);
assert_eq!(
counters.metrics().submissions_during_frees,
1,
"{name}: the submission during the free"
);
core.pool.hold_frees(false);
wait_until("both freed", || {
counters.metrics().allocations_freed == freed + 2 && !core.pool.freeing()
});
fill(&buffer);
assert_eq!(
counters.metrics().submissions_during_frees,
1,
"{name}: the submission after the free"
);
drop((buffer, target, queue));
drop(device);
wait_until("the teardown", || counters.gauges() == Gauges::default());
println!(
"memory: {name}: frees only in quiet gaps; metrics {:?}",
counters.metrics()
);
}
}
/// Seeded takes and releases of mixed lengths across both classes, with the block-maker
/// thread running: every take and release returns within a minute, every block is unmapped
/// once by the end, on the block-maker thread or the dropping one, and every gauge reads zero
@@ -1519,6 +1519,8 @@ impl Backend for NewRuntime {
metrics.consumer_allocation_nanos,
),
("maker_allocation_nanos", metrics.maker_allocation_nanos),
("allocations_freed", metrics.allocations_freed),
("submissions_during_frees", metrics.submissions_during_frees),
(
"dispatches_without_effects",
metrics.dispatches_without_effects,
@@ -2301,6 +2301,7 @@ field metal2vulkan-rt::HeapRange.offset pub offset: u64
field metal2vulkan-rt::IndexGrant.class pub class: IndexClass
field metal2vulkan-rt::IndexGrant.count pub count: u32
field metal2vulkan-rt::IndexGrant.first pub first: u32
field metal2vulkan-rt::Metrics.allocations_freed pub allocations_freed: u64
field metal2vulkan-rt::Metrics.barriers pub barriers: u64
field metal2vulkan-rt::Metrics.block_bytes_made pub block_bytes_made: u64
field metal2vulkan-rt::Metrics.blocks_made pub blocks_made: u64
@@ -2326,6 +2327,7 @@ field metal2vulkan-rt::Metrics.passes pub passes: u64
field metal2vulkan-rt::Metrics.pipelines_created pub pipelines_created: u64
field metal2vulkan-rt::Metrics.ring_writes pub ring_writes: u64
field metal2vulkan-rt::Metrics.submissions pub submissions: u64
field metal2vulkan-rt::Metrics.submissions_during_frees pub submissions_during_frees: u64
field metal2vulkan-rt::Metrics.submit_infos pub submit_infos: u64
field metal2vulkan-rt::Metrics.synchronizations pub synchronizations: u64
field metal2vulkan-rt::Metrics.translations pub translations: u64
Can't render this file because it is too large.