rt: given-back dedicated blocks are kept idle with the pooled ones, up to a byte bound per class
A block given back, pooled or dedicated, is now zeroed by the block-maker thread and kept as its class's latest idle block. It keeps its number, address and mapping, so the consumer's mapping stays too. Each class keeps at most a bound of idle bytes, MemoryClass::idle_bound: 256 MiB Shared and 128 MiB Private. The class's ready block (its latest idle pooled block) is a reserve outside that bound. Past the bound, the oldest kept block is freed through BlockMappings::unmap, whether it is pooled or dedicated. A block longer than the bound, or a spilled one, is freed at once. This byte bound replaces the count IDLE_MAX = 2. A take past the pooled length first takes the shortest kept dedicated block that it fits and fills at least half of (memory::fits), and only allocates when none does. Each reuse counts in Metrics::dedicated_blocks_reused. Gauges::shared_idle_bytes and private_idle_bytes count what is kept, the ready block included, and read zero after teardown. Why: a program that makes and releases large buffers frame after frame paid a fresh vkAllocateMemory each time, and the driver's hold on the device's other calls with it. On an RTX 3090 (NVIDIA's Linux driver, probe ecb66a34eb, job 44126) a 32.6 MB Managed buffer's dedicated Shared block cost 8.3-10.8 ms in the call and held submissions for up to 7-19 ms. Old took 1.6-1.8 ms for its second such buffer, a range in a 64 MiB block it already had. Under the hold, only the first pair pays. Probe 4b48aa5c9b (jobs 44208-44210) made the pair, gave it back and made it again. The second pair took 0.01-0.02 ms with no submission held (longest round trip 0.10-0.19 ms, against 0.09-0.11 median), and dedicated_blocks_reused went 0 to 2 with no block made. That held on the RTX 3090 and the RTX 2080. On the RX 550 the first pair took 3.8-4.6 ms and the second 0.01 ms. On that probe a fresh block's create, bind, address and map took 18-75 us, the allocation 6.0-11.1 ms and the zeroing 1.2-1.7 ms. Under the hold the zeroing runs on the block-maker thread at give-back. Tests: a_kept_dedicated_block_serves_a_request_it_fits_and_that_fills_half_of_it (the rule). every_device_keeps_given_back_dedicated_blocks_for_requests_they_fit: of three 100 MiB Shared blocks given back, two are kept beside the ready block and the oldest is freed through the hook. A 60 MiB request takes a kept one, zeroed, as it was, with nothing made; 40 MiB and 101 MiB requests make their own. A dedicated Private block is kept beside the Private ready block and taken again. Gauges read zero after teardown. every_device_keeps_idle_blocks_up_to_the_bound_and_frees_the_oldest replaces the two-block test: 18 Shared blocks given back leave 16 kept beside the ready one, and the oldest is freed. The hand-out test's dedicated block is past the bound, so it is still freed on release. API table re-blessed.
This commit is contained in:
1 parent
32d511d17d
commit
208887e13a
6 files changed
+363
-74
No files matched your search
@@ -117,9 +117,16 @@ in its memory.
|
||||
Shared block is zeroed through its mapping, which also makes every page resident before anyone
|
||||
holds it; a Private block by a GPU fill.
|
||||
- `Device::release_block` gives a block back. It takes effect once no buffer of the block remains.
|
||||
A pooled block is then zeroed and kept, with the same number, address and mapping, while its
|
||||
class has fewer than two idle blocks; the block-maker thread frees the rest. A dedicated block is
|
||||
always freed. Block numbers are never reused during the device's life.
|
||||
The block-maker thread then zeroes it and keeps it idle, pooled or dedicated, with the same
|
||||
number, address and mapping, as its class's latest idle block. Each class keeps at most a bound
|
||||
of idle bytes, 256 MiB of Shared memory and 128 MiB of Private, beside its ready block, which is
|
||||
a reserve outside the bound: past it the oldest kept block is freed (after
|
||||
`BlockMappings::unmap`), and a block longer than the bound is freed at once. A take
|
||||
past the pooled length takes a kept dedicated block that it fits and fills at least half of
|
||||
(`Metrics::dedicated_blocks_reused`) before it allocates, so a program that makes and releases
|
||||
large buffers frame after frame pays the allocation, and the driver's hold on the device's other
|
||||
calls that comes with it, once. `Gauges::shared_idle_bytes` and `Gauges::private_idle_bytes`
|
||||
count what is kept. Block numbers are never reused during the device's life.
|
||||
- `Device::new_buffer(block, offset, length, zeroed)` makes a `Buffer`: a view of the range, with
|
||||
no Vulkan object of its own. Its `gpu_address` is the block's address plus the offset, and its
|
||||
`contents` the block's mapping plus the offset, or `None` in a Private block. `zeroed` zeroes the
|
||||
|
||||
@@ -17,6 +17,8 @@ pub(crate) enum Metric {
|
||||
PipelinesCreated,
|
||||
/// [`Metrics::blocks_made`].
|
||||
BlocksMade,
|
||||
/// [`Metrics::dedicated_blocks_reused`].
|
||||
DedicatedBlocksReused,
|
||||
/// [`Metrics::dispatches_without_effects`].
|
||||
DispatchesWithoutEffects,
|
||||
/// [`Metrics::translations`].
|
||||
@@ -66,6 +68,10 @@ pub(crate) enum Gauge {
|
||||
DeviceSamplers,
|
||||
/// [`Gauges::spilled_bytes`].
|
||||
SpilledBytes,
|
||||
/// [`Gauges::shared_idle_bytes`].
|
||||
SharedIdleBytes,
|
||||
/// [`Gauges::private_idle_bytes`].
|
||||
PrivateIdleBytes,
|
||||
}
|
||||
|
||||
/// No Metal counterpart: a device's counters ([`Device::counters`](crate::Device::counters)).
|
||||
@@ -91,6 +97,7 @@ struct Atomics {
|
||||
first_use_wait_max_nanos: AtomicU64,
|
||||
blocks_made: AtomicU64,
|
||||
dispatches_without_effects: AtomicU64,
|
||||
dedicated_blocks_reused: AtomicU64,
|
||||
translations: AtomicU64,
|
||||
translations_loaded: AtomicU64,
|
||||
ring_writes: AtomicU64,
|
||||
@@ -114,6 +121,8 @@ struct Atomics {
|
||||
events: AtomicU64,
|
||||
device_samplers: AtomicU64,
|
||||
spilled_bytes: AtomicU64,
|
||||
shared_idle_bytes: AtomicU64,
|
||||
private_idle_bytes: AtomicU64,
|
||||
/// Segment ends whose barrier reaches the host, for the tests.
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
host_reaches: AtomicU64,
|
||||
@@ -139,6 +148,7 @@ impl Counters {
|
||||
Metric::Barriers => &a.barriers,
|
||||
Metric::PipelinesCreated => &a.pipelines_created,
|
||||
Metric::BlocksMade => &a.blocks_made,
|
||||
Metric::DedicatedBlocksReused => &a.dedicated_blocks_reused,
|
||||
Metric::DispatchesWithoutEffects => &a.dispatches_without_effects,
|
||||
Metric::Translations => &a.translations,
|
||||
Metric::TranslationsLoaded => &a.translations_loaded,
|
||||
@@ -222,7 +232,7 @@ impl Counters {
|
||||
self.gauge(gauge).fetch_sub(1, Relaxed);
|
||||
}
|
||||
|
||||
/// `amount` more of `gauge`'s kind: bytes, for [`Gauge::SpilledBytes`].
|
||||
/// `amount` more of `gauge`'s kind: bytes, for [`Gauge::SpilledBytes`] and the idle bytes.
|
||||
pub(crate) fn rise_by(&self, gauge: Gauge, amount: u64) {
|
||||
self.gauge(gauge).fetch_add(amount, Relaxed);
|
||||
}
|
||||
@@ -247,6 +257,8 @@ impl Counters {
|
||||
Gauge::Events => &a.events,
|
||||
Gauge::DeviceSamplers => &a.device_samplers,
|
||||
Gauge::SpilledBytes => &a.spilled_bytes,
|
||||
Gauge::SharedIdleBytes => &a.shared_idle_bytes,
|
||||
Gauge::PrivateIdleBytes => &a.private_idle_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,6 +275,7 @@ impl Counters {
|
||||
first_use_wait_nanos: a.first_use_wait_nanos.load(Relaxed),
|
||||
first_use_wait_max_nanos: a.first_use_wait_max_nanos.load(Relaxed),
|
||||
blocks_made: a.blocks_made.load(Relaxed),
|
||||
dedicated_blocks_reused: a.dedicated_blocks_reused.load(Relaxed),
|
||||
dispatches_without_effects: a.dispatches_without_effects.load(Relaxed),
|
||||
translations: a.translations.load(Relaxed),
|
||||
translations_loaded: a.translations_loaded.load(Relaxed),
|
||||
@@ -295,6 +308,8 @@ impl Counters {
|
||||
events: a.events.load(Relaxed),
|
||||
device_samplers: a.device_samplers.load(Relaxed),
|
||||
spilled_bytes: a.spilled_bytes.load(Relaxed),
|
||||
shared_idle_bytes: a.shared_idle_bytes.load(Relaxed),
|
||||
private_idle_bytes: a.private_idle_bytes.load(Relaxed),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -333,6 +348,10 @@ pub struct Metrics {
|
||||
/// `VkDeviceMemory` allocations made: pooled blocks (the texture blocks among them) and
|
||||
/// dedicated ones, the zero source and the parameter ring's blocks.
|
||||
pub blocks_made: u64,
|
||||
/// Dedicated blocks taken again: a request past its class's pooled length that took a
|
||||
/// dedicated block given back and kept idle, which it fits and fills at least half of,
|
||||
/// instead of a new allocation.
|
||||
pub dedicated_blocks_reused: u64,
|
||||
/// Dispatches of a kernel that writes no memory (`PipelineInterface::writes_memory`),
|
||||
/// direct and indirect: each was checked as Metal checks it, and nothing was recorded, bound
|
||||
/// or read for it, as it has no effect a program can observe.
|
||||
@@ -422,4 +441,10 @@ pub struct Gauges {
|
||||
/// was out of memory: blocks whose [`BlockInfo::device_local`](crate::BlockInfo) is false and
|
||||
/// textures' allocations of their own.
|
||||
pub spilled_bytes: u64,
|
||||
/// Bytes of idle Shared blocks the pool keeps, pooled and dedicated, zeroed, that no one
|
||||
/// holds: the ready block and at most the class's bound of 256 MiB beside it.
|
||||
pub shared_idle_bytes: u64,
|
||||
/// Bytes of idle Private blocks the pool keeps, pooled and dedicated, zeroed, that no one
|
||||
/// holds: the ready block and at most the class's bound of 128 MiB beside it.
|
||||
pub private_idle_bytes: u64,
|
||||
}
|
||||
@@ -426,6 +426,7 @@ impl Device {
|
||||
.fold(0, |bits, (index, _)| bits | 1 << index);
|
||||
|
||||
let work = Work::new(counters.clone());
|
||||
let pool = Pool::new(options.block_mappings, counters.clone());
|
||||
let core = Arc::new(Core {
|
||||
instance,
|
||||
physical: raw,
|
||||
@@ -445,7 +446,7 @@ impl Device {
|
||||
granularity,
|
||||
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
|
||||
fail_private: std::sync::atomic::AtomicU32::new(0),
|
||||
pool: Pool::new(options.block_mappings),
|
||||
pool,
|
||||
places: Places::new(),
|
||||
copies: Places::new(),
|
||||
filler,
|
||||
@@ -553,8 +554,10 @@ impl Device {
|
||||
/// For `len` up to the class's [`MemoryClass::block_len`] (16 MiB Shared, 64 MiB Private) it
|
||||
/// is a pooled block of that length. The device's making makes one of each class, and the
|
||||
/// block-maker thread makes the next ones ahead of need, off every caller's path, so this
|
||||
/// call waits only when no block of the class is ready. Past it, it is a dedicated block,
|
||||
/// made in this call.
|
||||
/// call waits only when no block of the class is ready. Past it, it is a dedicated block of
|
||||
/// `len` rounded up to 64 KiB: one given back earlier and kept idle that it fits and fills at
|
||||
/// least half of ([`Metrics::dedicated_blocks_reused`](crate::Metrics::dedicated_blocks_reused)),
|
||||
/// with that block's number, address and mapping, or else one made in this call.
|
||||
///
|
||||
/// Every block reads zero, as Metal's new buffers do, whether new or taken again: a Shared
|
||||
/// block is zeroed through its mapping, which also makes each page resident before the block
|
||||
@@ -615,9 +618,12 @@ impl Device {
|
||||
/// No Metal counterpart: gives a block back.
|
||||
///
|
||||
/// It takes effect once no [`Buffer`](crate::Buffer) of the block remains and every command
|
||||
/// buffer that used it has retired. A pooled block is then zeroed and kept ready, with the same number, address and mapping, while its class has
|
||||
/// fewer than two idle; otherwise the block-maker thread frees it, after
|
||||
/// [`BlockMappings::unmap`]. A dedicated block is always freed that way.
|
||||
/// buffer that used it has retired. The block-maker thread then zeroes it and keeps it idle,
|
||||
/// pooled or dedicated, with the same number, address and mapping, freeing the class's oldest
|
||||
/// kept blocks past its bound (256 MiB Shared, 128 MiB Private, beside the ready block) after
|
||||
/// [`BlockMappings::unmap`], and at once a block longer than the bound. A kept dedicated
|
||||
/// block serves a later [`take_block`](Device::take_block) past the pooled length that it
|
||||
/// fits and that fills at least half of it.
|
||||
///
|
||||
/// Err: [`Error::NoSuchBlock`] for a block the consumer does not hold.
|
||||
pub fn release_block(&self, block: BlockId) -> Result<(), Error> {
|
||||
@@ -1016,17 +1022,20 @@ impl Core {
|
||||
self.device_local & (1 << self.memory_types.shared) != 0
|
||||
}
|
||||
|
||||
/// A block of `class` for `len` bytes: a pooled one up to the class's block length, else a dedicated one
|
||||
/// of `len` rounded up to 64 KiB, made in the call.
|
||||
/// A block of `class` for `len` bytes: a pooled one up to the class's block length, else a
|
||||
/// dedicated one of `len` rounded up to 64 KiB: an idle one the pool kept that [`memory::fits`]
|
||||
/// it, or one made in the call.
|
||||
///
|
||||
/// Err: what [`Pool::take`] and [`memory::make`] return;
|
||||
/// [`Limit::BlockLen`](crate::Limit::BlockLen) past the device's longest block.
|
||||
pub(crate) fn take_memory(&self, class: MemoryClass, len: u64) -> Result<Memory, Error> {
|
||||
if len <= class.block_len() {
|
||||
self.pool.take(class)
|
||||
} else {
|
||||
let len = memory::dedicated_len(len, self.max_block_len)?;
|
||||
memory::make(self, class, len, self.pool.number()?, false)
|
||||
return self.pool.take(class);
|
||||
}
|
||||
let len = memory::dedicated_len(len, self.max_block_len)?;
|
||||
match self.pool.take_held(class, len) {
|
||||
Some(memory) => Ok(memory),
|
||||
None => memory::make(self, class, len, self.pool.number()?, false),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,9 +14,6 @@ use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
/// ready after it.
|
||||
const READY: usize = 1;
|
||||
|
||||
/// The most idle blocks of a class the pool keeps. A block released past them is freed.
|
||||
const IDLE_MAX: usize = 2;
|
||||
|
||||
/// A dedicated block's length is the length asked for, rounded up to this.
|
||||
const DEDICATED_GRANULE: u64 = 64 << 10;
|
||||
|
||||
@@ -55,6 +52,29 @@ impl MemoryClass {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most bytes of the class's kept idle blocks, pooled and dedicated together: 256 MiB of
|
||||
/// Shared memory, 128 MiB of Private. The class's ready block, its latest idle pooled one, is
|
||||
/// a reserve outside the bound. A block given back is zeroed and kept as the class's latest
|
||||
/// idle block; while the kept blocks pass the bound, the oldest is freed. A dedicated block so
|
||||
/// kept serves a later request it fits and that fills at least half of it
|
||||
/// ([`Pool::take_held`]), with no allocation: a program that makes and releases large buffers
|
||||
/// frame after frame pays the driver's allocation, and the hold on the device's other calls
|
||||
/// that comes with it, once.
|
||||
pub(crate) fn idle_bound(self) -> u64 {
|
||||
match self {
|
||||
MemoryClass::Private => 128 << 20,
|
||||
MemoryClass::Shared => 256 << 20,
|
||||
}
|
||||
}
|
||||
|
||||
/// The gauge of the class's idle bytes.
|
||||
fn idle_gauge(self) -> Gauge {
|
||||
match self {
|
||||
MemoryClass::Private => Gauge::PrivateIdleBytes,
|
||||
MemoryClass::Shared => Gauge::SharedIdleBytes,
|
||||
}
|
||||
}
|
||||
|
||||
fn index(self) -> usize {
|
||||
match self {
|
||||
MemoryClass::Private => 0,
|
||||
@@ -232,10 +252,20 @@ pub(crate) struct Pool {
|
||||
/// on it.
|
||||
changed: Condvar,
|
||||
mappings: Option<Arc<dyn BlockMappings>>,
|
||||
/// The device's counters: the idle bytes and the dedicated blocks taken again.
|
||||
counters: Counters,
|
||||
}
|
||||
|
||||
/// Whether a dedicated block of `held` bytes serves a dedicated request of `want`: it fits, and
|
||||
/// the request fills at least half of it.
|
||||
pub(crate) fn fits(held: u64, want: u64) -> bool {
|
||||
held >= want && want.saturating_mul(2) >= held
|
||||
}
|
||||
|
||||
struct State {
|
||||
/// Per class, zeroed blocks no one holds, the latest last.
|
||||
/// Per class, zeroed blocks no one holds, pooled and dedicated, the oldest first: the ready
|
||||
/// block (the latest pooled one) and at most the class's [`MemoryClass::idle_bound`] bytes
|
||||
/// beside it.
|
||||
idle: [Vec<Memory>; 2],
|
||||
/// Blocks given back, for the block-maker thread.
|
||||
returned: Vec<Memory>,
|
||||
@@ -251,7 +281,7 @@ struct State {
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
pub(crate) fn new(mappings: Option<Arc<dyn BlockMappings>>) -> Pool {
|
||||
pub(crate) fn new(mappings: Option<Arc<dyn BlockMappings>>, counters: Counters) -> Pool {
|
||||
Pool {
|
||||
state: Mutex::new(State {
|
||||
idle: [Vec::new(), Vec::new()],
|
||||
@@ -264,6 +294,7 @@ impl Pool {
|
||||
}),
|
||||
changed: Condvar::new(),
|
||||
mappings,
|
||||
counters,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,7 +329,9 @@ impl Pool {
|
||||
if state.stop {
|
||||
return Err(Error::Quiesced);
|
||||
}
|
||||
if let Some(memory) = state.idle[index].pop() {
|
||||
if let Some(at) = state.idle[index].iter().rposition(Memory::pooled) {
|
||||
let memory = state.idle[index].remove(at);
|
||||
self.counters.fall_by(class.idle_gauge(), memory.len);
|
||||
self.changed.notify_all();
|
||||
return Ok(memory);
|
||||
}
|
||||
@@ -310,6 +343,43 @@ impl Pool {
|
||||
}
|
||||
}
|
||||
|
||||
/// An idle dedicated block of `class` for a dedicated request of `len` bytes: the shortest
|
||||
/// that [`fits`] it, which reads zero and keeps its number, address and mapping. None where
|
||||
/// no idle block does, for the caller to make one.
|
||||
pub(crate) fn take_held(&self, class: MemoryClass, len: u64) -> Option<Memory> {
|
||||
let mut state = self.lock();
|
||||
let idle = &mut state.idle[class.index()];
|
||||
let at = (0..idle.len())
|
||||
.filter(|&at| !idle[at].pooled && fits(idle[at].len, len))
|
||||
.min_by_key(|&at| idle[at].len)?;
|
||||
let memory = idle.remove(at);
|
||||
self.counters.fall_by(class.idle_gauge(), memory.len);
|
||||
self.counters.count(Metric::DedicatedBlocksReused);
|
||||
Some(memory)
|
||||
}
|
||||
|
||||
/// Keeps `memory`, zeroed, as its class's latest idle block, and returns the oldest kept
|
||||
/// blocks of the class that then pass its bound, the ready block aside, for the caller to free
|
||||
/// without the lock. `memory` is at most the bound, so it stays.
|
||||
fn keep(&self, state: &mut State, memory: Memory) -> Vec<Memory> {
|
||||
let class = memory.class;
|
||||
let idle = &mut state.idle[class.index()];
|
||||
idle.push(memory);
|
||||
self.counters.rise_by(class.idle_gauge(), memory.len);
|
||||
let mut gone = Vec::new();
|
||||
loop {
|
||||
let ready = idle.iter().rposition(Memory::pooled);
|
||||
let mut kept = (0..idle.len()).filter(|&at| Some(at) != ready);
|
||||
let total: u64 = kept.clone().map(|at| idle[at].len).sum();
|
||||
let Some(oldest) = kept.next().filter(|_| total > class.idle_bound()) else {
|
||||
return gone;
|
||||
};
|
||||
let oldest = idle.remove(oldest);
|
||||
self.counters.fall_by(class.idle_gauge(), oldest.len);
|
||||
gone.push(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a block as handed to the consumer, so that freeing it calls the hook.
|
||||
pub(crate) fn hand(&self, block: BlockId) {
|
||||
let mut state = self.lock();
|
||||
@@ -351,8 +421,14 @@ impl Pool {
|
||||
/// At teardown, after the block-maker thread is joined: every block the pool still has.
|
||||
pub(crate) fn remaining(&mut self) -> Vec<Memory> {
|
||||
let state = self.state.get_mut().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut remaining: Vec<Memory> = state.idle.iter().flatten().copied().collect();
|
||||
remaining.extend(state.returned.iter().copied());
|
||||
let mut remaining = Vec::new();
|
||||
for class in MemoryClass::ALL {
|
||||
for memory in state.idle[class.index()].drain(..) {
|
||||
self.counters.fall_by(class.idle_gauge(), memory.len);
|
||||
remaining.push(memory);
|
||||
}
|
||||
}
|
||||
remaining.append(&mut state.returned);
|
||||
remaining
|
||||
}
|
||||
|
||||
@@ -388,21 +464,26 @@ pub(crate) fn stock(core: &Core) {
|
||||
let made =
|
||||
(core.pool.number()).and_then(|id| make(core, class, class.block_len(), id, true));
|
||||
let mut state = core.pool.lock();
|
||||
match made {
|
||||
Ok(memory) => state.idle[class.index()].push(memory),
|
||||
let gone = match made {
|
||||
Ok(memory) => core.pool.keep(&mut state, memory),
|
||||
Err(error) => {
|
||||
state.failed[class.index()] = Some(error);
|
||||
break;
|
||||
}
|
||||
};
|
||||
drop(state);
|
||||
for memory in gone {
|
||||
free(core, memory);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The block-maker thread, until the device's teardown stops it. Off every caller's path, it
|
||||
/// zeroes each pooled block given back and keeps it while its class has fewer than [`IDLE_MAX`]
|
||||
/// idle, and frees the rest through the hook; then it makes blocks until each class has
|
||||
/// [`READY`] idle.
|
||||
/// zeroes each block given back, pooled or dedicated, and keeps it as its class's latest idle
|
||||
/// block, freeing through the hook the oldest kept blocks past the class's
|
||||
/// [`MemoryClass::idle_bound`], the ready block aside (and at once a block longer than the bound,
|
||||
/// or spilled); then it makes pooled blocks until each class has [`READY`] idle.
|
||||
pub(crate) fn run(core: Arc<Core>) {
|
||||
let pool = &core.pool;
|
||||
let mut state = pool.lock();
|
||||
@@ -412,21 +493,22 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
}
|
||||
if let Some(memory) = state.returned.pop() {
|
||||
// A spilled block is freed, so the pool's next block tries device-local memory again.
|
||||
let room = memory.pooled
|
||||
&& !memory.spilled
|
||||
&& state.idle[memory.class.index()].len() < IDLE_MAX;
|
||||
let room = !memory.spilled && memory.len <= memory.class.idle_bound();
|
||||
drop(state);
|
||||
// Only this thread adds idle blocks, so the room is still there once it is zeroed. A
|
||||
// block that cannot be zeroed is freed.
|
||||
let kept = room && zero(&core, &memory, 0, memory.len).is_ok();
|
||||
if !kept {
|
||||
// A block that cannot be zeroed is freed.
|
||||
let zeroed = room && zero(&core, &memory, 0, memory.len).is_ok();
|
||||
let gone = match zeroed {
|
||||
true => {
|
||||
let gone = pool.keep(&mut pool.lock(), memory);
|
||||
pool.changed.notify_all();
|
||||
gone
|
||||
}
|
||||
false => vec![memory],
|
||||
};
|
||||
for memory in gone {
|
||||
free(&core, memory);
|
||||
}
|
||||
state = pool.lock();
|
||||
if kept {
|
||||
state.idle[memory.class.index()].push(memory);
|
||||
pool.changed.notify_all();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let wanted = MemoryClass::ALL.into_iter().find(|class| {
|
||||
@@ -437,11 +519,21 @@ pub(crate) fn run(core: Arc<Core>) {
|
||||
drop(state);
|
||||
let made = id.and_then(|id| make(&core, class, class.block_len(), id, true));
|
||||
state = pool.lock();
|
||||
match made {
|
||||
Ok(memory) => state.idle[class.index()].push(memory),
|
||||
Err(error) => state.failed[class.index()] = Some(error),
|
||||
}
|
||||
let gone = match made {
|
||||
Ok(memory) => pool.keep(&mut state, memory),
|
||||
Err(error) => {
|
||||
state.failed[class.index()] = Some(error);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
pool.changed.notify_all();
|
||||
if !gone.is_empty() {
|
||||
drop(state);
|
||||
for memory in gone {
|
||||
free(&core, memory);
|
||||
}
|
||||
state = pool.lock();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
state = pool.wait(state);
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
//! Memory blocks and buffers: the plan of a zero fill and a dedicated block's length; and, under a
|
||||
//! device cfg, on every device of the cfg's kind, that the device holds a block of each class as it
|
||||
//! is made, that blocks are handed out zeroed and buffers
|
||||
//! view them, that a block is freed through the consumer's hook only once nothing uses it, that
|
||||
//! the pool keeps two idle blocks of a class and frees the rest, and that teardown frees every
|
||||
//! block with the gauges at zero.
|
||||
//! Memory blocks and buffers: the plan of a zero fill, a dedicated block's length and which kept
|
||||
//! dedicated block serves a request; and, under a device cfg, on every device of the cfg's kind,
|
||||
//! that the device holds a block of each class as it is made, that blocks are handed out zeroed and
|
||||
//! buffers view them, that a block is freed through the consumer's hook only once nothing uses it,
|
||||
//! that the pool keeps a class's idle blocks, pooled and dedicated, up to its bound and frees the
|
||||
//! oldest past it, that a kept dedicated block serves a request it fits and fills at least half
|
||||
//! of, and that teardown frees every block with the gauges at zero.
|
||||
|
||||
use crate::fill::{plan, Plan};
|
||||
use crate::memory::dedicated_len;
|
||||
use crate::memory::{dedicated_len, fits};
|
||||
use crate::{Error, Limit};
|
||||
|
||||
#[test]
|
||||
@@ -63,6 +64,21 @@ fn a_dedicated_block_is_the_length_rounded_up_to_64_kib_within_the_device() {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A kept dedicated block serves a request it fits and that fills at least half of it.
|
||||
#[test]
|
||||
fn a_kept_dedicated_block_serves_a_request_it_fits_and_that_fills_half_of_it() {
|
||||
const MIB: u64 = 1 << 20;
|
||||
for (held, want, serves) in [
|
||||
(100 * MIB, 100 * MIB, true),
|
||||
(100 * MIB, 60 * MIB, true),
|
||||
(100 * MIB, 50 * MIB, true),
|
||||
(100 * MIB, 50 * MIB - 1, false),
|
||||
(100 * MIB, 101 * MIB, false),
|
||||
(u64::MAX, u64::MAX / 2 + 1, true),
|
||||
] {
|
||||
assert_eq!(fits(held, want), serves, "{held} for {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
|
||||
mod on_device {
|
||||
@@ -531,11 +547,13 @@ mod on_device {
|
||||
Err(Error::Limit(Limit::BlockLen { len: u64::MAX, .. }))
|
||||
));
|
||||
|
||||
// A dedicated block: past the class's block length, rounded up to 64 KiB, zeroed.
|
||||
// A dedicated block: past the class's block length, rounded up to 64 KiB, zeroed. It
|
||||
// is longer than the class's idle bound, so it is freed once given back.
|
||||
let past = MemoryClass::Shared.idle_bound();
|
||||
let dedicated = device
|
||||
.take_block(MemoryClass::Shared, shared_len + 1)
|
||||
.take_block(MemoryClass::Shared, past + 1)
|
||||
.expect("a dedicated block");
|
||||
assert_eq!(dedicated.len, shared_len + (64 << 10));
|
||||
assert_eq!(dedicated.len, past + (64 << 10));
|
||||
let dedicated_host = bytes(dedicated);
|
||||
assert!(
|
||||
dedicated_host.iter().all(|&byte| byte == 0),
|
||||
@@ -547,8 +565,8 @@ mod on_device {
|
||||
.new_buffer(dedicated.id, 0, 16, false)
|
||||
.expect("a buffer of the dedicated block");
|
||||
|
||||
// Released, it lives while its buffer does, then is freed through the hook on the
|
||||
// block-maker thread, still mapped.
|
||||
// Released, it lives while its buffer does, then, longer than the bound, is freed
|
||||
// through the hook on the block-maker thread, still mapped.
|
||||
device.release_block(dedicated.id).expect("a release");
|
||||
assert!(matches!(
|
||||
device.release_block(dedicated.id),
|
||||
@@ -632,11 +650,15 @@ mod on_device {
|
||||
}
|
||||
}
|
||||
|
||||
/// Past two idle blocks of a class, the pool frees what is given back through the hook; a
|
||||
/// block it keeps is zeroed and handed out again with its number, address and mapping, with no
|
||||
/// block made; and a Private block taken again reads zero too.
|
||||
/// The pool keeps a class's idle blocks up to its bound in bytes beside the ready block, a
|
||||
/// reserve outside the bound, and frees the oldest past it through the hook: of two more Shared
|
||||
/// blocks than the bound holds, taken and given back, the bound's worth are kept beside the
|
||||
/// latest, now the ready block, and the oldest freed (the ready block made while they were
|
||||
/// taken among them, freed without the hook); a block it keeps is zeroed and handed out again
|
||||
/// with its number, address and mapping, with no block made; and a Private block taken again
|
||||
/// reads zero too.
|
||||
#[test]
|
||||
fn every_device_keeps_two_idle_blocks_per_class_and_frees_the_rest() {
|
||||
fn every_device_keeps_idle_blocks_up_to_the_bound_and_frees_the_oldest() {
|
||||
let instance = Instance::new(&[]).expect("an instance at the floor");
|
||||
let devices = devices_of_the_cfgs_kind(&instance);
|
||||
assert!(
|
||||
@@ -649,10 +671,12 @@ mod on_device {
|
||||
let counters = device.counters();
|
||||
let mut handed = Vec::new();
|
||||
|
||||
let taken: Vec<BlockInfo> = (0..3)
|
||||
let shared_len = MemoryClass::Shared.block_len();
|
||||
let room = MemoryClass::Shared.idle_bound() / shared_len;
|
||||
let taken: Vec<BlockInfo> = (0..room + 2)
|
||||
.map(|_| {
|
||||
device
|
||||
.take_block(MemoryClass::Shared, MemoryClass::Shared.block_len())
|
||||
.take_block(MemoryClass::Shared, shared_len)
|
||||
.expect("a block")
|
||||
})
|
||||
.collect();
|
||||
@@ -663,40 +687,51 @@ mod on_device {
|
||||
host[host.len() - 1] = 0x5A;
|
||||
hook.record(block);
|
||||
}
|
||||
// The three, one ready block of each class, and the zero source.
|
||||
// The blocks taken, one ready block of each class, and the zero source.
|
||||
wait_until("a ready block of each class", || {
|
||||
counters.gauges().blocks == ZERO_SOURCE + 2 + 3
|
||||
counters.gauges().blocks == ZERO_SOURCE + 2 + room + 2
|
||||
});
|
||||
for block in &taken {
|
||||
device.release_block(block.id).expect("a release");
|
||||
}
|
||||
wait_until("two blocks freed", || hook.unmapped().len() == 2);
|
||||
// The bound's worth of Shared blocks kept beside the ready one, the ready Private
|
||||
// block, the zero source.
|
||||
wait_until("the pool settled", || {
|
||||
counters.gauges().blocks == ZERO_SOURCE + 1 + 2
|
||||
counters.gauges().blocks == ZERO_SOURCE + 1 + room + 1
|
||||
});
|
||||
let unmapped = hook.unmapped();
|
||||
assert_eq!(unmapped.len(), 1, "{name}: {unmapped:?}");
|
||||
for unmapped in &unmapped {
|
||||
assert_eq!(unmapped.thread.as_deref(), Some("m2v-blocks"));
|
||||
// Kept and zeroed first, then freed as the oldest past the bound.
|
||||
assert_eq!(
|
||||
unmapped.first,
|
||||
Some(0x5A),
|
||||
Some(0),
|
||||
"{name}: unmapped while still mapped"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
counters.gauges().shared_idle_bytes,
|
||||
MemoryClass::Shared.idle_bound() + shared_len,
|
||||
"{name}: the bound's worth kept beside the ready block"
|
||||
);
|
||||
let kept: Vec<&BlockInfo> = taken
|
||||
.iter()
|
||||
.filter(|block| unmapped.iter().all(|u| u.block != block.id.get()))
|
||||
.collect();
|
||||
assert_eq!(kept.len(), 1, "{name}: {unmapped:?}");
|
||||
assert_eq!(kept.len() as u64, room + 1, "{name}: {unmapped:?}");
|
||||
|
||||
// The kept block comes back first, zeroed, as it was, with nothing made.
|
||||
// A kept block comes back, zeroed, as it was, with nothing made.
|
||||
let made = counters.metrics().blocks_made;
|
||||
let again = device
|
||||
.take_block(MemoryClass::Shared, 1)
|
||||
.expect("a block again");
|
||||
assert_eq!(again.id, kept[0].id, "{name}: the latest idle block first");
|
||||
assert_eq!(again.gpu_address, kept[0].gpu_address);
|
||||
assert_eq!(again.contents, kept[0].contents);
|
||||
let was = kept
|
||||
.iter()
|
||||
.find(|block| block.id == again.id)
|
||||
.unwrap_or_else(|| panic!("{name}: a kept block"));
|
||||
assert_eq!(again.gpu_address, was.gpu_address);
|
||||
assert_eq!(again.contents, was.contents);
|
||||
let host = bytes(again);
|
||||
assert!(
|
||||
host.iter().all(|&byte| byte == 0),
|
||||
@@ -747,13 +782,131 @@ mod on_device {
|
||||
handed.dedup();
|
||||
assert_each_unmapped_once(name, &hook, &handed);
|
||||
println!(
|
||||
"memory: {name}: the pool kept {} and freed 2; metrics {:?}",
|
||||
kept[0].id.get(),
|
||||
"memory: {name}: the pool kept {room} Shared blocks beside the ready one; metrics {:?}",
|
||||
counters.metrics()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Released dedicated blocks are kept idle with the class's pooled ones, up to its bound in
|
||||
/// bytes beside the ready block, a reserve outside the bound, the oldest freed past it through
|
||||
/// the hook: of three 100 MiB Shared blocks given back, two are kept beside the ready block, and
|
||||
/// a Private block past the pooled length is kept beside the Private ready block. A later
|
||||
/// request past the pooled length takes a kept block it fits and fills at least half of,
|
||||
/// zeroed, with its number, address and mapping and nothing made; a request that fills less
|
||||
/// than half of every kept block, or that none fits, makes its own. Every gauge reads zero
|
||||
/// after teardown.
|
||||
#[test]
|
||||
fn every_device_keeps_given_back_dedicated_blocks_for_requests_they_fit() {
|
||||
const MIB: u64 = 1 << 20;
|
||||
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 hook = Arc::new(Hook::default());
|
||||
let device = device_with(&hook, physical, name);
|
||||
let counters = device.counters();
|
||||
let shared_len = MemoryClass::Shared.block_len();
|
||||
let taken: Vec<BlockInfo> = (0..3)
|
||||
.map(|_| {
|
||||
(device.take_block(MemoryClass::Shared, 100 * MIB))
|
||||
.unwrap_or_else(|error| panic!("{name}: a dedicated block: {error}"))
|
||||
})
|
||||
.collect();
|
||||
let mut handed: Vec<BlockId> = taken.iter().map(|block| block.id).collect();
|
||||
for block in &taken {
|
||||
assert_eq!(block.len, 100 * MIB, "{name}: a dedicated block");
|
||||
let host = bytes(*block);
|
||||
host[0] = 0x5A;
|
||||
host[host.len() - 1] = 0x5A;
|
||||
hook.record(block);
|
||||
}
|
||||
assert_eq!(counters.metrics().dedicated_blocks_reused, 0, "{name}");
|
||||
for block in &taken {
|
||||
device.release_block(block.id).expect("a release");
|
||||
}
|
||||
// Two kept beside the ready block; the oldest freed.
|
||||
wait_until("one dedicated block freed", || hook.unmapped().len() == 1);
|
||||
wait_until("two kept beside the ready block", || {
|
||||
counters.gauges().shared_idle_bytes == 200 * MIB + shared_len
|
||||
});
|
||||
let unmapped = hook.unmapped();
|
||||
assert_eq!(unmapped[0].thread.as_deref(), Some("m2v-blocks"), "{name}");
|
||||
let kept: Vec<&BlockInfo> = taken
|
||||
.iter()
|
||||
.filter(|block| block.id.get() != unmapped[0].block)
|
||||
.collect();
|
||||
assert_eq!(kept.len(), 2, "{name}: {unmapped:?}");
|
||||
|
||||
// A request that fills more than half of a kept block takes it.
|
||||
let made = counters.metrics().blocks_made;
|
||||
let again = (device.take_block(MemoryClass::Shared, 60 * MIB))
|
||||
.unwrap_or_else(|error| panic!("{name}: a block again: {error}"));
|
||||
let was = kept
|
||||
.iter()
|
||||
.find(|block| block.id == again.id)
|
||||
.unwrap_or_else(|| panic!("{name}: a kept block, not {:?}", again.id));
|
||||
assert_eq!(
|
||||
(again.len, again.gpu_address, again.contents),
|
||||
(was.len, was.gpu_address, was.contents),
|
||||
"{name}: the kept block as it was"
|
||||
);
|
||||
assert!(
|
||||
bytes(again).iter().all(|&byte| byte == 0),
|
||||
"{name}: a kept block taken again"
|
||||
);
|
||||
assert_eq!(counters.metrics().blocks_made, made, "{name}: a block made");
|
||||
assert_eq!(counters.metrics().dedicated_blocks_reused, 1, "{name}");
|
||||
assert_eq!(
|
||||
counters.gauges().shared_idle_bytes,
|
||||
100 * MIB + shared_len,
|
||||
"{name}: one kept block left"
|
||||
);
|
||||
|
||||
// A request that fills less than half of it, and one it does not fit, make their own.
|
||||
for len in [40 * MIB, 101 * MIB] {
|
||||
let own = (device.take_block(MemoryClass::Shared, len))
|
||||
.unwrap_or_else(|error| panic!("{name}: {len}: {error}"));
|
||||
assert_eq!(own.len, len, "{name}: a block of its own");
|
||||
handed.push(own.id);
|
||||
}
|
||||
assert_eq!(counters.metrics().blocks_made, made + 2, "{name}");
|
||||
assert_eq!(counters.metrics().dedicated_blocks_reused, 1, "{name}");
|
||||
|
||||
// A dedicated Private block is kept beside the Private ready block, and taken again.
|
||||
let private_len = MemoryClass::Private.block_len();
|
||||
let private = (device.take_block(MemoryClass::Private, private_len + 1))
|
||||
.unwrap_or_else(|error| panic!("{name}: a dedicated Private block: {error}"));
|
||||
handed.push(private.id);
|
||||
device.release_block(private.id).expect("a release");
|
||||
wait_until("the Private block kept", || {
|
||||
counters.gauges().private_idle_bytes == private_len + private.len
|
||||
});
|
||||
let made = counters.metrics().blocks_made;
|
||||
let again = (device.take_block(MemoryClass::Private, private_len + 1))
|
||||
.unwrap_or_else(|error| panic!("{name}: a Private block again: {error}"));
|
||||
assert_eq!(
|
||||
(again.id, again.gpu_address),
|
||||
(private.id, private.gpu_address),
|
||||
"{name}: the kept Private block"
|
||||
);
|
||||
assert_eq!(counters.metrics().blocks_made, made, "{name}: a block made");
|
||||
assert_eq!(counters.metrics().dedicated_blocks_reused, 2, "{name}");
|
||||
|
||||
drop(device);
|
||||
assert_eq!(
|
||||
counters.gauges(),
|
||||
Gauges::default(),
|
||||
"{name}: gauges after teardown"
|
||||
);
|
||||
handed.sort_unstable();
|
||||
assert_each_unmapped_once(name, &hook, &handed);
|
||||
println!(
|
||||
"memory: {name}: two dedicated blocks kept, one taken again; metrics {:?}",
|
||||
counters.metrics()
|
||||
);
|
||||
}
|
||||
}
|
||||
/// With the device's `maxMemoryAllocationCount` answered as the zero source's, the two ready
|
||||
/// blocks' and one more (`Device::open`), the count is reached once a texture takes the ready
|
||||
/// Private block and the pool makes it again. Past it, a texture larger than a block, which has
|
||||
|
||||
@@ -2269,7 +2269,9 @@ field metal2vulkan-rt::Gauges.events pub events: u64
|
||||
field metal2vulkan-rt::Gauges.kernel_entries pub kernel_entries: u64
|
||||
field metal2vulkan-rt::Gauges.kernels pub kernels: u64
|
||||
field metal2vulkan-rt::Gauges.pipelines pub pipelines: u64
|
||||
field metal2vulkan-rt::Gauges.private_idle_bytes pub private_idle_bytes: u64
|
||||
field metal2vulkan-rt::Gauges.samplers pub samplers: u64
|
||||
field metal2vulkan-rt::Gauges.shared_idle_bytes pub shared_idle_bytes: u64
|
||||
field metal2vulkan-rt::Gauges.spilled_bytes pub spilled_bytes: u64
|
||||
field metal2vulkan-rt::Gauges.textures pub textures: u64
|
||||
field metal2vulkan-rt::HeapRange.block pub block: BlockId
|
||||
@@ -2284,6 +2286,7 @@ field metal2vulkan-rt::Metrics.bytes_copied pub bytes_copied: u64
|
||||
field metal2vulkan-rt::Metrics.cache_bytes_written pub cache_bytes_written: u64
|
||||
field metal2vulkan-rt::Metrics.commit_lock_wait_max_nanos pub commit_lock_wait_max_nanos: u64
|
||||
field metal2vulkan-rt::Metrics.commit_lock_wait_nanos pub commit_lock_wait_nanos: u64
|
||||
field metal2vulkan-rt::Metrics.dedicated_blocks_reused pub dedicated_blocks_reused: u64
|
||||
field metal2vulkan-rt::Metrics.dispatches_without_effects pub dispatches_without_effects: u64
|
||||
field metal2vulkan-rt::Metrics.first_use_wait_max_nanos pub first_use_wait_max_nanos: u64
|
||||
field metal2vulkan-rt::Metrics.first_use_wait_nanos pub first_use_wait_nanos: u64
|
||||
|
||||
|
Can't render this file because it is too large.
|
Reference in new issue
Block a user