From d1e9062b5fe19af4982ec0a2f2801e53675f4b66 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 22:17:57 -0800 Subject: [PATCH] rt: blocks are ranges of 16 MiB allocations; the block-maker thread allocates only while a class's free bytes run low The pool handed a take of up to a block length a whole pooled block and kept one ready block per class, which the block-maker thread made again as soon as a take used it. A 16-byte Shared buffer took the ready block, and the 16 MiB allocation that followed held the consumer's next pipeline creation for its whole length on NVIDIA's driver. Now each block is a range of one of its class's allocations, with its own VkBuffer: - A take is a kept block of its length, else the first free range that fits, else the start of an allocation made in the call: 16 MiB, or the block's own length where that is longer. Lengths round up to 64 KiB (or bufferImageGranularity); a block starts at its length rounded up to a power of two, up to 2 MiB. - Device::new makes one 16 MiB allocation per class. After that, the block-maker thread makes another only while the class's free bytes are under 8 MiB. A take never waits on it for memory. - A take that no free range fits, while the class keeps blocks of other lengths, allocates at once. It also asks the block-maker thread to give those blocks' bytes back, after the consumer's hook. Only when its own allocation fails does it wait for those bytes, then look for a free range once more. - An allocation holding no live block is idle. A class keeps its idle allocations while their bytes plus 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. Past that it frees the oldest, except the reserve that keeps 8 MiB free. The rule runs at takes and give-backs on an injectable clock; there is no timer. - Removed: the dedicated path, fits-and-fills-half, the 256 and 128 MiB idle bounds and the 64 MiB Private block. - Metrics: blocks_reused replaces dedicated_blocks_reused. New metrics: block_bytes_made, and the vkAllocateMemory time on the consumer's threads (count, total, longest) apart from the block-maker thread's. Tests: - Unit: rounding, base alignment, and the window and surplus rule. - On device: - the first allocations, and the trigger at 8 MiB free; - kept blocks taken again with their number, address and mapping; - an allocation beside kept blocks of other lengths, with their bytes given back; - the failed-allocation path, at an answered maxMemoryAllocationCount; - idle allocations following the window down, the reserve kept; - a seeded 300-step stress of mixed takes and releases across both classes, each step under a one-minute timeout. - Tests that took a block of 1 byte and used more of it now take what they use. - The replay's rt counters read the new metrics. Verified: cargo fmt; api_signatures blessed; REFUSALS.md regenerated. Clippy, the suites and the device legs follow as potluck jobs. --- crates/metal2vulkan-rt/README.md | 62 +- crates/metal2vulkan-rt/src/counters.rs | 81 +- crates/metal2vulkan-rt/src/device.rs | 87 +- crates/metal2vulkan-rt/src/memory.rs | 1113 ++++++++++++----- crates/metal2vulkan-rt/src/places.rs | 48 +- crates/metal2vulkan-rt/src/tests/blit.rs | 8 +- crates/metal2vulkan-rt/src/tests/command.rs | 71 +- crates/metal2vulkan-rt/src/tests/heap.rs | 7 +- crates/metal2vulkan-rt/src/tests/managed.rs | 2 +- crates/metal2vulkan-rt/src/tests/memory.rs | 1027 +++++++++------ crates/metal2vulkan-rt/src/tests/over.rs | 11 +- crates/metal2vulkan-rt/src/tests/places.rs | 64 +- crates/metal2vulkan-rt/src/tests/spill.rs | 21 +- crates/metal2vulkan-rt/src/tests/upload.rs | 15 +- crates/metal2vulkan-rt/src/texture.rs | 33 +- .../src/replay/new_runtime/mod.rs | 9 +- crates/metal2vulkan/tests/api_signatures.tsv | 7 +- docs/REFUSALS.md | 4 +- docs/REPLAY-STREAM.md | 2 +- 19 files changed, 1771 insertions(+), 901 deletions(-) diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 60ba1c671..c2171c4fd 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -86,24 +86,29 @@ in its memory. the block's `BlockInfo` (its number, class, length, device address and, for Shared, its host address). One `VkBuffer` spans each block, with every buffer usage and a device address. Nothing in a block is exportable. -- Up to its class's `MemoryClass::block_len`, 16 MiB of Shared memory and 64 MiB of Private on - every device, a block is pooled. `Device::new` makes one block of each class before it returns, - and the block-maker thread keeps one of each class ready after that, made off every caller's - path, so a take waits only when none is ready. No block is so made beside the consumer's first - calls: on an RTX 3090 (NVIDIA's Linux driver), a pipeline state's creation right after - `Device::new` waited 47 to 61 ms behind the allocation of a first 256 MiB Shared block's memory. - A driver may hold the device's other calls for the whole of a block's allocation, longer for - more bytes, so the lengths are short: there a creation beside a Shared block's making took 6 to - 8 ms at 16 MiB (40 to 45 ms at 256 MiB), and 3.4 to 4.6 ms beside a 64 MiB Private block's. 16 - MiB is the largest piece a guest's allocator takes for its buffers; at 64 MiB a texture or a - Managed buffer's device copy of 32 MiB takes a pooled Private block. Past its class's length a - block is dedicated: the length rounded up to 64 KiB, made in the call, up to the device's - `maxMemoryAllocationSize` and `maxBufferSize` (`Limit::BlockLen` past them). +- A block is a range of one of the device's allocations of its class, with a `VkBuffer` of its + own bound there: the length asked rounded up to 64 KiB (to `bufferImageGranularity` where that is + larger), at an offset that is a multiple of that length rounded up to a power of two, up to 2 + MiB. A take is, in order: a kept block of its length (below), a free range of the class's + allocations, the first that fits, else the start of an allocation made in the call, of + `MemoryClass::block_len` (16 MiB of either class) or the block's length where that is longer, up + to the device's `maxMemoryAllocationSize` and `maxBufferSize` (`Limit::BlockLen` past them). Its + rest serves later takes. +- `Device::new` makes one allocation of each class before it returns. After that the block-maker + thread makes a class's next allocation of 16 MiB, off every caller's path, while the class's free + bytes are fewer than 8 MiB, and at no other time: a take that leaves more free sets nothing off + beside the consumer's next calls. A driver may hold the device's other calls for the whole of an + allocation, longer for more bytes: on an RTX 3090 (NVIDIA's Linux driver) a pipeline state's + creation beside a Shared allocation's making took 6 to 8 ms at 16 MiB and 40 to 45 ms at 256 + MiB; on an RTX 2080 a compute pipeline's creation waited out the whole 3.4 ms of a 16 MiB Shared + allocation made beside it. `Metrics::consumer_allocation_nanos` and + `consumer_allocation_max_nanos` count the time of allocations made on the consumer's threads, + and `maker_allocation_nanos` those of the block-maker thread. - A Private allocation takes the device-local Private type. Where that allocation itself fails out of device memory (never a budget poll), it takes the next memory type the resource allows, in the device's order: `BlockInfo::device_local` is false for such a block, and - `Gauges::spilled_bytes` counts the bytes until they are freed. A spilled pooled block is freed - when given back, so the pool's next block tries device-local memory again. Textures are not + `Gauges::spilled_bytes` counts the bytes until they are freed. A spilled allocation is freed + once its last block is given back, so the next tries device-local memory again. Textures are not placed in a spilled block: a texture then takes an allocation of its own, which spills in the same way where the image allows another type. A Managed buffer whose device copy finds no device-local room is its Shared range, as on a unified device, for its life. @@ -120,16 +125,20 @@ in its memory. - Dropping a block's last handle gives the block back; `Device::release_block` consumes a handle, that drop made explicit. Clones of a handle share one claim, so dropping one of two gives nothing back. It takes effect once no buffer, command buffer or upload using the block remains. 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. Once the last handle is gone the block's number names nothing + block-maker thread then zeroes it and keeps it, with the same number, address and mapping, for a + later take of its length (`Metrics::blocks_reused`). A take that no free range fits while the + class keeps blocks of other lengths makes its allocation at once, and the block-maker thread then + gives those blocks' bytes back to their allocations, after `BlockMappings::unmap` of each; only + where the take's allocation fails does it wait for those bytes and take a range of them. An + allocation that holds no block anyone holds is idle. 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 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 + 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 for it; a handle dropped after that does nothing. @@ -152,7 +161,8 @@ in its memory. which `contents` answers. The device's memory-type query picks its form. Where the Shared type is device-local, the buffer is its bytes, as a Shared buffer is, and `did_modify_range` does nothing. Elsewhere shaders reach a device copy at `gpu_address`: a place in a copy block, a - Private block of the pool (a dedicated one past 64 MiB) that holds device copies alone. Its + Private block of the pool of 16 MiB (of the copy's own length past that) that holds device + copies alone. Its first `copied` bytes are copied from the consumer's and the rest zeroed, in the upload. `Buffer::did_modify_range(start, length)` marks a range changed (`Refusal::ModifiedRange` past the buffer): the upload copies it into the device copy as it goes, ahead of every command buffer diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 6a41199e3..4d0806ed8 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -17,8 +17,8 @@ pub(crate) enum Metric { PipelinesCreated, /// [`Metrics::blocks_made`]. BlocksMade, - /// [`Metrics::dedicated_blocks_reused`]. - DedicatedBlocksReused, + /// [`Metrics::blocks_reused`]. + BlocksReused, /// [`Metrics::dispatches_without_effects`]. DispatchesWithoutEffects, /// [`Metrics::translations`]. @@ -101,8 +101,13 @@ struct Atomics { first_use_wait_nanos: AtomicU64, first_use_wait_max_nanos: AtomicU64, blocks_made: AtomicU64, + block_bytes_made: AtomicU64, + consumer_allocations: AtomicU64, + consumer_allocation_nanos: AtomicU64, + consumer_allocation_max_nanos: AtomicU64, + maker_allocation_nanos: AtomicU64, dispatches_without_effects: AtomicU64, - dedicated_blocks_reused: AtomicU64, + blocks_reused: AtomicU64, translations: AtomicU64, translations_loaded: AtomicU64, ring_writes: AtomicU64, @@ -155,7 +160,7 @@ impl Counters { Metric::Barriers => &a.barriers, Metric::PipelinesCreated => &a.pipelines_created, Metric::BlocksMade => &a.blocks_made, - Metric::DedicatedBlocksReused => &a.dedicated_blocks_reused, + Metric::BlocksReused => &a.blocks_reused, Metric::DispatchesWithoutEffects => &a.dispatches_without_effects, Metric::Translations => &a.translations, Metric::TranslationsLoaded => &a.translations_loaded, @@ -192,6 +197,24 @@ impl Counters { self.atomics.submit_infos.fetch_add(infos, Relaxed); } + /// An allocation of `bytes` made for blocks ([`Metrics::block_bytes_made`]). + pub(crate) fn allocated(&self, bytes: u64) { + self.atomics.block_bytes_made.fetch_add(bytes, Relaxed); + } + + /// A `vkAllocateMemory` that took `nanos` nanoseconds, on the block-maker thread where + /// `maker`, else on a thread of the consumer's ([`Metrics::consumer_allocation_nanos`]). + pub(crate) fn allocation_time(&self, nanos: u64, maker: bool) { + let a = &self.atomics; + if maker { + a.maker_allocation_nanos.fetch_add(nanos, Relaxed); + } else { + a.consumer_allocations.fetch_add(1, Relaxed); + a.consumer_allocation_nanos.fetch_add(nanos, Relaxed); + a.consumer_allocation_max_nanos.fetch_max(nanos, Relaxed); + } + } + /// `bytes` more copied for a call ([`Metrics::bytes_copied`]). pub(crate) fn copied(&self, bytes: u64) { self.atomics.bytes_copied.fetch_add(bytes, Relaxed); @@ -290,7 +313,12 @@ 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), + block_bytes_made: a.block_bytes_made.load(Relaxed), + consumer_allocations: a.consumer_allocations.load(Relaxed), + consumer_allocation_nanos: a.consumer_allocation_nanos.load(Relaxed), + consumer_allocation_max_nanos: a.consumer_allocation_max_nanos.load(Relaxed), + maker_allocation_nanos: a.maker_allocation_nanos.load(Relaxed), + blocks_reused: a.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), @@ -367,13 +395,30 @@ pub struct Metrics { /// The longest first-use wait, in nanoseconds; a maximum since the device was made, so the /// difference of two reads does not apply to it. pub first_use_wait_max_nanos: u64, - /// `VkDeviceMemory` allocations made: pooled blocks (the texture blocks among them) and - /// dedicated ones, the zero source and the parameter ring's blocks. + /// `VkDeviceMemory` allocations made: the allocations blocks are ranges of (the texture + /// blocks among them), 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, + /// Bytes of the allocations blocks are ranges of, made: what the device allocated for + /// blocks, by the block-maker thread or in a take. The difference of two reads is what a + /// frame allocated. + pub block_bytes_made: u64, + /// `vkAllocateMemory` calls made on the consumer's threads, inside its calls: the device's + /// making, takes that no free range fits, textures' allocations of their own, the staging + /// region and the parameter ring's blocks. A driver may hold the device's other calls for an + /// allocation's whole length. + pub consumer_allocations: u64, + /// The nanoseconds of [`host_time`](crate::host_time) those calls took, in total. + pub consumer_allocation_nanos: u64, + /// The longest of those calls, in nanoseconds; a maximum since the device was made, so the + /// difference of two reads does not apply to it. + pub consumer_allocation_max_nanos: u64, + /// The nanoseconds of [`host_time`](crate::host_time) the block-maker thread's + /// `vkAllocateMemory` calls took, in total: allocations made ahead of need, off the + /// consumer's threads. + pub maker_allocation_nanos: u64, + /// Blocks taken again: a take of the length of a block given back and kept, which took that + /// block with its number, address and mapping, and no new range or allocation. + pub 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. @@ -458,8 +503,8 @@ pub struct Gauges { /// Occupied indices of set 1's arrays: one for each texture made at an index and each sampler /// state. pub descriptor_slots: u64, - /// Live `VkDeviceMemory` allocations: blocks the consumer holds, blocks ready or idle in the - /// pool, and the runtime's own. + /// Live `VkDeviceMemory` allocations: those blocks are ranges of, the idle ones among them, + /// and the runtime's own. pub blocks: u64, /// Events and shared events (timeline semaphores). pub events: u64, @@ -471,10 +516,12 @@ 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. + /// Bytes of idle Shared allocations, which hold no block anyone holds: those the idle rule + /// keeps (at most the most bytes of Shared allocations in use over the last 10 seconds less + /// those in use now, and an eighth of the heap), and the reserve that keeps the free bytes at + /// 8 MiB or more. 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. + /// Bytes of idle Private allocations, as [`shared_idle_bytes`](Self::shared_idle_bytes) for + /// Shared ones. pub private_idle_bytes: u64, } diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index 600119e20..3194731de 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -271,9 +271,9 @@ impl Device { /// of the consumer's extensions ([`DeviceOptions::extensions`]) the device offers with the /// features the consumer needs, and chooses its memory types on it. It takes one queue of the floor's queue /// family for the runtime and, where that family has a second queue, a queue for presenting; - /// where it has one, presenting shares the runtime's queue and its lock. It makes one block of - /// each memory class ready, then starts the block-maker thread, which keeps one of each ready - /// after that, the submit thread and the completion thread. + /// where it has one, presenting shares the runtime's queue and its lock. It makes one + /// allocation of each memory class for blocks, then starts the block-maker thread, which makes + /// another while a class's free bytes run low, the submit thread and the completion thread. /// /// Err: [`Error::BelowFloor`] with every item the device lacks; [`Error::Vulkan`] where a /// Vulkan call fails; [`Limit::MemoryAllocations`](crate::Limit::MemoryAllocations) at a @@ -429,7 +429,13 @@ 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 heap = |memory_type: u32| { + let memory = &capabilities.memory; + let heap = memory.memory_types_as_slice()[memory_type as usize].heap_index; + memory.memory_heaps_as_slice()[heap as usize].size + }; + let heaps = [heap(memory_types.private), heap(memory_types.shared)]; + let pool = Pool::new(options.block_mappings, counters.clone(), heaps, granularity); let core = Arc::new(Core { instance, physical: raw, @@ -551,21 +557,27 @@ impl Device { self.shared.core.counters.clone() } - /// No Metal counterpart: takes a block of `class` memory at least `len` bytes long, for the - /// consumer to place buffers in: a handle ([`Block`]) whose last drop gives it back. + /// No Metal counterpart: takes a block of `class` memory of `len` bytes rounded up to 64 KiB + /// (to the device's `bufferImageGranularity` where that is larger), for the consumer to place + /// buffers in: a handle ([`Block`]) whose last drop gives it back. A block is a range of one + /// of the device's allocations, with a `VkBuffer` of its own. /// - /// 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 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. + /// It is, in order: a block of that length given back earlier and kept, with its number, + /// address and mapping ([`Metrics::blocks_reused`](crate::Metrics::blocks_reused)); a free + /// range of the class's allocations, the first that fits; else the start of an allocation + /// made in this call, of [`MemoryClass::block_len`] (16 MiB) or the block's length where that + /// is longer, whose rest later blocks share. The block-maker thread makes a class's next + /// allocation of 16 MiB off every caller's path while the class's free bytes are fewer than 8 + /// MiB, so a take that leaves more free sets nothing off beside the consumer's next calls. + /// Where a take finds no free range and the class keeps blocks of other lengths, the + /// block-maker thread then gives their bytes back to their allocations, after + /// [`BlockMappings::unmap`]; the take waits for that only where its own allocation fails, and + /// then takes a range of those bytes where one fits. /// - /// 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 - /// is handed out, and a Private block by a GPU fill. A pooled block released and taken again - /// keeps its number, address and mapping. + /// Every block reads zero, as Metal's new buffers do, whether new or taken again: an + /// allocation is zeroed as it is made, a block's bytes as it is given back, a Shared one + /// through the mapping (which also makes each page resident before the block is handed out) + /// and a Private one by a GPU fill. /// /// Err: [`Limit::BlockLen`](crate::Limit::BlockLen) past the device's largest allocation or /// buffer; [`Limit::BlockIds`](crate::Limit::BlockIds); @@ -622,12 +634,15 @@ impl Device { /// handle, made explicit ([`Block`]). /// /// It takes effect once no [`Buffer`](crate::Buffer) of the block remains and every command - /// 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. + /// buffer that used it has retired. The block-maker thread then zeroes it and keeps it, with + /// the same number, address and mapping, for a later [`take_block`](Device::take_block) of its + /// length. An allocation none of whose blocks is held is idle, and one that holds a block is + /// 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. /// /// Err: [`Refusal::OtherDevice`] for another device's block, whose handle is dropped all the /// same. @@ -1028,21 +1043,12 @@ 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: an idle one the pool kept that [`memory::fits`] - /// it, or one made in the call. + /// A block of `class` for `len` bytes ([`Pool::take`]). /// - /// Err: what [`Pool::take`] and [`memory::make`] return; - /// [`Limit::BlockLen`](crate::Limit::BlockLen) past the device's longest block. + /// Err: what [`Pool::take`] returns; [`Limit::BlockLen`](crate::Limit::BlockLen) past the + /// device's longest allocation or buffer. pub(crate) fn take_memory(&self, class: MemoryClass, len: u64) -> Result { - if len <= class.block_len() { - 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), - } + self.pool.take(self, class, len, self.max_block_len) } /// Quiesced or torn down. @@ -1119,13 +1125,8 @@ impl Drop for Core { unsafe { region.free(self) }; } let placed = (self.places.remaining().into_iter()).chain(self.copies.remaining()); - for memory in placed - .collect::>() - .into_iter() - .chain(self.pool.remaining()) - { - memory::free(self, memory); - } + let placed = placed.collect(); + memory::free_all(self, placed); let pools = std::mem::take( self.query_pools .get_mut() diff --git a/crates/metal2vulkan-rt/src/memory.rs b/crates/metal2vulkan-rt/src/memory.rs index e7b172c11..5cfc4b609 100644 --- a/crates/metal2vulkan-rt/src/memory.rs +++ b/crates/metal2vulkan-rt/src/memory.rs @@ -1,21 +1,94 @@ -//! Memory blocks: what the consumer takes and releases, the pool that makes them ahead of need on -//! its own thread, and how a block is made, zeroed and freed. +//! Memory: the blocks the consumer takes and releases, each a range of one of the device's +//! allocations; the pool that hands them out, keeps them, and frees idle allocations; the +//! allocations its own thread makes ahead of need, while a class's free bytes run low; and how +//! memory is made, zeroed and freed. use crate::counters::{Counters, Gauge, Metric}; use crate::device::{lock, Core}; use crate::error::{Error, Limit}; use crate::floor; +use crate::places::Ranges; use ash::vk; -use std::collections::HashSet; +use std::collections::{HashSet, VecDeque}; use std::ptr::NonNull; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant}; -/// Blocks of each class the device's making makes ([`stock`]) and the block-maker thread keeps -/// ready after it. -const READY: usize = 1; +/// The most bytes of a class's allocations in use (holding a live block) in each of the last +/// [`WINDOW_SECS`] seconds that had a take or a give-back, as `(second, bytes)`, the oldest first. +#[derive(Default)] +pub(crate) struct Peaks(VecDeque<(u64, u64)>); -/// A dedicated block's length is the length asked for, rounded up to this. -const DEDICATED_GRANULE: u64 = 64 << 10; +impl Peaks { + /// Records `live` bytes in use in second `now`, and forgets the seconds past the window. + pub(crate) fn note(&mut self, now: u64, live: u64) { + match self.0.back_mut() { + Some((second, most)) if *second == now => *most = (*most).max(live), + _ => self.0.push_back((now, live)), + } + while (self.0.front()).is_some_and(|&(second, _)| second + WINDOW_SECS <= now) { + self.0.pop_front(); + } + } + + /// The most bytes in use recorded in the window. + pub(crate) fn most(&self) -> u64 { + self.0.iter().map(|&(_, bytes)| bytes).max().unwrap_or(0) + } +} + +/// How many of a class's idle allocations of `idle` bytes, the oldest first, the idle rule frees: +/// the oldest, while the rest pass `peak`, the most bytes in use in the window, less `live`, the +/// bytes in use now, or `cap`. +pub(crate) fn surplus(idle: &[u64], peak: u64, live: u64, cap: u64) -> usize { + let room = peak.saturating_sub(live).min(cap); + let mut left: u64 = idle.iter().sum(); + idle.iter() + .take_while(|&&len| { + let over = left > room; + left -= len; + over + }) + .count() +} + +/// The length of each allocation the block-maker thread makes, and of an allocation a take makes +/// where no free range fits it, unless the take is longer: 16 MiB of either class. +/// +/// A driver may hold the device's other calls (pipeline creation, submissions, other allocations) +/// for the whole of an allocation's `vkAllocateMemory`, and the hold grows with the bytes: on an +/// RTX 3090 (NVIDIA's Linux driver) about 0.25 ms per MiB of Shared memory and a third of that of +/// Private; on a UHD Graphics 630 (Intel's Windows driver) 0.4 to 0.75 ms per MiB of Private +/// memory and about 0.1 of Shared. So allocations are short, and a take longer than one pays its +/// own length once: the allocation it makes serves later takes as free ranges. +const ALLOCATION_LEN: u64 = 16 << 20; + +/// The block-maker thread makes an allocation of a class while the class's free bytes, the free +/// ranges of all its allocations, are fewer than this: half an allocation. A take that leaves more +/// free makes nothing happen beside the consumer's next calls, so a small take beside a pipeline's +/// creation does not set off an allocation that the driver holds the creation for. +const MAKE_BELOW: u64 = ALLOCATION_LEN / 2; + +/// A block's length, and its first byte's offset in its allocation, are multiples of this, or of +/// the device's `bufferImageGranularity` where that is larger: no block shares a page of that +/// granularity with another, so a block of buffers lies beside a block of optimal images. +const GRANULE: u64 = 64 << 10; + +/// A block's first byte lies at a multiple of its length rounded up to a power of two, up to this +/// much, in its allocation: an image placed in a block at an offset its alignment allows from the +/// block's first byte is placed at one from the allocation's. +const BASE_ALIGN: u64 = 2 << 20; + +/// The idle rule's window: the pool keeps a class's idle allocations while their bytes and those +/// of the class's allocations in use stay at or under the most bytes the class had in use over the +/// last this many seconds. An allocation is in use while it holds a live block; weighing whole +/// allocations, not the blocks' bytes, keeps an allocation that serves the same blocks each frame, +/// whatever room they leave in it. +const WINDOW_SECS: u64 = 10; + +/// 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; /// `MTLStorageMode` of a block, as the buffers in it see it. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -31,40 +104,15 @@ pub enum MemoryClass { impl MemoryClass { const ALL: [MemoryClass; 2] = [MemoryClass::Private, MemoryClass::Shared]; - /// No Metal counterpart: the length of the class's pooled block, on every device: 16 MiB of - /// Shared memory, 64 MiB of Private. + /// No Metal counterpart: the length of the allocations the device makes for the class ahead + /// of need, 16 MiB of either class. /// - /// [`Device::take_block`](crate::Device::take_block) gives a pooled block for any length up - /// to it, and a dedicated one past it. - /// - /// A driver may hold the device's other calls (pipeline creation, submissions, other - /// allocations) for the whole of a block's `vkAllocateMemory`, and the hold grows with the - /// bytes, so the length sets how long one hold lasts. On an RTX 3090 (NVIDIA's Linux - /// driver) a pipeline state's creation beside a Shared block's making took 40 to 45 ms at - /// 256 MiB and 6 to 8 ms at 16 MiB, against 3 to 4 ms settled. Shared blocks are 16 MiB, the - /// largest piece a guest's allocator takes for its buffers. Private memory holds less: 3.4 to - /// 4.6 ms beside a 64 MiB block, at most 1 ms more than beside a 32 MiB one, and at 64 MiB a - /// texture or a Managed buffer's device copy of 32 MiB takes a pooled block. + /// A [`Device::take_block`](crate::Device::take_block) is a range of one of the class's + /// allocations, the first with room; the block-maker thread makes another while the class's + /// free bytes are fewer than half this. A take that no free range fits makes an allocation of + /// this length, or of its own where it is longer, which later takes share. pub const fn block_len(self) -> u64 { - match self { - MemoryClass::Private => 64 << 20, - MemoryClass::Shared => 16 << 20, - } - } - - /// 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, - } + ALLOCATION_LEN } /// The gauge of the class's idle bytes. @@ -84,7 +132,7 @@ impl MemoryClass { } /// No Metal counterpart: a block's number. Numbers start at 1 and are never reused during the -/// device's life; a block released and taken again keeps its number. +/// device's life; a block released and taken again at its length keeps its number. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct BlockId(u32); @@ -109,8 +157,8 @@ pub struct BlockInfo { pub id: BlockId, /// Its storage mode. pub class: MemoryClass, - /// [`MemoryClass::block_len`] for a pooled block; for a dedicated one, the length asked for - /// rounded up to 64 KiB. + /// The length asked for, rounded up to 64 KiB (to the device's `bufferImageGranularity` + /// where that is larger). pub len: u64, /// `gpuAddress` of the block's first byte: its `VkBuffer`'s device address. pub gpu_address: u64, @@ -118,9 +166,9 @@ pub struct BlockInfo { /// Private one. pub contents: Option>, /// Whether its memory type is device-local. A Private block is, unless the device-local type - /// was out of memory when it was made and it went to the next type its buffer takes (counted - /// in [`Gauges::spilled_bytes`](crate::Gauges::spilled_bytes)); a Shared block is where the - /// device's Shared type is. + /// was out of memory when its allocation was made and it went to the next type its buffer + /// takes (counted in [`Gauges::spilled_bytes`](crate::Gauges::spilled_bytes)); a Shared + /// block is where the device's Shared type is. pub device_local: bool, } @@ -130,12 +178,16 @@ unsafe impl Send for BlockInfo {} // SAFETY: as above. unsafe impl Sync for BlockInfo {} -/// No Metal counterpart: the consumer's hook before the runtime frees memory it handed out. +/// No Metal counterpart: the consumer's hook before the runtime frees memory it handed out, or +/// hands it out again in another block. /// -/// The runtime calls [`unmap`](BlockMappings::unmap) for every block it frees that -/// [`Device::take_block`](crate::Device::take_block) ever returned: a surplus released block, a -/// released dedicated block, and at teardown every such block still alive. Blocks the consumer -/// never took are freed without it. +/// The runtime calls [`unmap`](BlockMappings::unmap) once for every block +/// [`Device::take_block`](crate::Device::take_block) returned, before the block's bytes are freed +/// or become part of another block: when the pool gives a kept block's bytes back to its +/// allocation for a take of another length, when it frees an idle allocation, when a block given +/// back could not be zeroed or spilled, and at teardown for every block still alive. A block +/// released and taken again at its length keeps its number, address and mapping, and its hook has +/// not run. Blocks the consumer never took are freed without it. pub trait BlockMappings: Send + Sync { /// Returns only once every mapping of `block` the consumer made is gone and none of its /// threads touches the block's memory. The memory stays mapped and valid until it returns. @@ -147,16 +199,16 @@ pub trait BlockMappings: Send + Sync { fn unmap(&self, block: BlockId); } -/// A block's memory: its allocation, the `VkBuffer` that spans it, and its mapping. +/// A block: a range of an allocation, the `VkBuffer` bound to it alone, and its mapping. #[derive(Clone, Copy)] pub(crate) struct Memory { pub(crate) id: BlockId, pub(crate) class: MemoryClass, pub(crate) len: u64, - /// Made by the pool, to return to it when released; a dedicated block is freed instead. - pooled: bool, - pub(crate) buffer: vk::Buffer, + /// Its allocation, and its first byte's offset there. memory: vk::DeviceMemory, + base: u64, + pub(crate) buffer: vk::Buffer, pub(crate) address: u64, pub(crate) mapping: Option, /// Its memory type is device-local. @@ -166,14 +218,15 @@ pub(crate) struct Memory { } impl Memory { - /// The allocation. + /// The allocation the block is a range of; an image bound in the block binds at + /// [`base`](Self::base) plus its offset in the block. pub(crate) fn device_memory(&self) -> vk::DeviceMemory { self.memory } - /// Whether the pool made it, to keep once it is given back; a dedicated block is freed then. - pub(crate) fn pooled(&self) -> bool { - self.pooled + /// The offset of the block's first byte in its allocation. + pub(crate) fn base(&self) -> u64 { + self.base } /// Whether it is a Private block in another memory type than the Private one. @@ -193,13 +246,13 @@ impl Memory { } } -/// A host address in a Shared block's mapping, which lives as long as the block: its first byte, -/// or a buffer's. +/// A host address in a Shared allocation's mapping, which lives as long as the allocation: its +/// first byte, a block's or a buffer's. #[derive(Clone, Copy)] pub(crate) struct Mapping(NonNull); // SAFETY: an address. The runtime writes through it only while it owns the bytes: the block-maker -// thread zeroing a block no one holds, and `new_buffer` zeroing the range of the buffer it makes. +// thread zeroing memory no one holds, and `new_buffer` zeroing the range of the buffer it makes. unsafe impl Send for Mapping {} // SAFETY: as above. unsafe impl Sync for Mapping {} @@ -217,10 +270,10 @@ impl Mapping { /// /// # Safety /// - /// `self` is a block's first byte and `offset` is at most the block's length. + /// `self` is an allocation's or a block's first byte and `offset` is at most its length. pub(crate) unsafe fn at(self, offset: u64) -> NonNull { - // SAFETY: the mapping spans the block, and `offset` is inside it or one past its end; a - // block that was mapped has a length that fits the address space. + // SAFETY: the mapping spans the memory, and `offset` is inside it or one past its end; + // memory that was mapped has a length that fits the address space. unsafe { self.0.add(offset as usize) } } } @@ -245,57 +298,153 @@ impl Drop for Block { } } -/// The pool: blocks made ahead of need and blocks given back, which the block-maker thread -/// ([`run`]) zeroes, keeps or frees. +/// One `VkDeviceMemory` of a class and the ranges of it no block holds. +struct Allocation { + memory: vk::DeviceMemory, + len: u64, + mapping: Option, + device_local: bool, + spilled: bool, + /// Bytes no block holds, handed out or kept: zeroed. + free: Ranges, + /// Its blocks handed out and not yet given back to the pool. + live: usize, + /// When its last live block came back, in the pool's give-backs: the oldest idle allocation + /// is freed first. + emptied: u64, +} + +/// The pool: every allocation of each class, and the blocks given back and kept for a take of +/// their length. +/// +/// The block-maker thread ([`run`]) makes an allocation of a class while the class's free bytes +/// are fewer than [`MAKE_BELOW`]; a take never waits for it. A take that no free range fits, and +/// that no kept block of its length serves, makes an allocation itself, and where the class keeps +/// blocks of other lengths, asks the block-maker thread to give their bytes back to their +/// allocations, after the consumer's hook on that thread. Only where its allocation fails does it +/// wait, for those bytes, and look for a free range once more. It waits only while the block-maker +/// thread works for it, by one predicate both read: [`State::needs_maker`]. +/// +/// 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. pub(crate) struct Pool { state: Mutex, /// Signalled whenever the state changes, for the block-maker thread and for takers waiting /// on it. changed: Condvar, mappings: Option>, - /// The device's counters: the idle bytes and the dedicated blocks taken again. + /// The device's counters: the idle bytes, the allocations made and the blocks taken again. counters: Counters, + /// Per class, the most bytes of idle allocations: [`IDLE_SHARE`] of its memory type's heap. + caps: [u64; 2], + /// A block's length and its first byte's offset are multiples of this: [`GRANULE`], or the + /// device's `bufferImageGranularity` where that is larger. + granule: u64, + /// The idle rule's clock: seconds since the pool was made. + clock: Clock, } -/// 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 +/// The idle rule's clock, which the device tests move on. +struct Clock { + origin: Instant, + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + skew: Mutex, +} + +impl Clock { + fn new() -> Clock { + Clock { + origin: Instant::now(), + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + skew: Mutex::new(Duration::ZERO), + } + } + + fn seconds(&self) -> u64 { + let elapsed: Duration = self.origin.elapsed(); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + let elapsed = elapsed + *lock(&self.skew); + elapsed.as_secs() + } } struct State { - /// 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; 2], + /// Per class, its allocations in the order they were made. + allocations: [Vec; 2], + /// Per class, blocks given back, zeroed, the oldest first, with their number, buffer, address + /// and mapping, for a take of their length. Their bytes stay out of their allocation's free + /// ranges until the block-maker thread gives them back there, after the consumer's hook. + kept: [Vec; 2], + /// Per class, a take asked the block-maker thread for the class's kept blocks' bytes. + unkeep: [bool; 2], /// Blocks given back, for the block-maker thread. returned: Vec, - /// Per class, why the block-maker thread could not make the last block it tried, for the - /// next taker. It tries again once a taker has the error. - failed: [Option; 2], + /// Per class, the block-maker thread could not make the last allocation it tried. It tries + /// again after the class's next take or give-back. + failed: [bool; 2], stop: bool, next_id: u32, - /// The blocks `take_block` returned that are not yet freed: freeing one calls the hook. + /// The blocks `take_block` returned whose hook has not run: running it removes one. handed: HashSet, /// The hook has run for every block handed out ([`Pool::unmap_all`]); it never runs again. unmapped: bool, + /// Per class, the most bytes in use in each of the last seconds with a take or a give-back. + peaks: [Peaks; 2], + /// Per class, the idle allocations' bytes the class's gauge shows. + idle_bytes: [u64; 2], + /// Blocks given back so far: when each idle allocation emptied. + give_backs: u64, +} + +thread_local! { + /// Whether this thread is the block-maker thread ([`run`]), for the allocation-time metrics. + static ON_MAKER: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// What a block's `VkBuffer` is bound to: a range of an allocation. +#[derive(Clone, Copy)] +struct Carve { + memory: vk::DeviceMemory, + base: u64, + mapping: Option, + device_local: bool, + spilled: bool, } impl Pool { - pub(crate) fn new(mappings: Option>, counters: Counters) -> Pool { + /// The pool of a device whose classes' memory types are in heaps of `heaps` bytes (Private, + /// Shared) and whose `bufferImageGranularity` is `granularity`. + pub(crate) fn new( + mappings: Option>, + counters: Counters, + heaps: [u64; 2], + granularity: u64, + ) -> Pool { Pool { state: Mutex::new(State { - idle: [Vec::new(), Vec::new()], + allocations: [Vec::new(), Vec::new()], + kept: [Vec::new(), Vec::new()], + unkeep: [false, false], returned: Vec::new(), - failed: [None, None], + failed: [false, false], stop: false, next_id: 1, handed: HashSet::new(), unmapped: false, + peaks: [Peaks::default(), Peaks::default()], + idle_bytes: [0, 0], + give_backs: 0, }), changed: Condvar::new(), mappings, counters, + caps: heaps.map(|heap| heap / IDLE_SHARE), + granule: GRANULE.max(granularity.next_power_of_two()), + clock: Clock::new(), } } @@ -303,85 +452,257 @@ impl Pool { lock(&self.state) } - /// The zeroed pooled blocks of `class` no one holds: the tests wait for the block-maker thread - /// to have made its ready ones, and with them its fills' submissions. - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - pub(crate) fn idle(&self, class: MemoryClass) -> usize { - self.lock().ready(class) - } - fn wait<'a>(&self, state: MutexGuard<'a, State>) -> MutexGuard<'a, State> { self.changed .wait(state) .unwrap_or_else(PoisonError::into_inner) } - /// A new block number. - pub(crate) fn number(&self) -> Result { - number(&mut self.lock()) + /// 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). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn stocked(&self, class: MemoryClass) -> bool { + self.lock().free(class) >= MAKE_BELOW } - /// Takes a ready block of `class`, waiting for the block-maker thread where none is ready. - /// Err: why the block-maker thread could not make one; [`Error::Quiesced`] once it is stopped. - pub(crate) fn take(&self, class: MemoryClass) -> Result { + /// For the device tests: the class's allocations. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn allocations(&self, class: MemoryClass) -> usize { + self.lock().allocations[class.index()].len() + } + + /// For the device tests: the class's blocks given back, zeroed and kept. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn kept(&self, class: MemoryClass) -> usize { + self.lock().kept[class.index()].len() + } + + /// For the device tests: moves the idle rule's clock on by `by`. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn advance_clock(&self, by: Duration) { + *lock(&self.clock.skew) += by; + } + + /// The length and alignment of a block for a take of `len` bytes: its buffer's size rounded + /// up to the granule, at a multiple of that rounded up to a power of two (at most + /// [`BASE_ALIGN`]), of its buffer's alignment and of the granule. + /// + /// Err: [`Limit::BlockLen`] past `max`, the device's longest allocation and buffer. + fn shape(&self, core: &Core, len: u64, max: u64) -> Result<(u64, u64), Error> { + let asked = round(len, self.granule, max)?; + let info = vk::BufferCreateInfo::default() + .size(asked) + .usage(floor::BUFFER_USAGE) + .sharing_mode(vk::SharingMode::EXCLUSIVE); + let of = vk::DeviceBufferMemoryRequirements::default().create_info(&info); + let mut needs = vk::MemoryRequirements2::default(); + // SAFETY: the device is live, and the create info valid: `asked` is at most its + // `maxBufferSize`. + unsafe { + core.device + .get_device_buffer_memory_requirements(&of, &mut needs) + }; + let requirements = needs.memory_requirements; + let len = round(requirements.size.max(asked), self.granule, max)?; + Ok((len, base_align(len, requirements.alignment, self.granule))) + } + + /// Takes a block of `class` of at least `len` bytes for `core`: a kept block of its length, + /// with its number, buffer, address and mapping; else a free range, the first that fits in the + /// order the allocations were made, with a new number and buffer; else a range of an + /// allocation made here, of [`ALLOCATION_LEN`] or the block's length where that is longer. + /// Where the class keeps blocks of other lengths, that take also asks the block-maker thread to + /// give their bytes back; and where its allocation fails, it waits for them, and takes a free + /// range of them where one fits. Every block reads zero. + /// + /// Err: [`Limit::BlockLen`] past the device's longest allocation or buffer; + /// [`Limit::BlockIds`]; what [`make_allocation`] and binding the block's buffer return; + /// [`Error::Quiesced`] once the pool is stopped. + pub(crate) fn take( + &self, + core: &Core, + class: MemoryClass, + len: u64, + max: u64, + ) -> Result { + let (len, align) = self.shape(core, len, max)?; let index = class.index(); let mut state = self.lock(); - loop { + // A take is a pool event: the block-maker thread tries a failed allocation again. + state.failed[index] = false; + // Why this take's allocation failed, once it has waited for the kept blocks' bytes. + let mut failure = None; + let made = loop { if state.stop { return Err(Error::Quiesced); } - 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); + if let Some(at) = state.kept[index].iter().rposition(|kept| kept.len == len) { + let memory = state.kept[index].remove(at); + self.counters.count(Metric::BlocksReused); + self.hold(&mut state, &memory); + self.settle(&mut state, class); self.changed.notify_all(); return Ok(memory); } - if let Some(error) = state.failed[index].take() { - self.changed.notify_all(); + if let Some(carve) = state.fit(class, len, align) { + let id = number(&mut state)?; + drop(state); + break self.bind_range(core, class, len, carve, id); + } + if let Some(error) = failure { return Err(error); } - state = self.wait(state); - } - } - - /// 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 { + let asked = !state.kept[index].is_empty(); + if asked { + // The block-maker thread gives the kept blocks' bytes back, after the hook; this + // take does not wait for it. + state.unkeep[index] = true; + self.changed.notify_all(); + } + let id = number(&mut state)?; + drop(state); + match self.own(core, class, len, align, id) { + Ok(memory) => break Ok(memory), + Err(error) => { + state = self.lock(); + if !asked && !state.needs_maker(class) { + return Err(error); + } + while state.needs_maker(class) && !state.stop { + state = self.wait(state); + } + failure = Some(error); + } + } + }; + let memory = made?; 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) + state.note(class, self.clock.seconds()); + self.settle(&mut state, class); + // The block-maker thread runs the idle rule on this take, and makes an allocation where + // the class's free bytes ran low. + self.changed.notify_all(); + Ok(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 { - 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); + /// Makes block `id` of `len` bytes at `carve`, a range reserved for it; where that fails, the + /// range goes back, its bytes still zero. + fn bind_range( + &self, + core: &Core, + class: MemoryClass, + len: u64, + carve: Carve, + id: BlockId, + ) -> Result { + let bound = bind(core, class, len, carve, id); + if bound.is_err() { + let mut state = self.lock(); + let emptied = state.give_backs; + if let Some(allocation) = state.find(class, carve.memory) { + allocation.free.give(carve.base, len); + allocation.live -= 1; + if allocation.live == 0 { + allocation.emptied = emptied; + } + } + self.settle(&mut state, class); + } + bound + } + + /// Makes block `id` of `len` bytes at a multiple of `align` at the start of an allocation of + /// its own, of [`ALLOCATION_LEN`] or `len` where that is longer, whose rest later takes share. + fn own( + &self, + core: &Core, + class: MemoryClass, + len: u64, + align: u64, + id: BlockId, + ) -> Result { + let mut allocation = make_allocation(core, class, len.max(ALLOCATION_LEN))?; + let base = allocation.free.take(len, align).unwrap_or(0); + let carve = allocation.carve(base); + match bind(core, class, len, carve, id) { + Ok(memory) => { + allocation.live = 1; + self.lock().allocations[class.index()].push(allocation); + Ok(memory) + } + Err(error) => { + free_allocation(core, allocation); + Err(error) + } } } - /// Records a block as handed to the consumer, so that freeing it calls the hook. + /// Counts a kept block taken again as live in its allocation. + fn hold(&self, state: &mut State, memory: &Memory) { + if let Some(allocation) = state.find(memory.class, memory.memory) { + allocation.live += 1; + } + state.note(memory.class, self.clock.seconds()); + } + + /// Sets the class's idle gauge to its idle allocations' bytes. + fn settle(&self, state: &mut State, class: MemoryClass) { + let index = class.index(); + let idle: u64 = (state.allocations[index].iter()) + .filter(|allocation| allocation.live == 0) + .map(|allocation| allocation.len) + .sum(); + let was = state.idle_bytes[index]; + if idle > was { + self.counters.rise_by(class.idle_gauge(), idle - was); + } else { + self.counters.fall_by(class.idle_gauge(), was - idle); + } + 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)> { + let index = class.index(); + state.note(class, self.clock.seconds()); + let allocations = &state.allocations[index]; + let mut free: u64 = (allocations.iter()) + .filter(|allocation| allocation.live > 0) + .map(|allocation| allocation.free.bytes()) + .sum(); + let mut idle: Vec<(u64, vk::DeviceMemory, u64, u64)> = (allocations.iter()) + .filter(|allocation| allocation.live == 0) + .map(|allocation| { + let bytes = allocation.free.bytes(); + (allocation.emptied, allocation.memory, allocation.len, bytes) + }) + .collect(); + idle.sort_unstable_by_key(|&(emptied, ..)| std::cmp::Reverse(emptied)); + idle.retain(|&(.., bytes)| { + let reserve = free < MAKE_BELOW && bytes > 0; + if reserve { + free += bytes; + } + !reserve + }); + idle.reverse(); + let lens: Vec = 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 + } + + /// Records a block as handed to the consumer, so that its hook runs before its bytes are + /// freed or handed out in another block. pub(crate) fn hand(&self, block: BlockId) { let mut state = self.lock(); if !state.unmapped { @@ -389,9 +710,17 @@ impl Pool { } } + /// Runs the consumer's hook for `block` where it was handed out and its hook has not run. + fn unmap(&self, block: BlockId) { + let handed = self.lock().handed.remove(&block); + if let Some(mappings) = self.mappings.as_ref().filter(|_| handed) { + mappings.unmap(block); + } + } + /// In [`Device::quiesce`](crate::Device::quiesce) and at teardown, once the runtime's other - /// threads are stopped: calls the hook for every block handed out and not yet freed, on this - /// thread. No block's hook runs again: a block freed later is freed without it. + /// threads are stopped: calls the hook for every block handed out whose hook has not run, on + /// this thread. No block's hook runs again: a block freed later is freed without it. pub(crate) fn unmap_all(&self) { let mut handed: Vec = { let mut state = self.lock(); @@ -407,7 +736,7 @@ impl Pool { } /// Takes back a block taken with [`take`](Self::take), for the block-maker thread to zero and - /// keep, or free. + /// keep, or give back to its allocation. pub(crate) fn give_back(&self, memory: Memory) { self.lock().returned.push(memory); self.changed.notify_all(); @@ -419,42 +748,115 @@ impl Pool { self.changed.notify_all(); } - /// At teardown, after the block-maker thread is joined: every block the pool still has. - pub(crate) fn remaining(&mut self) -> Vec { - let state = self.state.get_mut().unwrap_or_else(PoisonError::into_inner); - 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 - } - - /// For the device tests: whether the pool has the block back, idle or still to be zeroed. + /// For the device tests: whether the pool has the block back, kept or still to be zeroed. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn holds(&self, block: BlockId) -> bool { let state = self.lock(); - state - .idle - .iter() - .flatten() + (state.kept.iter().flatten()) .chain(&state.returned) .any(|memory| memory.id == block) } } impl State { - /// The idle pooled blocks of `class`: those [`Pool::take`] hands out. The idle dedicated - /// blocks beside them serve only [`Pool::take_held`]. - fn ready(&self, class: MemoryClass) -> usize { - self.idle[class.index()] - .iter() - .filter(|memory| memory.pooled) - .count() + /// Whether the block-maker thread works for a take of `class`: a take asked for the class's + /// kept blocks' bytes, which the thread has not yet given back to their allocations. + /// [`Pool::take`] waits only while this holds, and [`run`] works while it holds for any class. + fn needs_maker(&self, class: MemoryClass) -> bool { + self.unkeep[class.index()] } + + /// The bytes of the free ranges of the class's allocations. + fn free(&self, class: MemoryClass) -> u64 { + (self.allocations[class.index()].iter()) + .map(|allocation| allocation.free.bytes()) + .sum() + } + + /// The allocation of `class` whose memory is `memory`. + fn find(&mut self, class: MemoryClass, memory: vk::DeviceMemory) -> Option<&mut Allocation> { + (self.allocations[class.index()].iter_mut()).find(|allocation| allocation.memory == memory) + } + + /// Reserves `len` bytes at a multiple of `align` in the first allocation of `class` with such + /// a free range, counting a block live there. + fn fit(&mut self, class: MemoryClass, len: u64, align: u64) -> Option { + (self.allocations[class.index()].iter_mut()).find_map(|allocation| { + let base = allocation.free.take(len, align)?; + allocation.live += 1; + Some(allocation.carve(base)) + }) + } + + /// The bytes of the class's allocations that hold a live block. + fn in_use(&self, class: MemoryClass) -> u64 { + (self.allocations[class.index()].iter()) + .filter(|allocation| allocation.live > 0) + .map(|allocation| allocation.len) + .sum() + } + + /// Records the class's bytes in use now in the second `now`. + fn note(&mut self, class: MemoryClass, now: u64) { + let in_use = self.in_use(class); + self.peaks[class.index()].note(now, in_use); + } + + /// Takes the allocation of `class` whose memory is `memory` out of the pool, with its kept + /// blocks, for the caller to free once they are retired. + fn take_out( + &mut self, + class: MemoryClass, + memory: vk::DeviceMemory, + ) -> Option<(Allocation, Vec)> { + let index = class.index(); + let at = + (self.allocations[index].iter()).position(|allocation| allocation.memory == memory)?; + let allocation = self.allocations[index].remove(at); + let (kept, stay): (Vec, Vec) = + (self.kept[index].drain(..)).partition(|kept| kept.memory == memory); + self.kept[index] = stay; + Some((allocation, kept)) + } +} + +impl Allocation { + /// What a block's buffer at `base` binds to. + fn carve(&self, base: u64) -> Carve { + Carve { + memory: self.memory, + base, + // SAFETY: `base` is inside the allocation, which the mapping spans. + mapping: self + .mapping + .map(|mapping| Mapping(unsafe { mapping.at(base) })), + device_local: self.device_local, + spilled: self.spilled, + } + } +} + +/// A block's length for `len` bytes: `len` (at least 1) rounded up to `granule`, a power of two. +/// +/// Err: [`Limit::BlockLen`] past `max`, the device's longest allocation and buffer. +pub(crate) fn round(len: u64, granule: u64, max: u64) -> Result { + match len.max(1).checked_next_multiple_of(granule) { + Some(rounded) if rounded <= max => Ok(rounded), + rounded => Err(Error::Limit(Limit::BlockLen { + len: rounded.unwrap_or(u64::MAX), + max, + })), + } +} + +/// The alignment of the first byte of a block of `len` bytes in its allocation: `len` rounded up +/// to a power of two, at most [`BASE_ALIGN`], and at least its buffer's `alignment` and the +/// `granule`. +pub(crate) fn base_align(len: u64, alignment: u64, granule: u64) -> u64 { + (len.checked_next_power_of_two().unwrap_or(BASE_ALIGN)) + .min(BASE_ALIGN) + .max(alignment) + .max(granule) } fn number(state: &mut State) -> Result { @@ -463,108 +865,137 @@ fn number(state: &mut State) -> Result { Ok(BlockId(id)) } -/// In the device's making, before the block-maker thread starts: makes [`READY`] blocks of each -/// class, so the consumer's first block of each class is ready as the device is, and no block is -/// made beside the consumer's first calls. A driver may hold the device's other calls while it -/// allocates a block's memory: on an RTX 3090 (NVIDIA's Linux driver), a pipeline state's creation -/// right after the device's making waited 47 to 61 ms behind the block-maker thread's first 256 MiB -/// Shared block, against 2.4 to 3.1 ms once the block was made here. A class whose block cannot be made -/// keeps why for its next taker, as the block-maker thread does. +/// In the device's making, before the block-maker thread starts: makes each class's first +/// allocation, so the consumer's first blocks of each class are ranges of it as the device is +/// ready, and nothing is allocated beside the consumer's first calls. Where one cannot be made, +/// the block-maker thread tries again after the class's next take or give-back. pub(crate) fn stock(core: &Core) { for class in MemoryClass::ALL { - for _ in 0..READY { - let made = - (core.pool.number()).and_then(|id| make(core, class, class.block_len(), id, true)); - let mut state = core.pool.lock(); - 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); - } + let made = make_allocation(core, class, ALLOCATION_LEN); + let mut state = core.pool.lock(); + match made { + Ok(allocation) => state.allocations[class.index()].push(allocation), + Err(_) => state.failed[class.index()] = true, } + core.pool.settle(&mut state, class); } } -/// The block-maker thread, until the device's teardown stops it. Off every caller's path, it -/// 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`] pooled ones idle, -/// whatever dedicated ones it keeps. +/// 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 zeroes each block given back and keeps it for a take of its +/// length (or gives its bytes back, after the hook, where it cannot be zeroed or 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`]. pub(crate) fn run(core: Arc) { + ON_MAKER.set(true); let pool = &core.pool; let mut state = pool.lock(); loop { if state.stop { return; } - 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.spilled && memory.len <= memory.class.idle_bound(); + if let Some(class) = MemoryClass::ALL + .into_iter() + .find(|c| state.unkeep[c.index()]) + { + let kept: Vec = state.kept[class.index()].drain(..).collect(); drop(state); - // 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 + for memory in &kept { + retire(&core, memory); + } + state = pool.lock(); + for memory in &kept { + if let Some(allocation) = state.find(class, memory.memory) { + allocation.free.give(memory.base, memory.len); } - false => vec![memory], - }; - for memory in gone { - free(&core, memory); + } + state.unkeep[class.index()] = false; + pool.changed.notify_all(); + continue; + } + if let Some(memory) = state.returned.pop() { + drop(state); + // A block that cannot be zeroed, or spilled, 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. + let kept = !memory.spilled && zero(&core, &memory, 0, memory.len).is_ok(); + if !kept { + retire(&core, &memory); + } + state = pool.lock(); + let class = memory.class; + // The block's allocation was in use until now, however long ago it was taken. + state.note(class, pool.clock.seconds()); + 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 { + allocation.free.give(memory.base, memory.len); + } + if allocation.live == 0 { + allocation.emptied = emptied; + spilled = allocation.spilled.then_some(allocation.memory); + } + } + 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.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 wanted = MemoryClass::ALL - .into_iter() - .find(|class| state.ready(*class) < READY && state.failed[class.index()].is_none()); - if let Some(class) = wanted { - let id = number(&mut state); + let gone: Vec<(Allocation, Vec)> = (MemoryClass::ALL.into_iter()) + .flat_map(|class| pool.trim(&mut state, class)) + .collect(); + if !gone.is_empty() { drop(state); - let made = id.and_then(|id| make(&core, class, class.block_len(), id, true)); - state = pool.lock(); - let gone = match made { - Ok(memory) => pool.keep(&mut state, memory), - Err(error) => { - state.failed[class.index()] = Some(error); - Vec::new() + for (allocation, kept) in gone { + for memory in &kept { + retire(&core, memory); } - }; - pool.changed.notify_all(); - if !gone.is_empty() { - drop(state); - for memory in gone { - free(&core, memory); - } - state = pool.lock(); + free_allocation(&core, allocation); } + state = pool.lock(); + continue; + } + let wanted = (MemoryClass::ALL.into_iter()) + .find(|&class| !state.failed[class.index()] && state.free(class) < MAKE_BELOW); + if let Some(class) = wanted { + drop(state); + let made = make_allocation(&core, class, ALLOCATION_LEN); + state = pool.lock(); + match made { + Ok(mut allocation) => { + // Newer than every idle allocation: the idle rule frees it last. + allocation.emptied = state.give_backs; + state.allocations[class.index()].push(allocation); + } + Err(_) => state.failed[class.index()] = true, + } + pool.settle(&mut state, class); + pool.changed.notify_all(); continue; } state = pool.wait(state); } } -/// The length of a dedicated block for `len` bytes: `len` rounded up to 64 KiB, where the device -/// holds that in one allocation and one buffer (`max`). -pub(crate) fn dedicated_len(len: u64, max: u64) -> Result { - match len.checked_next_multiple_of(DEDICATED_GRANULE) { - Some(rounded) if rounded <= max => Ok(rounded), - rounded => Err(Error::Limit(Limit::BlockLen { - len: rounded.unwrap_or(len), - max, - })), - } -} - /// [`allocate`] of `info`, and for Private memory, where the device-local type is out of device /// memory, of each other type `bits` allows in the device's order until one is not: the spill /// the plan decided, on the allocation's own error and never a budget poll. Returns the memory @@ -608,7 +1039,8 @@ pub(crate) unsafe fn allocate_spilling( /// `vkAllocateMemory`, every allocation the runtime makes: one more live allocation in /// `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. +/// 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. /// /// # Safety /// @@ -622,8 +1054,11 @@ pub(crate) unsafe fn allocate( if !counters.rise_below(Gauge::Blocks, u64::from(max)) { return Err(Error::Limit(Limit::MemoryAllocations { max })); } + let start = crate::host_time(); // SAFETY: the caller's. - unsafe { device.allocate_memory(info, None) }.map_err(|result| { + let allocated = unsafe { device.allocate_memory(info, None) }; + counters.allocation_time(crate::host_time().saturating_sub(start), ON_MAKER.get()); + allocated.map_err(|result| { counters.fall(Gauge::Blocks); Error::Vulkan { call: "vkAllocateMemory", @@ -632,36 +1067,35 @@ pub(crate) unsafe fn allocate( }) } -/// Makes a zeroed block of `len` bytes of `class`: a `VkBuffer` with every buffer usage, bound to -/// an allocation of its own with a device address, and for Shared mapped and zeroed through the -/// mapping, which also makes every page resident before anyone holds the block. -pub(crate) fn make( - core: &Core, - class: MemoryClass, - len: u64, - id: BlockId, - pooled: bool, -) -> Result { - let device = &core.device; +/// A `VkBuffer` of `len` bytes with every buffer usage. +fn new_buffer(device: &ash::Device, len: u64) -> Result { let info = vk::BufferCreateInfo::default() .size(len) .usage(floor::BUFFER_USAGE) .sharing_mode(vk::SharingMode::EXCLUSIVE); // SAFETY: the device is live; `len` is at most the device's `maxBufferSize`. - let buffer = - unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?; + unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer")) +} + +/// Makes a zeroed allocation of `len` bytes of `class` with device addresses, mapped whole if +/// Shared, its free ranges all of it. A Shared allocation is zeroed through the mapping, which +/// also makes every page resident before any block holds it; a Private one by a GPU fill through +/// a buffer over it, destroyed after. +fn make_allocation(core: &Core, class: MemoryClass, len: u64) -> Result { + let device = &core.device; + let buffer = new_buffer(device, len)?; // SAFETY: `buffer` is the device's. let requirements = unsafe { device.get_buffer_memory_requirements(buffer) }; let mut flags = vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); - let allocation = vk::MemoryAllocateInfo::default() - .allocation_size(requirements.size) + let info = vk::MemoryAllocateInfo::default() + .allocation_size(requirements.size.max(len)) .memory_type_index(core.memory_type(class)) .push_next(&mut flags); let bits = requirements.memory_type_bits; // SAFETY: the floor chose the memory type for buffers of this usage on this device, and // `bufferDeviceAddress` is enabled; a spill takes a type the buffer's requirements allow. - let allocated = unsafe { allocate_spilling(core, class, bits, &allocation) }; + let allocated = unsafe { allocate_spilling(core, class, bits, &info) }; let (memory, spilled) = match allocated { Ok(memory) => memory, Err(error) => { @@ -671,52 +1105,102 @@ pub(crate) fn make( } }; core.counters.count(Metric::BlocksMade); - let device_local = match spilled { - true => false, - false => core.device_local & (1 << core.memory_type(class)) != 0, - }; + core.counters.allocated(len); if spilled { core.counters.rise_by(Gauge::SpilledBytes, len); } - let mut block = Memory { - id, - class, - len, - pooled, - buffer, + let device_local = !spilled && core.device_local & (1 << core.memory_type(class)) != 0; + let mut allocation = Allocation { memory, - address: 0, + len, mapping: None, device_local, spilled, + free: Ranges::new(len), + live: 0, + emptied: 0, }; - match finish(core, &mut block) { - Ok(()) => Ok(block), + let zeroed = finish(core, class, &mut allocation, buffer); + // SAFETY: the fill that used it completed, or none was recorded. + unsafe { device.destroy_buffer(buffer, None) }; + match zeroed { + Ok(()) => Ok(allocation), Err(error) => { - free(core, block); + free_allocation(core, allocation); Err(error) } } } -/// Binds a new block's memory, reads its address, maps it if Shared, and zeroes it. -fn finish(core: &Core, block: &mut Memory) -> Result<(), Error> { +/// Maps a new Shared allocation, and zeroes a new allocation through `buffer`, bound to it whole +/// for a Private one. +fn finish( + core: &Core, + class: MemoryClass, + allocation: &mut Allocation, + buffer: vk::Buffer, +) -> Result<(), Error> { let device = &core.device; - // SAFETY: the allocation is the buffer's size and of a type its requirements allow. - unsafe { device.bind_buffer_memory(block.buffer, block.memory, 0) } - .map_err(Error::vulkan("vkBindBufferMemory"))?; - let address = vk::BufferDeviceAddressInfo::default().buffer(block.buffer); - // SAFETY: the buffer has device-address usage and is bound. - block.address = unsafe { device.get_buffer_device_address(&address) }; - if block.class == MemoryClass::Shared { + if class == MemoryClass::Shared { // SAFETY: the memory type is host-visible, and the memory is not mapped. let pointer = unsafe { - device.map_memory(block.memory, 0, vk::WHOLE_SIZE, vk::MemoryMapFlags::empty()) + device.map_memory( + allocation.memory, + 0, + vk::WHOLE_SIZE, + vk::MemoryMapFlags::empty(), + ) } .map_err(Error::vulkan("vkMapMemory"))?; - block.mapping = NonNull::new(pointer.cast::()).map(Mapping); + allocation.mapping = NonNull::new(pointer.cast::()).map(Mapping); + if let Some(mapping) = allocation.mapping { + // SAFETY: the mapping spans the allocation, which no one else holds. + unsafe { mapping.0.as_ptr().write_bytes(0, allocation.len as usize) }; + } + return Ok(()); } - zero(core, block, 0, block.len) + // SAFETY: the allocation is the buffer's size and of a type its requirements allow. + unsafe { device.bind_buffer_memory(buffer, allocation.memory, 0) } + .map_err(Error::vulkan("vkBindBufferMemory"))?; + core.filler.zero(core, buffer, 0, allocation.len) +} + +/// Makes block `id` of `class`: a buffer of `len` bytes bound at `carve`'s range, its address and +/// its mapping. Its bytes are already zero. +fn bind( + core: &Core, + class: MemoryClass, + len: u64, + carve: Carve, + id: BlockId, +) -> Result { + let device = &core.device; + let buffer = new_buffer(device, len)?; + // SAFETY: the range is `len` bytes of an allocation of a type the buffer's requirements allow, + // at a multiple of their alignment ([`Pool::shape`]), and no other buffer is bound there. + if let Err(result) = unsafe { device.bind_buffer_memory(buffer, carve.memory, carve.base) } { + // SAFETY: `buffer` is unused. + unsafe { device.destroy_buffer(buffer, None) }; + return Err(Error::Vulkan { + call: "vkBindBufferMemory", + result, + }); + } + let info = vk::BufferDeviceAddressInfo::default().buffer(buffer); + // SAFETY: the buffer has device-address usage and is bound. + let address = unsafe { device.get_buffer_device_address(&info) }; + Ok(Memory { + id, + class, + len, + memory: carve.memory, + base: carve.base, + buffer, + address, + mapping: carve.mapping, + device_local: carve.device_local, + spilled: carve.spilled, + }) } /// Zeroes `offset..end` of a block: through the mapping for Shared, by a GPU fill for Private. @@ -737,25 +1221,52 @@ fn zero(core: &Core, memory: &Memory, offset: u64, end: u64) -> Result<(), Error } } -/// Frees a block, calling the consumer's hook first where it was handed out and the hook has not -/// run for it. Freeing the memory also unmaps it. -pub(crate) fn free(core: &Core, memory: Memory) { - let handed = core.pool.lock().handed.remove(&memory.id); - if handed { - if let Some(mappings) = &core.pool.mappings { - mappings.unmap(memory.id); - } - } - let device = &core.device; +/// Ends a block: the consumer's hook where it was handed out and its hook has not run, then its +/// buffer. Its bytes stay in its allocation. +fn retire(core: &Core, memory: &Memory) { + core.pool.unmap(memory.id); // SAFETY: no GPU work that uses the block is pending: a command buffer or upload that uses it // holds it until it retires, and the fills of the block-maker thread are waited for. The // consumer's mappings are gone. - unsafe { - device.destroy_buffer(memory.buffer, None); - device.free_memory(memory.memory, None); - } + unsafe { core.device.destroy_buffer(memory.buffer, None) }; +} + +/// 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. + unsafe { core.device.free_memory(allocation.memory, None) }; core.counters.fall(Gauge::Blocks); - if memory.spilled { - core.counters.fall_by(Gauge::SpilledBytes, memory.len); + if allocation.spilled { + core.counters.fall_by(Gauge::SpilledBytes, allocation.len); + } +} + +/// At teardown, after the block-maker thread is joined and every resource is freed: retires +/// `blocks`, the blocks the runtime's own places still hold, and the blocks the pool has back, +/// then frees every allocation. +pub(crate) fn free_all(core: &mut Core, blocks: Vec) { + let mut retired: Vec = blocks; + let mut allocations = Vec::new(); + let mut idle = [0; 2]; + { + let state = (core.pool.state.get_mut()).unwrap_or_else(PoisonError::into_inner); + for class in MemoryClass::ALL { + let index = class.index(); + retired.extend(state.kept[index].drain(..)); + allocations.extend(state.allocations[index].drain(..)); + idle[index] = state.idle_bytes[index]; + state.idle_bytes[index] = 0; + } + retired.append(&mut state.returned); + } + for class in MemoryClass::ALL { + core.counters + .fall_by(class.idle_gauge(), idle[class.index()]); + } + for memory in &retired { + retire(core, memory); + } + for allocation in allocations { + free_allocation(core, allocation); } } diff --git a/crates/metal2vulkan-rt/src/places.rs b/crates/metal2vulkan-rt/src/places.rs index c819130bd..671d9031b 100644 --- a/crates/metal2vulkan-rt/src/places.rs +++ b/crates/metal2vulkan-rt/src/places.rs @@ -4,11 +4,12 @@ //! buffer lies beside an optimal image in one allocation. //! //! A place is a resource's bytes at a multiple of its alignment: the first that fits, in the -//! blocks in the order they were taken; where none fits, the next block comes from the pool, or, -//! for a place longer than a pooled block, a dedicated block of its own. A place is free again once -//! its resource is freed, after every command buffer and upload that used it retired. One empty -//! pooled block of a set is kept for the next place; another that empties, and a dedicated block -//! once empty, goes back to the pool, which zeroes and keeps a pooled block or frees it. +//! blocks in the order they were taken; where none fits, the next block comes from the pool: of +//! the class's block length ([`MemoryClass::block_len`]), or of the place's own length where that +//! is longer. A place is free again once its resource is freed, after every command buffer and +//! upload that used it retired. One empty block of the block length is kept for the next place; +//! another block that empties goes back to the pool, which zeroes and keeps it for a take of its +//! length. //! //! An image in a texture block is optimal. The block's own `VkBuffer`, which spans it, aliases the //! images (Vulkan's memory aliasing), and only the pool uses it: to zero the block before it is @@ -20,6 +21,9 @@ use crate::error::Error; use crate::memory::{BlockId, Memory, MemoryClass}; use std::sync::{Mutex, PoisonError}; +/// The length of the blocks a set takes for places no longer than it. +const BLOCK_LEN: u64 = MemoryClass::Private.block_len(); + /// One set of blocks. pub(crate) struct Places { blocks: Mutex>, @@ -48,8 +52,8 @@ impl Places { } /// A place of `len` bytes at a multiple of `align`, a power of two, and its block. Where no - /// block has room, a Private block is taken, without the lock: from the pool, or a dedicated - /// one for a place longer than a pooled block. + /// block has room, a Private block is taken from the pool, without the lock: of the block + /// length, or of `len` where that is longer. /// /// Err: what [`Core::take_memory`] returns. pub(crate) fn place( @@ -61,7 +65,8 @@ impl Places { let mut blocks = lock(&self.blocks); loop { for block in blocks.iter_mut() { - if let Some(offset) = block.free.take(len, align) { + // The image's alignment holds in the allocation the block is a range of. + if let Some(offset) = block.free.take_from(len, align, block.memory.base()) { block.live += 1; let place = Place { block: block.memory.id, @@ -72,7 +77,7 @@ impl Places { } } drop(blocks); - let memory = core.take_memory(MemoryClass::Private, len)?; + let memory = core.take_memory(MemoryClass::Private, len.max(BLOCK_LEN))?; // A block that spilled out of device-local memory holds no place: textures then take // memory of their own, and a Managed buffer its Shared range. if memory.spilled() { @@ -88,8 +93,8 @@ impl Places { } } - /// Frees `place`. Where its block empties and is dedicated, or another pooled block of the - /// set is empty, the block goes back to the pool. + /// Frees `place`. Where its block empties and is longer than the block length, or another + /// block of the set of that length is empty, the block goes back to the pool. pub(crate) fn release(&self, core: &Core, place: Place) { let mut blocks = lock(&self.blocks); let Some(index) = (blocks.iter()).position(|block| block.memory.id == place.block) else { @@ -98,9 +103,9 @@ impl Places { let block = &mut blocks[index]; block.free.give(place.offset, place.len); block.live -= 1; - let empty = |block: &PlaceBlock| block.live == 0 && block.memory.pooled(); - let surplus = - !block.memory.pooled() || blocks.iter().filter(|block| empty(block)).count() > 1; + let standard = |block: &PlaceBlock| block.memory.len == BLOCK_LEN; + let empty = |block: &PlaceBlock| block.live == 0 && standard(block); + let surplus = !standard(block) || blocks.iter().filter(|block| empty(block)).count() > 1; if blocks[index].live == 0 && surplus { let emptied = blocks.remove(index); drop(blocks); @@ -140,8 +145,16 @@ impl Ranges { /// Takes `len` bytes, more than 0, at the first offset that is a multiple of `align`, a power /// of two, with the bytes free from it; `None` where there is none. pub(crate) fn take(&mut self, len: u64, align: u64) -> Option { + self.take_from(len, align, 0) + } + + /// Takes `len` bytes, more than 0, at the first offset that lies `base` bytes past a multiple + /// of `align`, a power of two, less `base`, with the bytes free from it: the first offset + /// aligned where the ranges start `base` bytes into something larger. `None` where there is + /// none. + pub(crate) fn take_from(&mut self, len: u64, align: u64, base: u64) -> Option { let (index, at) = (self.free.iter().enumerate()).find_map(|(index, &(start, end))| { - let at = start.checked_next_multiple_of(align)?; + let at = start.checked_add(base)?.checked_next_multiple_of(align)? - base; (at.checked_add(len)? <= end).then_some((index, at)) })?; let (start, end) = self.free[index]; @@ -177,6 +190,11 @@ impl Ranges { } } + /// The bytes free. + pub(crate) fn bytes(&self) -> u64 { + self.free.iter().map(|&(start, end)| end - start).sum() + } + /// For the tests: the free ranges. #[cfg(test)] pub(crate) fn free(&self) -> &[(u64, u64)] { diff --git a/crates/metal2vulkan-rt/src/tests/blit.rs b/crates/metal2vulkan-rt/src/tests/blit.rs index 7dbea7051..9652b8341 100644 --- a/crates/metal2vulkan-rt/src/tests/blit.rs +++ b/crates/metal2vulkan-rt/src/tests/blit.rs @@ -1690,13 +1690,13 @@ pub(crate) mod on_device { }); } - /// Returns once the pool holds a ready block of each class again: the block-maker thread - /// makes one after a block is taken, a Private one zeroed in a submission of its own, which a + /// Returns once the block-maker thread has nothing to make: it makes an allocation of a + /// class whose free bytes run low, a Private one zeroed in a submission of its own, which a /// count of a test's own work must not take in. pub(crate) fn settled(device: &Device) { - within("a ready block of each class", || { + within("8 MiB free in each class", || { let pool = &device.core().pool; - pool.idle(MemoryClass::Private) > 0 && pool.idle(MemoryClass::Shared) > 0 + pool.stocked(MemoryClass::Private) && pool.stocked(MemoryClass::Shared) }); } diff --git a/crates/metal2vulkan-rt/src/tests/command.rs b/crates/metal2vulkan-rt/src/tests/command.rs index a413044e6..d028c07cd 100644 --- a/crates/metal2vulkan-rt/src/tests/command.rs +++ b/crates/metal2vulkan-rt/src/tests/command.rs @@ -915,14 +915,14 @@ pub(crate) mod on_device { } /// A Private buffer of a whole block, for work that keeps the GPU busy. It returns once the - /// block-maker thread has made the next ready Private block, whose zero fill is a submission - /// of its own, so the submissions a test counts after it are its command buffers'. + /// block-maker thread has made any Private allocation the take set off, whose zero fill is a + /// submission of its own, so the submissions a test counts after it are its command buffers'. fn private(device: &Device) -> Buffer { let block = device - .take_block(MemoryClass::Private, 1) + .take_block(MemoryClass::Private, MemoryClass::Private.block_len()) .expect("a Private block"); - within("the next ready Private block", || { - device.core().pool.idle(MemoryClass::Private) > 0 + within("8 MiB of Private memory free", || { + device.core().pool.stocked(MemoryClass::Private) }); device .new_buffer(block.id, 0, MemoryClass::Private.block_len(), false) @@ -1655,20 +1655,14 @@ pub(crate) mod on_device { } /// A block whose last handle drops, with no `release_block`, while a held command buffer uses - /// it: its number names nothing at once, and the block stays live until the command buffer - /// completes, then is freed. It is a dedicated block, which the pool does not keep, so the - /// live allocations fall back to where they were. + /// it: its number names nothing at once, and the block stays out of the pool until the + /// command buffer completes, then comes back to it. #[test] - fn every_device_frees_a_dropped_block_once_its_last_command_buffer_retires() { + fn every_device_gives_back_a_dropped_block_once_its_last_command_buffer_retires() { each_device("block_drop", |name, _, device| { - let counters = device.counters(); let f = shared_event(&device); let queue = queue(&device); - crate::tests::blit::on_device::settled(&device); - let before = counters.gauges().blocks; - // Longer than the class's idle bound, so it is freed once given back. - let len = MemoryClass::Shared.idle_bound() + 1; - let block = (device.take_block(MemoryClass::Shared, len)).expect("a dedicated block"); + let block = (device.take_block(MemoryClass::Shared, 1)).expect("a Shared block"); let id = block.id; let buffer = (device.new_buffer(id, 0, 4096, false)).expect("a buffer"); let held = queue.command_buffer().expect("a command buffer"); @@ -1681,50 +1675,42 @@ pub(crate) mod on_device { "{name}: the dropped block's number" ); thread::sleep(Duration::from_millis(50)); - assert_eq!( - counters.gauges().blocks, - before + 1, - "{name}: live while in use" - ); + let pool = &device.core().pool; + assert!(!pool.holds(id), "{name}: back while in use"); f.set_signaled_value(1); finished(name, &held); - within("the dropped block freed", || { - counters.gauges().blocks == before - }); + within("the dropped block's return", || pool.holds(id)); drop((f, queue, device)); }); } /// Clones of a block's handle share one claim: dropping one of two gives nothing back, and - /// the block's number still names it; releasing the other frees it. A handle that outlives - /// its device finds its block freed by the teardown, every gauge zero, and its drop does - /// nothing. + /// the block's number still names it; releasing the other gives it back. A handle that + /// outlives its device finds its block freed by the teardown, every gauge zero, and its drop + /// does nothing. #[test] - fn every_device_frees_a_block_at_its_last_clone_and_at_teardown() { + fn every_device_gives_back_a_block_at_its_last_clone_and_frees_it_at_teardown() { each_device("block_clones", |name, _, device| { let counters = device.counters(); - crate::tests::blit::on_device::settled(&device); - let before = counters.gauges().blocks; - // Longer than the class's idle bound, so it is freed once given back. - let len = MemoryClass::Shared.idle_bound() + 1; - let block = (device.take_block(MemoryClass::Shared, len)).expect("a dedicated block"); + let pool = &device.core().pool; + let block = (device.take_block(MemoryClass::Shared, 1)).expect("a Shared block"); + let id = block.id; let clone = block.clone(); drop(block); thread::sleep(Duration::from_millis(50)); - assert_eq!( - counters.gauges().blocks, - before + 1, - "{name}: one of two clones dropped" + assert!( + !pool.holds(id), + "{name}: back with one of two clones dropped" ); let buffer = (device.new_buffer(clone.id, 0, 256, false)) .unwrap_or_else(|error| panic!("{name}: the clone's number: {error}")); drop(buffer); device.release_block(clone).expect("a release"); - within("the block freed at its last clone", || { - counters.gauges().blocks == before - }); + within("the block back at its last clone", || pool.holds(id)); - let kept = (device.take_block(MemoryClass::Shared, len)).expect("a dedicated block"); + let kept = (device + .take_block(MemoryClass::Shared, 2 * MemoryClass::Shared.block_len())) + .expect("a long block"); drop(device); within("the teardown", || counters.gauges() == Gauges::default()); drop(kept); @@ -1789,7 +1775,10 @@ pub(crate) mod on_device { .take_block(MemoryClass::Shared, MemoryClass::Shared.block_len()) .expect("a Shared block"); let released: Vec<_> = (0..3) - .map(|_| device.take_block(MemoryClass::Shared, 1).expect("a block")) + .map(|_| { + (device.take_block(MemoryClass::Shared, MemoryClass::Shared.block_len())) + .expect("a block") + }) .collect(); let address = block.contents.expect("contents").as_ptr() as usize; *lock(&READER) = Some(thread::spawn(move || { diff --git a/crates/metal2vulkan-rt/src/tests/heap.rs b/crates/metal2vulkan-rt/src/tests/heap.rs index 9fe5a1576..bdb528e8d 100644 --- a/crates/metal2vulkan-rt/src/tests/heap.rs +++ b/crates/metal2vulkan-rt/src/tests/heap.rs @@ -31,11 +31,10 @@ mod on_device { each_device("heap", |name, _, device| { let core = device.core(); let counters = device.counters(); - let block = (device.take_block(MemoryClass::Private, 1)) + let block = (device.take_block(MemoryClass::Private, MemoryClass::Private.block_len())) .unwrap_or_else(|error| panic!("{name}: {error}")); - wait_until("a ready block of each class", || { - core.pool.idle(MemoryClass::Private) == 1 - && core.pool.idle(MemoryClass::Shared) == 1 + wait_until("8 MiB free in each class", || { + core.pool.stocked(MemoryClass::Private) && core.pool.stocked(MemoryClass::Shared) }); let blocks = counters.gauges().blocks; let heap = HeapRange { diff --git a/crates/metal2vulkan-rt/src/tests/managed.rs b/crates/metal2vulkan-rt/src/tests/managed.rs index 91ce09e5d..9f01d1b32 100644 --- a/crates/metal2vulkan-rt/src/tests/managed.rs +++ b/crates/metal2vulkan-rt/src/tests/managed.rs @@ -96,7 +96,7 @@ mod on_device { let core = device.core(); let copied = !core.shared_is_device_local(); let counters = device.counters(); - let cpu = (device.take_block(MemoryClass::Shared, 1)) + let cpu = (device.take_block(MemoryClass::Shared, 2 * LEN)) .unwrap_or_else(|error| panic!("{name}: {error}")); let into = (device.new_buffer(cpu.id, LEN, LEN, true)) .unwrap_or_else(|error| panic!("{name}: {error}")); diff --git a/crates/metal2vulkan-rt/src/tests/memory.rs b/crates/metal2vulkan-rt/src/tests/memory.rs index c857af2b6..6b33b80b2 100644 --- a/crates/metal2vulkan-rt/src/tests/memory.rs +++ b/crates/metal2vulkan-rt/src/tests/memory.rs @@ -1,13 +1,14 @@ -//! 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. +//! Memory blocks and buffers: the plan of a zero fill, a block's length and alignment, the idle +//! rule's window and surplus; and, under a device cfg, on every device of the cfg's kind, that the +//! device makes an allocation of each class as it is made and the next only while a class's free +//! bytes run low, that blocks are handed out zeroed and buffers view them, that a block given back +//! is kept for a take of its length, that a take beside kept blocks of other lengths allocates and +//! their bytes are given back after the hook, and taken where its allocation fails, that idle +//! allocations follow the window's peak down, that seeded takes and releases of mixed lengths all +//! return, and that teardown frees everything with the gauges at zero. use crate::fill::{plan, Plan}; -use crate::memory::{dedicated_len, fits}; +use crate::memory::{base_align, round, surplus, Peaks}; use crate::{Error, Limit}; #[test] @@ -45,18 +46,23 @@ fn a_zero_fill_fills_whole_words_and_copies_the_bytes_outside_them() { } } +/// A block's length is the length asked (at least 1) rounded up to the granule, within the +/// device's longest allocation and buffer. #[test] -fn a_dedicated_block_is_the_length_rounded_up_to_64_kib_within_the_device() { +fn a_block_is_the_length_rounded_up_to_the_granule_within_the_device() { let max = 4 << 30; let granule = 64 << 10; - assert_eq!(dedicated_len(257 << 20, max).unwrap(), 257 << 20); + assert_eq!(round(0, granule, max).unwrap(), granule); + assert_eq!(round(1, granule, max).unwrap(), granule); + assert_eq!(round(257 << 20, granule, max).unwrap(), 257 << 20); assert_eq!( - dedicated_len((256 << 20) + 1, max).unwrap(), + round((256 << 20) + 1, granule, max).unwrap(), (256 << 20) + granule ); - assert_eq!(dedicated_len(max, max).unwrap(), max); + assert_eq!(round(max, granule, max).unwrap(), max); + assert_eq!(round(1, 128 << 10, max).unwrap(), 128 << 10); for (len, reported) in [(max + 1, max + granule), (u64::MAX, u64::MAX)] { - match dedicated_len(len, max) { + match round(len, granule, max) { Err(Error::Limit(Limit::BlockLen { len, max: limit })) => { assert_eq!((len, limit), (reported, max)) } @@ -64,22 +70,70 @@ 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. + +/// A block's first byte lies at a multiple of its length rounded up to a power of two, at most +/// 2 MiB, and at least its buffer's alignment and the granule. #[test] -fn a_kept_dedicated_block_serves_a_request_it_fits_and_that_fills_half_of_it() { +fn a_block_starts_at_its_length_rounded_to_a_power_of_two_up_to_2_mib() { + const KIB: u64 = 1 << 10; 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), + let granule = 64 * KIB; + for (len, alignment, expected) in [ + (64 * KIB, 256, 64 * KIB), + (192 * KIB, 256, 256 * KIB), + (MIB, 256, MIB), + (3 * MIB, 256, 2 * MIB), + (16 * MIB, 256, 2 * MIB), + (16 * MIB, 4 * MIB, 4 * MIB), + (64 * KIB, 128 * KIB, 128 * KIB), ] { - assert_eq!(fits(held, want), serves, "{held} for {want}"); + assert_eq!(base_align(len, alignment, granule), expected, "{len}"); } } +/// The window holds the most live bytes of each second with a take or a give-back for 10 +/// seconds: the peak falls as the clock passes it, and the idle rule frees the oldest idle +/// allocations while the rest pass the peak less the live bytes, or the cap. +#[test] +fn the_idle_rule_keeps_idle_allocations_under_the_window_s_peak_and_the_cap() { + const MIB: u64 = 1 << 20; + let mut peaks = Peaks::default(); + // Four blocks of 16 MiB live in second 0, then given back. + peaks.note(0, 0); + peaks.note(0, 64 * MIB); + peaks.note(0, 0); + assert_eq!(peaks.most(), 64 * MIB); + let idle = [16 * MIB; 4]; + let cap = u64::MAX; + assert_eq!( + surplus(&idle, peaks.most(), 0, cap), + 0, + "all within the peak" + ); + // Five seconds on, the peak stands. + peaks.note(5, 0); + assert_eq!(surplus(&idle, peaks.most(), 0, cap), 0, "within the window"); + // A block of 16 MiB live in second 9: the peak of second 0 still stands. + peaks.note(9, 16 * MIB); + assert_eq!(surplus(&idle, peaks.most(), 16 * MIB, cap), 1); + // Second 10 forgets second 0: the peak is second 9's. + peaks.note(10, 16 * MIB); + assert_eq!(peaks.most(), 16 * MIB); + assert_eq!(surplus(&idle, peaks.most(), 16 * MIB, cap), 4); + assert_eq!(surplus(&idle, peaks.most(), 0, cap), 3); + // Second 20 forgets second 9 and 10: only what is live now. + peaks.note(20, 0); + assert_eq!(peaks.most(), 0); + assert_eq!(surplus(&idle, peaks.most(), 0, cap), 4); + // The cap bounds the idle bytes whatever the peak. + assert_eq!(surplus(&idle, 64 * MIB, 0, 16 * MIB), 3); + assert_eq!(surplus(&idle, 64 * MIB, 0, 15 * MIB), 4); + assert_eq!(surplus(&[], 64 * MIB, 0, 0), 0); + // Oldest first: allocations of other lengths are counted by their bytes. + assert_eq!(surplus(&[48 * MIB, 16 * MIB], 20 * MIB, 0, cap), 1); + assert_eq!(surplus(&[16 * MIB, 48 * MIB], 20 * MIB, 0, cap), 2); +} + #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { use crate::device::lock; @@ -94,7 +148,7 @@ mod on_device { use std::thread; use std::time::{Duration, Instant}; - /// The runtime's own allocation besides blocks: the zero source of Private fills. + /// The runtime's own allocation besides the pool's: the zero source of Private fills. const ZERO_SOURCE: u64 = 1; /// The consumer's hook as a test sees it: each unmap, the thread it ran on, and the first byte @@ -383,9 +437,11 @@ mod on_device { } /// Blocks of both classes are handed out zeroed, buffers view them, a zeroed buffer zeroes - /// exactly its bytes, the refusals are Metal's, a released block lives until its last buffer - /// is gone and is then freed through the hook while still mapped, and teardown frees the rest - /// through the hook on the dropping thread, with every gauge at zero. + /// exactly its bytes, the refusals are Metal's, a block longer than an allocation has an + /// allocation of its own, a released block lives until its last buffer is gone and is then + /// zeroed and kept, and freed once the window no longer holds its bytes, through the hook on + /// the block-maker thread while still mapped; and teardown frees the rest through the hook on + /// the dropping thread, with every gauge at zero. #[test] fn every_device_hands_out_zeroed_blocks_and_buffers_and_frees_them_through_the_hook() { let instance = Instance::new(&[]).expect("an instance at the floor"); @@ -398,12 +454,13 @@ mod on_device { for (name, physical) in &devices { let hook = Arc::new(Hook::default()); let device = device_with(&hook, physical, name); + let core = device.core(); let counters = device.counters(); let gpu = Gpu::new(&device); // A new Shared block reads zero, through its mapping. let shared = device - .take_block(MemoryClass::Shared, 1) + .take_block(MemoryClass::Shared, MemoryClass::Shared.block_len()) .expect("a Shared block"); assert_eq!( (shared.class, shared.len), @@ -547,31 +604,35 @@ 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. 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, past + 1) - .expect("a dedicated block"); - assert_eq!(dedicated.len, past + (64 << 10)); - let dedicated_host = bytes(&dedicated); + // A block longer than an allocation: an allocation of its own length, rounded up to + // the granule, zeroed. + let asked = 2 * MemoryClass::Shared.block_len() + 1; + let long = device + .take_block(MemoryClass::Shared, asked) + .expect("a long block"); assert!( - dedicated_host.iter().all(|&byte| byte == 0), - "{name}: a dedicated block" + long.len >= asked && long.len % (64 << 10) == 0, + "{name}: a long block of {} bytes", + long.len ); - dedicated_host[0] = 0x5A; - hook.record(&dedicated); + let long_host = bytes(&long); + assert!( + long_host.iter().all(|&byte| byte == 0), + "{name}: a long block" + ); + long_host[0] = 0x5A; + hook.record(&long); let last_view: Buffer = device - .new_buffer(dedicated.id, 0, 16, false) - .expect("a buffer of the dedicated block"); + .new_buffer(long.id, 0, 16, false) + .expect("a buffer of the long block"); - // Released, it lives while its buffer does, then, longer than the bound, is freed - // through the hook on the block-maker thread, still mapped. - let dedicated_id = dedicated.id; - device.release_block(dedicated).expect("a release"); + // Released, it lives while its buffer does, then is zeroed and kept, its allocation + // idle. + let long_id = long.id; + device.release_block(long).expect("a release"); assert!(matches!( - device.new_buffer(dedicated_id, 0, 16, false), - Err(Error::NoSuchBlock(id)) if id == dedicated_id + device.new_buffer(long_id, 0, 16, false), + Err(Error::NoSuchBlock(id)) if id == long_id )); assert!( hook.unmapped().is_empty(), @@ -581,17 +642,29 @@ mod on_device { let first = unsafe { last_view.contents().unwrap().as_ptr().read_volatile() }; assert_eq!(first, 0x5A); drop(last_view); - wait_until("the dedicated block's unmap", || { - !hook.unmapped().is_empty() + wait_until("the long block kept", || { + core.pool.kept(MemoryClass::Shared) == 1 }); + assert!(hook.unmapped().is_empty(), "{name}: unmapped while kept"); + + // Eleven seconds on, the window no longer holds its allocation: the next take, of a + // small Private block, frees it through the hook on the block-maker thread, zeroed and + // still mapped. + core.pool.advance_clock(Duration::from_secs(11)); + let nudge = device + .take_block(MemoryClass::Private, 1) + .expect("a small Private block"); + let nudge_id = nudge.id; + device.release_block(nudge).expect("a release"); + wait_until("the long block's unmap", || !hook.unmapped().is_empty()); let unmapped = hook.unmapped(); assert_eq!(unmapped.len(), 1, "{name}: {unmapped:?}"); - assert_eq!(unmapped[0].block, dedicated_id.get()); + assert_eq!(unmapped[0].block, long_id.get()); assert_eq!(unmapped[0].thread.as_deref(), Some("m2v-blocks")); assert_eq!( unmapped[0].first, - Some(0x5A), - "{name}: unmapped while still mapped" + Some(0), + "{name}: zeroed, and unmapped while still mapped" ); // Teardown unmaps the rest on this thread, and frees every block. @@ -600,7 +673,7 @@ mod on_device { let gauges = counters.gauges(); print_gauges_at_drop("blocks_teardown", gauges); assert_eq!(gauges, Gauges::default(), "{name}: gauges after teardown"); - assert_each_unmapped_once(name, &hook, &[shared.id, private.id, dedicated_id]); + assert_each_unmapped_once(name, &hook, &[shared.id, private.id, long_id, nudge_id]); for unmapped in &hook.unmapped()[1..] { assert_eq!(unmapped.thread, this_thread, "{name}: {unmapped:?}"); } @@ -611,11 +684,14 @@ mod on_device { } } - /// The device's making makes one block of each class before it returns: each class holds a - /// ready block as `Device::new` returns, made before the block-maker thread started, which - /// then makes none, each class having its ready block. + /// The device's making makes one allocation of each class before it returns, before the + /// block-maker thread started, which then makes none while small takes leave 8 MiB or more + /// free: a Shared take of a byte is a range of the first allocation. A take that leaves fewer + /// free sets the block-maker thread off, which makes the class's next allocation off the + /// taker's thread. #[test] - fn every_device_holds_a_block_of_each_class_when_it_is_made() { + fn every_device_makes_an_allocation_only_while_a_class_s_free_bytes_run_low() { + 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"); @@ -624,153 +700,519 @@ mod on_device { .unwrap_or_else(|error| panic!("{name}: {error}")); let core = device.core(); let counters = device.counters(); - let made = counters.metrics().blocks_made; + let before = counters.metrics(); + let made = before.blocks_made; + let len = MemoryClass::Shared.block_len(); + assert!( + core.pool.stocked(MemoryClass::Private) && core.pool.stocked(MemoryClass::Shared), + "{name}: the first allocations as the device returns" + ); + let gauges = counters.gauges(); assert_eq!( ( - core.pool.idle(MemoryClass::Private), - core.pool.idle(MemoryClass::Shared) + gauges.blocks, + gauges.shared_idle_bytes, + gauges.private_idle_bytes ), - (1, 1), - "{name}: the ready blocks as the device returns" - ); - assert_eq!( - counters.gauges().blocks, - ZERO_SOURCE + 2, - "{name}: the zero source and the two ready blocks" + (ZERO_SOURCE + 2, len, len), + "{name}: the zero source and the first allocations" ); + let small = (device.take_block(MemoryClass::Shared, 1)) + .unwrap_or_else(|error| panic!("{name}: a small block: {error}")); thread::sleep(Duration::from_millis(200)); assert_eq!( counters.metrics().blocks_made, made, - "{name}: the block-maker thread made a block" + "{name}: an allocation beside a small take" + ); + assert_eq!(counters.gauges().shared_idle_bytes, 0, "{name}: in use"); + let half = (device.take_block(MemoryClass::Shared, 8 * MIB)) + .unwrap_or_else(|error| panic!("{name}: a block of 8 MiB: {error}")); + wait_until("the next Shared allocation", || { + counters.metrics().blocks_made == made + 1 && core.pool.stocked(MemoryClass::Shared) + }); + let metrics = counters.metrics(); + assert_eq!( + (metrics.block_bytes_made, metrics.consumer_allocations), + (3 * len, before.consumer_allocations), + "{name}: three allocations of 16 MiB, the third off this thread" + ); + assert!( + metrics.maker_allocation_nanos > before.maker_allocation_nanos, + "{name}: the block-maker thread's allocation time" + ); + drop((small, half)); + drop(device); + assert_eq!( + counters.gauges(), + Gauges::default(), + "{name}: gauges after teardown" + ); + println!( + "memory: {name}: an allocation made only below 8 MiB free; metrics {:?}", + counters.metrics() ); } } - /// 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. + /// A block given back is zeroed and kept, and a take of its length takes it again with its + /// number, address and mapping, allocating nothing and running no hook: Shared blocks of + /// 16 MiB, 1 MiB and 40 MiB (an allocation of its own), and a Private block the GPU wrote, + /// which reads zero when taken again. #[test] - fn every_device_keeps_idle_blocks_up_to_the_bound_and_frees_the_oldest() { + fn every_device_keeps_given_back_blocks_for_takes_of_their_length() { + 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(), - "the loader lists no device of this cfg's kind" - ); + 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 core = device.core(); + let counters = device.counters(); + let lens = [MemoryClass::Shared.block_len(), MIB, 40 * MIB]; + let taken: Vec = (lens.iter()) + .map(|&len| { + (device.take_block(MemoryClass::Shared, len)) + .unwrap_or_else(|error| panic!("{name}: a block of {len}: {error}")) + }) + .collect(); + let infos: Vec = taken.iter().map(|block| **block).collect(); + for info in &infos { + assert!(lens.contains(&info.len), "{name}: {} bytes", info.len); + let host = bytes(info); + host[0] = 0x5A; + host[host.len() - 1] = 0x5A; + hook.record(info); + } + for block in taken { + device.release_block(block).expect("a release"); + } + wait_until("the three blocks kept", || { + core.pool.kept(MemoryClass::Shared) == 3 && core.pool.stocked(MemoryClass::Shared) + }); + let made = counters.metrics().blocks_made; + let reused = counters.metrics().blocks_reused; + let again: Vec = (infos.iter().rev()) + .map(|info| { + let block = (device.take_block(MemoryClass::Shared, info.len)) + .unwrap_or_else(|error| panic!("{name}: {} again: {error}", info.len)); + assert_eq!( + (block.id, block.gpu_address, block.contents, block.len), + (info.id, info.gpu_address, info.contents, info.len), + "{name}: the kept block of {} bytes", + info.len + ); + assert!( + bytes(&block).iter().all(|&byte| byte == 0), + "{name}: a kept block taken again" + ); + block + }) + .collect(); + assert_eq!( + counters.metrics().blocks_made, + made, + "{name}: an allocation" + ); + assert_eq!(counters.metrics().blocks_reused, reused + 3, "{name}"); + assert!(hook.unmapped().is_empty(), "{name}: {:?}", hook.unmapped()); + + // A Private block written by the GPU and given back reads zero when taken again. + let gpu = Gpu::new(&device); + let private_len = MemoryClass::Private.block_len(); + let private = (device.take_block(MemoryClass::Private, private_len)) + .unwrap_or_else(|error| panic!("{name}: a Private block: {error}")); + let private_info = *private; + gpu.fill(vk_buffer(&device, private.id), 0, private_len, u32::MAX); + device.release_block(private).expect("a release"); + wait_until("the Private block kept", || { + core.pool.kept(MemoryClass::Private) == 1 + }); + let back = (device.take_block(MemoryClass::Private, private_len)) + .unwrap_or_else(|error| panic!("{name}: the Private block again: {error}")); + assert_eq!( + (back.id, back.gpu_address), + (private_info.id, private_info.gpu_address), + "{name}: the kept Private block" + ); + let shared = (again.iter()) + .find(|block| block.len == MemoryClass::Shared.block_len()) + .expect("the 16 MiB block"); + assert!( + gpu.reads_zero( + vk_buffer(&device, back.id), + vk_buffer(&device, shared.id), + bytes(shared) + ), + "{name}: a Private block taken again" + ); + let mut handed: Vec = infos.iter().map(|info| info.id).collect(); + handed.push(private_info.id); + drop((again, back, gpu)); + drop(device); + assert_eq!( + counters.gauges(), + Gauges::default(), + "{name}: gauges after teardown" + ); + assert_each_unmapped_once(name, &hook, &handed); + println!( + "memory: {name}: four blocks kept and taken again; metrics {:?}", + counters.metrics() + ); + } + } + + /// A take that no free range fits while the class keeps only blocks of other lengths makes its + /// allocation at once, counted as a taker's allocation, and the block-maker thread then gives + /// the kept blocks' bytes back to their allocations, after each one's hook on that thread, + /// still mapped and zeroed; a later take is a range of those bytes, allocating nothing: three + /// kept Shared blocks of 24 MiB and takes of 20 MiB, each returning within 30 seconds. + #[test] + fn every_device_allocates_beside_kept_blocks_of_other_lengths_and_gives_their_bytes_back() { + 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 core = device.core(); + let counters = device.counters(); + let kept: Vec = (0..3) + .map(|_| { + (device.take_block(MemoryClass::Shared, 24 * MIB)) + .unwrap_or_else(|error| panic!("{name}: a block of 24 MiB: {error}")) + }) + .collect(); + let first = *kept[0]; + let mut handed: Vec = kept.iter().map(|block| block.id).collect(); + for block in &kept { + hook.record(block); + } + for block in kept { + device.release_block(block).expect("a release"); + } + wait_until("the three kept", || { + core.pool.kept(MemoryClass::Shared) == 3 + }); + let before = counters.metrics(); + let take = |what: &str| { + let (sender, receiver) = std::sync::mpsc::channel(); + let taker = device.clone(); + thread::spawn(move || { + let block = taker.take_block(MemoryClass::Shared, 20 * MIB); + drop(taker); + let _ = sender.send(block); + }); + (receiver.recv_timeout(Duration::from_secs(30))) + .unwrap_or_else(|_| panic!("{name}: {what} waited 30 s")) + .unwrap_or_else(|error| panic!("{name}: {what}: {error}")) + }; + let own = take("the first take"); + let after = counters.metrics(); + assert_eq!( + (after.blocks_made, after.consumer_allocations), + (before.blocks_made + 1, before.consumer_allocations + 1), + "{name}: the first take's allocation, on its thread" + ); + assert!( + after.consumer_allocation_nanos > before.consumer_allocation_nanos + && after.consumer_allocation_max_nanos > 0, + "{name}: the taker's allocation time" + ); + wait_until("the kept blocks' bytes given back", || { + hook.unmapped().len() == 3 && core.pool.kept(MemoryClass::Shared) == 0 + }); + for unmapped in hook.unmapped() { + assert_eq!(unmapped.thread.as_deref(), Some("m2v-blocks"), "{name}"); + assert_eq!(unmapped.first, Some(0), "{name}: zeroed, still mapped"); + } + let shared = take("the second take"); + assert_eq!( + shared.contents.map(|c| c.as_ptr() as usize), + first.contents.map(|c| c.as_ptr() as usize), + "{name}: a range of the first kept block's bytes" + ); + assert!( + bytes(&shared).iter().all(|&byte| byte == 0), + "{name}: a block of a kept block's bytes" + ); + assert_eq!( + counters.metrics().blocks_made, + before.blocks_made + 1, + "{name}: an allocation for the second take" + ); + handed.extend([own.id, shared.id]); + drop((own, shared)); + drop(device); + assert_eq!( + counters.gauges(), + Gauges::default(), + "{name}: gauges after teardown" + ); + assert_each_unmapped_once(name, &hook, &handed); + println!( + "memory: {name}: takes beside kept blocks of other lengths; metrics {:?}", + counters.metrics() + ); + } + } + + /// Where a take's own allocation fails while the class keeps blocks of other lengths, the + /// take waits for the block-maker thread to give their bytes back and takes a range of them: + /// with the device's `maxMemoryAllocationCount` answered as its live allocations once a + /// 24 MiB Shared block has one of its own, that block kept, a take of 20 MiB returns within + /// 30 seconds in its bytes, and a take of 40 MiB, which no free range fits, returns the + /// allocation's `Limit::MemoryAllocations`. + #[test] + fn every_device_takes_kept_blocks_bytes_where_its_allocation_fails() { + const MIB: u64 = 1 << 20; + const MAX: u32 = ZERO_SOURCE as u32 + 3; + 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 options = DeviceOptions { + block_mappings: Some(Arc::clone(&hook) as Arc), + ..DeviceOptions::default() + }; + let device = Device::open(physical, options, |limits| { + limits.max_memory_allocation_count = MAX; + }) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let core = device.core(); + let counters = device.counters(); + let kept = (device.take_block(MemoryClass::Shared, 24 * MIB)) + .unwrap_or_else(|error| panic!("{name}: a block of 24 MiB: {error}")); + assert_eq!(counters.gauges().blocks, u64::from(MAX), "{name}"); + let kept_info = *kept; + device.release_block(kept).expect("a release"); + wait_until("the block kept", || { + core.pool.kept(MemoryClass::Shared) == 1 + }); + let (sender, receiver) = std::sync::mpsc::channel(); + let taker = device.clone(); + thread::spawn(move || { + let block = taker.take_block(MemoryClass::Shared, 20 * MIB); + drop(taker); + let _ = sender.send(block); + }); + let block = (receiver.recv_timeout(Duration::from_secs(30))) + .unwrap_or_else(|_| panic!("{name}: the take waited 30 s")) + .unwrap_or_else(|error| panic!("{name}: the take: {error}")); + assert_eq!( + block.gpu_address, kept_info.gpu_address, + "{name}: the kept block's bytes" + ); + let unmapped = hook.unmapped(); + assert_eq!(unmapped.len(), 1, "{name}: {unmapped:?}"); + assert_eq!( + (unmapped[0].block, unmapped[0].thread.as_deref()), + (kept_info.id.get(), Some("m2v-blocks")), + "{name}" + ); + match device.take_block(MemoryClass::Shared, 40 * MIB) { + Err(Error::Limit(Limit::MemoryAllocations { max: MAX })) => {} + other => panic!("{name}: a take past the count: {other:?}"), + } + assert_eq!(counters.gauges().blocks, u64::from(MAX), "{name}"); + let handed = [kept_info.id, block.id]; + drop(block); + drop(device); + assert_eq!( + counters.gauges(), + Gauges::default(), + "{name}: gauges after teardown" + ); + assert_each_unmapped_once(name, &hook, &handed); + println!("memory: {name}: a failed allocation took the kept block's bytes"); + } + } + + /// 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. + #[test] + fn every_device_frees_idle_allocations_as_the_window_s_peak_falls() { + 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 core = device.core(); + let counters = device.counters(); + let len = MemoryClass::Shared.block_len(); + let small = (device.take_block(MemoryClass::Shared, 1)) + .unwrap_or_else(|error| panic!("{name}: a small block: {error}")); + let taken: Vec = (0..4) + .map(|_| { + (device.take_block(MemoryClass::Shared, len)) + .unwrap_or_else(|error| panic!("{name}: a block: {error}")) + }) + .collect(); + let four: Vec = taken.iter().map(|block| block.id.get()).collect(); + let mut handed: Vec = taken.iter().map(|block| block.id).collect(); + let small_id = small.id; + handed.push(small_id); + for block in taken { + device.release_block(block).expect("a release"); + } + wait_until("the four kept", || core.pool.kept(MemoryClass::Shared) == 4); + assert_eq!( + counters.gauges().shared_idle_bytes, + 4 * len, + "{name}: four idle allocations" + ); + + // Five seconds on, a Private take and give-back runs the rule for both classes: 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); + device.release_block(nudge).expect("a release"); + wait_until("the Private block kept", || { + core.pool.kept(MemoryClass::Private) == 1 + }); + assert_eq!( + (counters.gauges().shared_idle_bytes, hook.unmapped().len()), + (4 * len, 0), + "{name}: the four within the window" + ); + + // Eleven seconds on: the small block's give-back frees the three oldest. + core.pool.advance_clock(Duration::from_secs(6)); + device.release_block(small).expect("a release"); + wait_until("three idle Shared allocations freed", || { + hook.unmapped().len() == 3 + }); + wait_until("the idle gauge", || { + counters.gauges().shared_idle_bytes == 2 * len + }); + for (unmapped, block) in hook.unmapped().iter().zip(&four) { + assert_eq!(unmapped.block, *block, "{name}: the oldest first"); + assert_eq!(unmapped.thread.as_deref(), Some("m2v-blocks"), "{name}"); + assert_eq!(unmapped.first, None, "{name}: no block recorded"); + } + assert_eq!( + counters.gauges().blocks, + ZERO_SOURCE + 3, + "{name}: the zero source, the reserve, the fourth and the Private allocation" + ); + + // 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 + }); + 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" + ); + drop(device); + assert_eq!( + counters.gauges(), + Gauges::default(), + "{name}: gauges after teardown" + ); + assert_each_unmapped_once(name, &hook, &handed); + println!( + "memory: {name}: idle allocations freed as the peak fell; 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 + /// after teardown. + #[test] + fn every_device_returns_every_seeded_take_and_release_of_mixed_lengths() { + use std::sync::mpsc::RecvTimeoutError; + const OPS: usize = 300; + /// The most live bytes of a class the run keeps: past it, it releases. + const MOST: u64 = 192 << 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"); + let this_thread = thread::current().name().map(str::to_string); for (name, physical) in &devices { let hook = Arc::new(Hook::default()); let device = device_with(&hook, physical, name); let counters = device.counters(); - let mut handed = Vec::new(); - - let shared_len = MemoryClass::Shared.block_len(); - let room = MemoryClass::Shared.idle_bound() / shared_len; - let taken: Vec = (0..room + 2) - .map(|_| { - device - .take_block(MemoryClass::Shared, shared_len) - .expect("a block") - }) - .collect(); - for block in &taken { - handed.push(block.id); - let host = bytes(block); - host[0] = 0x5A; - host[host.len() - 1] = 0x5A; - hook.record(block); - } - // 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 + room + 2 + let worker = device.clone(); + let (sender, receiver) = std::sync::mpsc::channel(); + let run = thread::spawn(move || -> Result, String> { + const MIB: u64 = 1 << 20; + let mut seed: u64 = 0x2545_F491_4F6C_DD1D; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let lens = [64 << 10, MIB, 3 * MIB, 16 * MIB, 20 * MIB, 40 * MIB]; + let index = |class: MemoryClass| usize::from(class == MemoryClass::Shared); + let mut live: Vec = Vec::new(); + let mut bytes = [0u64; 2]; + let mut handed = Vec::new(); + for op in 0..OPS { + let full = bytes.iter().any(|&bytes| bytes > MOST); + if !live.is_empty() && (full || next() % 3 == 0) { + let block = live.swap_remove((next() % live.len() as u64) as usize); + bytes[index(block.class)] -= block.len; + (worker.release_block(block)).map_err(|error| format!("{op}: {error}"))?; + } else { + let class = match next() % 2 { + 0 => MemoryClass::Shared, + _ => MemoryClass::Private, + }; + let len = lens[(next() % lens.len() as u64) as usize]; + let block = (worker.take_block(class, len)) + .map_err(|error| format!("{op}: {class:?} {len}: {error}"))?; + bytes[index(class)] += block.len; + handed.push(block.id); + live.push(block); + } + if sender.send(op).is_err() { + break; + } + } + drop(live); + drop(worker); + Ok(handed) }); - let infos: Vec = taken.iter().map(|block| **block).collect(); - for block in taken { - device.release_block(block).expect("a release"); + for op in 0..OPS { + match receiver.recv_timeout(Duration::from_secs(60)) { + Ok(_) => {} + Err(RecvTimeoutError::Timeout) => { + panic!("{name}: operation {op} did not return within a minute") + } + Err(RecvTimeoutError::Disconnected) => break, + } } - // 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 + 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(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> = infos - .iter() - .filter(|block| unmapped.iter().all(|u| u.block != block.id.get())) - .collect(); - assert_eq!(kept.len() as u64, room + 1, "{name}: {unmapped:?}"); - - // 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"); - 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), - "{name}: a block taken again" - ); - assert_eq!(counters.metrics().blocks_made, made, "{name}: a block made"); - - // A Private block written by the GPU and released reads zero when taken again. - let gpu = Gpu::new(&device); - let private_block = device - .take_block(MemoryClass::Private, 1) - .expect("a Private block"); - let private = *private_block; - handed.push(private.id); - gpu.fill( - vk_buffer(&device, private.id), - 0, - MemoryClass::Private.block_len(), - u32::MAX, - ); - device.release_block(private_block).expect("a release"); - // The pool zeroes and keeps it before it makes anything, so it is one of the next two. - let next: Vec = (0..2) - .map(|_| device.take_block(MemoryClass::Private, 1).expect("a block")) - .collect(); - handed.extend(next.iter().map(|block| block.id)); - let back = next - .iter() - .find(|block| block.id == private.id) - .expect("the released Private block among the next two"); - assert_eq!(back.gpu_address, private.gpu_address); - assert!( - gpu.reads_zero( - vk_buffer(&device, private.id), - vk_buffer(&device, again.id), - host - ), - "{name}: a Private block taken again" - ); - - drop(gpu); + let mut handed = (run.join()) + .expect("the run's thread") + .unwrap_or_else(|error| panic!("{name}: operation {error}")); drop(device); assert_eq!( counters.gauges(), @@ -780,206 +1222,29 @@ mod on_device { handed.sort_unstable(); handed.dedup(); assert_each_unmapped_once(name, &hook, &handed); - println!( - "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 = (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 = 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}"); - let infos: Vec = taken.iter().map(|block| **block).collect(); - for block in taken { - device.release_block(block).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> = infos - .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, - // held to the teardown. - let mut owns = Vec::new(); - 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); - owns.push(own); - } - 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_block = (device.take_block(MemoryClass::Private, private_len + 1)) - .unwrap_or_else(|error| panic!("{name}: a dedicated Private block: {error}")); - let private = *private_block; - handed.push(private.id); - device.release_block(private_block).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() - ); - } - } - /// A take of a pooled block while the class keeps only dedicated blocks idle: the block-maker - /// thread makes the class's next pooled block whatever dedicated blocks it keeps, so the take - /// returns. A Shared block of twice the pooled length is given back and kept beside the ready - /// block; the first pooled take takes the ready block, and the second waits only for the - /// block-maker thread to make the next. - #[test] - fn every_device_makes_pooled_blocks_while_it_keeps_dedicated_ones() { - 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 dedicated = (device.take_block(MemoryClass::Shared, 2 * shared_len)) - .unwrap_or_else(|error| panic!("{name}: a dedicated block: {error}")); - let dedicated_id = dedicated.id; - device.release_block(dedicated).expect("a release"); - wait_until("the dedicated block kept beside the ready one", || { - counters.gauges().shared_idle_bytes == 3 * shared_len - }); - let mut handed = vec![dedicated_id]; - // Each pooled block's handle is held to the end, so the second take cannot take the - // first's block back. - let mut held = Vec::new(); - for take in 0..2 { - let (sender, receiver) = std::sync::mpsc::channel(); - let taker = device.clone(); - thread::spawn(move || { - let taken = taker.take_block(MemoryClass::Shared, 1); - drop(taker); - let _ = sender.send(taken); - }); - let block = (receiver.recv_timeout(Duration::from_secs(30))) - .unwrap_or_else(|_| panic!("{name}: pooled take {take} waited 30 s")) - .unwrap_or_else(|error| panic!("{name}: pooled take {take}: {error}")); - assert_eq!(block.len, shared_len, "{name}: a pooled block"); - assert_ne!( - block.id, dedicated_id, - "{name}: the dedicated block as pooled" + for unmapped in hook.unmapped() { + assert!( + unmapped.thread.as_deref() == Some("m2v-blocks") + || unmapped.thread == this_thread, + "{name}: unmapped on {:?}", + unmapped.thread ); - handed.push(block.id); - held.push(block); } - assert_eq!(counters.metrics().dedicated_blocks_reused, 0, "{name}"); - drop(device); - drop(held); - assert_eq!( - counters.gauges(), - Gauges::default(), - "{name}: gauges after teardown" - ); - handed.sort_unstable(); - assert_each_unmapped_once(name, &hook, &handed); println!( - "memory: {name}: two pooled takes beside a kept dedicated block; metrics {:?}", + "memory: {name}: {OPS} seeded takes and releases, {} blocks; metrics {:?}", + handed.len(), 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 - /// memory of its own, and the staging region of a first copy are `Limit::MemoryAllocations` - /// with the device's count, refused before the driver is called, the gauges unchanged; - /// textures placed in the texture block still come and go; and every gauge reads zero after - /// teardown. + /// With the device's `maxMemoryAllocationCount` answered as the zero source's, the first two + /// allocations' and one more (`Device::open`), the count is reached once a texture's block + /// takes the first Private allocation whole and the block-maker thread makes the next. Past + /// it, a texture longer than an allocation, whose block takes an allocation of its own, and + /// the staging region of a first copy are `Limit::MemoryAllocations` with the device's count, + /// refused before the driver is called, the gauges unchanged; textures placed in the texture + /// block still come and go; and every gauge reads zero after teardown. #[test] fn every_device_refuses_an_allocation_past_its_count() { use crate::{IndexClass, PixelFormat, Region, TextureDescriptor, TextureType}; @@ -993,7 +1258,7 @@ mod on_device { }) .unwrap_or_else(|error| panic!("{name}: {error}")); let counters = device.counters(); - wait_until("a ready block of each class", || { + wait_until("the first allocation of each class", || { counters.gauges().blocks == ZERO_SOURCE + 2 }); device @@ -1002,10 +1267,10 @@ mod on_device { let d = TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 4, 4); let first = (device.new_texture(&d, Some(4096))) .unwrap_or_else(|error| panic!("{name}: the first texture: {error}")); - wait_until("the pool's block made again", || { + wait_until("the next Private allocation", || { counters.gauges().blocks == u64::from(MAX) }); - // Three layers of 4096 x 4096 RGBA16Float, 384 MiB: more than a block. + // Three layers of 4096 x 4096 RGBA16Float, 384 MiB: longer than an allocation. let mut large = TextureDescriptor::new( TextureType::Type2DArray, PixelFormat::RGBA16Float, @@ -1015,8 +1280,8 @@ mod on_device { large.array_length = 3; match device.new_texture(&large, Some(4097)) { Err(Error::Limit(Limit::MemoryAllocations { max: MAX })) => {} - Err(error) => panic!("{name}: a texture of its own memory past the count: {error}"), - Ok(_) => panic!("{name}: a texture of its own memory past the count was made"), + Err(error) => panic!("{name}: a long texture past the count: {error}"), + Ok(_) => panic!("{name}: a long texture past the count was made"), } let gauges = counters.gauges(); assert_eq!( diff --git a/crates/metal2vulkan-rt/src/tests/over.rs b/crates/metal2vulkan-rt/src/tests/over.rs index dad2aecd8..43d782e51 100644 --- a/crates/metal2vulkan-rt/src/tests/over.rs +++ b/crates/metal2vulkan-rt/src/tests/over.rs @@ -73,15 +73,14 @@ mod on_device { .collect() } - /// The device's live allocations once the block-maker thread holds a ready block of each - /// class, refilling off this thread any a take used, and the texture blocks among them. + /// The device's live allocations once the block-maker thread has nothing to make (8 MiB free + /// in each class), and the texture blocks among them. fn settled(name: &str, core: &Core) -> (u64, usize) { let deadline = Instant::now() + Duration::from_secs(120); - while core.pool.idle(MemoryClass::Private) == 0 || core.pool.idle(MemoryClass::Shared) == 0 - { + while !core.pool.stocked(MemoryClass::Private) || !core.pool.stocked(MemoryClass::Shared) { assert!( Instant::now() < deadline, - "{name}: a ready block of each class" + "{name}: 8 MiB free in each class" ); thread::sleep(Duration::from_millis(1)); } @@ -128,7 +127,7 @@ mod on_device { let counters = device.counters(); let core = device.core(); - let cpu = (device.take_block(MemoryClass::Shared, 1)) + let cpu = (device.take_block(MemoryClass::Shared, AT + LEN)) .unwrap_or_else(|error| panic!("{name}: {error}")); let buffer = (device.new_buffer(cpu.id, AT, LEN, true)) .unwrap_or_else(|error| panic!("{name}: {error}")); diff --git a/crates/metal2vulkan-rt/src/tests/places.rs b/crates/metal2vulkan-rt/src/tests/places.rs index 093195c8c..d20b72701 100644 --- a/crates/metal2vulkan-rt/src/tests/places.rs +++ b/crates/metal2vulkan-rt/src/tests/places.rs @@ -3,8 +3,9 @@ //! blocks of the pool with no allocation of their own: a block's worth of 1 MiB textures takes //! one block and then a second, releasing them gives one back to the pool and keeps the other, //! textures made and released in that block allocate nothing, and every gauge reads zero after -//! teardown; pooled blocks are 16 MiB Shared and 64 MiB Private, and a texture of 32 MiB takes a -//! place in one. +//! teardown; the pool's allocations are 16 MiB of either class, a take is a range of one rounded +//! up to 64 KiB, a longer take an allocation of its own, and a texture of 32 MiB takes a texture +//! block of its own length. use crate::places::Ranges; @@ -115,9 +116,8 @@ mod on_device { .unwrap_or_else(|error| panic!("{name}: {error}")); let core = device.core(); let counters = device.counters(); - wait_until("a ready block of each class", || { - core.pool.idle(MemoryClass::Private) == 1 - && core.pool.idle(MemoryClass::Shared) == 1 + wait_until("8 MiB free in each class", || { + core.pool.stocked(MemoryClass::Private) && core.pool.stocked(MemoryClass::Shared) }); let base = counters.gauges().blocks; let made = counters.metrics().blocks_made; @@ -147,19 +147,19 @@ mod on_device { in_first > MemoryClass::Private.block_len() / MIB / 2, "{name}: the first block held {in_first} textures of 1 MiB" ); - // Each block the pool's ready one, which the pool made again. - wait_until("the pool's two blocks made again", || { + // Each block an allocation whole, after which the block-maker thread made the next. + wait_until("the pool's next two allocations", || { counters.metrics().blocks_made == made + 2 }); assert_eq!(counters.gauges().blocks, base + 2, "{name}: two blocks"); - // Released: one block back to the pool, which keeps it idle; one kept for textures. + // Released: one block back to the pool, which keeps it; one kept for textures. drop(textures); wait_until("the textures freed", || { counters.gauges().textures == 0 && core.places.blocks() == 1 }); wait_until("the block back in the pool", || { - core.pool.idle(MemoryClass::Private) == 2 + core.pool.kept(MemoryClass::Private) == 1 }); assert_eq!(counters.gauges().blocks, base + 2, "{name}: after release"); @@ -198,11 +198,12 @@ mod on_device { } } - /// Pooled blocks are 16 MiB of Shared memory and 64 MiB of Private, on every device: a take - /// up to its class's length is a pooled block of that length, one past it a dedicated block, - /// and a texture of 32 MiB is placed in a texture block, with no allocation of its own. + /// The pool's allocations are 16 MiB of either class, on every device: a take of a byte is a + /// range of one rounded up to 64 KiB (to `bufferImageGranularity` where that is larger) and + /// allocates nothing; a take longer than an allocation makes one of its own length, rounded + /// up the same way; and a texture of 32 MiB is placed in a texture block of its own length. #[test] - fn every_device_pools_16_mib_shared_and_64_mib_private_blocks() { + fn every_device_takes_blocks_from_16_mib_allocations() { const MIB: u64 = 1 << 20; let instance = Instance::new(&[]).expect("an instance at the floor"); let devices = devices_of_the_cfgs_kind(&instance); @@ -212,22 +213,29 @@ mod on_device { .unwrap_or_else(|error| panic!("{name}: {error}")); let core = device.core(); let counters = device.counters(); - for (class, len) in [ - (MemoryClass::Shared, 16 * MIB), - (MemoryClass::Private, 64 * MIB), - ] { - assert_eq!(class.block_len(), len, "{name}: {class:?}"); - let pooled = (device.take_block(class, len)) - .unwrap_or_else(|error| panic!("{name}: a pooled {class:?} block: {error}")); - assert_eq!(pooled.len, len, "{name}: a pooled {class:?} block"); - let dedicated = (device.take_block(class, len + 1)) - .unwrap_or_else(|error| panic!("{name}: a dedicated {class:?} block: {error}")); - assert_eq!( - dedicated.len, - len + (64 << 10), - "{name}: a dedicated {class:?} block" + for class in [MemoryClass::Shared, MemoryClass::Private] { + assert_eq!(class.block_len(), 16 * MIB, "{name}: {class:?}"); + let made = counters.metrics().blocks_made; + let small = (device.take_block(class, 1)) + .unwrap_or_else(|error| panic!("{name}: a small {class:?} block: {error}")); + assert!( + small.len.is_multiple_of(64 << 10) && small.len < MIB, + "{name}: a small {class:?} block of {} bytes", + small.len ); - for block in [pooled, dedicated] { + let long = (device.take_block(class, 16 * MIB + 1)) + .unwrap_or_else(|error| panic!("{name}: a long {class:?} block: {error}")); + assert!( + long.len > 16 * MIB && long.len.is_multiple_of(64 << 10), + "{name}: a long {class:?} block of {} bytes", + long.len + ); + assert_eq!( + counters.metrics().blocks_made, + made + 1, + "{name}: the long {class:?} block's allocation alone" + ); + for block in [small, long] { (device.release_block(block)) .unwrap_or_else(|error| panic!("{name}: a release: {error}")); } diff --git a/crates/metal2vulkan-rt/src/tests/spill.rs b/crates/metal2vulkan-rt/src/tests/spill.rs index 2d360c42d..036eae102 100644 --- a/crates/metal2vulkan-rt/src/tests/spill.rs +++ b/crates/metal2vulkan-rt/src/tests/spill.rs @@ -28,12 +28,12 @@ mod on_device { each_device("spill", |name, _, device| { let core = device.core(); let counters = device.counters(); - wait_until("a ready block of each class", || { - core.pool.idle(MemoryClass::Private) == 1 - && core.pool.idle(MemoryClass::Shared) == 1 + wait_until("8 MiB free in each class", || { + core.pool.stocked(MemoryClass::Private) && core.pool.stocked(MemoryClass::Shared) }); - // A dedicated Private block, made in the call, whose device-local allocation fails. + // A Private block longer than an allocation, which makes its own in the call, whose + // device-local allocation fails. core.fail_private.store(1, Relaxed); let spilled = device.take_block(MemoryClass::Private, MemoryClass::Private.block_len() + 1); @@ -60,14 +60,15 @@ mod on_device { return; } - // Every Private-type allocation fails from here: the ready block, made before, is - // device-local; the pool's next one spills. + // Every Private-type allocation fails from here: the first allocation, made before, is + // device-local; the next, which the block-maker thread makes once a block takes the + // first whole, spills. core.fail_private.store(u32::MAX, Relaxed); - let plain = (device.take_block(MemoryClass::Private, 1)) + let plain = (device.take_block(MemoryClass::Private, MemoryClass::Private.block_len())) .unwrap_or_else(|error| panic!("{name}: {error}")); - assert!(plain.device_local, "{name}: the ready block"); - wait_until("the pool's spilled block", || { - core.pool.idle(MemoryClass::Private) == 1 + assert!(plain.device_local, "{name}: the first allocation"); + wait_until("the pool's spilled allocation", || { + core.pool.stocked(MemoryClass::Private) && counters.gauges().spilled_bytes >= MemoryClass::Private.block_len() }); diff --git a/crates/metal2vulkan-rt/src/tests/upload.rs b/crates/metal2vulkan-rt/src/tests/upload.rs index c840177b8..190e9d2a6 100644 --- a/crates/metal2vulkan-rt/src/tests/upload.rs +++ b/crates/metal2vulkan-rt/src/tests/upload.rs @@ -61,23 +61,22 @@ mod on_device { .unwrap_or_else(|error| panic!("{name}: {error}")); let core = device.core(); let counters = device.counters(); - // The pool's ready blocks, which the block-maker thread makes after the device. - wait_until("a ready block of each class", || { - core.pool.idle(MemoryClass::Private) == 1 - && core.pool.idle(MemoryClass::Shared) == 1 + // The pool's first allocations, which the device's making makes. + wait_until("8 MiB free in each class", || { + core.pool.stocked(MemoryClass::Private) && core.pool.stocked(MemoryClass::Shared) }); device .grant_indices(IndexClass::Texture, 4096, 8) .unwrap_or_else(|error| panic!("{name}: {error}")); let submissions = || counters.metrics().submissions; - // The first texture takes the ready Private block as its texture block, which the pool - // makes again, zeroing it in a submission of its own. + // The first texture's texture block takes the first Private allocation whole, and the + // block-maker thread makes the next, zeroing it in a submission of its own. drop( (device.new_texture(&square(256), Some(4096))) .unwrap_or_else(|error| panic!("{name}: {error}")), ); - wait_until("the pool's block made again", || { - core.pool.idle(MemoryClass::Private) == 1 && counters.gauges().textures == 0 + wait_until("the next Private allocation", || { + core.pool.stocked(MemoryClass::Private) && counters.gauges().textures == 0 }); let base = counters.gauges().blocks; diff --git a/crates/metal2vulkan-rt/src/texture.rs b/crates/metal2vulkan-rt/src/texture.rs index a4a855b40..9177afab4 100644 --- a/crates/metal2vulkan-rt/src/texture.rs +++ b/crates/metal2vulkan-rt/src/texture.rs @@ -702,6 +702,7 @@ impl Device { Source::Heap(block, heap, offset) => { let bind = Bind::Heap { memory: block.memory.device_memory(), + base: block.memory.base(), block_len: block.memory.len, heap, offset, @@ -722,6 +723,7 @@ impl Device { }; let bind = Bind::InPlace { memory: memory.device_memory(), + base: memory.base(), memory_type: core.memory_type(class), block_len: memory.len, at: at + offset, @@ -1377,19 +1379,22 @@ enum Source<'a> { enum Bind { /// A place in a texture block, or memory of its own. Pooled, - /// A linear image, made preinitialized, at `at` in a block whose memory is `memory`, of type - /// `memory_type` and of `block_len` bytes, where the device lays its rows `bytes_per_row` - /// apart from there. + /// A linear image, made preinitialized, at `at` in a block at `base` in the allocation + /// `memory`, of type `memory_type` and of `block_len` bytes, where the device lays its rows + /// `bytes_per_row` apart from there. InPlace { memory: vk::DeviceMemory, + base: u64, memory_type: u32, block_len: u64, at: u64, bytes_per_row: u64, }, - /// `offset` in `heap`, whose block's memory is `memory`, of `block_len` bytes. + /// `offset` in `heap`, whose block of `block_len` bytes lies at `base` in the allocation + /// `memory`. Heap { memory: vk::DeviceMemory, + base: u64, block_len: u64, heap: HeapRange, offset: u64, @@ -1482,9 +1487,9 @@ impl Made { let requirements = needs.memory_requirements; let bits = requirements.memory_type_bits; // A place in a texture block where the image takes the blocks' memory type and the device - // does not require an allocation of its own for it (preferring one is no reason). + // does not require an allocation of its own for it (preferring one is no reason): one of + // its own length where it is longer than a block. let placed = dedicated.requires_dedicated_allocation == vk::FALSE - && requirements.size <= MemoryClass::Private.block_len() && bits & (1 << core.memory_type(MemoryClass::Private)) != 0; // Where the device-local memory has no texture block left, memory of its own. let pooled = match placed && matches!(bind, Bind::Pooled) { @@ -1497,6 +1502,7 @@ impl Made { }; let (backing, memory, offset) = if let Bind::InPlace { memory, + base, memory_type, block_len, at, @@ -1514,7 +1520,7 @@ impl Made { && layout.row_pitch == bytes_per_row && dedicated.requires_dedicated_allocation == vk::FALSE && bits & (1 << memory_type) != 0 - && at.is_multiple_of(requirements.alignment) + && (base + at).is_multiple_of(requirements.alignment) && at .checked_add(requirements.size) .is_some_and(|end| end <= block_len); @@ -1523,9 +1529,10 @@ impl Made { pixel_format: d.pixel_format, })); } - (Backing::InBlock, memory, at) + (Backing::InBlock, memory, base + at) } else if let Bind::Heap { memory, + base, block_len, heap, offset, @@ -1543,13 +1550,17 @@ impl Made { let end = offset.checked_add(fit.size); let fits = heap_end.is_some_and(|heap_end| heap_end <= block_len) && end.is_some_and(|end| end <= heap.len) - && at.is_some_and(|at| at.is_multiple_of(fit.align)); + && at.is_some_and(|at| (base + at).is_multiple_of(fit.align)); match (fits, at) { - (true, Some(at)) => (Backing::InBlock, memory, at), + (true, Some(at)) => (Backing::InBlock, memory, base + at), _ => return Err(refused), } } else if let Some((place, block)) = pooled { - (Backing::Placed(place), block.device_memory(), place.offset) + ( + Backing::Placed(place), + block.device_memory(), + block.base() + place.offset, + ) } else { // Vulkan gives every image of no external handle type a device-local type. let local = bits & core.device_local; diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index 0a30591a1..fa97d7805 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -1490,7 +1490,14 @@ impl Backend for NewRuntime { ("first_use_waits", metrics.first_use_waits), ("first_use_wait_nanos", metrics.first_use_wait_nanos), ("blocks_made", metrics.blocks_made), - ("dedicated_blocks_reused", metrics.dedicated_blocks_reused), + ("block_bytes_made", metrics.block_bytes_made), + ("blocks_reused", metrics.blocks_reused), + ("consumer_allocations", metrics.consumer_allocations), + ( + "consumer_allocation_nanos", + metrics.consumer_allocation_nanos, + ), + ("maker_allocation_nanos", metrics.maker_allocation_nanos), ( "dispatches_without_effects", metrics.dispatches_without_effects, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 9d18547d3..ed63b77cb 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2302,12 +2302,16 @@ 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.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 +field metal2vulkan-rt::Metrics.blocks_reused pub blocks_reused: u64 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.consumer_allocation_max_nanos pub consumer_allocation_max_nanos: u64 +field metal2vulkan-rt::Metrics.consumer_allocation_nanos pub consumer_allocation_nanos: u64 +field metal2vulkan-rt::Metrics.consumer_allocations pub consumer_allocations: 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 @@ -2315,6 +2319,7 @@ field metal2vulkan-rt::Metrics.first_use_waits pub first_use_waits: u64 field metal2vulkan-rt::Metrics.forced_flushes_across_queues pub forced_flushes_across_queues: u64 field metal2vulkan-rt::Metrics.groups_beside_another_queue pub groups_beside_another_queue: u64 field metal2vulkan-rt::Metrics.lone_submissions_across_queues pub lone_submissions_across_queues: u64 +field metal2vulkan-rt::Metrics.maker_allocation_nanos pub maker_allocation_nanos: u64 field metal2vulkan-rt::Metrics.over_copies pub over_copies: u64 field metal2vulkan-rt::Metrics.passes pub passes: u64 field metal2vulkan-rt::Metrics.pipelines_created pub pipelines_created: u64 diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index bceae12e0..cf1a5c56c 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -665,7 +665,7 @@ Columns: | Variant | What it blocks | Where | Basis | Sites | Reach | |---|---|---|---|---|---| -| `BlockLen` | A block longer than one allocation and one buffer hold on the device (`Device::take_block` past `maxMemoryAllocationSize` or `maxBufferSize`) | at the device's limit | `device`: the device's `maxMemoryAllocationSize` and `maxBufferSize` | 1: `crates/metal2vulkan-rt/src/memory.rs (dedicated_len)` | `-` | +| `BlockLen` | A block longer than one allocation and one buffer hold on the device (`Device::take_block` past `maxMemoryAllocationSize` or `maxBufferSize`) | at the device's limit | `device`: the device's `maxMemoryAllocationSize` and `maxBufferSize` | 1: `crates/metal2vulkan-rt/src/memory.rs (round)` | `-` | | `BlockIds` | A block after every block number has been used (`Device::take_block`) | every device (a public call's own check of its arguments) | `ours`: block numbers are 32 bits | 1: `crates/metal2vulkan-rt/src/memory.rs (number)` | `-` | | `ThreadgroupShape` | A threadgroup longer on an axis than the device's `maxComputeWorkGroupSize` (the floor holds 1,024 by 1,024 by 64), where the threadgroup is the... | at the device's limit | `device`: the device's `maxComputeWorkGroupSize` | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | | `ThreadgroupMemory` | A dispatch whose threadgroup memory, the kernel's own and the lengths set (each rounded up to 16 bytes), is past the device's... | at the device's limit | `device`: the device's `maxComputeSharedMemorySize` | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | @@ -1235,7 +1235,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::AttachmentUsage`: `crates/metal2vulkan-rt/src/texture.rs (attachment)` - `rt:Refusal::AttachmentPlace`: `crates/metal2vulkan-rt/src/texture.rs (attachment)` - `rt:Refusal::AttachmentFormat`: `crates/metal2vulkan-rt/src/pass.rs (check, 2 sites)` -- `rt:Limit::BlockLen`: `crates/metal2vulkan-rt/src/memory.rs (dedicated_len)` +- `rt:Limit::BlockLen`: `crates/metal2vulkan-rt/src/memory.rs (round)` - `rt:Limit::BlockIds`: `crates/metal2vulkan-rt/src/memory.rs (number)` - `rt:Limit::ThreadgroupShape`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` - `rt:Limit::ThreadgroupMemory`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index 83ce326b1..703f34630 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -476,7 +476,7 @@ their times and memory compare. `command-replay dump --stream FILE` prints the c The counts are among its executed counters. A play with any of them above zero is no gate result: `report.txt` says so on a `skipped` line. It places buffers of their own in the - runtime's pooled blocks (16 MiB Shared, 64 MiB Private; a longer one in a block of its own), a + runtime's blocks of 16 MiB of either class (a longer one in a block of its own), a range freed for reuse once every command buffer committed before its release completed, gives the runtime back a block or heap of the stream at its release (`release_block`), and gives textures and sampler states indices from the whole of each index class. Its readback serves