diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 4a57ee6bf..85d5f5ed1 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -139,14 +139,15 @@ //! //! - **Blocks made ahead** (`memory/ready.rs`). Each pool the encodings and commits place their //! own resources in ([`keep_room`]) and each pool of exportable buffers ([`allocate_exported`]) -//! gets a block made off the program's thread while it grows or is near its next block, and the -//! pool a color texture's host-transfer image places in ([`Memory::host_copy_pool`]) gets its -//! blocks so: each made right after a burst of the device's submissions ended, since a block's +//! gets a block's worth of bytes made off the program's thread while it grows or is near its +//! next block (as many of its blocks as one of [`BLOCK_BYTES`] holds), and the pool a color +//! texture's host-transfer image places in ([`Memory::host_copy_pool`]) gets its blocks so: each +//! made right after a burst of the device's submissions ended, since a block's //! `vkAllocateMemory` holds the device's submissions while it runs on RADV and on NVIDIA's //! driver, then every page of its mapping read once before anything is placed in it, so that no //! host copy's first touch faults on memory whose kernel work waits behind the program's queued //! GPU work. A call that needs room takes the pool's block made ahead, or waits for its making, -//! rather than make a block of its own. +//! started for it where none is under way, rather than make a block of its own. use super::buffer::usage; use super::device::lock; @@ -861,6 +862,9 @@ pub(super) struct Pool { kept_bytes: u64, /// When it last grew: a pooled block added to it while it held another ([`Pool::grew`]). grew: Option, + /// The bytes of the largest block a placement larger than its blocks took within + /// [`KEPT_EMPTY_FOR`] of the last such placement, and when that was ([`Pool::took_large`]). + large: Option<(u64, Instant)>, } #[derive(Debug)] @@ -910,6 +914,7 @@ impl Default for Pool { freed: 0, kept_bytes: 0, grew: None, + large: None, } } } @@ -1255,6 +1260,21 @@ impl Pool { self.grew } + /// A placement larger than its blocks took a pooled block of `bytes` at `now` + /// ([`pooled_block_bytes`]): blocks of that size are made ahead for it while such placements + /// are recent (`memory/ready.rs`). + fn took_large(&mut self, bytes: u64, now: Instant) { + let recent = self.large(now).unwrap_or(0); + self.large = Some((bytes.max(recent), now)); + } + + /// The bytes of the largest block a placement larger than its blocks took within + /// [`KEPT_EMPTY_FOR`] before `now`, of the placements since one came after a longer gap. + fn large(&self, now: Instant) -> Option { + let (bytes, at) = self.large?; + (now.saturating_duration_since(at) < KEPT_EMPTY_FOR).then_some(bytes) + } + /// Whether it holds a pooled block. fn holds_pooled(&self) -> bool { self.blocks.iter().flatten().any(|block| !block.dedicated) @@ -1988,9 +2008,13 @@ pub(super) struct Memory { /// The pool a color texture's host-transfer image places in, once asked: `Some(None)` where /// the device copies no color texture on the host ([`Memory::host_copy_pool`]). host_copy_pool: Option>, - /// The blocks being made ahead, or made and not yet in their pool, one a pool at most: each - /// enters its pool at a call that needs room there (`memory/ready.rs`). + /// The blocks being made ahead, or made and not yet in their pool, one readying a pool at + /// most: each block enters its pool at a call that needs room there (`memory/ready.rs`). readying: Vec, + /// What a making ahead is made through, from the first [`keep_room`] on: the device's + /// functions, its queues' quiet and its counts. A placement that starts a making it waits for + /// ([`place`]) takes them here. + ahead_with: Option, /// Of that pool, its blocks made ready ahead and added to it, and the blocks a placement in it /// made itself, finding none ready (`WorkCounts`). host_copy_blocks: HostCopyBlocks, @@ -2005,19 +2029,27 @@ pub(super) struct Memory { keeps_none: bool, } +/// What a making ahead is made through ([`Memory::ahead_with`]). +struct AheadWith { + functions: Arc, + quiet: Arc, + counts: Arc, +} + /// The counts of the blocks made ahead (`memory/ready.rs`), and of those made in place in the pools /// blocks are made ahead for ([`Memory::makes_ahead`]), by the kind of pool. #[derive(Clone, Copy, Debug, Default)] pub(super) struct AheadBlocks { /// Blocks of buffers made ahead and added to their pool. pub(super) buffers_ahead: u64, - /// Blocks of buffers a call made itself, finding none made ahead. + /// Blocks of buffers a call made itself, where no making ahead served it. pub(super) buffers_in_place: u64, /// Blocks of images made ahead and added to their pool. pub(super) images_ahead: u64, - /// Blocks of images a call made itself, finding none made ahead. + /// Blocks of images a call made itself, where no making ahead served it. pub(super) images_in_place: u64, - /// Of the blocks made ahead, those a call waited for, their making under way. + /// Of the blocks made ahead, those a call waited for, their making under way or started for + /// it. pub(super) waited_for: u64, /// Of those, the blocks whose making a call's wait cut short in its wait for a burst of /// submissions to end, so that the call waited for the allocation alone. @@ -2031,15 +2063,16 @@ pub(super) struct AheadBlocks { impl AheadBlocks { /// A block of a pool of `holds` was made ahead and added, a call having waited for it where - /// `waited_for`, after its wait for a burst's end ended as `waited` says. - fn made_ahead(&mut self, holds: Holds, waited_for: bool, waited: Waited) { + /// `waited_for`, after its wait for a burst's end ended as `waited` says (`None`: it waited + /// for none, made after another of its wake or for a call already waiting). + fn made_ahead(&mut self, holds: Holds, waited_for: bool, waited: Option) { match holds { Holds::Images => self.images_ahead += 1, _ => self.buffers_ahead += 1, } self.waited_for += u64::from(waited_for); - self.hurried += u64::from(waited == Waited::Asked); - self.past_quiet_wait += u64::from(waited == Waited::Bound); + self.hurried += u64::from(waited == Some(Waited::Asked)); + self.past_quiet_wait += u64::from(waited == Some(Waited::Bound)); } /// A call made a block of a pool of `holds` itself. @@ -2135,6 +2168,7 @@ impl Memory { zero_images: false, host_copy_pool: None, readying: Vec::new(), + ahead_with: None, host_copy_blocks: HostCopyBlocks::default(), ahead: AheadBlocks::default(), next_sweep: Instant::now() + KEPT_SWEEP_EVERY, @@ -2359,10 +2393,11 @@ impl Memory { .filter(|&(at, _)| in_heap(at % count)) .map(|(_, pool)| pool.kept_bytes()) .sum(); - let ahead = (self.readying.iter()) + let ahead: u64 = (self.readying.iter()) .filter(|ready| in_heap(ready.pool().1 as usize)) - .count() as u64; - kept + ahead * self.block_bytes + .map(ready::Readying::outstanding_bytes) + .sum(); + kept + ahead } /// A block of `size` bytes of memory type `type_index` left the heap's live blocks. @@ -2600,23 +2635,124 @@ impl Memory { .collect() } - /// Add the block made ahead for `pool` to it where its making ended (`memory/ready.rs`): - /// whether one was added. A making that failed is let go of. - fn add_ready(&mut self, pool: (Holds, u32)) -> bool { + /// The blocks `pool` keeps made ahead (`memory/ready.rs`), its blocks of `bytes`: one of the + /// bytes of the largest block its placements larger than its blocks took lately + /// ([`Pool::large`]), and as many of `bytes` as the rest of one block of + /// [`Memory::block_bytes`] holds, at least one, so that a pool whose blocks of plain memory + /// are made smaller ([`Memory::plain_block_made`]) keeps the bytes ahead it kept before. + fn ahead_sizes(&mut self, pool: (Holds, u32), bytes: u64) -> (Option, u64) { + let bytes = bytes.max(1); + let large = + (self.pool(pool.0, pool.1).large(Instant::now())).filter(|&large| large > bytes); + let rest = self.block_bytes.saturating_sub(large.unwrap_or(0)); + (large, (rest / bytes).max(1)) + } + + /// Of the blocks `pool`, its blocks of `bytes`, keeps made ahead ([`ahead_sizes`]), those + /// `held` lacks (the bytes of each block made, being made and still to make): the larger + /// first. + /// + /// [`ahead_sizes`]: Self::ahead_sizes + fn lacking(&mut self, pool: (Holds, u32), bytes: u64, held: &[u64]) -> Vec { + let (large, count) = self.ahead_sizes(pool, bytes); + let mut held = held.to_vec(); + let mut lacking = Vec::new(); + if let Some(large) = large { + match held.iter().position(|&size| size >= large) { + Some(at) => { + held.swap_remove(at); + } + None => lacking.push(large), + } + } + let have: u64 = held.iter().sum(); + let more = (count * bytes).saturating_sub(have) / bytes.max(1); + lacking.extend((0..more).map(|_| bytes)); + lacking + } + + /// What a making ahead for `pool` is made through, once [`keep_room`] gave it. + fn making(&self, pool: (Holds, u32)) -> Option { + let with = self.ahead_with.as_ref()?; + Some(ready::Making { + maker: self.maker(), + functions: Arc::clone(&with.functions), + quiet: Arc::clone(&with.quiet), + addressed: pool.0.buffers().then(|| Arc::clone(&with.counts)), + }) + } + + /// Keep `pool`'s blocks made ahead, its blocks of `bytes` (`memory/ready.rs`, + /// [`ahead_sizes`](Self::ahead_sizes)): those it lacks made after the blocks its thread + /// still makes, or on a new thread, once a burst of the device's queue uses ended. + fn keep_ahead(&mut self, pool: (Holds, u32), bytes: u64) { + let held = match self.readying_at(pool) { + Some(at) => self.readying[at].held(), + None => Vec::new(), + }; + let lacking = self.lacking(pool, bytes, &held); + if lacking.is_empty() { + return; + } + let Some(making) = self.making(pool) else { + return; + }; + match self.readying_at(pool) { + Some(at) => { + let _ = self.readying[at].queue(making, &lacking, false); + } + None => { + let started = ready::Readying::start(making, pool, lacking.into(), None); + self.readying.extend(started.map(|(readying, _)| readying)); + } + } + } + + /// A call's wait for a block of `need` bytes or more made ahead for `pool`, its blocks of + /// `bytes` (`memory/ready.rs`), where none is made: the block being made or still to make, or + /// else one queued first for the call, its thread started where it has none, the rest of the + /// pool's blocks kept ahead after it. `None` where the pool host copies place in reads a + /// block's pages now, as a page's first touch may wait behind the program's GPU work, before + /// [`keep_room`] gave the makings what they are made through, or where no thread starts. + fn wait_for(&mut self, pool: (Holds, u32), bytes: u64, need: u64) -> Option { + let making = self.making(pool)?; + let host_copies = self.host_copy_pool == Some(Some(pool)); + match self.readying_at(pool) { + Some(at) => { + let readying = &mut self.readying[at]; + let waiter = readying.waiter(need, host_copies)?; + match readying.will_hold(need) || readying.queue(making, &[need], true) { + true => Some(waiter), + false => None, + } + } + None => { + let rest = self.lacking(pool, bytes, &[need]); + let sizes = std::iter::once(need).chain(rest).collect(); + let (readying, waiter) = ready::Readying::start(making, pool, sizes, Some(need))?; + self.readying.push(readying); + waiter + } + } + } + + /// Add the smallest block of `need` bytes or more made ahead for `pool` and not yet added to + /// it (`memory/ready.rs`): whether one was added. A readying whose thread ended and that holds + /// no block more goes. + fn add_ready(&mut self, pool: (Holds, u32), need: u64) -> bool { let Some(at) = self.readying_at(pool) else { return false; }; - if !self.readying[at].finished() { - return false; + let made = self.readying[at].take_block(need); + if self.readying[at].finished() && !self.readying[at].has_block() { + self.readying.swap_remove(at).end(); } - let readying = self.readying.swap_remove(at); - let waited_for = readying.waited_for(); - let Some(made) = readying.take() else { + let Some(made) = made else { return false; }; let bytes = made.block.size; self.add_block(pool, made.block, bytes, false, 0); - self.ahead.made_ahead(pool.0, waited_for, made.waited); + self.ahead.made_ahead(pool.0, made.waited_for, made.waited); if self.host_copy_pool == Some(Some(pool)) { self.host_copy_blocks.readied += 1; } @@ -2827,6 +2963,16 @@ impl Memory { .collect() } + /// The bytes of the blocks made ahead for the pools of `holds` and not yet added, and of those + /// still to make (`memory/ready.rs`), for the crate's device tests. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(super) fn ahead_bytes(&self, holds: Holds) -> u64 { + (self.readying.iter()) + .filter(|ready| ready.pool().0 == holds) + .map(ready::Readying::outstanding_bytes) + .sum() + } + /// The bytes a pooled block of plain memory is made of now ([`Memory::plain_block_made`]), for /// the crate's tests. #[cfg(test)] @@ -3118,10 +3264,10 @@ impl Memory { at += 1; continue; } - if let Some(made) = self.readying.swap_remove(at).take() { + for block in self.readying.swap_remove(at).stop() { self.ahead.unused += 1; // SAFETY: nothing was placed in the block, and no command reads it. - drop(unsafe { self.let_go(device, made.block, FreeCause::KeptStale, None) }); + drop(unsafe { self.let_go(device, block, FreeCause::KeptStale, None) }); } } } @@ -3412,7 +3558,7 @@ impl Memory { let mut making = Vec::new(); for readying in self.readying.drain(..) { match readying.finished() { - true => ready.extend(readying.take().map(|made| made.block)), + true => ready.extend(readying.stop()), false => making.push(readying), } } @@ -3435,7 +3581,7 @@ impl Memory { // The blocks being made ahead, those whose making began waited for: nothing is placed in // them. let readied: Vec = (self.readying.drain(..)) - .filter_map(ready::Readying::stop) + .flat_map(ready::Readying::stop) .collect(); let blocks: Vec = (self.pools.iter_mut()) .flat_map(|pool| pool.drain()) @@ -4441,16 +4587,32 @@ fn place( return Ok(guard.mark_overflowed(placement, overflowing)); } } - // A pooled placement without room: the block made ahead for the pool, rather than - // one of the placement's own (`memory/ready.rs`), waited for where its making is - // under way, but in the pool host copies place in, whose making may itself wait - // behind the program's GPU work, which no making waits for. - if !dedicated && take_ready(memory, guard, pool) { - let mut guard = lock(memory); - if let Some(placement) = - guard.place_pooled(device, pool, (size, align), addressed, class)? - { - return Ok(guard.mark_overflowed(placement, overflowing)); + // A pooled placement without room: a block made ahead for the pool of its block's + // size or more, rather than one of the placement's own (`memory/ready.rs`), waited for + // where none is made: the one being made or still to make, or else one the ready + // thread makes first for it. A placement larger than the pool's blocks, which takes a + // block of its own size ([`pooled_block_bytes`]), has blocks of that size kept ahead + // while such placements are recent. Made here: one of the pool host copies place in + // while that pool's making reads a block's pages, which may wait behind the + // program's GPU work, which no placement waits for. + if !dedicated { + let large = block_size > guard.pooled_bytes(pool); + if large { + guard + .pool(pool.0, pool.1) + .took_large(block_size, Instant::now()); + } + if guard.makes_ahead(pool) && take_ready(memory, guard, pool, block_size) { + let mut guard = lock(memory); + if large { + let bytes = guard.pooled_bytes(pool); + guard.keep_ahead(pool, bytes); + } + if let Some(placement) = + guard.place_pooled(device, pool, (size, align), addressed, class)? + { + return Ok(guard.mark_overflowed(placement, overflowing)); + } } } } @@ -4515,7 +4677,7 @@ fn make_room(memory: &Mutex, device: &ash::Device, type_index: u32) -> b pub(super) fn keep_none(memory: &Mutex, device: &ash::Device) { let making = lock(memory).keep_none(device); for readying in making { - if let Some(block) = readying.stop() { + for block in readying.stop() { // SAFETY: nothing is placed in a block made ahead, and no command reads it. drop(unsafe { lock(memory).let_go(device, block, FreeCause::Teardown, None) }); } @@ -4526,16 +4688,18 @@ pub(super) fn keep_none(memory: &Mutex, device: &ash::Device) { /// commits place their own resources in ([`Memory::kept`]), and start making a block ahead for /// each such pool that grows (`memory/ready.rs`). The device's creation calls, which may wait, /// keep it, so that an encoding or a commit, which must wait for no other process's GPU work, -/// finds a block with room rather than making one. A pool without that room takes its block made -/// ahead, waited for where its making is under way, or else a block made here, with `memory`'s -/// lock released; a block of buffers gets its buffer of addresses (counted in `counts`) where -/// blocks carry one. A block that fails to be made, or a pool the query fails for, is left to the -/// placement that needs it. A pool that grew within [`KEPT_EMPTY_FOR`] and lacks room for a whole -/// block, holding no block made ahead, gets one started, through `functions`, made once a burst -/// of `quiet`'s queue uses ended; so does each pool of exportable buffers that grew so +/// finds a block with room rather than making one. A pool without that room takes a block made +/// ahead, or waits for one with `memory`'s lock released: the one being made or still to make, or +/// else one the pool's thread makes first for the call, started where it has none +/// (`memory/ready.rs`); only where that making fails or no thread starts is the block made here. A block of buffers gets +/// its buffer of addresses (counted in `counts`) where blocks carry one. A block that fails to be +/// made, or a pool the query fails for, is left to the placement that needs it. A pool that grew +/// within [`KEPT_EMPTY_FOR`] and lacks room for a whole block gets the blocks it lacks of a block's +/// worth made ahead ([`Memory::keep_ahead`]), through `functions`, made once a burst of `quiet`'s +/// queue uses ended; so does each pool of exportable buffers that grew so /// (`allocate_exported`), whose room is otherwise left to its placements, which are the creation /// calls themselves. The pool host copies place in, where `copies` says the device -/// copies color textures on the host, gets its block made ahead once it lacks room for half a +/// copies color textures on the host, gets its blocks made ahead once it lacks room for half a /// block; its making is never waited for here, as its pages' reads may wait behind the program's /// GPU work, and its block is never added here: the placement there that finds no room adds it /// ([`place`]), so that the pool's blocks change only at its placements, whenever the making @@ -4559,7 +4723,12 @@ pub(super) fn keep_room( (functions, quiet): (&Arc, &Arc), (copies, own, pages): (impl FnOnce() -> bool, Holds, bool), ) { - ready_ahead(memory, device, (functions, quiet), copies); + lock(memory).ahead_with.get_or_insert_with(|| AheadWith { + functions: Arc::clone(functions), + quiet: Arc::clone(quiet), + counts: Arc::clone(counts), + }); + ready_ahead(memory, device, copies); let (kept, maker) = { let mut memory = lock(memory); memory.sweep_stale(device, Instant::now()); @@ -4577,45 +4746,8 @@ pub(super) fn keep_room( 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(bytes / 2) { - break; - } - // The host copies' block made ahead joins its pool at the placement that needs it - // (`place`), never here, whenever its making ended: its pool's blocks change only at - // its placements. - let host_copies = guard.host_copy_pool == Some(Some(pool)); - if host_copies && guard.readying_at(pool).is_some() { - break; - } - if guard.add_ready(pool) { - break; - } - if guard.readying_at(pool).is_some() { - // Another call's making to wait for. - if take_ready(memory, guard, pool) { - break; - } - continue; - } - drop(guard); - if !crate::allocations::room_ahead(device.handle()) { - break; - } - let Ok(block) = maker.make(device, pool, bytes, addressed) else { - break; - }; - let mut guard = lock(memory); - guard.add_block(pool, block, bytes, false, 0); - guard.ahead.made_in_place(pool.0); - #[cfg(test)] - { - *guard.in_place_bytes.entry(bytes).or_default() += 1; - } - break; - } - ready_if_growing(&mut lock(memory), pool, counts, (functions, quiet)); + keep_pool_room(memory, device, (&maker, addressed), (pool, bytes)); + ready_if_growing(&mut lock(memory), pool); } // The pools of exportable buffers, which the creation calls themselves place in // (`allocate_exported`): a block made ahead once one grew, which the placement that finds no @@ -4623,7 +4755,49 @@ pub(super) fn keep_room( // block made here, which that placement would make as soon. let mut guard = lock(memory); for pool in guard.exported_growing() { - ready_if_growing(&mut guard, pool, counts, (functions, quiet)); + ready_if_growing(&mut guard, pool); + } +} + +/// Keep room for half a block of `bytes` in `pool` ([`keep_room`]): a block made ahead, or one +/// the call waits for with `memory`'s lock released, or, where no making serves it, one made +/// here by `maker`, with a buffer of addresses counted in `addressed` where blocks carry one. +fn keep_pool_room( + memory: &Mutex, + device: &ash::Device, + (maker, addressed): (&BlockMaker, Option<&Counters>), + (pool, bytes): ((Holds, u32), u64), +) { + let mut guard = lock(memory); + if guard.pool(pool.0, pool.1).has_room(bytes / 2) { + return; + } + // The host copies' block made ahead joins its pool at the placement that needs it + // (`place`), never here, whenever its making ended: its pool's blocks change only at its + // placements. + let host_copies = guard.host_copy_pool == Some(Some(pool)); + if host_copies && guard.readying_at(pool).is_some() { + return; + } + // No making for the pool and no room ahead within the device's allocations: none. + if guard.readying_at(pool).is_none() && !crate::allocations::room_ahead(device.handle()) { + return; + } + // A block made ahead, or one the call waits for: the one being made or still to make, or + // else one the ready thread makes first for it (`memory/ready.rs`). + if take_ready(memory, guard, pool, bytes) { + return; + } + // No making serves the call (its making failed, or no thread started): made here. + let Ok(block) = maker.make(device, pool, bytes, addressed) else { + return; + }; + let mut guard = lock(memory); + guard.add_block(pool, block, bytes, false, 0); + guard.ahead.made_in_place(pool.0); + #[cfg(test)] + { + *guard.in_place_bytes.entry(bytes).or_default() += 1; } } @@ -4634,83 +4808,55 @@ pub(super) fn ahead_room(bytes: u64) -> u64 { bytes - bytes / 4 } -/// Start making a block ahead for `pool` (`memory/ready.rs`), through `functions`, made once a -/// burst of `quiet`'s queue uses ended, with a buffer of addresses counted in `counts` where its -/// blocks carry one, where the pool holds no block made ahead and grew within [`KEPT_EMPTY_FOR`] -/// lacking room for a whole block, or, grown or not, is near its next block -/// ([`Pool::near_next`]). -fn ready_if_growing( - memory: &mut Memory, - pool: (Holds, u32), - counts: &Arc, - (functions, quiet): (&Arc, &Arc), -) { +/// Keep `pool`'s blocks made ahead (`memory/ready.rs`, [`Memory::keep_ahead`]), made once a burst +/// of the device's queue uses ended, with a buffer of addresses where its blocks carry one, where +/// the pool grew within [`KEPT_EMPTY_FOR`] lacking room for a whole block, or, grown or not, is +/// near its next block ([`Pool::near_next`]). +fn ready_if_growing(memory: &mut Memory, pool: (Holds, u32)) { 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); let near = pool_of.near_next(bytes); - if !(grew || near) || pool_of.has_room(bytes) || ahead { + if !(grew || near) || pool_of.has_room(bytes) { return; } - let addressed = pool.0.buffers().then(|| Arc::clone(counts)); - let started = ready::Readying::start( - memory.maker(), - Arc::clone(functions), - Arc::clone(quiet), - addressed, - (pool, bytes), - ); - memory.readying.extend(started); + memory.keep_ahead(pool, bytes); } -/// Start making a block ahead for the pool host copies place in (`memory/ready.rs`, +/// Keep blocks made ahead for the pool host copies place in (`memory/ready.rs`, /// [`Memory::host_copy_pool`], where `copies`, asked with `memory`'s lock released until the pool -/// was found, says the device copies color textures on the host), through `functions`, made once -/// a burst of `quiet`'s queue uses ended, where it lacks room for half a block and holds no block -/// made ahead. -fn ready_ahead( - memory: &Mutex, - device: &ash::Device, - (functions, quiet): (&Arc, &Arc), - copies: impl FnOnce() -> bool, -) { +/// was found, says the device copies color textures on the host; [`Memory::keep_ahead`]), made +/// once a burst of the device's queue uses ended, where it lacks room for half a block. +fn ready_ahead(memory: &Mutex, device: &ash::Device, copies: impl FnOnce() -> bool) { let copies = lock(memory).host_copy_pool.is_none() && copies(); let mut memory = lock(memory); let Some(pool) = memory.host_copy_pool(device, copies) else { return; }; let bytes = memory.pooled_bytes(pool); - if memory.readying_at(pool).is_some() || memory.pool(pool.0, pool.1).has_room(bytes / 2) { + if memory.pool(pool.0, pool.1).has_room(bytes / 2) { return; } - let maker = memory.maker(); - let functions = Arc::clone(functions); - let started = ready::Readying::start(maker, functions, Arc::clone(quiet), None, (pool, bytes)); - memory.readying.extend(started); + memory.keep_ahead(pool, bytes); } -/// Add the block made ahead for `pool` to it, `guard` held on `memory` (`memory/ready.rs`): at -/// once where its making ended; where it is under way, once it ends, waited for with the lock -/// released, but in the pool host copies place in. Whether one may have been added, so that the -/// caller looks for room again; the lock is released as it returns. +/// Add a block of `need` bytes or more made ahead for `pool` to it, `guard` held on `memory` +/// (`memory/ready.rs`): at once where one is made; else once one is, waited for with the lock +/// released ([`Memory::wait_for`]). Whether one was added; the lock is released as it returns. fn take_ready( memory: &Mutex, mut guard: MutexGuard<'_, Memory>, pool: (Holds, u32), + need: u64, ) -> bool { - if guard.add_ready(pool) { + if guard.add_ready(pool, need) { return true; } - let Some(at) = guard.readying_at(pool) else { + let bytes = guard.pooled_bytes(pool); + let Some(waiter) = guard.wait_for(pool, bytes, need) else { return false; }; - if guard.host_copy_pool == Some(Some(pool)) { - return false; - } - let waiter = guard.readying[at].waiter(); drop(guard); waiter.wait(); - lock(memory).add_ready(pool); - true + lock(memory).add_ready(pool, need) } diff --git a/crates/metal2vulkan-runtime/src/memory/ready.rs b/crates/metal2vulkan-runtime/src/memory/ready.rs index 563e6be43..5f581c994 100644 --- a/crates/metal2vulkan-runtime/src/memory/ready.rs +++ b/crates/metal2vulkan-runtime/src/memory/ready.rs @@ -2,8 +2,9 @@ //! for each pool the runtime's encodings and commits place their own resources in //! (`memory::keep_room`) and each pool of exportable buffers (`memory::allocate_exported`) while //! it grows, and for the pool a color texture's host-transfer image places in -//! (`texture/host_copy.rs`). Each is allocated right after a burst of the device's -//! submissions returned, then every page of its mapping is read once by the host. +//! (`texture/host_copy.rs`). A pool's are allocated right after a burst of the device's +//! submissions returned, one after another, and every page of each one's mapping is read once by +//! the host. //! //! **Why right after a burst.** A block's `vkAllocateMemory` holds the device's submissions //! while it runs, on whichever thread it runs. On RADV (a Radeon 780M, kernel 7.3.1) the kernel @@ -14,6 +15,8 @@ //! submission until it returns (`memory.rs`). So a making waits for a burst of the device's queue //! uses to end (`device/queue_quiet.rs`), at most [`QUIET_MOST`], and runs in the gap before the //! next: a program that presents at 60 Hz leaves 16.7 ms a frame less its frame's submissions. +//! The blocks of one wake are made one `vkAllocateMemory` each, so a submission waits for one +//! block's making at most, however many blocks the wake makes. //! //! **Why the pages are read.** A host copy (`replace_region`, `get_bytes`) reads and writes //! through the block's mapping, which the driver's copies share with the runtime's own @@ -38,44 +41,62 @@ //! that its first growth, and the first after a pause, finds one made too, where a guest's //! scroll on a Radeon 780M made its buffers' pool's first growth in place, on the guest's //! thread (`tests::reclaim_submit_bench`'s scroll arm: of each phase's 8 blocks, the first was -//! made in place in three runs out of three, quiet and fragmented, and none is now). Such a -//! pool keeps that block at rest for as long as it stays near its next one: one block at most a -//! pool, none for a pool with room for three quarters of a block. And for the -//! host copies' pool once that lacks room for half a block, the first by the device's first -//! creation call, before the program queued work. A pool of exportable buffers, which the -//! creation calls themselves place in, gets its block started the same way once it grew or is -//! near its next block, so that the creation call that finds no room there takes a block made -//! ahead rather than make one on the program's thread (on a Radeon 780M a creation call that -//! made such a 64 MiB block itself took 10.0 to 15.0 ms in three of four phases of +//! made in place in three runs out of three, quiet and fragmented, and none is now). A pool +//! keeps a block's worth of bytes ahead: as many of its blocks as one block of +//! `memory::BLOCK_BYTES` holds (one of 64 MiB; four where its blocks of plain memory are made of +//! 16 MiB after a slow making, `Memory::plain_block_made`); and, while its placements larger +//! than its blocks are recent (the last within `KEPT_EMPTY_FOR`), each of which takes a block of +//! its own size (`memory::pooled_block_bytes`), one block of the largest such size, its own +//! blocks filling the rest of the block's worth. They are made one after another once a burst +//! ended; those it lacks are queued after the blocks its thread still makes, or made on a new +//! thread where that ended. So each making stays as short as its block, and the pool's growth +//! still finds its blocks made: with one block of 16 MiB ahead at a time, a guest's scroll on a +//! Radeon 780M whose blocks were made so made 82 to 114 blocks of images on its own threads and +//! waited for 110 to 159 of those made ahead. It keeps them for as long as it stays near its +//! next block; none for a pool with room for three quarters of a block. And for the host +//! copies' pool once that lacks room for half a block, the first by the device's first creation +//! call, before the program queued work. A pool of exportable buffers, which the creation calls +//! themselves place in, gets its blocks started the same way once it grew or is near its next +//! block, so that the creation call that finds no room there takes a block made ahead rather +//! than make one on the program's thread (on a Radeon 780M a creation call that made such a +//! 64 MiB block itself took 10.0 to 15.0 ms in three of four phases of //! `tests::reclaim_submit_bench`, quiet and fragmented, and none took over 0.3 ms with the //! blocks made ahead); none of its blocks is made by a creation call that places nothing there. //! - **Added where room is needed.** A creation call that finds such a pool without room for //! half a block (`memory::keep_room`), and a placement that finds no room (`memory::place`), -//! add the pool's block made ahead once its making ended. Where the making is under way they -//! wait for it, rather than make a second block: no two threads make one for the same pool, and -//! none is made only to be freed. A making still waiting for a burst's end when a call comes -//! allocates at once, so that the call waits for the allocation alone, never for the program's -//! own submissions to pause; a making that reads its pages as a call comes reads no more of -//! them, the pages left unread faulting in at their first touch, as a block made in place does. -//! The host copies' pool's block is added by its placements alone, and never waited for, as its -//! making reads pages whose touch may wait behind the program's GPU work: a placement there that -//! finds the making under way makes its own block. Where no block is made ahead, the call makes -//! its own (`WorkCounts::buffer_blocks_made_in_place`, `image_blocks_made_in_place`). A pool's -//! blocks change only at those calls, never as a making here ends. +//! add the pool's smallest block made ahead of the size they need. Where none is made they wait +//! for the one being made or still to make, or else for one the pool's thread makes first for +//! them, the thread started where the pool has none, the rest of its block's worth made after +//! it: no two threads make blocks for the same pool, none is made only to be freed, and a call +//! makes no block of a pool whose blocks are made ahead where a making can serve it. A making +//! still waiting for a burst's end when a call comes allocates at once, so that the call waits +//! for the allocation alone, never for the program's own submissions to pause; while a call +//! waits the thread reads no page, the pages left unread faulting in at their first touch, as a +//! block made in place does. The host copies' pool's blocks are added by its placements alone, +//! and a placement there never waits while its thread reads a block's pages, whose first touch +//! may wait behind the program's GPU work: the call counts itself waiting before it looks, and +//! the thread looks for a waiting call after it says it reads and before each run of reads. A +//! call makes its own block (`WorkCounts::buffer_blocks_made_in_place`, +//! `image_blocks_made_in_place`) only where no making serves it: a placement in the host copies' +//! pool while its thread reads; a call whose making failed, or whose host starts no thread; and +//! a placement before the device's first creation call, which gives the makings the device's +//! functions and queues. A pool's blocks change only at those calls, never as a making here +//! ends. //! - **Within the allocation margin, none.** A making no call waits for yet makes no block while //! the device's allocations are within the margin of its `maxMemoryAllocationCount` the //! runtime's work ahead leaves to the objects (`allocations.rs`'s `Allocations::room_ahead`). -//! - **Bounded.** One making a pool at most, on a thread of its own that ends with the block. -//! While it waits to be added, its bytes count against its heap's budget of kept empty blocks -//! (`Memory::kept_budget`); one whose pool stopped growing for `KEPT_EMPTY_FOR`, the pool -//! having room for three quarters of a block, goes (`Memory::sweep_stale`). The device's teardown stops a -//! making that has not begun, joins every one and frees its block. Its Vulkan calls run in a -//! section of the exit guard (`exit_guard.rs`): once the process exits, no block is made. +//! - **Bounded.** One thread a pool at most, which makes its blocks one after another and ends +//! with the last; the next starts once it ended. The bytes of the blocks made and not yet added, +//! and of those still to make, count against their heap's budget of kept empty blocks +//! (`Memory::kept_budget`); a pool's that stopped growing for `KEPT_EMPTY_FOR`, the pool having +//! room for three quarters of a block, go (`Memory::sweep_stale`). The device's teardown stops +//! a making that has not begun, joins every thread and frees their blocks. Its Vulkan calls run +//! in a section of the exit guard (`exit_guard.rs`): once the process exits, no block is made. //! - **Counted** (`WorkCounts`): the blocks made ahead and added, by kind //! (`buffer_blocks_made_ahead`, `image_blocks_made_ahead`; of them the host copies' pool's, -//! `host_copy_blocks_readied`), those a call waited for (`blocks_ahead_waited_for`; of them -//! those whose wait for a burst's end the call cut short, `blocks_ahead_hurried`), and those -//! whose wait for a burst's end reached [`QUIET_MOST`] (`blocks_ahead_past_quiet_wait`). +//! `host_copy_blocks_readied`), those made while a call waited (`blocks_ahead_waited_for`; of +//! them those whose wait for a burst's end the call cut short, `blocks_ahead_hurried`), and +//! those whose wait for a burst's end reached [`QUIET_MOST`] (`blocks_ahead_past_quiet_wait`). //! - **Not what a suspend evicts.** Where the kernel moves a block out of device memory as the GPU //! suspends and back at the next submission, the mapping's pages go with the move, and the first //! touch after it waits for the moves back (docs/FAST-PATHS.md, known gaps). @@ -86,7 +107,8 @@ use crate::device::lock; use crate::device::queue_quiet::{QueueQuiet, Waited}; use crate::exit_guard; use crate::work_counts::Counters; -use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; @@ -95,7 +117,7 @@ use std::time::{Duration, Instant}; /// host with larger pages reads each of its pages more than once. const PAGE: usize = 4096; -/// The bytes of a block's pages read between two looks at whether a call waits for the block +/// The bytes of a block's pages read between two looks at whether a call waits for a block /// ([`ready`]). const ASK_EVERY: usize = 64 * PAGE; @@ -104,104 +126,207 @@ const ASK_EVERY: usize = 64 * PAGE; /// idle, its making begun at once (`QueueQuiet::wait_after_burst`): three frames at 60 Hz. pub(super) const QUIET_MOST: Duration = Duration::from_millis(50); -/// A making's [`Shared::go`] word: wait for a burst's end, make at once, or make nothing. +/// A thread's [`Shared::go`] word: wait for a burst's end, make at once, or make nothing more. const WAIT: u8 = 0; const NOW: u8 = 1; const STOP: u8 = 2; -/// A block's making under way, or ended and its block not yet added (the module docs). +/// A pool's blocks made ahead: the thread that makes them, and the blocks made and not yet added +/// (the module docs). pub(super) struct Readying { /// The pool it is for. pool: (Holds, u32), - /// When it started. + /// When it was last given blocks to make. started: Instant, - /// What its thread and the calls that wait for it share. + /// What its thread and the calls that wait for its blocks share. shared: Arc, - /// Its thread, which ends once it left its answer in `shared`. - thread: JoinHandle<()>, + /// Its thread, which ends once it has no block left to make; joined as the next one starts or + /// the readying goes. + thread: Option>, } -/// What a making's thread and the calls that wait for it share. +/// What a readying's thread and the calls that wait for its blocks share. struct Shared { - /// What the thread does while it has not begun the making: [`WAIT`], [`NOW`] or [`STOP`]. + /// What the thread does while it has not begun its first block: [`WAIT`], [`NOW`] or + /// [`STOP`]; [`STOP`] also ends it before its next block. go: AtomicU8, - /// A call waited for the making ([`Waiter::wait`]). - waited_for: AtomicBool, - /// Whether the making ended, and its block until a call takes it: `None` where it could not - /// be made, it was stopped, or the process exits. - made: Mutex<(bool, Option)>, - /// The answer was left. - ended: Condvar, + /// The calls waiting for a block ([`Waiter`]), each counted from its making to its drop. + waiting: AtomicUsize, + /// The thread reads a block's pages now ([`ready`]). + reading: AtomicBool, + /// Its blocks made and not yet added, the one being made, those still to make, and whether + /// its thread ended. + state: Mutex, + /// A block was made, or the thread ended. + changed: Condvar, } -/// A block made ahead, and how its wait for a burst's end ended. +/// A readying's blocks ([`Shared::state`]). +struct State { + /// Made and not yet added, in the order made. + made: VecDeque, + /// The bytes of the block being made. + making: Option, + /// The bytes of each block still to make, in turn. + to_make: VecDeque, + /// The thread ended: it had no block left to make, one failed to be made, it was stopped, or + /// the process exits. Nothing is queued on it from then on. + ended: bool, +} + +impl State { + /// Whether a block of `need` bytes or more is made. + fn holds(&self, need: u64) -> bool { + self.made.iter().any(|made| made.block.size >= need) + } + + /// Whether a block of `need` bytes or more is made, being made or still to make. + fn will_hold(&self, need: u64) -> bool { + self.holds(need) + || self.making.is_some_and(|bytes| bytes >= need) + || self.to_make.iter().any(|&bytes| bytes >= need) + } +} + +/// A block made ahead, and how it was made. pub(super) struct Made { pub(super) block: Block, - pub(super) waited: Waited, + /// How the wait for a burst's end before it ended: `None` for a block made after another of + /// the same wake, or on a thread started for a call already waiting, which waits for none. + pub(super) waited: Option, + /// A call waited for a block as it was made. + pub(super) waited_for: bool, } -/// A call's wait for a making under way ([`Readying::waiter`]), with no lock of the memory held. -pub(super) struct Waiter(Arc); +/// A call's wait for a readying's block of `need` bytes or more ([`Readying::waiter`]), with no +/// lock of the memory held: counted among the waiting from its making to its drop, so that the +/// thread reads no page meanwhile. +pub(super) struct Waiter { + shared: Arc, + need: u64, +} impl Waiter { - /// Ask the making to stop waiting for a burst's end, and wait for it to end. + /// A wait on `shared` for a block of `need` bytes or more, counted from now. + fn new(shared: &Arc, need: u64) -> Waiter { + shared.waiting.fetch_add(1, Ordering::SeqCst); + Waiter { + shared: Arc::clone(shared), + need, + } + } + + /// Ask the thread to stop waiting for a burst's end, and wait for a block of the bytes it + /// needs made, or for the thread to end. pub(super) fn wait(self) { - let shared = self.0; - shared.waited_for.store(true, Ordering::Release); + let shared = &self.shared; let _ = shared .go .compare_exchange(WAIT, NOW, Ordering::AcqRel, Ordering::Acquire); - let mut made = lock(&shared.made); - while !made.0 { - made = (shared.ended.wait(made)).unwrap_or_else(PoisonError::into_inner); + let mut state = lock(&shared.state); + while !state.holds(self.need) && !state.ended { + state = (shared.changed.wait(state)).unwrap_or_else(PoisonError::into_inner); } } } +impl Drop for Waiter { + fn drop(&mut self) { + self.shared.waiting.fetch_sub(1, Ordering::SeqCst); + } +} + +/// What a readying's thread makes its blocks with. +pub(super) struct Making { + pub(super) maker: BlockMaker, + pub(super) functions: Arc, + pub(super) quiet: Arc, + /// The counts of buffers of addresses, where the pool's blocks carry one. + pub(super) addressed: Option>, +} + impl Readying { - /// Start making a block of `bytes` for `pool` with `maker` on a thread of its own, through - /// `functions`, once a burst of `quiet`'s uses ended, with a buffer of addresses counted in - /// `addressed` where given: `None` where the host cannot start a thread. + /// Start making blocks of `sizes` bytes for `pool`, one after another, on a thread of its own: + /// once a burst of the device's queue uses ended, or at once for a call that waits for a + /// block of `need` bytes or more, whose wait it gives back. `None` where the host cannot + /// start a thread. pub(super) fn start( - maker: BlockMaker, - functions: Arc, - quiet: Arc, - addressed: Option>, - (pool, bytes): ((Holds, u32), u64), - ) -> Option { - let shared = Arc::new(Shared { - go: AtomicU8::new(WAIT), - waited_for: AtomicBool::new(false), - made: Mutex::new((false, None)), - ended: Condvar::new(), - }); - let builder = std::thread::Builder::new().name("metal2vulkan-ready".into()); - let thread = { - let shared = Arc::clone(&shared); - exit_guard::spawn(builder, move || { - let go = || shared.go.load(Ordering::Acquire); - let waited = quiet.wait_after_burst(QUIET_MOST, || go() != WAIT); - let made = match go() { - STOP => None, - _ => ready( - &maker, - &functions, - addressed.as_deref(), - (pool, bytes), - || go() != WAIT, - ) - .map(|block| Made { block, waited }), - }; - *lock(&shared.made) = (true, made); - shared.ended.notify_all(); - }) + making: Making, + pool: (Holds, u32), + sizes: VecDeque, + need: Option, + ) -> Option<(Readying, Option)> { + let go = match need { + Some(_) => NOW, + None => WAIT, }; - Some(Readying { + let shared = Arc::new(Shared { + go: AtomicU8::new(go), + waiting: AtomicUsize::new(0), + reading: AtomicBool::new(false), + state: Mutex::new(State { + made: VecDeque::new(), + making: None, + to_make: sizes, + ended: false, + }), + changed: Condvar::new(), + }); + // Counted before the thread runs, which so reads none of that block's pages. + let waiter = need.map(|need| Waiter::new(&shared, need)); + let thread = spawn(making, &shared, pool).ok()?; + let readying = Readying { pool, started: Instant::now(), shared, - thread: thread.ok()?, - }) + thread: Some(thread), + }; + Some((readying, waiter)) + } + + /// Make blocks of `sizes` bytes too: after those its thread has still to make (before them + /// where `first`), or, its thread ended, on a new one, which waits for a burst's end unless a + /// call waits for a block. Whether they will be made. + pub(super) fn queue(&mut self, making: Making, sizes: &[u64], first: bool) -> bool { + self.started = Instant::now(); + { + let mut state = lock(&self.shared.state); + if !state.ended { + match first { + true => sizes + .iter() + .rev() + .for_each(|&bytes| state.to_make.push_front(bytes)), + false => state.to_make.extend(sizes), + } + return true; + } + } + if let Some(thread) = self.thread.take() { + drop(thread.join()); + } + let go = match self.shared.waiting.load(Ordering::SeqCst) { + 0 => WAIT, + _ => NOW, + }; + self.shared.go.store(go, Ordering::Release); + { + let mut state = lock(&self.shared.state); + state.to_make = sizes.iter().copied().collect(); + state.ended = false; + } + match spawn(making, &self.shared, self.pool) { + Ok(thread) => { + self.thread = Some(thread); + true + } + Err(_) => { + let mut state = lock(&self.shared.state); + state.to_make.clear(); + state.ended = true; + false + } + } } /// The pool it is for. @@ -209,61 +334,166 @@ impl Readying { self.pool } - /// When it started. + /// When it was last given blocks to make. pub(super) fn started(&self) -> Instant { self.started } - /// Whether its making ended, its block ready or its making failed: [`take`](Self::take) waits - /// for nothing. + /// Whether its thread ended: it makes no block until it is given more. pub(super) fn finished(&self) -> bool { - lock(&self.shared.made).0 + lock(&self.shared.state).ended } - /// Whether a call waited for it ([`Waiter::wait`]). - pub(super) fn waited_for(&self) -> bool { - self.shared.waited_for.load(Ordering::Acquire) + /// Whether it holds a block made and not yet added. + pub(super) fn has_block(&self) -> bool { + !lock(&self.shared.state).made.is_empty() } - /// A wait for its making, to run with no lock of the memory held. - pub(super) fn waiter(&self) -> Waiter { - Waiter(Arc::clone(&self.shared)) + /// Whether a block of `need` bytes or more is made, being made or still to make. + pub(super) fn will_hold(&self, need: u64) -> bool { + lock(&self.shared.state).will_hold(need) } - /// Its block, its thread joined: where its making has not ended, asked first to stop waiting - /// for a burst's end, and waited for. `None` where it could not be made. - pub(super) fn take(self) -> Option { - let _ = self - .shared - .go - .compare_exchange(WAIT, NOW, Ordering::AcqRel, Ordering::Acquire); - drop(self.thread.join()); - lock(&self.shared.made).1.take() + /// The bytes of each of its blocks made and not yet added, being made, and still to make. + pub(super) fn held(&self) -> Vec { + let state = lock(&self.shared.state); + let made = state.made.iter().map(|made| made.block.size); + (made + .chain(state.making) + .chain(state.to_make.iter().copied())) + .collect() } - /// Its block where its making began, its thread joined; a making that has not begun makes - /// none. - pub(super) fn stop(self) -> Option { - let _ = self - .shared - .go - .compare_exchange(WAIT, STOP, Ordering::AcqRel, Ordering::Acquire); - drop(self.thread.join()); - let made = lock(&self.shared.made).1.take(); - made.map(|made| made.block) + /// What it holds against its heap's budget of kept empty blocks: the bytes of [`held`]. + /// + /// [`held`]: Self::held + pub(super) fn outstanding_bytes(&self) -> u64 { + self.held().iter().sum() + } + + /// Its smallest block made and not yet added of `need` bytes or more, taken. + pub(super) fn take_block(&self, need: u64) -> Option { + let mut state = lock(&self.shared.state); + let at = (state.made.iter().enumerate()) + .filter(|(_, made)| made.block.size >= need) + .min_by_key(|(_, made)| made.block.size) + .map(|(at, _)| at)?; + state.made.remove(at) + } + + /// A wait for its block of `need` bytes or more, to run with no lock of the memory held. + /// `None` where `unless_reading` and its thread reads a block's pages now: a page's first + /// touch may wait behind the program's GPU work (the module docs). + pub(super) fn waiter(&self, need: u64, unless_reading: bool) -> Option { + let waiter = Waiter::new(&self.shared, need); + // Counted first: a thread that begins its reads after this sees the wait and reads none, + // and one that began them before is seen here. + match unless_reading && self.shared.reading.load(Ordering::SeqCst) { + true => None, + false => Some(waiter), + } + } + + /// Its thread joined, where it ended (the readying holds no block): nothing is left of it. + pub(super) fn end(mut self) { + if let Some(thread) = self.thread.take() { + drop(thread.join()); + } + } + + /// Its blocks made, its thread asked to make no more and joined: a block whose making began + /// is among them. + pub(super) fn stop(mut self) -> Vec { + self.shared.go.store(STOP, Ordering::Release); + if let Some(thread) = self.thread.take() { + drop(thread.join()); + } + let mut state = lock(&self.shared.state); + state.made.drain(..).map(|made| made.block).collect() } } +/// Start the thread that makes `pool`'s blocks into `shared` (the module docs): it waits for a +/// burst of the device's queue uses to end where its `go` says so, then makes the blocks still to +/// make one after another, those queued meanwhile among them, each made available as it is made, +/// until none is left, [`STOP`], or a block fails to be made. +fn spawn( + making: Making, + shared: &Arc, + pool: (Holds, u32), +) -> std::io::Result> { + let builder = std::thread::Builder::new().name("metal2vulkan-ready".into()); + let shared = Arc::clone(shared); + exit_guard::spawn(builder, move || { + let Making { + maker, + functions, + quiet, + addressed, + } = making; + let go = || shared.go.load(Ordering::Acquire); + let mut waited = match go() { + WAIT => Some(quiet.wait_after_burst(QUIET_MOST, || go() != WAIT)), + _ => None, + }; + let wanted = || shared.waiting.load(Ordering::SeqCst) > 0 || go() == STOP; + loop { + if go() == STOP { + break; + } + let bytes = { + let mut state = lock(&shared.state); + let Some(bytes) = state.to_make.pop_front() else { + // Ended with the queue seen empty, under the same lock as a queuing call. + state.ended = true; + drop(state); + shared.changed.notify_all(); + return; + }; + state.making = Some(bytes); + bytes + }; + let block = ready( + &maker, + &functions, + addressed.as_deref(), + (pool, bytes), + (&shared.reading, &wanted), + ); + let waited_for = shared.waiting.load(Ordering::SeqCst) > 0; + let mut state = lock(&shared.state); + state.making = None; + let Some(block) = block else { + break; + }; + state.made.push_back(Made { + block, + waited: waited.take(), + waited_for, + }); + drop(state); + shared.changed.notify_all(); + } + let mut state = lock(&shared.state); + state.making = None; + state.to_make.clear(); + state.ended = true; + drop(state); + shared.changed.notify_all(); + }) +} + /// Make a block of `bytes` for `pool`, with a buffer of addresses counted in `addressed` where -/// given, and read every page of its mapping (the module docs) until `wanted` says a call waits -/// for the block (or the device's teardown stops the making): that call waits for the allocation -/// alone, and the pages left unread fault in at their first touch, as a block made in place does. +/// given, and read every page of its mapping (the module docs), `reading` set meanwhile, until +/// `wanted` says a call waits for a block (or the device's teardown stops the making): that call +/// waits for the allocation alone, and the pages left unread fault in at their first touch, as a +/// block made in place does. fn ready( maker: &BlockMaker, functions: &Functions, addressed: Option<&Counters>, (pool, bytes): ((Holds, u32), u64), - wanted: impl Fn() -> bool, + (reading, wanted): (&AtomicBool, &dyn Fn() -> bool), ) -> Option { let busy = exit_guard::enter()?; // Ahead of any placement, none within the margin of the device's allocations the runtime's @@ -273,6 +503,9 @@ fn ready( } let block = maker.make(functions.get(), pool, bytes, addressed).ok()?; if let Some(mapped) = block.mapped { + // Set before the first look at `wanted`, which a waiting call counted before it looked at + // this ([`Readying::waiter`]). + reading.store(true, Ordering::SeqCst); let length = usize::try_from(block.size).unwrap_or(usize::MAX); for offset in (0..length).step_by(PAGE) { if offset % ASK_EVERY == 0 && wanted() { @@ -282,6 +515,7 @@ fn ready( // nothing is placed in the block yet, so nothing else reads or writes it. unsafe { std::ptr::read_volatile(mapped.as_ptr().add(offset)) }; } + reading.store(false, Ordering::SeqCst); } drop(busy); Some(block) diff --git a/crates/metal2vulkan-runtime/src/tests/blocks_ahead.rs b/crates/metal2vulkan-runtime/src/tests/blocks_ahead.rs index 95e3a2a6c..80b45059e 100644 --- a/crates/metal2vulkan-runtime/src/tests/blocks_ahead.rs +++ b/crates/metal2vulkan-runtime/src/tests/blocks_ahead.rs @@ -20,7 +20,8 @@ use super::freed_memory::device; use crate::device::queue_quiet::QueueQuiet; -use crate::{Buffer, Device, Error, ResourceOptions, TextureDescriptor, WorkCounts}; +use crate::memory::{Holds, BLOCK_BYTES, MAKING_BOUND, MIN_PLAIN_BLOCK_BYTES}; +use crate::{Buffer, Device, Error, ResourceOptions, Texture, TextureDescriptor, WorkCounts}; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use std::time::{Duration, Instant}; @@ -45,6 +46,18 @@ const MOST: usize = 400; /// The creation calls that place nothing in the host copies' pool once its making ended. const CREATIONS: usize = 20; +/// The side of the small-blocks runs' `RGBA8Unorm` textures: 4 MiB, four to a block of 16 MiB. +const TEXTURE_SIDE: u64 = 1024; + +/// The large-blocks run's textures larger than a block of 16 MiB: 20 MiB, each in a block of +/// 32 MiB ([`LARGE_EVERY`] textures one of them), and how many it makes. +const LARGE_SIDES: (u64, u64) = (2560, 2048); +const LARGE_EVERY: usize = 4; +const LARGE_TEXTURES: usize = 4; + +/// The most textures the small-blocks run makes, well past what `GROWTH` blocks hold. +const MOST_TEXTURES: usize = 64; + /// A scratch directory for a device's shader cache, removed when dropped. struct Scratch(std::path::PathBuf); @@ -75,6 +88,33 @@ fn makings_ended(device: &Device) { } } +/// A device told of a pooled block's making that took four times `memory::MAKING_BOUND`, so that +/// it makes its pooled blocks of plain memory of the least size (`Memory::plain_block_made`). +fn small_blocks_device(scratch: &Scratch) -> Device { + let device = device(&scratch.0); + { + 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); + } + device +} + +/// A `Private` `RGBA8Unorm` texture of `width` by `height` on `device`, sampled and rendered to, +/// made into `held`; then wait for the makings it started. +fn texture(device: &Device, (width, height): (u64, u64), held: &mut Vec) { + assert!( + held.len() < MOST_TEXTURES, + "the pool of images never grew as far" + ); + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, width, height, false); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::private(); + held.push(device.new_texture(&descriptor).unwrap()); + makings_ended(device); +} + /// The blocks the buffers' pool grew by from `before` to `after`, made ahead or in place. fn grown(before: &WorkCounts, after: &WorkCounts) -> u64 { (after.buffer_blocks_made_ahead + after.buffer_blocks_made_in_place) @@ -169,7 +209,7 @@ fn a_growing_pool_of_exportable_buffers_gets_its_new_blocks_made_ahead() { let blocks = |counts: &WorkCounts| counts.pooled_memory_blocks_made - start.pooled_memory_blocks_made; let mut counts = start; - // Its first growth, made in place, as nothing grew before it. + // Its first growth, made for the creation call that needs it, as nothing grew before it. while blocks(&counts) < 1 { counts = make(&mut held).unwrap(); let dedicated = counts.dedicated_memory_blocks_live - start.dedicated_memory_blocks_live; @@ -206,6 +246,103 @@ fn a_growing_pool_of_exportable_buffers_gets_its_new_blocks_made_ahead() { ); } +/// A pool whose blocks of plain memory are made small after a slow making +/// (`Memory::plain_block_made`) keeps as many of them made ahead as one block of +/// `memory::BLOCK_BYTES` holds, the bytes it kept ahead before they were made small, and no +/// creation call makes a block of the pool itself while one can be made ahead: where none is +/// made or under way, the call starts the pool's making and waits for its first block, the pool's +/// first block among them. With one small block ahead at a time, a guest's creation calls on a +/// Radeon 780M whose blocks were made of 16 MiB made 82 to 114 blocks of images themselves. +#[test] +fn a_pool_of_small_blocks_keeps_a_block_s_bytes_ahead_and_no_creation_call_makes_one() { + let scratch = Scratch::new("small-blocks"); + let device = small_blocks_device(&scratch); + let start = device.work_counts(); + let blocks = |counts: &WorkCounts| { + (counts.image_blocks_made_ahead + counts.image_blocks_made_in_place) + - (start.image_blocks_made_ahead + start.image_blocks_made_in_place) + }; + let mut held: Vec = Vec::new(); + let (mut counts, mut most_ahead) = (start, 0); + // One texture at a time, every making it started ended before the next: what this holds is + // where each block is made and what is kept ahead, not how soon a making ends. + while blocks(&counts) < GROWTH { + texture(&device, (TEXTURE_SIDE, TEXTURE_SIDE), &mut held); + counts = device.work_counts(); + let ahead = crate::device::lock(&device.shared().memory).ahead_bytes(Holds::Images); + most_ahead = most_ahead.max(ahead); + } + let in_place = counts.image_blocks_made_in_place - start.image_blocks_made_in_place; + let ahead = counts.image_blocks_made_ahead - start.image_blocks_made_ahead; + println!( + "BLOCKS-AHEAD {}: {} textures of 4 MiB in blocks of {} MiB; of the images' pool's {} \ + blocks, {ahead} made ahead, {in_place} in place, {} waited for; most kept ahead {} MiB", + device.name(), + held.len(), + MIN_PLAIN_BLOCK_BYTES >> 20, + blocks(&counts), + counts.blocks_ahead_waited_for - start.blocks_ahead_waited_for, + most_ahead >> 20, + ); + assert_eq!(in_place, 0, "a creation call made a block of images itself"); + assert_eq!( + most_ahead, BLOCK_BYTES, + "the pool kept {most_ahead} bytes ahead, not a block's worth" + ); +} + +/// A pool of small blocks whose placements larger than its blocks, each taking a block of its +/// own size (`memory::pooled_block_bytes`), are recent keeps a block of that size made ahead +/// too: the first such placement waits for the ready thread's making of its block, and each +/// later one finds its block made; no creation call makes one itself. +#[test] +fn placements_past_a_pool_s_small_blocks_find_a_block_of_their_size_made_ahead() { + let scratch = Scratch::new("large-blocks"); + let device = small_blocks_device(&scratch); + let start = device.work_counts(); + let mut held: Vec = Vec::new(); + let mut first = None; + for at in 0..LARGE_EVERY * LARGE_TEXTURES { + let large = at % LARGE_EVERY == LARGE_EVERY - 1; + let sides = match large { + true => LARGE_SIDES, + false => (TEXTURE_SIDE, TEXTURE_SIDE), + }; + texture(&device, sides, &mut held); + if large && first.is_none() { + first = Some(device.work_counts()); + } + } + let (first, counts) = (first.unwrap(), device.work_counts()); + let in_place = counts.image_blocks_made_in_place - start.image_blocks_made_in_place; + let waited_after = counts.blocks_ahead_waited_for - first.blocks_ahead_waited_for; + let sizes = crate::device::lock(&device.shared().memory).pooled_block_sizes(Holds::Images); + println!( + "BLOCKS-AHEAD {}: {} textures, one of 20 MiB every {LARGE_EVERY}, in blocks of {} MiB; \ + blocks of images made ahead {}, in place {in_place}, waited for {} (after the first \ + 20 MiB texture {waited_after}); the pool's blocks {:?} MiB", + device.name(), + held.len(), + MIN_PLAIN_BLOCK_BYTES >> 20, + counts.image_blocks_made_ahead - start.image_blocks_made_ahead, + counts.blocks_ahead_waited_for - start.blocks_ahead_waited_for, + sizes.iter().map(|size| size >> 20).collect::>(), + ); + assert_eq!(in_place, 0, "a creation call made a block of images itself"); + assert_eq!( + sizes + .iter() + .filter(|&&size| size == 2 * MIN_PLAIN_BLOCK_BYTES) + .count(), + LARGE_TEXTURES, + "the 20 MiB textures did not each take a block of 32 MiB" + ); + assert_eq!( + waited_after, 0, + "a 20 MiB texture after the first waited for its block's making" + ); +} + /// A use of the device's queues held open while it lives (`device/queue_quiet.rs`): a making's /// wait for a burst's end sees a use under way throughout, so no pause ends it. struct InUse<'a>(&'a QueueQuiet); @@ -243,8 +380,8 @@ fn a_creation_that_needs_a_block_whose_making_waits_for_quiet_waits_for_its_allo held.push(buffer.unwrap()); made.elapsed() }; - // The buffers' pool's first growth, made in place; the next creation starts its next block's - // making, which waits for a pause the held use never leaves. + // The buffers' pool's first growth, made for the creation call that needs it; the next + // creation starts its next block's making, which waits for a pause the held use never leaves. new_buffer(&mut held); let start = device.work_counts(); while grown(&start, &device.work_counts()) == 0 { diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 634079042..6ec422772 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -5045,11 +5045,14 @@ pub struct WorkCounts { /// mapping read once by the host, then added to the pool by the first placement there that /// found no room, so that no host copy faults on memory whose kernel work waits behind the /// program's queued GPU work (`memory/ready.rs`; on RADV after runtime suspend, a new - /// block's clear). None on a device that copies no color texture on the host. + /// block's clear). A block whose making a placement started and waited for, finding none made + /// or under way, is among them with none of its pages read, as a block made in place. None + /// on a device that copies no color texture on the host. pub host_copy_blocks_readied: u64, /// The blocks of that pool a placement made itself, finding no room and no block made ready - /// (none held, or its making still under way): their pages untouched, a host copy's first - /// touch there may wait for the memory's kernel work (`memory/ready.rs`). + /// while its thread read a block's pages (or its making failed, or no thread started): their + /// pages untouched, a host copy's first touch there may wait for the memory's kernel work + /// (`memory/ready.rs`). pub host_copy_blocks_made_in_place: u64, /// Of `pooled_memory_blocks_made`, the blocks of buffers made ahead off the program's thread, /// each right after a burst of the device's submissions ended, and added to their pool where @@ -5058,9 +5061,10 @@ pub struct WorkCounts { /// such a pool grows (`memory/ready.rs`). A block's `vkAllocateMemory` holds the device's /// submissions while it runs on RADV and on NVIDIA's driver, so it is made between them. pub buffer_blocks_made_ahead: u64, - /// The blocks of buffers of those pools a call made itself, finding none made ahead: a - /// creation call that found its pool without room for half a block, or a placement that - /// found no room (`memory/ready.rs`). + /// The blocks of buffers of those pools a call made itself, where no making ahead served it: + /// its making failed or its host started no thread, or the placement came before the + /// device's first creation call (`memory/ready.rs`). Elsewhere a call that finds no block made + /// ahead of the size it needs waits for one (`blocks_ahead_waited_for`). pub buffer_blocks_made_in_place: u64, /// The blocks the runtime's own buffers and the program's lie in (`memory.rs`'s /// `Holds::FdBuffers`) made so far, pooled or dedicated, allocated exportable as an opaque @@ -5112,9 +5116,10 @@ pub struct WorkCounts { /// As `buffer_blocks_made_in_place`, of images, those of the pool host copies place in among /// them (`host_copy_blocks_made_in_place`). pub image_blocks_made_in_place: u64, - /// Of the blocks made ahead, those a call needed while their making was under way, and - /// waited for, rather than make a second block (`memory/ready.rs`): never in the pool host - /// copies place in, whose making is not waited for. + /// Of the blocks made ahead, those made while a call that found none of the size it needed + /// waited, rather than make a block itself (`memory/ready.rs`): the block being made or still + /// to make, or one the pool's thread made first for the call. In the pool host copies place + /// in, never while its thread reads a block's pages. pub blocks_ahead_waited_for: u64, /// Of those, the blocks whose making was still waiting for a burst of the device's /// submissions to end as the call came: the call's wait made it allocate at once, so that the diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 830f29c21..355e5ec9a 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -989,12 +989,15 @@ driver's. Each is open work. its own, with 3 to 5 commits waiting 1 ms or more (longest 10.9 to 19.6 ms): its blocks' `vkAllocateMemory` holds every submission. A pool that grew, and one near its next block (it holds a pooled block and lacks room for three quarters of one, its first growth among them), gets - its next block made ahead (`memory/ready.rs`; the pools of exportable buffers, which hold the - pictures, among them), right after a burst of the device's submissions ended, and a creation - call that needs it while its making still waits for that end makes it at once and waits for it, - as for a block made in place. A pool near its next block keeps that block at rest for as long as - it stays so: one block a pool at most (64 MiB, or a plain pool's smaller block), counted against - the kept empty blocks' budget. Metal's command buffers wait for no allocation. Not announced. + a block's worth of bytes made ahead (`memory/ready.rs`; the pools of exportable buffers, which + hold the pictures, among them): as many of its blocks as one 64 MiB block holds, and while its + placements larger than a plain pool's smaller blocks are recent, one block of their size among + them, one `vkAllocateMemory` each, right after a burst of the device's submissions ended. A + creation call that needs one while its making still waits for that end makes it at once and + waits for it, as for a block made in place, and one that finds none of its size made waits for + the ready thread to make it first. A pool near its next block keeps those blocks at rest for as + long as it stays so: 64 MiB a pool at most, counted against the kept empty blocks' budget. Metal's command buffers wait for no allocation. Not + announced. - **With unified memory, `Private` memory lies in the system heap's types before the device-local ones, its buffers' blocks there allocated exportable but for buffers that declare their padding unobserved: about 1 µs a submission for each such block held.** Where the device has unified memory and a heap that is not