diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index da21d1533..e4f7d36dc 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -340,7 +340,15 @@ in its memory. longest. Where the block-maker thread's make failed, or the thread had stopped, the call makes it on its own thread with the same function, counted at its site. Every device holds these 18 MiB from its start, used or not, and the ring's second block of 2 MiB from its first take of - a chunk (a parameter write, or a buffer argument bound to nothing). + a chunk (a parameter write, or a buffer argument bound to nothing). A take takes a chunk of the + oldest block with one free, so the newest blocks fall idle first. A ring block past the first + goes on the block-maker thread once every chunk of it has been free for the idle age (250 ms), + where the ring, at its fewest free chunks since, kept more than a block's chunks free without + it, so no take would have asked for a block; the first block stays, and so does a block that + holds the nil buffer, the zero range or the whole execution range. So a burst's blocks go once + the device's parameter writes fall back, down to what the writes since need and a block's + chunks ahead of them: an idle device keeps the first block and the one ahead of it, and a ring + in steady use frees no block it would make again. - 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 diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index d949ddca9..c6a056a68 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -851,6 +851,11 @@ pub(crate) enum Loose { memory: vk::DeviceMemory, bytes: u64, }, + /// An idle parameter ring block, its buffer and memory (`crate::ring::Ring::due`). + RingBlock { + buffer: vk::Buffer, + memory: vk::DeviceMemory, + }, } struct State { @@ -1517,7 +1522,7 @@ impl Pool { } /// Wakes the block-maker thread to weigh what another part of the device made idle: a - /// preprocess region ([`crate::indirect`]). + /// preprocess region ([`crate::indirect`]), or a parameter ring block ([`crate::ring`]). pub(crate) fn nudge(&self) { drop(self.lock()); self.changed.notify_all(); @@ -1815,7 +1820,8 @@ pub(crate) fn stock(core: &Core) { /// frees each imported or exported block given back, then runs an import's release; it makes an /// allocation of a class that holds no wholly free unit ([`State::whole`]), having the consumer /// map it before it joins the pool; and it frees each allocation idle for [`IDLE_AGE_NANOS`], -/// after the consumer's unmap of it, one at a time. Each of its allocations and frees starts once +/// after the consumer's unmap of it, one at a time, and each parameter ring block the ring's idle +/// rule gives it ([`crate::ring::Ring::due`]). Each of its allocations and frees starts once /// the submit calls inside the driver as its previous one returned have returned /// ([`maker_call`]), and what it made is handed on as its call returns. It sleeps until /// the next change, or until the oldest idle allocation reaches the idle age. Stopped, it makes @@ -1902,7 +1908,7 @@ pub(crate) fn run(core: Arc) { continue; } // The idle rule, both classes: the next allocation to free; first, a preprocess region - // idle for the idle age. + // idle for the idle age, and a ring block. let now = crate::host_time(); let mut wake: Option = None; match (core.indirect.as_ref()).and_then(|indirect| indirect.due(now)) { @@ -1916,6 +1922,21 @@ pub(crate) fn run(core: Arc) { Some(Err(at)) => wake = Some(Duration::from_nanos(at.saturating_sub(now))), None => {} } + // Then a parameter ring block past the first, idle for the idle age. + match core.ring.due(now) { + Some(Ok(block)) => { + drop(state); + // SAFETY: every chunk of the block is free, so no pending work reads it. + unsafe { free_loose(&core, block) }; + state = pool.lock(); + continue; + } + Some(Err(at)) => { + let due = Duration::from_nanos(at.saturating_sub(now)); + wake = Some(wake.map_or(due, |wake| wake.min(due))); + } + None => {} + } let mut gone = None; for class in MemoryClass::ALL { let due = match pool.rule(&state, class, now) { @@ -2915,6 +2936,15 @@ unsafe fn free_loose(core: &Core, loose: Loose) { counters.fall(Gauge::Blocks); counters.fall_by(Gauge::PreprocessIdleBytes, bytes); } + Loose::RingBlock { buffer, memory } => { + (core.spans).freed(buffer, core.pool.in_flight(), None); + // SAFETY: the caller's; freeing the memory unmaps it. + unsafe { + core.device.destroy_buffer(buffer, None); + free(&core.device, memory); + } + counters.fall(Gauge::Blocks); + } } } diff --git a/crates/metal2vulkan-runtime/src/ring.rs b/crates/metal2vulkan-runtime/src/ring.rs index 862e55f3b..2549b8ff6 100644 --- a/crates/metal2vulkan-runtime/src/ring.rs +++ b/crates/metal2vulkan-runtime/src/ring.rs @@ -8,7 +8,8 @@ //! block's address at a multiple of that alignment, and 31 where it places it off it //! ([`chunk_starts`]). A command buffer takes //! chunks as it records, writes each byte once, and gives them back when it retires, so the GPU -//! never reads a chunk the host is writing. Each block is kept for the device's life. The +//! never reads a chunk the host is writing. A take takes a chunk of the first block, in the order +//! the blocks were made, that has one free, so the later blocks are the first to fall idle. The //! block-maker thread makes them, off every caller's thread (`crate::memory::Internal`): the //! first as its first work once the device's making starts it, and the next each time a take //! leaves fewer chunks free than a block holds, so a block's chunks are free ahead of the takes @@ -24,6 +25,15 @@ //! [`Metrics::ring_block_allocations`](crate::Metrics::ring_block_allocations), and takes that //! meet it then wait for it. The runtime never reads the ring back. //! +//! The idle rule ([`Ring::due`]) frees a block past the first on the block-maker thread once every +//! chunk of it has been free for the idle age (`crate::memory::IDLE_AGE_NANOS`, 250 ms), where the +//! ring, at its fewest free chunks since the block fell idle, kept more than a block's chunks free +//! without it, so neither a take in that time nor the next would have asked for a block. The first +//! block is kept for the device's life, and so is a block that holds a chunk kept for it (below). +//! So the blocks a burst made go once the takes fall back, down to what the takes since need and +//! a block's chunks ahead of them; an idle ring keeps its first block and the one ahead of it, and +//! a ring in steady use frees no block it would make again. +//! //! One chunk, taken at the first ask and kept for the device's life, is the nil buffer //! ([`Ring::nil`]): 64 KiB of zeros, at a multiple of 16 like every chunk, so it meets any buffer //! argument's alignment. A buffer argument nothing is bound to reads it, as Metal's nil buffer @@ -86,8 +96,10 @@ pub(crate) struct Ring { } struct State { + /// The blocks in the order they were made: a take takes a chunk of the first with one free. blocks: Vec, - free: Vec, + /// The free chunks of every block. + free: usize, /// Who makes the next block. next: Next, } @@ -106,6 +118,26 @@ enum Next { struct RingBlock { buffer: vk::Buffer, memory: vk::DeviceMemory, + /// Its free chunks. + free: Vec, + /// Its chunks ([`chunk_starts`]). + chunks: usize, + /// Where every chunk of it is free: since when, and the fewest chunks the ring had free since + /// then. + idle: Option, +} + +/// A block's idle time ([`RingBlock::idle`]). +#[derive(Clone, Copy)] +struct Idle { + since: u64, + low: usize, +} + +/// A block made ([`make`]), before the ring keeps it. +struct Made { + buffer: vk::Buffer, + memory: vk::DeviceMemory, } /// A chunk: its device address, its host address, and its block's buffer with its offset there. @@ -134,7 +166,7 @@ impl Ring { align: align.max(ALIGN), state: Mutex::new(State { blocks: Vec::new(), - free: Vec::new(), + free: 0, next: Next::Maker, }), nil: OnceLock::new(), @@ -155,8 +187,8 @@ impl Ring { // When this take began to wait for the block-maker thread's block. let mut since = None; loop { - if let Some(chunk) = state.free.pop() { - let ask = state.next == Next::Unasked && state.free.len() < SPARE; + if let Some(chunk) = state.take() { + let ask = state.next == Next::Unasked && state.free < SPARE; if ask { state.next = Next::Maker; } @@ -187,7 +219,9 @@ impl Ring { state.next = Next::Unasked; self.changed.notify_all(); let (block, address, host) = made?; - Ok(state.add(block, address, host, self.align)) + let chunk = state.add(block, address, host, self.align); + state.taken(); + Ok(chunk) } /// On the block-maker thread: makes the block asked of it ([`Internal::RingBlock`]) and hands @@ -200,7 +234,7 @@ impl Ring { self.changed.notify_all(); let (block, address, host) = made?; let first = state.add(block, address, host, self.align); - state.free.push(first); + state.give(vec![first], crate::host_time()); Ok(()) } @@ -257,29 +291,63 @@ impl Ring { let address = *which.get_or_init(|| chunk.address); if address != chunk.address { // Another thread's ask made it first: the chunk goes back. - let mut state = lock(&self.state); - state.free.push(chunk); - if state.next != Next::Unasked { - self.changed.notify_all(); - } + self.give_back(core, vec![chunk]); } Ok(address) } - /// Takes back a retired command buffer's chunks. - fn give_back(&self, chunks: Vec) { + /// Takes back a retired command buffer's chunks. Where a block past the first has every chunk + /// free then, the block-maker thread is woken to weigh it ([`due`](Self::due)). + fn give_back(&self, core: &Core, chunks: Vec) { + let now = crate::host_time(); let mut state = lock(&self.state); - state.free.extend(chunks); + let idle = state.give(chunks, now); if state.next != Next::Unasked { self.changed.notify_all(); } + drop(state); + if idle { + core.pool.nudge(); + } + } + + /// On the block-maker thread, the idle rule (the module docs): the last block past the first + /// whose chunks have all been free for the idle age ([`memory::IDLE_AGE_NANOS`]) at `now`, + /// where the ring at its fewest free chunks since kept more than a block's chunks free without + /// it, taken out of the ring to free; else the host time when one such block will be due where + /// nothing changes (`Err`). `None` where no block past the first meets it, or a block is being + /// made. A block that does not meet it now meets it in this idle time no more: the ring's + /// fewest free chunks since only fall. + pub(crate) fn due(&self, now: u64) -> Option> { + let mut state = lock(&self.state); + if state.next != Next::Unasked { + return None; + } + let mut wake: Option = None; + let mut gone = None; + for (index, block) in state.blocks.iter().enumerate().skip(1).rev() { + let Some(idle) = block.idle.filter(|idle| idle.low > block.chunks + SPARE) else { + continue; + }; + match memory::idle_due(idle.since, now) { + None => { + gone = Some(index); + break; + } + Some(at) => wake = Some(wake.map_or(at, |wake| wake.min(at))), + } + } + match gone { + Some(index) => Some(Ok(state.remove(index))), + None => wake.map(Err), + } } /// For the device tests: the ring's blocks and free chunks where its lock is free now, else /// None. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn chunks(&self) -> Option<(usize, usize)> { - (self.state.try_lock().ok()).map(|state| (state.blocks.len(), state.free.len())) + (self.state.try_lock().ok()).map(|state| (state.blocks.len(), state.free)) } /// For the device tests: whether the ring's next block waits on an ask of the block-maker @@ -317,7 +385,7 @@ impl Ring { device.free_memory(block.memory, None); } } - state.free.clear(); + state.free = 0; self.nil.take(); self.zero.take(); freed @@ -328,9 +396,8 @@ impl State { /// Keeps a block made at `address`, mapped at `host`, whose writes lie at multiples of /// `align`: its chunks but the first are free, and the first is the caller's /// ([`chunk_starts`]). - fn add(&mut self, block: RingBlock, address: u64, host: Mapping, align: u64) -> Chunk { - let buffer = block.buffer; - self.blocks.push(block); + fn add(&mut self, made: Made, address: u64, host: Mapping, align: u64) -> Chunk { + let buffer = made.buffer; let (skew, chunks) = chunk_starts(address, align); let chunk = |index: u64| { let offset = skew + index * CHUNK; @@ -342,9 +409,87 @@ impl State { offset, } }; - self.free.extend((1..chunks).rev().map(chunk)); + let free: Vec = (1..chunks).rev().map(chunk).collect(); + self.free += free.len(); + self.blocks.push(RingBlock { + buffer, + memory: made.memory, + free, + chunks: chunks as usize, + idle: None, + }); chunk(0) } + + /// A free chunk of the first block that has one, taken. + fn take(&mut self) -> Option { + let block = self + .blocks + .iter_mut() + .find(|block| !block.free.is_empty())?; + let chunk = block.free.pop()?; + block.idle = None; + self.free -= 1; + self.taken(); + Some(chunk) + } + + /// A take, which leaves the ring the chunks it has free: the low of every idle block. + fn taken(&mut self) { + let free = self.free; + for idle in self + .blocks + .iter_mut() + .filter_map(|block| block.idle.as_mut()) + { + idle.low = idle.low.min(free); + } + } + + /// Takes back `chunks` at `now`, one give-back: each block that then has every chunk free is + /// idle from `now`, with the chunks the ring has free once all are back. True where such a + /// block is past the first. + fn give(&mut self, chunks: Vec, now: u64) -> bool { + let mut idle = Vec::new(); + for chunk in chunks { + let Some(index) = (self.blocks.iter()).position(|block| block.buffer == chunk.buffer) + else { + continue; + }; + self.free += 1; + let block = &mut self.blocks[index]; + block.free.push(chunk); + if block.free.len() == block.chunks { + idle.push(index); + } + } + let free = self.free; + for &index in &idle { + self.blocks[index].idle = Some(Idle { + since: now, + low: free, + }); + } + idle.iter().any(|&index| index > 0) + } + + /// Takes the block at `index` out, every chunk of it free, for the block-maker thread to free: + /// the ring has its chunks free no longer, so neither has any idle block's low. + fn remove(&mut self, index: usize) -> memory::Loose { + let block = self.blocks.remove(index); + self.free -= block.chunks; + for idle in self + .blocks + .iter_mut() + .filter_map(|block| block.idle.as_mut()) + { + idle.low = idle.low.saturating_sub(block.chunks); + } + memory::Loose::RingBlock { + buffer: block.buffer, + memory: block.memory, + } + } } /// Where the chunks of a block at device address `address` lie, for writes at multiples of @@ -371,7 +516,7 @@ fn waited(core: &Core, since: Option) { /// Makes a ring block: a buffer with every buffer usage on an allocation of the ring type with a /// device address, mapped. Returns it with its device and host addresses. Its allocation is /// counted at [`Site::RingBlock`] on a consumer's thread. -fn make(core: &Core) -> Result<(RingBlock, u64, Mapping), Error> { +fn make(core: &Core) -> Result<(Made, u64, Mapping), Error> { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] core.ring.meet_park(); let device = &core.device; @@ -410,10 +555,10 @@ fn make(core: &Core) -> Result<(RingBlock, u64, Mapping), Error> { } }; core.counters.count(Metric::BlocksMade); - let block = RingBlock { buffer, memory }; + let block = Made { buffer, memory }; match finish(device, &block) { Ok((address, host)) => { - // Kept for the device's life: noted, and never freed before its teardown. + // Noted; freed by the idle rule (`Ring::due`) or at the teardown. (core.spans).made(block.buffer, address, BLOCK, RangeKind::RingBlock); Ok((block, address, host)) } @@ -430,7 +575,7 @@ fn make(core: &Core) -> Result<(RingBlock, u64, Mapping), Error> { } /// Binds a ring block's memory, reads its address and maps it. -fn finish(device: &ash::Device, block: &RingBlock) -> Result<(u64, Mapping), Error> { +fn finish(device: &ash::Device, block: &Made) -> Result<(u64, Mapping), Error> { // 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"))?; @@ -495,7 +640,7 @@ impl Writes { /// Gives the chunks back once the command buffer retired or never ran. pub(crate) fn give_back(self, core: &Core) { if !self.chunks.is_empty() { - core.ring.give_back(self.chunks); + core.ring.give_back(core, self.chunks); } } }