1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
use {
    crate::counts::DescriptorCounts,
    hal::{
        device::{Device, OutOfMemory},
        pso::{AllocationError, DescriptorPool as _, DescriptorPoolCreateFlags},
        Backend,
    },
    std::{
        collections::{HashMap, VecDeque},
        hash::BuildHasherDefault,
    },
};

type PoolIndex = u32;

const MIN_SETS: u32 = 64;
const MAX_SETS: u32 = 512;

/// Descriptor set from allocator.
#[derive(Debug)]
pub struct DescriptorSet<B: Backend> {
    raw: B::DescriptorSet,
    pool_id: PoolIndex,
    counts: DescriptorCounts,
}

impl<B: Backend> DescriptorSet<B> {
    /// Get a reference to gfx-hal descriptor set.
    pub fn raw(&self) -> &B::DescriptorSet {
        &self.raw
    }

    /// Get a mutable reference to gfx-hal descriptor set.
    ///
    /// # Safety
    /// Object needs not to be replaced.
    pub unsafe fn raw_mut(&mut self) -> &mut B::DescriptorSet {
        &mut self.raw
    }
}

#[derive(Debug)]
struct Allocation<B: Backend> {
    sets: Vec<B::DescriptorSet>,
    pools: Vec<PoolIndex>,
}

impl<B: Backend> Allocation<B> {
    fn grow(
        &mut self,
        pool: &mut B::DescriptorPool,
        layout: &B::DescriptorSetLayout,
        count: u32,
    ) -> Result<(), OutOfMemory> {
        let sets_were = self.sets.len();
        match unsafe {
            pool.allocate(
                std::iter::repeat(layout).take(count as usize),
                &mut self.sets,
            )
        } {
            Err(err) => {
                unsafe { pool.free(self.sets.drain(sets_were..)) };
                match err {
                    AllocationError::OutOfMemory(oom) => Err(oom),
                    _ => {
                        // We check pool for free descriptors and sets before calling this function,
                        // so it can't be exhausted.
                        // And it can't be fragmented either according to spec
                        //
                        // https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#VkDescriptorPoolCreateInfo
                        //
                        // """
                        // Additionally, if all sets allocated from the pool since it was created or most recently reset
                        // use the same number of descriptors (of each type) and the requested allocation also
                        // uses that same number of descriptors (of each type), then fragmentation must not cause an allocation failure
                        // """
                        panic!("Unexpected error: {:?}", err);
                    }
                }
            }
            Ok(()) => {
                assert_eq!(self.sets.len(), sets_were + count as usize);
                Ok(())
            }
        }
    }
}

#[derive(Debug)]
struct DescriptorPool<B: Backend> {
    raw: B::DescriptorPool,
    capacity: u32,
    // Number of available sets.
    available: u32,
}

#[derive(Debug)]
struct DescriptorBucket<B: Backend> {
    pools_offset: PoolIndex,
    pools: VecDeque<DescriptorPool<B>>,
    total: u64,
}

impl<B: Backend> DescriptorBucket<B> {
    fn new() -> Self {
        DescriptorBucket {
            pools_offset: 0,
            pools: VecDeque::new(),
            total: 0,
        }
    }

    fn new_pool_size(&self, count: u32) -> u32 {
        MIN_SETS // at least MIN_SETS
            .max(count) // at least enough for allocation
            .max(self.total.min(MAX_SETS as u64) as u32) // at least as much as was allocated so far capped to MAX_SETS
            .next_power_of_two() // rounded up to nearest 2^N
    }

    fn dispose(mut self, device: &B::Device) {
        if self.total > 0 {
            log::error!("Not all descriptor sets were deallocated");
        }

        for pool in self.pools.drain(..) {
            if pool.available < pool.capacity {
                log::error!(
                    "Descriptor pool is still in use during allocator disposal. {:?}",
                    pool
                );
            }
            unsafe { device.destroy_descriptor_pool(pool.raw) };
        }
    }

    fn allocate(
        &mut self,
        device: &B::Device,
        layout: &B::DescriptorSetLayout,
        layout_counts: &DescriptorCounts,
        mut count: u32,
        allocation: &mut Allocation<B>,
    ) -> Result<(), OutOfMemory> {
        if count == 0 {
            return Ok(());
        }

        for (index, pool) in self.pools.iter_mut().enumerate().rev() {
            if pool.available == 0 {
                continue;
            }

            let allocate = pool.available.min(count);
            log::trace!("Allocate {} from exising pool", allocate);
            allocation.grow(&mut pool.raw, layout, allocate)?;
            allocation.pools.extend(
                std::iter::repeat(index as PoolIndex + self.pools_offset).take(allocate as usize),
            );
            count -= allocate;
            pool.available -= allocate;
            self.total += allocate as u64;

            if count == 0 {
                return Ok(());
            }
        }

        while count > 0 {
            let size = self.new_pool_size(count);
            let pool_counts = layout_counts.multiply(size);
            log::trace!(
                "Create new pool with {} sets and {:?} descriptors",
                size,
                pool_counts,
            );
            let mut raw = unsafe {
                device.create_descriptor_pool(
                    size as usize,
                    pool_counts.filtered(),
                    DescriptorPoolCreateFlags::FREE_DESCRIPTOR_SET,
                )?
            };

            let allocate = size.min(count);
            allocation.grow(&mut raw, layout, allocate)?;

            let index = self.pools.len();
            allocation.pools.extend(
                std::iter::repeat(index as PoolIndex + self.pools_offset).take(allocate as usize),
            );

            count -= allocate;
            self.pools.push_back(DescriptorPool {
                raw,
                capacity: size,
                available: size - allocate,
            });
            self.total += allocate as u64;
        }

        Ok(())
    }

    fn free(&mut self, sets: impl IntoIterator<Item = B::DescriptorSet>, pool_id: PoolIndex) {
        let pool = &mut self.pools[(pool_id - self.pools_offset) as usize];
        let mut count = 0;
        unsafe {
            pool.raw.free(sets.into_iter().map(|set| {
                count += 1;
                set
            }))
        };
        pool.available += count;
        self.total -= count as u64;
        log::trace!("Freed {} from descriptor bucket", count);
    }

    fn cleanup(&mut self, device: &B::Device) {
        while let Some(pool) = self.pools.pop_front() {
            if pool.available < pool.capacity {
                self.pools.push_front(pool);
                break;
            }
            log::trace!("Destroying used up descriptor pool");
            unsafe { device.destroy_descriptor_pool(pool.raw) };
            self.pools_offset += 1;
        }
    }
}

/// Descriptor allocator.
/// Can be used to allocate descriptor sets for any layout.
#[derive(Debug)]
pub struct DescriptorAllocator<B: Backend> {
    buckets: HashMap<DescriptorCounts, DescriptorBucket<B>, BuildHasherDefault<fxhash::FxHasher>>,
    allocation: Allocation<B>,
    total: u64,
    free_sets: Vec<B::DescriptorSet>,
}

impl<B: Backend> Drop for DescriptorAllocator<B> {
    fn drop(&mut self) {
        if !self.buckets.is_empty() {
            log::error!("DescriptorAllocator is dropped");
        }
    }
}

impl<B: Backend> DescriptorAllocator<B> {
    /// Create new allocator instance.
    ///
    /// # Safety
    /// All later operations assume the device is not lost.
    pub unsafe fn new() -> Self {
        DescriptorAllocator {
            buckets: HashMap::default(),
            allocation: Allocation {
                sets: Vec::new(),
                pools: Vec::new(),
            },
            total: 0,
            free_sets: Vec::new(),
        }
    }

    /// Allocate descriptor set with specified layout.
    /// `DescriptorCounts` must match descriptor numbers of the layout.
    /// `DescriptorCounts` can be constructed [from bindings] that were used
    /// to create layout instance.
    ///
    /// [from bindings]: .
    pub fn allocate(
        &mut self,
        device: &B::Device,
        layout: &B::DescriptorSetLayout,
        layout_counts: &DescriptorCounts,
        count: u32,
        extend: &mut impl Extend<DescriptorSet<B>>,
    ) -> Result<(), OutOfMemory> {
        if count == 0 {
            return Ok(());
        }

        log::trace!(
            "Allocating {} sets with layout {:?} @ {:?}",
            count,
            layout,
            layout_counts
        );

        let bucket = self
            .buckets
            .entry(layout_counts.clone())
            .or_insert_with(DescriptorBucket::new);
        match bucket.allocate(device, layout, layout_counts, count, &mut self.allocation) {
            Ok(()) => {
                extend.extend(
                    self.allocation
                        .pools
                        .drain(..)
                        .zip(self.allocation.sets.drain(..))
                        .map(|(pool_id, set)| DescriptorSet {
                            raw: set,
                            counts: layout_counts.clone(),
                            pool_id,
                        }),
                );
                Ok(())
            }
            Err(err) => {
                // Free sets allocated so far.
                let mut last = None;
                for (index, pool_id) in self.allocation.pools.drain(..).enumerate().rev() {
                    if Some(pool_id) != last {
                        if let Some(last_id) = last {
                            // Free contiguous range of sets from one pool in one go.
                            bucket.free(self.allocation.sets.drain(index + 1..), last_id);
                        }
                        last = Some(pool_id);
                    }
                }

                if let Some(last_id) = last {
                    bucket.free(self.allocation.sets.drain(..), last_id);
                }

                Err(err)
            }
        }
    }

    /// Free descriptor sets.
    ///
    /// # Safety
    ///
    /// None of descriptor sets can be referenced in any pending command buffers.
    /// All command buffers where at least one of descriptor sets referenced
    /// move to invalid state.
    pub unsafe fn free(&mut self, all_sets: impl IntoIterator<Item = DescriptorSet<B>>) {
        let mut free_counts = DescriptorCounts::EMPTY;
        let mut free_pool_id: PoolIndex = !0;

        for set in all_sets {
            if free_counts != set.counts || free_pool_id != set.pool_id {
                if free_pool_id != !0 {
                    let bucket = self
                        .buckets
                        .get_mut(&free_counts)
                        .expect("Set should be allocated from this allocator");
                    debug_assert!(bucket.total >= self.free_sets.len() as u64);
                    bucket.free(self.free_sets.drain(..), free_pool_id);
                }
                free_counts = set.counts;
                free_pool_id = set.pool_id;
            }
            self.free_sets.push(set.raw);
        }

        if free_pool_id != !0 {
            let bucket = self
                .buckets
                .get_mut(&free_counts)
                .expect("Set should be allocated from this allocator");
            debug_assert!(bucket.total >= self.free_sets.len() as u64);

            bucket.free(self.free_sets.drain(..), free_pool_id);
        }
    }

    /// Clear the allocator instance.
    /// All sets allocated from this allocator become invalid.
    ///
    /// # Safety
    /// Assumes none of the allocated blocks will be used from here.
    pub unsafe fn clear(&mut self, device: &B::Device) {
        for (_, bucket) in self.buckets.drain() {
            bucket.dispose(device);
        }
    }

    /// Perform cleanup to allow resources reuse.
    pub fn cleanup(&mut self, device: &B::Device) {
        for bucket in self.buckets.values_mut() {
            bucket.cleanup(device)
        }
    }
}