diff --git a/crates/reims-vgpu/src/backend/vulkan/engine/exec.rs b/crates/reims-vgpu/src/backend/vulkan/engine/exec.rs index 5a46ebbd9..f64a14d96 100644 --- a/crates/reims-vgpu/src/backend/vulkan/engine/exec.rs +++ b/crates/reims-vgpu/src/backend/vulkan/engine/exec.rs @@ -187,18 +187,15 @@ unsafe fn plan_buffer_gather_dispatches( } } } + // One staging slot for every table this command buffer's gathers need, not + // one apiece. A gathered window's table is ~200 bytes and this rail issues + // ~40 000 of them a second against ~2 200 command buffers, so the acquire + // and the write were being paid eighteen times over for bytes that fit in a + // single slot. + let words: Vec<&[u32]> = planned.iter().map(|(_, _, _, t)| &t.words[..]).collect(); + let (runs_slot, places) = unsafe { super::stage_run_tables(ctx, pools, counters, &words) }?; let mut out = Vec::with_capacity(planned.len()); - for (source, dst, dst_have, table) in &planned { - let bytes = super::run_table_bytes(&table.words); - let runs_slot = unsafe { - pools.acquire_staging( - ctx, - bytes.len() as u64, - vk::BufferUsageFlags::empty(), - counters, - ) - }?; - unsafe { pools.write_staging(ctx, &runs_slot, bytes) }?; + for ((source, dst, dst_have, table), place) in planned.iter().zip(&places) { let set = unsafe { pools.alloc_scatter_descriptor_set(&ctx.device, pipeline.dsl, counters) }?; unsafe { @@ -207,7 +204,7 @@ unsafe fn plan_buffer_gather_dispatches( set, (*source, table.bind_offset, table.bind_range), (*dst, 0, *dst_have), - (runs_slot.buffer, bytes.len() as u64), + (runs_slot.buffer, place.bind_offset, place.bind_range), ); } out.push(GatherDispatch { diff --git a/crates/reims-vgpu/src/backend/vulkan/engine/guest_scatter.rs b/crates/reims-vgpu/src/backend/vulkan/engine/guest_scatter.rs index f5702b52c..61900e0d1 100644 --- a/crates/reims-vgpu/src/backend/vulkan/engine/guest_scatter.rs +++ b/crates/reims-vgpu/src/backend/vulkan/engine/guest_scatter.rs @@ -483,16 +483,23 @@ impl ScatterPipeline { /// windows `dst` and the gather windows `src`, and which side is which is /// the only difference between the two — see [`build_gather_run_tables`]. /// + /// `runs` is `(buffer, offset, range)` for a different reason: a whole + /// submission's tables share one staging slot, so a dispatch's own table + /// starts wherever [`super::stage_run_tables`] placed it. The kernel indexes + /// from zero of its *bound range*, which is what makes the offset the only + /// thing that has to say which of them this dispatch reads. + /// /// # Safety /// /// `set` must have been allocated from [`Self::dsl`], and every buffer must - /// be live and cover the offset/range pair given for it. + /// be live and cover the offset/range pair given for it. Every offset must + /// be a multiple of the device's `minStorageBufferOffsetAlignment`. pub(crate) unsafe fn write_set( device: &ash::Device, set: vk::DescriptorSet, src: (vk::Buffer, u64, u64), dst: (vk::Buffer, u64, u64), - runs: (vk::Buffer, u64), + runs: (vk::Buffer, u64, u64), ) { let infos = [ vk::DescriptorBufferInfo::default() @@ -505,20 +512,25 @@ impl ScatterPipeline { .range(dst.2), vk::DescriptorBufferInfo::default() .buffer(runs.0) - .offset(0) - .range(runs.1), + .offset(runs.1) + .range(runs.2), ]; - let writes: Vec<_> = [BINDING_SRC, BINDING_DST, BINDING_RUNS] - .iter() - .enumerate() - .map(|(i, binding)| { - vk::WriteDescriptorSet::default() - .dst_set(set) - .dst_binding(*binding) - .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) - .buffer_info(std::slice::from_ref(&infos[i])) - }) - .collect(); + // An array and not a collected `Vec`: this runs once per dispatch and + // the draw-time gather issues ~40 000 of those a second, so a heap + // allocation here is 40 000 a second for three elements whose count is + // fixed by the layout. + let writes = [ + (BINDING_SRC, &infos[0]), + (BINDING_DST, &infos[1]), + (BINDING_RUNS, &infos[2]), + ] + .map(|(binding, info)| { + vk::WriteDescriptorSet::default() + .dst_set(set) + .dst_binding(binding) + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) + .buffer_info(std::slice::from_ref(info)) + }); unsafe { device.update_descriptor_sets(&writes, &[]) }; } diff --git a/crates/reims-vgpu/src/backend/vulkan/engine/mod.rs b/crates/reims-vgpu/src/backend/vulkan/engine/mod.rs index ed73f7ed4..fb4c0611c 100644 --- a/crates/reims-vgpu/src/backend/vulkan/engine/mod.rs +++ b/crates/reims-vgpu/src/backend/vulkan/engine/mod.rs @@ -2886,18 +2886,15 @@ unsafe fn plan_guest_scatter_dispatches( } } } + // One staging slot for every table this writeback needs; see + // [`stage_run_tables`]. This rail issues far fewer dispatches than the draw + // -time gather does, so the saving is small here — it shares the arena + // because a second copy of the placement arithmetic is a second place to + // name a descriptor offset the driver will not accept. + let words: Vec<&[u32]> = tables.iter().map(|(_, t)| &t.words[..]).collect(); + let (runs_slot, places) = unsafe { stage_run_tables(ctx, pools, counters, &words) }?; let mut groups = Vec::with_capacity(tables.len()); - for (buffer, table) in &tables { - let bytes: &[u8] = run_table_bytes(&table.words); - let runs_slot = unsafe { - pools.acquire_staging( - ctx, - bytes.len() as u64, - ash::vk::BufferUsageFlags::empty(), - counters, - ) - }?; - unsafe { pools.write_staging(ctx, &runs_slot, bytes) }?; + for ((buffer, table), place) in tables.iter().zip(&places) { let set = unsafe { pools.alloc_scatter_descriptor_set(&ctx.device, pipeline.dsl, counters) }?; unsafe { @@ -2908,7 +2905,7 @@ unsafe fn plan_guest_scatter_dispatches( // side, because a RAMBlock is wider than `maxStorageBufferRange`. (scratch.buffer, 0, scratch.size), (*buffer, table.bind_offset, table.bind_range), - (runs_slot.buffer, bytes.len() as u64), + (runs_slot.buffer, place.bind_offset, place.bind_range), ); } groups.push(ScatterGroup { @@ -2935,6 +2932,99 @@ pub(crate) fn run_table_bytes(words: &[u32]) -> &[u8] { unsafe { std::slice::from_raw_parts(words.as_ptr().cast::(), std::mem::size_of_val(words)) } } +/// Where each of a submission's run tables sits inside the one staging slot they +/// share: byte offset and byte length, in the order they were given. +/// +/// `bind_offset` is a multiple of `minStorageBufferOffsetAlignment` by +/// construction, which is what makes it legal as a `VkDescriptorBufferInfo` +/// offset; `bind_range` is the table's own length and not the padded stride, so +/// the shader's bound range never covers a neighbour's words. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct RunTablePlace { + bind_offset: u64, + bind_range: u64, +} + +/// Lay `tables` end to end at `align` and produce the arena's bytes, along with +/// each table's place inside them. +/// +/// Split out from [`stage_run_tables`] because it is the whole of the layout — +/// the arithmetic *and* which bytes land where — and it needs no device, so a +/// test can walk both. What is left in the caller is an acquire and a write. +fn pack_run_tables(tables: &[&[u32]], align: u64) -> (Vec, Vec) { + let align = align.max(1); + let mut cursor = 0u64; + let places: Vec = tables + .iter() + .map(|words| { + // `max(4)` because a zero-length table would give a descriptor a + // zero range, which Vulkan refuses. It cannot arise — every planner + // declines an empty table before it gets here — but the bound + // belongs where the range is chosen rather than in a comment on the + // planners. + let len = (std::mem::size_of_val(*words) as u64).max(4); + let place = RunTablePlace { + bind_offset: cursor, + bind_range: len, + }; + // Pad to the next legal descriptor offset. `align` is a power of two + // (Vulkan requires it of `minStorageBufferOffsetAlignment`), so this + // is the round-up and not an approximation of one. + cursor += len.div_ceil(align) * align; + place + }) + .collect(); + let mut packed = vec![0u8; cursor.max(4) as usize]; + for (place, words) in places.iter().zip(tables) { + let at = place.bind_offset as usize; + let bytes = run_table_bytes(words); + packed[at..at + bytes.len()].copy_from_slice(bytes); + } + (packed, places) +} + +/// Write a whole submission's run tables into **one** staging slot, each at an +/// offset a storage-buffer descriptor may name. +/// +/// This is the arena that made the draw-time compute gather affordable. Each +/// dispatch used to take a staging slot of its own for a ~200-byte table, which +/// is an `acquire_staging` and a `write_staging` apiece — ~40 000 of each a +/// second on a driven macos-13 boot, against ~2 200 command buffers. Sharing one +/// slot makes it one of each per command buffer, and the descriptor's own +/// `offset` field is what tells a dispatch which table is its own, so nothing in +/// the kernel changes. +/// +/// The writeback's scatter shares it for the same reason it shares +/// [`run_table_bytes`]: it is the same table and the same staging write, and a +/// second copy of the padding arithmetic is a second place to get a descriptor +/// offset wrong. +/// +/// # Safety +/// +/// `ctx` must be the device `pools` belongs to. +unsafe fn stage_run_tables( + ctx: &context::DeviceContext, + pools: &mut pools::ResourcePools, + counters: &counters::EngineCounters, + tables: &[&[u32]], +) -> Result<(pools::BufferSlot, Vec), types::DrawError> { + // One host-side buffer laid out exactly as the slot wants it, so the slot + // takes one `write_staging`. A whole command buffer's tables come to a few + // kilobytes, which is why this is cheaper than the per-table slots it + // replaces even with the extra copy. + let (packed, places) = pack_run_tables(tables, ctx.guest_bind_offset_align); + let slot = unsafe { + pools.acquire_staging( + ctx, + packed.len() as u64, + ash::vk::BufferUsageFlags::empty(), + counters, + ) + }?; + unsafe { pools.write_staging(ctx, &slot, &packed) }?; + Ok((slot, places)) +} + /// Add one stretch's copy to the group for `buffer`, opening a group if this is /// the first stretch to name it. /// @@ -4350,3 +4440,106 @@ mod probe_visibility_tests { } } } + +#[cfg(test)] +mod run_table_arena_tests { + use super::*; + + /// `minStorageBufferOffsetAlignment` on the three hosts this rail runs: + /// 16 on Apple/MoltenVK, 32 on the NVIDIA proprietary driver, 256 on the + /// several drivers that report the Vulkan maximum-permitted value. + const ALIGNS: [u64; 3] = [16, 32, 256]; + + fn table(runs: usize, seed: u32) -> Vec { + (0..runs as u32 * 4).map(|w| w ^ seed).collect() + } + + /// A descriptor offset the driver refuses is the whole failure mode this + /// arena introduced, so it is the first thing asserted. + #[test] + fn every_place_starts_at_a_legal_descriptor_offset() { + for align in ALIGNS { + let words: Vec> = (1..=9).map(|n| table(n, n as u32)).collect(); + let borrowed: Vec<&[u32]> = words.iter().map(|w| &w[..]).collect(); + let (_, places) = pack_run_tables(&borrowed, align); + for place in &places { + assert_eq!( + place.bind_offset % align, + 0, + "align {align}: offset {} is not a multiple", + place.bind_offset + ); + } + } + } + + /// A range reaching into the next table would let a dispatch read runs that + /// belong to another gather — a wrong window, not a slow one. + #[test] + fn no_places_bound_range_reaches_its_neighbour() { + for align in ALIGNS { + let words: Vec> = (1..=9).map(|n| table(n, n as u32)).collect(); + let borrowed: Vec<&[u32]> = words.iter().map(|w| &w[..]).collect(); + let (packed, places) = pack_run_tables(&borrowed, align); + for pair in places.windows(2) { + assert!( + pair[0].bind_offset + pair[0].bind_range <= pair[1].bind_offset, + "align {align}: {:?} overlaps {:?}", + pair[0], + pair[1] + ); + } + let last = places.last().expect("nine tables"); + assert!( + last.bind_offset + last.bind_range <= packed.len() as u64, + "align {align}: last place reaches past the arena" + ); + } + } + + /// The bytes a dispatch reads at its own place must be its own table's, in + /// order. This is the property the per-table staging slots gave for free and + /// the arena has to earn. + #[test] + fn each_table_reads_back_its_own_words_at_its_own_place() { + for align in ALIGNS { + let words: Vec> = (1..=9) + .map(|n| table(n * 3, 0xa5a5_0000 + n as u32)) + .collect(); + let borrowed: Vec<&[u32]> = words.iter().map(|w| &w[..]).collect(); + let (packed, places) = pack_run_tables(&borrowed, align); + for (place, want) in places.iter().zip(&words) { + let at = place.bind_offset as usize; + let bytes = &packed[at..at + std::mem::size_of_val(&want[..])]; + assert_eq!(bytes, run_table_bytes(want), "align {align}"); + assert_eq!( + place.bind_range, + std::mem::size_of_val(&want[..]) as u64, + "align {align}: a range wider than the table would bind padding" + ); + } + } + } + + /// One table is the writeback's ordinary case and it must not pay for the + /// arena: its place is the buffer's own start, exactly as the per-table slot + /// it replaces was. + #[test] + fn a_lone_table_sits_at_offset_zero() { + let words = table(7, 1); + let (packed, places) = pack_run_tables(&[&words[..]], 256); + assert_eq!(places.len(), 1); + assert_eq!(places[0].bind_offset, 0); + assert_eq!(places[0].bind_range, 7 * 4 * 4); + assert_eq!(packed.len(), 256, "rounded up to the alignment stride"); + } + + /// `acquire_staging` and `VkDescriptorBufferInfo` both refuse a zero size, + /// and a caller with nothing to stage would otherwise reach both with one. + #[test] + fn no_tables_still_asks_for_a_buffer_a_descriptor_could_name() { + let (packed, places) = pack_run_tables(&[], 256); + assert!(places.is_empty()); + assert_eq!(packed.len(), 4); + } +} diff --git a/crates/reims-vgpu/src/backend/vulkan/engine/pools/mod.rs b/crates/reims-vgpu/src/backend/vulkan/engine/pools/mod.rs index a38e15bb1..126ed5f6b 100644 --- a/crates/reims-vgpu/src/backend/vulkan/engine/pools/mod.rs +++ b/crates/reims-vgpu/src/backend/vulkan/engine/pools/mod.rs @@ -415,6 +415,29 @@ pub(crate) struct ResourcePools { /// submitting anything leaves it here for the next seal, which is correct: /// no submitted command buffer ever named it, so any later fence will do. scatter_dsets: Vec<(vk::DescriptorSet, vk::DescriptorPool)>, + /// Guest-scatter descriptor sets whose fence has retired, ready to be + /// rewritten and handed out again. + /// + /// Every set here was allocated against the one [`guest_scatter`] layout, so + /// unlike a draw's — which are keyed by a per-pipeline binding signature — + /// they are interchangeable, and a `vkAllocateDescriptorSets` per use buys + /// nothing. The draw-time gather issues ~40 000 dispatches a second on a + /// driven macos-13 boot and an allocate plus its matching free is two driver + /// calls apiece, which is the larger half of the per-dispatch cost that kept + /// the compute gather switched off. Recycling makes the steady state zero of + /// both. + /// + /// A set returns here only from `drain_cleanup`, which runs after the fence + /// of the submission that named it — the same rule the staging and gather + /// free lists keep, and the reason a rewrite cannot race a dispatch still + /// reading the old bindings. + /// + /// Bounded by construction rather than by a cap: nothing enters that was not + /// already allocated and retired, so the high-water is the peak number of + /// dispatches in flight at once and never more. + /// + /// [`guest_scatter`]: crate::backend::vulkan::engine::guest_scatter + scatter_dset_free: Vec<(vk::DescriptorSet, vk::DescriptorPool)>, /// N-deep in-flight ring: each slot is one CB + fence + the cleanup it /// owes. Entries rotate through slots; a slot is reused only after its /// fence retires (begin_entry blocks on the oldest when the ring is full). @@ -711,6 +734,9 @@ impl ResourcePools { /// still be owed to the cache. pub(crate) struct PendingGpuCleanup { dsets: Vec<(vk::DescriptorSet, vk::DescriptorPool)>, + /// The guest-scatter sets, kept apart from `dsets` because they recycle + /// rather than free — see [`ResourcePools::scatter_dset_free`]. + scatter_dsets: Vec<(vk::DescriptorSet, vk::DescriptorPool)>, staging: Vec, gather: Vec, readback: Vec, diff --git a/crates/reims-vgpu/src/backend/vulkan/engine/pools/submission_and_buffers.rs b/crates/reims-vgpu/src/backend/vulkan/engine/pools/submission_and_buffers.rs index d65b12a0a..7dbb4bd09 100644 --- a/crates/reims-vgpu/src/backend/vulkan/engine/pools/submission_and_buffers.rs +++ b/crates/reims-vgpu/src/backend/vulkan/engine/pools/submission_and_buffers.rs @@ -137,6 +137,7 @@ impl ResourcePools { scatter: None, scatter_refused: false, scatter_dsets: Vec::new(), + scatter_dset_free: Vec::new(), slots: Vec::new(), cur: 0, in_flight: 0, @@ -723,23 +724,59 @@ impl ResourcePools { } } - /// Allocate a descriptor set for the guest-scatter kernel and park it on the - /// list [`Self::seal_entry`] drains, so the caller owes it nothing. + /// A descriptor set for the guest-scatter kernel, recycled if one has + /// retired and allocated if not, parked on the list [`Self::seal_entry`] + /// drains so the caller owes it nothing. + /// + /// The caller must write it before dispatching: a recycled set still names + /// the previous dispatch's three buffers, and `ScatterPipeline::write_set` + /// is the only writer. Every caller does, because writing is how it names + /// its own buffers at all — there is no path that binds a set it did not + /// just write. /// /// # Safety /// - /// `device` must be the device these pools belong to. + /// `device` must be the device these pools belong to, and `dsl` must be the + /// guest-scatter layout every set on the free list was allocated against. pub(crate) unsafe fn alloc_scatter_descriptor_set( &mut self, device: &ash::Device, dsl: vk::DescriptorSetLayout, counters: &EngineCounters, ) -> Result { - let (set, pool) = unsafe { self.alloc_descriptor_set(device, dsl, counters) }?; + let (set, pool) = match self.take_free_scatter_dset() { + Some(recycled) => recycled, + None => unsafe { self.alloc_descriptor_set(device, dsl, counters) }?, + }; self.scatter_dsets.push((set, pool)); Ok(set) } + /// Take a retired guest-scatter set off the free list, or `None` when there + /// is none. + /// + /// Split out of [`Self::alloc_scatter_descriptor_set`] for the same reason + /// [`Self::take_free_gather`] is split out of `acquire_guest_gather`: it is + /// the whole of the no-aliasing property and it is the half that needs no + /// device, so a test can exercise it. A set **leaves** the free list when it + /// is handed out and only `drain_cleanup` puts it back, which runs after the + /// fence of the submission that named it — so two dispatches inside one + /// command buffer cannot be handed one set and have the second's + /// `write_set` overwrite the first's bindings. + fn take_free_scatter_dset(&mut self) -> Option<(vk::DescriptorSet, vk::DescriptorPool)> { + self.scatter_dset_free.pop() + } + + /// Return a retired entry's guest-scatter sets to the free list. + /// + /// The other half of [`Self::take_free_scatter_dset`], named for the same + /// reason: the fence is what makes a rewrite safe, and this is the only + /// caller that has one. `drain_cleanup` is the only call site and it runs + /// after the wait. + fn recycle_scatter_dsets(&mut self, sets: &mut Vec<(vk::DescriptorSet, vk::DescriptorPool)>) { + self.scatter_dset_free.append(sets); + } + /// Free `(set, owning_pool)` pairs back to their allocating blocks. pub(crate) unsafe fn free_descriptor_sets( &self, @@ -1170,12 +1207,13 @@ impl ResourcePools { let mut sampled = std::mem::take(&mut self.sampled_live); let admissions = take_retained_slots(&mut sampled, sampled_retains); // Both seal points reach here, which is the whole reason the scatter's - // sets are parked on `self` instead of travelling with its plan. - let mut dsets = dsets; - dsets.append(&mut self.scatter_dsets); + // sets are parked on `self` instead of travelling with its plan. They + // travel in their own field rather than joining `dsets`, because they + // recycle at retire and a draw's do not. SealedEntry { cleanup: PendingGpuCleanup { dsets, + scatter_dsets: std::mem::take(&mut self.scatter_dsets), staging: std::mem::take(&mut self.staging_live), gather: std::mem::take(&mut self.gather_live), readback, @@ -1767,6 +1805,9 @@ impl ResourcePools { /// The CB that referenced these resources must have retired. unsafe fn drain_cleanup(&mut self, device: &ash::Device, mut pending: PendingGpuCleanup) { self.desc_arena.free(device, &pending.dsets); + // The fence this entry waited on is exactly what makes a rewrite of + // these safe, so the free list is fed from here and nowhere else. + self.recycle_scatter_dsets(&mut pending.scatter_dsets); // No cache admissions here: `seal_entry` lifted them out and // `finish_entry_async` gave them to the cache at submit. What is left in // `pending.sampled` is every slot nothing retained, which recycles. @@ -4505,6 +4546,7 @@ mod recycle_tests { fence: vk::Fence::null(), pending: Some(PendingGpuCleanup { dsets: Vec::new(), + scatter_dsets: Vec::new(), staging: Vec::new(), gather: Vec::new(), readback: Vec::new(), @@ -5089,3 +5131,87 @@ mod gather_slots_do_not_alias { ); } } + +/// The guest-scatter descriptor pool's no-aliasing property, which is what makes +/// recycling a set cheaper than allocating one *and* correct. +/// +/// These exercise [`ResourcePools::take_free_scatter_dset`] and +/// [`ResourcePools::recycle_scatter_dsets`] rather than +/// `alloc_scatter_descriptor_set`, because the miss path allocates and needs a +/// device while the property under test does not — the same split, for the same +/// reason, as [`gather_slots_do_not_alias`]. +/// +/// The property: a set is *removed* from the free list when it is handed out, +/// and only a retired entry puts it back. A dispatch's bindings are written into +/// its set immediately before it is recorded, so two dispatches handed one set +/// would have the second's `write_set` silently retarget the first — a gather +/// reading another window's runs, which is wrong pixels rather than slow ones. +#[cfg(test)] +mod scatter_descriptor_sets_do_not_alias { + use super::*; + use ash::vk::Handle; + + fn pair(raw: u64) -> (vk::DescriptorSet, vk::DescriptorPool) { + ( + vk::DescriptorSet::from_raw(raw), + vk::DescriptorPool::from_raw(1), + ) + } + + /// Two takes with no retire between them cannot resolve to one set. + #[test] + fn two_takes_with_no_retire_between_them_give_two_sets() { + let mut pools = ResourcePools::new(); + pools.recycle_scatter_dsets(&mut vec![pair(1), pair(2)]); + let first = pools.take_free_scatter_dset().expect("two were recycled"); + let second = pools.take_free_scatter_dset().expect("two were recycled"); + assert_ne!(first.0, second.0); + assert!( + pools.take_free_scatter_dset().is_none(), + "the list held exactly what was recycled into it" + ); + } + + /// A retired set comes back, which is the whole point: the steady state must + /// stop calling `vkAllocateDescriptorSets`. + #[test] + fn a_retired_set_is_handed_out_again() { + let mut pools = ResourcePools::new(); + pools.recycle_scatter_dsets(&mut vec![pair(7)]); + let taken = pools.take_free_scatter_dset().expect("one was recycled"); + assert_eq!(taken.0.as_raw(), 7); + assert!(pools.take_free_scatter_dset().is_none()); + pools.recycle_scatter_dsets(&mut vec![taken]); + assert_eq!( + pools + .take_free_scatter_dset() + .expect("it was recycled again") + .0 + .as_raw(), + 7 + ); + } + + /// A fresh device has nothing to recycle, so the first dispatch of a boot + /// allocates rather than reading an empty `pop` as a usable handle. + #[test] + fn a_fresh_pool_has_nothing_to_hand_out() { + let mut pools = ResourcePools::new(); + assert!(pools.take_free_scatter_dset().is_none()); + } + + /// Recycling drains the caller's vector, so a `PendingGpuCleanup` cannot be + /// drained twice into the free list and hand the same set to two live + /// dispatches. + #[test] + fn recycling_takes_the_sets_out_of_the_entry_that_owed_them() { + let mut pools = ResourcePools::new(); + let mut owed = vec![pair(3), pair(4)]; + pools.recycle_scatter_dsets(&mut owed); + assert!(owed.is_empty()); + pools.recycle_scatter_dsets(&mut owed); + assert!(pools.take_free_scatter_dset().is_some()); + assert!(pools.take_free_scatter_dset().is_some()); + assert!(pools.take_free_scatter_dset().is_none()); + } +} diff --git a/crates/reims-vgpu/src/backend/vulkan/engine/pools/teardown.rs b/crates/reims-vgpu/src/backend/vulkan/engine/pools/teardown.rs index a4c8aebd2..006cf9231 100644 --- a/crates/reims-vgpu/src/backend/vulkan/engine/pools/teardown.rs +++ b/crates/reims-vgpu/src/backend/vulkan/engine/pools/teardown.rs @@ -170,7 +170,10 @@ impl ResourcePools { // before the arena because its sets were allocated against this layout. // Freed before the arena that owns their blocks. Anything still here was // never submitted, or its fence has already retired above. - let owed = std::mem::take(&mut self.scatter_dsets); + let mut owed = std::mem::take(&mut self.scatter_dsets); + // The recycle list holds only sets from entries whose fence retired, + // which is the same "nothing can still name it" state this relies on. + owed.append(&mut self.scatter_dset_free); self.desc_arena.free(device, &owed); if let Some(scatter) = self.scatter.take() { scatter.destroy(device);