diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index e7ba1f5e4..c39b500da 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -6,7 +6,15 @@ //! at offsets). //! - **Pooling.** Resources share blocks of [`BLOCK_BYTES`], so `maxMemoryAllocationCount` (4096 //! on many devices) stays out of reach. A request larger than half a block takes a dedicated -//! block of its own size. +//! block of its own size. Where a block of plain memory (allocated with no export) took longer +//! than [`MAKING_BOUND`] to make, the device's later pooled blocks of plain memory are made of +//! the largest power of two its rate makes within the bound, at least [`MIN_PLAIN_BLOCK_BYTES`] +//! ([`Memory::plain_block_made`]), a placement larger than such a block taking one of the power +//! of two that holds it: on RADV such a block shares the reservation of the process's buffer +//! objects, and its making holds every submission of the process for as long as it runs (a +//! Radeon 780M whose free memory lies in single pages took 9 to 23 ms for 64 MiB at the median). +//! The blocks of exportable buffers keep their size: each is a buffer object of its own +//! reservation, whose making holds no submission. //! - **Kept for reuse.** A block that empties is kept for the next placements rather than freed: //! a pooled one while fewer than [`KEPT_EMPTY_BLOCKS`] empty ones are kept in its pool, and //! past that, as a dedicated one of the runtime's own memory, while the empty blocks kept in its @@ -167,6 +175,15 @@ mod ready; /// The size of a pooled block, at most the device's `maxMemoryAllocationSize`. pub(super) const BLOCK_BYTES: u64 = 64 << 20; +/// The longest a making of a block of plain memory may take before the device's later pooled +/// blocks of plain memory are made smaller ([`Memory::plain_block_made`]): half a frame at 60 Hz. +/// On RADV such a making holds every submission of the process for as long as it runs (the module +/// docs), so a frame submitted meanwhile is late by what is left of it. +pub(super) const MAKING_BOUND: Duration = Duration::from_millis(8); + +/// The smallest a pooled block of plain memory is made ([`Memory::plain_block_made`]). +pub(super) const MIN_PLAIN_BLOCK_BYTES: u64 = 16 << 20; + /// The empty pooled blocks a pool keeps for its next placements whatever its heap's budget /// ([`Pool::release`], [`Memory::kept_budget`]). In a pool the encodings place in, one of them is /// mostly the block [`keep_room`] made for room: with one kept, every other block that emptied was @@ -1376,6 +1393,8 @@ pub(super) struct Block { /// ([`place_carried`]): the buffers carried from one block of the lost generation lie in it at /// their offsets, and nothing else is placed in it, so it goes once they do. carried: bool, + /// How long its making took ([`BlockMaker::make`]): zero for an import. + took: Duration, } /// The external memory a placement's memory is, as an image bound in it names it @@ -1864,6 +1883,10 @@ pub(super) struct Memory { /// The buffers' pools by memory type, then the images' ([`Memory::pool`]). pools: Vec>, block_bytes: u64, + /// The bytes a pooled block of plain memory is made of now: [`Memory::block_bytes`], made + /// smaller at each making that took longer than [`MAKING_BOUND`], down to + /// [`MIN_PLAIN_BLOCK_BYTES`] ([`Memory::plain_block_made`]). + plain_block_bytes: u64, /// Blocks are allocated with `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT`: the device enabled /// `bufferDeviceAddress`, so buffers carry device addresses. device_address: bool, @@ -2065,6 +2088,7 @@ impl Memory { .collect(), types, block_bytes: BLOCK_BYTES.min(max_allocation.max(1)), + plain_block_bytes: BLOCK_BYTES.min(max_allocation.max(1)), device_address, address_types: None, fd_address_types: None, @@ -2562,7 +2586,7 @@ impl Memory { let Some(made) = readying.take() else { return false; }; - let bytes = self.block_bytes; + let bytes = made.block.size; self.add_block(pool, made.block, bytes, false, 0); self.ahead.made_ahead(pool.0, waited_for, made.waited); if self.host_copy_pool == Some(Some(pool)) { @@ -2727,6 +2751,9 @@ impl Memory { Holds::PageBuffers => self.fd_blocks.pages_plain += 1, Holds::Images | Holds::Exports | Holds::DmaBufs => {} } + if block.exported.is_none() && !block.fd && !block.pooled_pages { + self.plain_block_made(block.size, block.took); + } self.allocated += size; let heap = self.heap_of(type_index); if let Some((_, live)) = self.heaps.get_mut(heap) { @@ -2740,6 +2767,61 @@ impl Memory { pool.add_as(size, dedicated, block, used, zeroed) } + /// The bytes of a pooled block made for `pool` with room for half of it + /// ([`pooled_block_bytes`]). + fn pooled_bytes(&self, pool: (Holds, u32)) -> u64 { + let types = ( + self.fd_buffer_types.unwrap_or(0), + self.page_buffer_types.unwrap_or(0), + ); + let plain = plain(pool, types.0, types.1).then_some(self.plain_block_bytes); + pooled_block_bytes(self.block_bytes, plain, 0) + } + + /// The bytes of each live pooled block that holds `holds`, of every memory type, for the + /// crate's tests. + #[cfg(test)] + pub(super) fn pooled_block_sizes(&self, holds: Holds) -> Vec { + let count = self.types.len() as u32; + (0..count) + .flat_map(|type_index| { + let pool = self.pool_ref(holds, type_index); + pool.blocks + .iter() + .flatten() + .filter(|block| !block.dedicated) + }) + .map(|block| block.size) + .collect() + } + + /// The bytes a pooled block of plain memory is made of now ([`Memory::plain_block_made`]), for + /// the crate's tests. + #[cfg(test)] + pub(super) fn plain_block_bytes(&self) -> u64 { + self.plain_block_bytes + } + + /// A block of plain memory of `size` bytes was made in `took` (`vkAllocateMemory`, its + /// mapping and its buffer of addresses): where that is longer than [`MAKING_BOUND`], the later + /// pooled blocks of plain memory are made of the largest power of two that the making's rate + /// (`size` in `took`) makes within the bound, where that is smaller than those made now, at + /// least [`MIN_PLAIN_BLOCK_BYTES`]. A block that took that long held every submission of the + /// process on RADV as long, and a block's making there takes about as much longer as the block + /// is larger. Never made larger again: the host's state that made it slow (its free memory in + /// single pages, no freed pages at hand in the kernel's pools) comes back. + pub(super) fn plain_block_made(&mut self, size: u64, took: Duration) { + if took <= MAKING_BOUND { + return; + } + let within = u128::from(size) * MAKING_BOUND.as_nanos() / took.as_nanos(); + let fits = match u64::try_from(within).unwrap_or(u64::MAX).checked_ilog2() { + Some(log) => 1 << log, + None => 0, + }; + self.plain_block_bytes = self.plain_block_bytes.min(fits.max(MIN_PLAIN_BLOCK_BYTES)); + } + /// What making a block takes, copied out so that the block is made with the memory's lock /// released ([`place`], [`keep_room`]). fn maker(&self) -> BlockMaker { @@ -2748,6 +2830,7 @@ impl Memory { .fold(0, |bits, (index, _)| bits | 1 << index); BlockMaker { block_bytes: self.block_bytes, + plain_block_bytes: self.plain_block_bytes, host_visible, fd_types: self.fd_buffer_types.unwrap_or(0), page_types: self.page_buffer_types.unwrap_or(0), @@ -2988,11 +3071,11 @@ impl Memory { } // A block made ahead for a pool that stopped growing that long ago, where the pool has // room for half a block (`memory/ready.rs`). - let room = self.block_bytes / 2; let mut at = 0; while at < self.readying.len() { let (holds, type_index) = self.readying[at].pool(); let started = self.readying[at].started(); + let room = self.pooled_bytes((holds, type_index)) / 2; let pool = self.pool(holds, type_index); let since = pool.grew(None).map_or(started, |grew| grew.max(started)); let unused = now.saturating_duration_since(since) >= KEPT_EMPTY_FOR @@ -3340,11 +3423,37 @@ impl Memory { } } +/// Whether the blocks of `pool` are of plain memory, allocated with no export +/// ([`BlockMaker::make`]): not those of exportable buffers ([`Holds::handle`]), nor those of +/// [`Holds::FdBuffers`] of a memory type `fd_types` names (as bits), which are allocated +/// exportable as [`FD_BLOCKS_HANDLE`], nor those of [`Holds::PageBuffers`] of a memory type +/// `page_types` names, which are pages the runtime maps and imports. +fn plain((holds, type_index): (Holds, u32), fd_types: u32, page_types: u32) -> bool { + let named = |types: u32| types & 1 << type_index != 0; + holds.handle().is_none() + && !(holds == Holds::FdBuffers && named(fd_types)) + && !(holds == Holds::PageBuffers && named(page_types)) +} + +/// The bytes of a pooled block that holds a placement of `size` bytes, at most half of +/// `block_bytes` ([`place`]): `block_bytes` where its blocks are allocated exportable (`plain` +/// `None`); else the bytes `plain` says a pooled block of plain memory is made of now +/// ([`Memory::plain_block_made`]), or the power of two that holds the placement where that is +/// larger. +pub(super) fn pooled_block_bytes(block_bytes: u64, plain: Option, size: u64) -> u64 { + match plain { + None => block_bytes, + Some(plain) => (plain.max(size.next_power_of_two())).min(block_bytes), + } +} + /// What making a block of the runtime's memory takes ([`Memory::maker`]): a copy of the memory's /// constants, so that the block is made with its lock released. struct BlockMaker { /// A pooled block's size ([`BLOCK_BYTES`], or the device's largest allocation). block_bytes: u64, + /// As [`Memory`]'s. + plain_block_bytes: u64, /// The host-visible memory types, as bits: a block of one is mapped whole. host_visible: u32, /// The memory types whose [`Holds::FdBuffers`] blocks are allocated exportable, as bits. @@ -3364,6 +3473,13 @@ struct BlockMaker { } impl BlockMaker { + /// The bytes of a pooled block made for `pool` that holds a placement of `size` bytes, at + /// most half a block ([`place`]; [`pooled_block_bytes`]). + fn pooled_bytes(&self, pool: (Holds, u32), size: u64) -> u64 { + let plain = plain(pool, self.fd_types, self.page_types).then_some(self.plain_block_bytes); + pooled_block_bytes(self.block_bytes, plain, size) + } + /// A new block of `size` bytes of memory type `type_index` that holds `holds`, with a buffer /// of addresses where `addressed` gives the counts of such buffers made (its memory then as /// long as that buffer requires, if longer), allocated zero-initialized where it holds images @@ -3481,6 +3597,7 @@ impl BlockMaker { zeroed: false, pooled_pages: true, carried: false, + took: Duration::ZERO, })) } @@ -3497,6 +3614,7 @@ impl BlockMaker { export: Exportable, zeroed: bool, ) -> Result { + let began = Instant::now(); let addresses = if addressed.is_some() && self.device_address { let sharing = Sharing::new(&self.families); Some(address_buffer(device, size, sharing, export.handle())?) @@ -3598,6 +3716,7 @@ impl BlockMaker { zeroed, pooled_pages: false, carried: false, + took: began.elapsed(), }) } } @@ -3848,6 +3967,7 @@ pub(super) unsafe fn import_host( zeroed: false, pooled_pages: false, carried: false, + took: Duration::ZERO, }; let host = pointer.as_ptr() as usize; let mut memory = lock(memory); @@ -3887,6 +4007,7 @@ pub(super) fn import_own_pages( zeroed: false, pooled_pages: false, carried: false, + took: Duration::ZERO, }; let mut memory = lock(memory); memory.say_block("imported fresh pages for a buffer", &block); @@ -3949,6 +4070,7 @@ pub(super) fn place_carried( zeroed: false, pooled_pages: true, carried: true, + took: Duration::ZERO, }; let mut guard = lock(memory); match carried_in(&guard) { @@ -4261,13 +4383,16 @@ fn place( return Err(Error::OutOfMemory(MemoryKind::Device)); } let dedicated = fit == Fit::Apart || size > maker.block_bytes / 2; - let block_size = if dedicated { size } else { maker.block_bytes }; let mut failure = Error::OutOfMemory(MemoryKind::Device); // The class's own types first, then those it overflows into where none of them has room. let order = (candidates.iter().map(|&type_index| (type_index, false))) .chain(overflow.iter().map(|&type_index| (type_index, true))); for (type_index, overflowing) in order { let pool = (holds, type_index); + let block_size = match dedicated { + true => size, + false => maker.pooled_bytes(pool, size), + }; if fit == Fit::Pooled { let mut guard = lock(memory); if let Some(placement) = @@ -4412,12 +4537,12 @@ pub(super) fn keep_room( let first = (kept.iter()).filter(|&&(holds, _)| holds == own || (page(holds) && pages)); let rest = (kept.iter()) .filter(|&&(holds, _)| holds != own && holds != Holds::FdBuffers && !page(holds)); - let room = maker.block_bytes / 2; for &pool in first.chain(rest) { let addressed = pool.0.buffers().then_some(&**counts); + let bytes = maker.pooled_bytes(pool, 0); loop { let mut guard = lock(memory); - if guard.pool(pool.0, pool.1).has_room(room) { + if guard.pool(pool.0, pool.1).has_room(bytes / 2) { break; } // The host copies' block made ahead joins its pool at the placement that needs it @@ -4441,11 +4566,11 @@ pub(super) fn keep_room( if !crate::allocations::room_ahead(device.handle()) { break; } - let Ok(block) = maker.make(device, pool, maker.block_bytes, addressed) else { + let Ok(block) = maker.make(device, pool, bytes, addressed) else { break; }; let mut guard = lock(memory); - guard.add_block(pool, block, maker.block_bytes, false, 0); + guard.add_block(pool, block, bytes, false, 0); guard.ahead.made_in_place(pool.0); break; } @@ -4471,7 +4596,7 @@ fn ready_if_growing( counts: &Arc, (functions, quiet): (&Arc, &Arc), ) { - let bytes = memory.block_bytes; + let bytes = memory.pooled_bytes(pool); let ahead = memory.readying_at(pool).is_some(); let pool_of = memory.pool(pool.0, pool.1); let grew = (pool_of.grew(None)).is_some_and(|at| at.elapsed() < KEPT_EMPTY_FOR); @@ -4505,12 +4630,11 @@ fn ready_ahead( let Some(pool) = memory.host_copy_pool(device, copies) else { return; }; - let room = memory.block_bytes / 2; - if memory.readying_at(pool).is_some() || memory.pool(pool.0, pool.1).has_room(room) { + let bytes = memory.pooled_bytes(pool); + if memory.readying_at(pool).is_some() || memory.pool(pool.0, pool.1).has_room(bytes / 2) { return; } let maker = memory.maker(); - let bytes = maker.block_bytes; let functions = Arc::clone(functions); let started = ready::Readying::start(maker, functions, Arc::clone(quiet), None, (pool, bytes)); memory.readying.extend(started); diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 0d9a4b983..8dcbaba65 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -354,6 +354,7 @@ mod pipeline; mod pipeline_wait_order; #[cfg(unix)] mod pixel_format_info; +mod plain_blocks; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod point_size_notices; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] diff --git a/crates/metal2vulkan-runtime/src/tests/plain_blocks.rs b/crates/metal2vulkan-runtime/src/tests/plain_blocks.rs new file mode 100644 index 000000000..380e60ee5 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/plain_blocks.rs @@ -0,0 +1,201 @@ +//! A device whose making of a block of plain memory took longer than `memory::MAKING_BOUND` makes +//! its later pooled blocks of plain memory of the largest power of two that making's rate makes +//! within the bound, down to `memory::MIN_PLAIN_BLOCK_BYTES` (`Memory::plain_block_made`): on RADV +//! such a making holds every submission of the process for as long as it runs. A placement larger +//! than such a block, up to half of `memory::BLOCK_BYTES`, takes a block of the power of two that +//! holds it, and the blocks of exportable buffers keep their size. +//! +//! The first two tests are of the memory's bookkeeping alone. The third makes textures on a device +//! told of a slow making and reads the sizes of the blocks of images it made: device tests compile +//! only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). + +use crate::memory::{pooled_block_bytes, Memory, BLOCK_BYTES, MAKING_BOUND, MIN_PLAIN_BLOCK_BYTES}; +use ash::vk; +use std::time::Duration; + +const MIB: u64 = 1 << 20; + +/// The memory of a device of one host-visible memory type, whose largest allocation is +/// `max_allocation` bytes. +fn memory_of(max_allocation: u64) -> Memory { + let mut properties = vk::PhysicalDeviceMemoryProperties { + memory_type_count: 1, + memory_heap_count: 1, + ..Default::default() + }; + properties.memory_types[0] = vk::MemoryType { + property_flags: vk::MemoryPropertyFlags::DEVICE_LOCAL + | vk::MemoryPropertyFlags::HOST_VISIBLE + | vk::MemoryPropertyFlags::HOST_COHERENT, + heap_index: 0, + }; + properties.memory_heaps[0] = vk::MemoryHeap { + size: 8 << 30, + flags: vk::MemoryHeapFlags::DEVICE_LOCAL, + }; + Memory::new( + &properties, + max_allocation, + false, + true, + vec![0], + None, + None, + ) +} + +#[test] +fn a_making_past_the_bound_makes_the_later_plain_blocks_of_what_its_rate_makes_within_it() { + let ms = |micros: u64| Duration::from_micros(micros); + let mut memory = memory_of(u64::MAX); + assert_eq!(memory.plain_block_bytes(), BLOCK_BYTES); + // A making within the bound leaves the size. + memory.plain_block_made(BLOCK_BYTES, MAKING_BOUND); + assert_eq!(memory.plain_block_bytes(), BLOCK_BYTES); + // 64 MiB in 9.6 ms (a Radeon 780M's slowest on a quiet host, the kernel's page pools empty) + // makes 53 MiB in the bound: 32 MiB blocks. + memory.plain_block_made(BLOCK_BYTES, ms(9_600)); + assert_eq!(memory.plain_block_bytes(), 32 * MIB); + // A fast making never makes them larger again, nor a slow one whose rate makes more. + memory.plain_block_made(32 * MIB, Duration::ZERO); + assert_eq!(memory.plain_block_bytes(), 32 * MIB); + memory.plain_block_made(4 * BLOCK_BYTES, MAKING_BOUND * 2); + assert_eq!(memory.plain_block_bytes(), 32 * MIB); + // A dedicated block of an odd size: 48 MiB in twice the bound makes 24 MiB in it. + memory.plain_block_made(48 * MIB, MAKING_BOUND * 2); + assert_eq!(memory.plain_block_bytes(), 16 * MIB); + // Never below the least. + memory.plain_block_made(MIN_PLAIN_BLOCK_BYTES, MAKING_BOUND * 100); + assert_eq!(memory.plain_block_bytes(), MIN_PLAIN_BLOCK_BYTES); + // 64 MiB in 23.1 ms (the 780M's median with its free memory in single pages) makes 22 MiB in + // the bound: one such making takes the blocks to 16 MiB. + let mut fragmented = memory_of(u64::MAX); + fragmented.plain_block_made(BLOCK_BYTES, ms(23_100)); + assert_eq!(fragmented.plain_block_bytes(), 16 * MIB); + // A device whose largest allocation is below the least keeps its blocks of that size. + let mut small = memory_of(4 * MIB); + small.plain_block_made(4 * MIB, MAKING_BOUND * 100); + assert_eq!(small.plain_block_bytes(), 4 * MIB); +} + +#[test] +fn a_pooled_block_holds_its_placement_and_exportable_blocks_keep_their_size() { + let plain = Some(16 * MIB); + assert_eq!(pooled_block_bytes(BLOCK_BYTES, plain, MIB), 16 * MIB); + assert_eq!(pooled_block_bytes(BLOCK_BYTES, plain, 16 * MIB), 16 * MIB); + assert_eq!( + pooled_block_bytes(BLOCK_BYTES, plain, 16 * MIB + 1), + 32 * MIB + ); + assert_eq!( + pooled_block_bytes(BLOCK_BYTES, plain, BLOCK_BYTES / 2), + BLOCK_BYTES / 2 + ); + // A largest allocation that is no power of two bounds the block. + assert_eq!(pooled_block_bytes(48 * MIB, plain, 20 * MIB), 32 * MIB); + assert_eq!( + pooled_block_bytes(48 * MIB, Some(48 * MIB), 20 * MIB), + 48 * MIB + ); + // The blocks of exportable buffers. + assert_eq!(pooled_block_bytes(BLOCK_BYTES, None, MIB), BLOCK_BYTES); +} + +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod device { + use super::{BLOCK_BYTES, MAKING_BOUND, MIB, MIN_PLAIN_BLOCK_BYTES}; + use crate::memory::Holds; + use crate::tests::freed_memory::device; + use crate::{Device, ResourceOptions, Texture, TextureDescriptor}; + use metal2vulkan::metal::{PixelFormat, TextureUsage}; + + /// The textures each run makes at most before the image pool makes the block it waits for. + const MOST: usize = 256; + + /// A `Private` `RGBA8Unorm` texture of `width` by `height`, sampled and rendered to. + fn texture(device: &Device, width: u64, height: u64) -> Texture { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, width, height, false); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::private(); + device.new_texture(&descriptor).unwrap() + } + + /// The device's pooled blocks of images, by size. + fn image_blocks(device: &Device) -> Vec { + let mut sizes = + crate::device::lock(&device.shared().memory).pooled_block_sizes(Holds::Images); + sizes.sort_unstable(); + sizes + } + + /// The blocks in `after` that `before` does not hold, as many times as they are more. + fn new_blocks(before: &[u64], after: &[u64]) -> Vec { + let mut left = before.to_vec(); + (after.iter()) + .filter(|size| match left.iter().position(|kept| kept == *size) { + Some(at) => { + left.swap_remove(at); + false + } + None => true, + }) + .copied() + .collect() + } + + /// Make textures of `width` by `height` until the device made a block of images of more than + /// `past` bytes: the blocks made meanwhile. + fn until_a_block( + device: &Device, + (width, height): (u64, u64), + past: u64, + held: &mut Vec, + ) -> Vec { + let before = image_blocks(device); + for _ in 0..MOST { + held.push(texture(device, width, height)); + let made = new_blocks(&before, &image_blocks(device)); + if made.iter().any(|&size| size > past) { + return made; + } + } + panic!("{MOST} textures of {width} x {height} made no block of images past {past} bytes"); + } + + #[test] + fn textures_after_a_slow_making_lie_in_smaller_blocks_or_one_that_holds_them() { + let scratch = std::env::temp_dir().join(format!("m2v-plain-blocks-{}", std::process::id())); + std::fs::create_dir_all(&scratch).unwrap(); + let device = device(&scratch); + { + // A pooled block's making that took four times the bound. + let mut memory = crate::device::lock(&device.shared().memory); + memory.plain_block_made(BLOCK_BYTES, MAKING_BOUND * 4); + assert_eq!(memory.plain_block_bytes(), MIN_PLAIN_BLOCK_BYTES); + } + let mut held = Vec::new(); + // 1 MiB textures: blocks of the least size. + let small = until_a_block(&device, (512, 512), 0, &mut held); + // 20 MiB ones: past that size, a block of 32 MiB each. + let large = until_a_block(&device, (2560, 2048), MIN_PLAIN_BLOCK_BYTES, &mut held); + println!( + "PLAIN-BLOCKS {}: after a slow making, 1 MiB textures made blocks of images of {:?} \ + MiB, 20 MiB ones {:?} MiB", + device.name(), + small.iter().map(|size| size / MIB).collect::>(), + large.iter().map(|size| size / MIB).collect::>(), + ); + assert!( + small.iter().all(|&size| size == MIN_PLAIN_BLOCK_BYTES), + "1 MiB textures made blocks of {small:?} bytes" + ); + assert!( + large.contains(&(32 * MIB)) && large.iter().all(|&size| size <= 32 * MIB), + "20 MiB textures made blocks of {large:?} bytes" + ); + drop(held); + drop(device); + let _ = std::fs::remove_dir_all(&scratch); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/reclaim_submit_bench.rs b/crates/metal2vulkan-runtime/src/tests/reclaim_submit_bench.rs index 6cb5da42e..658a5cbb3 100644 --- a/crates/metal2vulkan-runtime/src/tests/reclaim_submit_bench.rs +++ b/crates/metal2vulkan-runtime/src/tests/reclaim_submit_bench.rs @@ -43,6 +43,13 @@ //! [`RUNTIME_BUFFERS`] a phase: the pool of exportable buffers grows, its blocks made ahead //! (`memory/ready.rs`), each a buffer object of its own reservation, so that the makings timed //! are the creation calls, on the calling thread. +//! - **Images, made by the runtime**: a `Private` `RGBA8Unorm` texture of [`IMAGE_SIDE`] square (4 +//! MiB), rendered to and sampled, every [`IMAGE_EVERY`] (a frame at 60 Hz), at most +//! [`IMAGE_TEXTURES`] a phase: the runtime's pool of images grows, its blocks made ahead +//! (`memory/ready.rs`), plain blocks whose making holds the device's submissions on RADV. +//! - **Images of mixed sizes, made by the runtime**: the same, in turn the sizes of +//! [`MIXED_SIDES`] (a frame's textures and two screen-sized ones, larger than a small block), at +//! most [`MIXED_TEXTURES`] a phase. //! - **System heap, 64 MiB**, **System heap, 16 MiB** and **System heap, 4 MiB**: allocations of //! the device's first memory type that is host-visible and host-coherent but not device-local or //! cached (where a unified-memory device's `Private` blocks lie, `memory.rs`, `candidates`), of @@ -92,9 +99,12 @@ //! (`WorkCounts::batches_submitted_at_commit`) and the time spent in `vkQueueSubmit` //! (`WorkCounts::batch_submit_nanos`); the makings, their median and slowest, the runtime's blocks //! made ahead and in place and the blocks made ahead a call waited for -//! (`WorkCounts::blocks_ahead_waited_for`), its buffers' blocks made exportable and plain, every -//! plain block of buffers made (`WorkCounts::plain_buffer_blocks_made`), and its buffers laid in -//! plain blocks while the check was pending or once it refused such blocks; the host's reclaim over +//! (`WorkCounts::blocks_ahead_waited_for`), its blocks of images made ahead and in place, every +//! pooled block made (`WorkCounts::pooled_memory_blocks_made`), the dedicated blocks added +//! (`WorkCounts::dedicated_memory_blocks_live`), its buffers' blocks made exportable and plain, +//! every plain block of buffers made (`WorkCounts::plain_buffer_blocks_made`), and its buffers laid +//! in plain blocks while the check was pending or once it refused such blocks; the size its pooled +//! blocks of plain memory were made of at the end (`memory.rs`'s "Pooling"); the host's reclaim over //! the phase (`/proc/vmstat`: pages kswapd and direct reclaim scanned, compaction stalls, //! allocation stalls, pages swapped out); the memory the fragmenting took, the host's free memory //! and the cgroup's room it was sized from; the free blocks of each order before and after the @@ -108,9 +118,10 @@ use super::host_residency::{device, Scratch}; use crate::{ Buffer, CommandBufferStatus, CommandQueue, Device, DeviceKind, DeviceOptions, HostMemory, - ResourceOptions, ShaderCacheOptions, + ResourceOptions, ShaderCacheOptions, Texture, TextureDescriptor, }; use ash::vk; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; use std::ptr::NonNull; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -129,6 +140,25 @@ const GIB: u64 = 1 << 30; const RUNTIME_BUFFER_BYTES: u64 = 32 * MIB; const RUNTIME_BUFFERS: usize = 24; const RUNTIME_EVERY: Duration = Duration::from_millis(400); +/// The images arm's textures: `RGBA8Unorm` of this side (4 MiB), one a frame at 60 Hz, at most +/// this many a phase (768 MiB). +const IMAGE_SIDE: u64 = 1024; +const IMAGE_EVERY: Duration = Duration::from_micros(16_667); +const IMAGE_TEXTURES: usize = 192; +/// The mixed images arm's textures, in turn, one a frame at 60 Hz, at most [`MIXED_TEXTURES`] a +/// phase: six of 4 MiB, one of 14.1 MiB (2560 x 1440) and one of 31.6 MiB (3840 x 2160), 836 MiB +/// a phase. +const MIXED_SIDES: [(u64, u64); 8] = [ + (1024, 1024), + (1024, 1024), + (1024, 1024), + (2560, 1440), + (1024, 1024), + (1024, 1024), + (1024, 1024), + (3840, 2160), +]; +const MIXED_TEXTURES: usize = 96; /// The raw arms' bytes a phase, and the gap between their 64 MiB allocations. const RAW_BYTES: u64 = 768 * MIB; const RAW_EVERY: Duration = Duration::from_millis(800); @@ -401,6 +431,10 @@ enum Making { Runtime, /// The runtime's exportable `Private` buffers (the module docs). Exportable, + /// The runtime's `Private` textures (the module docs). + Images, + /// The runtime's `Private` textures of mixed sizes (the module docs). + ImagesMixed, /// Allocations of `bytes` of the memory type `index`, [`RAW_BYTES`] a phase, exportable as /// `export`'s handle type where given. Raw { @@ -415,6 +449,7 @@ enum Making { #[derive(Default)] struct Made { buffers: Vec, + textures: Vec, raw: Vec, } @@ -428,6 +463,8 @@ fn make( let mut times = Vec::new(); let (every, most) = match making { Making::Runtime | Making::Exportable => (RUNTIME_EVERY, RUNTIME_BUFFERS), + Making::Images => (IMAGE_EVERY, IMAGE_TEXTURES), + Making::ImagesMixed => (IMAGE_EVERY, MIXED_TEXTURES), Making::Raw { bytes, .. } => ( RAW_EVERY.mul_f64(bytes as f64 / (64 * MIB) as f64), (RAW_BYTES / bytes) as usize, @@ -448,6 +485,17 @@ fn make( .new_exportable_buffer(RUNTIME_BUFFER_BYTES, ResourceOptions::private()) .unwrap(), ), + Making::Images | Making::ImagesMixed => { + let (width, height) = match making { + Making::Images => (IMAGE_SIDE, IMAGE_SIDE), + _ => MIXED_SIDES[times.len() % MIXED_SIDES.len()], + }; + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, width, height, false); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::private(); + made.textures.push(device.new_texture(&descriptor).unwrap()); + } Making::Raw { index, bytes, @@ -548,7 +596,8 @@ fn phase( {turn_p99:.3}, slowest {turn_slowest:.3}; command buffers submitted {submitted}, by the \ committing thread {}, in vkQueueSubmit {:.1} ms, {:.3} ms each; {} makings, ms median \ {make_median:.1}, slowest {make_slowest:.1}; blocks made ahead {}, in place {}, \ - waited for {}; \ + waited for {}; image blocks made ahead {}, in place {}; pooled blocks made {}; \ + dedicated blocks added {}; \ blocks of the runtime's buffers made exportable {}, made plain {}, plain blocks of \ buffers made {}; buffers in plain blocks awaiting the check {}, by its refusal {}; \ reclaim: {}; blocks live {}, empty {}; MemAvailable {} MiB", @@ -565,6 +614,10 @@ fn phase( counts.buffer_blocks_made_ahead - earlier.buffer_blocks_made_ahead, counts.buffer_blocks_made_in_place - earlier.buffer_blocks_made_in_place, counts.blocks_ahead_waited_for - earlier.blocks_ahead_waited_for, + counts.image_blocks_made_ahead - earlier.image_blocks_made_ahead, + counts.image_blocks_made_in_place - earlier.image_blocks_made_in_place, + counts.pooled_memory_blocks_made - earlier.pooled_memory_blocks_made, + (counts.dedicated_memory_blocks_live).saturating_sub(earlier.dedicated_memory_blocks_live), counts.fd_buffer_blocks_made - earlier.fd_buffer_blocks_made, counts.fd_buffer_blocks_plain - earlier.fd_buffer_blocks_plain, counts.plain_buffer_blocks_made - earlier.plain_buffer_blocks_made, @@ -604,6 +657,10 @@ enum Arm { }, /// The runtime's exportable buffers. Exportable, + /// The runtime's textures. + Images, + /// The runtime's textures of mixed sizes. + ImagesMixed, SystemHeap { bytes: u64, export: Option, @@ -648,6 +705,8 @@ fn arm(label: &str, arm: Arm) { Making::Runtime } Arm::Exportable => Making::Exportable, + Arm::Images => Making::Images, + Arm::ImagesMixed => Making::ImagesMixed, Arm::SystemHeap { bytes, export } => Making::Raw { index: system_heap(), bytes, @@ -708,8 +767,12 @@ fn arm(label: &str, arm: Arm) { &mut made, ); buddies("after the pressed phase"); + eprintln!( + "RECLAIM-SUBMIT {label}: pooled blocks of plain memory made of {} MiB at the end", + crate::device::lock(&device.shared().memory).plain_block_bytes() >> 20 + ); drop(pressing); - drop((source, middle, out, made.buffers)); + drop((source, middle, out, made.buffers, made.textures)); for memory in made.raw { // SAFETY: nothing uses the memory. unsafe { crate::release::object(device.shared().vk(), memory) }; @@ -1137,6 +1200,21 @@ fn reclaim_submit_bench_runtime_settled() { ); } +#[test] +#[ignore = "a measurement that presses the host's memory: run alone on its host by name"] +fn reclaim_submit_bench_images() { + arm("images, made by the runtime", Arm::Images); +} + +#[test] +#[ignore = "a measurement that presses the host's memory: run alone on its host by name"] +fn reclaim_submit_bench_images_mixed() { + arm( + "images of mixed sizes, made by the runtime", + Arm::ImagesMixed, + ); +} + #[test] #[ignore = "a measurement that presses the host's memory: run alone on its host by name"] fn reclaim_submit_bench_exportable() {