Skip to main content

feldera_storage/fbuf/
slab.rs

1//! Slab-backed allocation and recycling for [`FBuf`].
2//!
3//! This module keeps a small set of per-size-class freelists for power-of-two
4//! `FBuf` capacities. Allocations that do not fit a slab size class fall back
5//! to direct allocation and deallocation.
6
7use std::{
8    alloc,
9    array::from_fn,
10    cell::RefCell,
11    ops::{Add, AddAssign},
12    ptr::NonNull,
13    sync::{
14        Arc, LazyLock,
15        atomic::{AtomicU64, Ordering as AtomicOrdering},
16    },
17};
18
19use crossbeam::queue::ArrayQueue;
20
21use super::FBuf;
22
23thread_local! {
24    /// Per-thread override for the active `FBuf` slab set.
25    ///
26    /// When unset, allocation and recycle operations fall back to the
27    /// process-wide slab set in [`FALLBACK_SLAB_POOL`].
28    static THREAD_SLAB_POOL: RefCell<Option<Arc<FBufSlabs>>> = const { RefCell::new(None) };
29}
30
31tokio::task_local! {
32    /// Per-task override for the active `FBuf` slab set.
33    ///
34    /// This is used by async merger tasks, which can move across worker
35    /// threads and therefore cannot rely on thread-local slab state.
36    pub static TOKIO_FBUF_SLABS: Arc<FBufSlabs>;
37}
38
39/// Process-wide fallback `FBuf` slab set used when a thread has not installed
40/// its own slab set via [`set_thread_slab_pool`].
41///
42/// This is for stuff that doesn't use a runtime. If we get it wrong
43/// somehow, we'll know because we will probably contend on this horribly.
44static FALLBACK_SLAB_POOL: LazyLock<Arc<FBufSlabs>> =
45    LazyLock::new(|| Arc::new(FBufSlabs::default()));
46
47// Locking in some constraints for my sanity
48const _: () = {
49    assert!(FBuf::ALIGNMENT.is_power_of_two());
50    assert!(FBufSlabs::HIGHEST_SLAB_CLASS_CAPACITY.is_power_of_two());
51    assert!(FBufSlabs::HIGHEST_SLAB_CLASS_CAPACITY >= FBuf::ALIGNMENT);
52};
53
54/// One power-of-two slab class that caches recycled `FBuf` allocations of a
55/// single capacity.
56#[derive(Debug)]
57struct FBufSlab {
58    /// Fixed-capacity free-list queue for recycled raw buffer pointers.
59    buffers: ArrayQueue<CachedAllocation>,
60    /// Counters for requests and hits observed by this slab class.
61    stats: FBufSlabStats,
62}
63
64/// A recycled `FBuf` allocation stored in a slab free list.
65#[derive(Clone, Copy, Debug)]
66struct CachedAllocation {
67    /// Pointer to an owned heap allocation that can be reused for a future
68    /// `FBuf`.
69    ptr: NonNull<u8>,
70}
71
72// SAFETY: These pointers represent owned heap allocations. Access is
73// synchronized by the enclosing `ArrayQueue`, and moving the pointer value
74// itself across threads does not transfer aliasing guarantees beyond raw
75// ownership.
76unsafe impl Send for CachedAllocation {}
77
78/// Mutable counters for requests and hits recorded by a single slab class.
79#[derive(Debug, Default)]
80struct FBufSlabStats {
81    /// Total allocation attempts routed to this slab class.
82    alloc_requests: AtomicU64,
83    /// Allocation attempts satisfied from a cached buffer.
84    alloc_hits: AtomicU64,
85    /// Total recycle attempts routed to this slab class.
86    recycle_requests: AtomicU64,
87    /// Recycle attempts that successfully returned a buffer to the cache.
88    recycle_hits: AtomicU64,
89}
90
91impl FBufSlabStats {
92    fn snapshot(&self, size: usize, available_buffers: usize) -> FBufSlabStatsSnapshot {
93        FBufSlabStatsSnapshot {
94            size,
95            available_buffers,
96            alloc_requests: self.alloc_requests.load(AtomicOrdering::Relaxed),
97            alloc_hits: self.alloc_hits.load(AtomicOrdering::Relaxed),
98            recycle_requests: self.recycle_requests.load(AtomicOrdering::Relaxed),
99            recycle_hits: self.recycle_hits.load(AtomicOrdering::Relaxed),
100        }
101    }
102}
103
104/// Snapshot of one slab size class.
105#[derive(Clone, Debug, Default, PartialEq, Eq)]
106pub struct FBufSlabStatsSnapshot {
107    /// Buffer capacity in bytes for this slab class.
108    pub size: usize,
109    /// Number of available buffers currently retained in this slab class.
110    pub available_buffers: usize,
111    /// Total allocation requests routed to this slab class.
112    pub alloc_requests: u64,
113    /// Allocation requests served from cached buffers in this slab class.
114    pub alloc_hits: u64,
115    /// Total recycle requests routed to this slab class.
116    pub recycle_requests: u64,
117    /// Recycle requests accepted into this slab class.
118    pub recycle_hits: u64,
119}
120
121impl FBufSlabStatsSnapshot {
122    /// Returns the number of allocation requests that missed this slab class
123    /// and fell back to direct allocation.
124    pub fn malloc_fallbacks(&self) -> u64 {
125        self.alloc_requests.saturating_sub(self.alloc_hits)
126    }
127
128    /// Returns the number of recycle requests that missed this slab class and
129    /// fell back to direct deallocation.
130    pub fn free_fallbacks(&self) -> u64 {
131        self.recycle_requests.saturating_sub(self.recycle_hits)
132    }
133}
134
135/// Snapshot of an [`FBufSlabs`].
136#[derive(Clone, Debug, Default, PartialEq, Eq)]
137pub struct FBufSlabsStats {
138    /// Number of cached buffers currently retained across all slab classes.
139    pub cached_buffers: usize,
140    /// Allocation requests that bypassed slab reuse because the requested
141    /// capacity does not map to any slab size class.
142    pub fallback_alloc_requests: u64,
143    /// Recycle requests that bypassed slab reuse because the buffer capacity
144    /// does not map to any slab size class.
145    pub fallback_recycle_requests: u64,
146    /// Per-size-class request counters and free-list occupancy information.
147    pub classes: Vec<FBufSlabStatsSnapshot>,
148}
149
150impl FBufSlabsStats {
151    /// Returns the total number of allocation requests observed across the
152    /// slab set, including fallback-only requests.
153    pub fn alloc_requests(&self) -> u64 {
154        self.fallback_alloc_requests
155            + self
156                .classes
157                .iter()
158                .map(|class| class.alloc_requests)
159                .sum::<u64>()
160    }
161
162    /// Returns the total number of recycle requests observed across the slab
163    /// set, including fallback-only requests.
164    pub fn recycle_requests(&self) -> u64 {
165        self.fallback_recycle_requests
166            + self
167                .classes
168                .iter()
169                .map(|class| class.recycle_requests)
170                .sum::<u64>()
171    }
172
173    /// Returns the number of allocations that reused an already cached buffer.
174    pub fn mallocs_saved(&self) -> u64 {
175        self.classes.iter().map(|class| class.alloc_hits).sum()
176    }
177
178    /// Returns the number of allocation requests that fell back to direct
179    /// allocation, either because no cached buffer was available or because
180    /// the request was outside the slabbed range.
181    pub fn malloc_fallbacks(&self) -> u64 {
182        self.fallback_alloc_requests
183            + self
184                .classes
185                .iter()
186                .map(FBufSlabStatsSnapshot::malloc_fallbacks)
187                .sum::<u64>()
188    }
189
190    /// Returns the number of frees that were converted into slab reuse by
191    /// caching the buffer instead of immediately deallocating it.
192    pub fn frees_saved(&self) -> u64 {
193        self.classes.iter().map(|class| class.recycle_hits).sum()
194    }
195
196    /// Returns the number of recycle requests that fell back to direct
197    /// deallocation, either because a slab class was full or because the
198    /// buffer capacity was outside the slabbed range.
199    pub fn free_fallbacks(&self) -> u64 {
200        self.fallback_recycle_requests
201            + self
202                .classes
203                .iter()
204                .map(FBufSlabStatsSnapshot::free_fallbacks)
205                .sum::<u64>()
206    }
207}
208
209impl Add for FBufSlabsStats {
210    type Output = Self;
211
212    fn add(mut self, rhs: Self) -> Self::Output {
213        self += rhs;
214        self
215    }
216}
217
218impl AddAssign for FBufSlabsStats {
219    fn add_assign(&mut self, rhs: Self) {
220        self.cached_buffers += rhs.cached_buffers;
221        self.fallback_alloc_requests += rhs.fallback_alloc_requests;
222        self.fallback_recycle_requests += rhs.fallback_recycle_requests;
223
224        if self.classes.is_empty() {
225            self.classes = rhs.classes;
226            return;
227        }
228        if rhs.classes.is_empty() {
229            return;
230        }
231
232        assert_eq!(self.classes.len(), rhs.classes.len());
233        for (lhs, rhs) in self.classes.iter_mut().zip(rhs.classes) {
234            assert_eq!(lhs.size, rhs.size);
235            lhs.available_buffers += rhs.available_buffers;
236            lhs.alloc_requests += rhs.alloc_requests;
237            lhs.alloc_hits += rhs.alloc_hits;
238            lhs.recycle_requests += rhs.recycle_requests;
239            lhs.recycle_hits += rhs.recycle_hits;
240        }
241    }
242}
243
244/// Power-of-two free lists for recycling [`FBuf`] allocations.
245#[derive(Debug)]
246pub struct FBufSlabs {
247    /// Slab classes indexed by capacity bucket.
248    slabs: [FBufSlab; Self::NUM_CLASSES],
249    /// Allocation requests that never entered a slab class because the
250    /// requested capacity was not slab-eligible.
251    fallback_alloc_requests: AtomicU64,
252    /// Recycle requests that never entered a slab class because the buffer
253    /// capacity was not slab-eligible.
254    fallback_recycle_requests: AtomicU64,
255}
256
257impl FBufSlabs {
258    /// Largest allocation capacity that maps to a dedicated slab size class.
259    /// Requests above this bypass slab reuse and fall back to malloc/free.
260    pub const HIGHEST_SLAB_CLASS_CAPACITY: usize = 64 * 1024;
261
262    /// Default byte budget retained per slab size class when callers do not
263    /// supply an explicit setting.
264    pub const DEFAULT_BYTES_PER_CLASS: usize = 16 * 1024 * 1024;
265
266    const MIN_SHIFT: u32 = FBuf::ALIGNMENT.trailing_zeros();
267    const MAX_SHIFT: u32 = Self::HIGHEST_SLAB_CLASS_CAPACITY.trailing_zeros();
268    const NUM_CLASSES: usize = (Self::MAX_SHIFT - Self::MIN_SHIFT + 1) as usize;
269
270    fn slab_size(index: usize) -> usize {
271        1usize << (Self::MIN_SHIFT as usize + index)
272    }
273
274    /// Returns a stable identifier for this slab allocator instance.
275    pub fn backend_id(&self) -> usize {
276        self as *const Self as usize
277    }
278
279    /// Creates a new slab set with a fixed byte budget per size class.
280    ///
281    /// The effective cached buffer count for each class is
282    /// `max(bytes_per_class, class_size) / class_size`, which guarantees that
283    /// every slab class can cache at least one buffer.
284    pub fn new(bytes_per_class: usize) -> Self {
285        Self {
286            slabs: from_fn(|index| {
287                let size = Self::slab_size(index);
288                let max_buffers = bytes_per_class.max(size) / size;
289                FBufSlab {
290                    buffers: ArrayQueue::new(max_buffers),
291                    stats: FBufSlabStats::default(),
292                }
293            }),
294            fallback_alloc_requests: AtomicU64::new(0),
295            fallback_recycle_requests: AtomicU64::new(0),
296        }
297    }
298
299    fn try_take(&self, requested_capacity: usize) -> Option<(NonNull<u8>, usize)> {
300        let Some(index) = Self::request_index(requested_capacity) else {
301            self.fallback_alloc_requests
302                .fetch_add(1, AtomicOrdering::Relaxed);
303            return None;
304        };
305        let slab = &self.slabs[index];
306        let size = Self::slab_size(index);
307        slab.stats
308            .alloc_requests
309            .fetch_add(1, AtomicOrdering::Relaxed);
310
311        let ptr = slab.buffers.pop();
312        if ptr.is_some() {
313            slab.stats.alloc_hits.fetch_add(1, AtomicOrdering::Relaxed);
314        }
315        ptr.map(|ptr| (ptr.ptr, size))
316    }
317
318    fn try_put(&self, ptr: NonNull<u8>, capacity: usize) -> bool {
319        let slab = match Self::capacity_index(capacity) {
320            Some(index) => &self.slabs[index],
321            None => {
322                self.fallback_recycle_requests
323                    .fetch_add(1, AtomicOrdering::Relaxed);
324                return false;
325            }
326        };
327        slab.stats
328            .recycle_requests
329            .fetch_add(1, AtomicOrdering::Relaxed);
330        if slab.buffers.push(CachedAllocation { ptr }).is_err() {
331            return false;
332        }
333        slab.stats
334            .recycle_hits
335            .fetch_add(1, AtomicOrdering::Relaxed);
336        true
337    }
338
339    /// Returns a snapshot of slab occupancy and request counters for this slab
340    /// set.
341    pub fn stats(&self) -> FBufSlabsStats {
342        let classes = self
343            .slabs
344            .iter()
345            .enumerate()
346            .map(|(index, slab)| {
347                let size = Self::slab_size(index);
348                let available_buffers = slab.buffers.len();
349                slab.stats.snapshot(size, available_buffers)
350            })
351            .collect::<Vec<_>>();
352
353        FBufSlabsStats {
354            cached_buffers: classes.iter().map(|class| class.available_buffers).sum(),
355            fallback_alloc_requests: self.fallback_alloc_requests.load(AtomicOrdering::Relaxed),
356            fallback_recycle_requests: self.fallback_recycle_requests.load(AtomicOrdering::Relaxed),
357            classes,
358        }
359    }
360
361    fn request_index(requested_capacity: usize) -> Option<usize> {
362        if requested_capacity == 0 || requested_capacity > Self::HIGHEST_SLAB_CLASS_CAPACITY {
363            return None;
364        }
365        let rounded = requested_capacity.max(FBuf::ALIGNMENT).next_power_of_two();
366        Some((rounded.trailing_zeros() - Self::MIN_SHIFT) as usize)
367    }
368
369    fn capacity_index(capacity: usize) -> Option<usize> {
370        if !(FBuf::ALIGNMENT..=Self::HIGHEST_SLAB_CLASS_CAPACITY).contains(&capacity)
371            || !capacity.is_power_of_two()
372        {
373            return None;
374        }
375        Some((capacity.trailing_zeros() - Self::MIN_SHIFT) as usize)
376    }
377
378    #[cfg(test)]
379    fn cached_buffers(&self, capacity: usize) -> usize {
380        Self::capacity_index(capacity)
381            .map(|index| self.slabs[index].buffers.len())
382            .unwrap_or_default()
383    }
384}
385
386impl Default for FBufSlabs {
387    fn default() -> Self {
388        Self::new(Self::DEFAULT_BYTES_PER_CLASS)
389    }
390}
391
392impl Drop for FBufSlabs {
393    fn drop(&mut self) {
394        for (index, slab) in self.slabs.iter_mut().enumerate() {
395            let size = Self::slab_size(index);
396            while let Some(ptr) = slab.buffers.pop() {
397                // SAFETY: Each pointer in `buffers` came from an allocation for
398                // this slab class's `size`, so deallocating it with the
399                // matching layout is correct.
400                unsafe {
401                    alloc::dealloc(ptr.ptr.as_ptr(), layout_for(size));
402                }
403            }
404        }
405    }
406}
407
408/// Installs a slab pool for the current thread and returns the previous one.
409///
410/// Passing `None` clears the thread-local override and restores use of the
411/// process-wide fallback slab set.
412pub fn set_thread_slab_pool(pool: Option<Arc<FBufSlabs>>) -> Option<Arc<FBufSlabs>> {
413    THREAD_SLAB_POOL.with(|current| current.replace(pool))
414}
415
416fn with_active_slab_pool<R>(f: impl FnOnce(&FBufSlabs) -> R) -> R {
417    let mut f = Some(f);
418
419    if let Ok(result) = TOKIO_FBUF_SLABS.try_with(|pool| f.take().unwrap()(pool)) {
420        return result;
421    }
422
423    if let Ok(Some(result)) = THREAD_SLAB_POOL.try_with(|pool| {
424        let pool = pool.borrow();
425        pool.as_ref().map(|pool| f.take().unwrap()(pool))
426    }) {
427        return result;
428    }
429
430    f.take().unwrap()(FALLBACK_SLAB_POOL.as_ref())
431}
432
433/// Attempts to satisfy an `FBuf` allocation request from the active slab set,
434/// falling back to a fresh allocation when the request is not slab-eligible or
435/// no cached buffer is available.
436pub(super) fn acquire_allocation(capacity: usize) -> (NonNull<u8>, usize) {
437    with_active_slab_pool(|pool| pool.try_take(capacity)).unwrap_or_else(|| {
438        let ptr = allocate_exact(capacity);
439        (ptr, capacity)
440    })
441}
442
443/// Attempts to recycle an `FBuf` allocation into the active slab set, falling
444/// back to immediate deallocation when the capacity is not slab-eligible or
445/// the target slab class is already full.
446pub(super) fn recycle_or_dealloc(ptr: NonNull<u8>, capacity: usize) {
447    if !with_active_slab_pool(|pool| pool.try_put(ptr, capacity)) {
448        // SAFETY: `ptr` is an owned allocation for `capacity` bytes produced
449        // by this module or by `FBuf`, and the fallback path deallocates it
450        // with the same layout that was used to allocate it.
451        unsafe {
452            alloc::dealloc(ptr.as_ptr(), layout_for(capacity));
453        }
454    }
455}
456
457fn allocate_exact(capacity: usize) -> NonNull<u8> {
458    let layout = layout_for(capacity);
459    // SAFETY: `layout` is constructed by `layout_for`, which enforces the
460    // invariants required by the allocator API.
461    let ptr = unsafe { alloc::alloc(layout) };
462    if ptr.is_null() {
463        alloc::handle_alloc_error(layout);
464    }
465    // SAFETY: The pointer was checked for null just above.
466    unsafe { NonNull::new_unchecked(ptr) }
467}
468
469pub(super) fn layout_for(capacity: usize) -> alloc::Layout {
470    // SAFETY: `FBuf::ALIGNMENT` is non-zero and power-of-two by the module
471    // const assertion, all callers pass capacities produced or
472    // validated by the surrounding `FBuf` allocation logic.
473    unsafe { alloc::Layout::from_size_align_unchecked(capacity, FBuf::ALIGNMENT) }
474}
475
476#[cfg(test)]
477mod tests {
478    use std::sync::Arc;
479
480    use crate::fbuf::FBuf;
481
482    use super::{FBufSlabs, TOKIO_FBUF_SLABS, set_thread_slab_pool};
483
484    #[test]
485    fn slab_pool_reuses_buffers_across_matching_size_classes() {
486        let pool = Arc::new(FBufSlabs::default());
487        let previous = set_thread_slab_pool(Some(pool));
488
489        let first = FBuf::with_capacity(4096);
490        let first_ptr = first.as_ptr();
491        drop(first);
492
493        let second = FBuf::with_capacity(3000);
494        assert_eq!(second.capacity(), 4096);
495        assert_eq!(second.as_ptr(), first_ptr);
496
497        set_thread_slab_pool(previous);
498    }
499
500    #[test]
501    fn slab_pool_has_fixed_capacity_per_size_class() {
502        let pool = Arc::new(FBufSlabs::new(4096));
503        let previous = set_thread_slab_pool(Some(pool.clone()));
504
505        let first = FBuf::with_capacity(4096);
506        let second = FBuf::with_capacity(4096);
507        drop(first);
508        drop(second);
509
510        assert_eq!(pool.cached_buffers(4096), 1);
511
512        set_thread_slab_pool(previous);
513    }
514
515    #[test]
516    fn slab_pool_stats_track_reuse_and_fallbacks() {
517        let pool = Arc::new(FBufSlabs::new(4096));
518        let previous = set_thread_slab_pool(Some(pool.clone()));
519
520        let first = FBuf::with_capacity(4096);
521        drop(first);
522
523        let second = FBuf::with_capacity(3000);
524        drop(second);
525
526        let big = FBuf::with_capacity(FBufSlabs::HIGHEST_SLAB_CLASS_CAPACITY + FBuf::ALIGNMENT);
527        drop(big);
528
529        let stats = pool.stats();
530        let class = stats
531            .classes
532            .iter()
533            .find(|class| class.size == 4096)
534            .unwrap();
535
536        assert_eq!(stats.alloc_requests(), 3);
537        assert_eq!(stats.mallocs_saved(), 1);
538        assert_eq!(stats.malloc_fallbacks(), 2);
539        assert_eq!(stats.recycle_requests(), 3);
540        assert_eq!(stats.frees_saved(), 2);
541        assert_eq!(stats.free_fallbacks(), 1);
542        assert_eq!(stats.cached_buffers, 1);
543        assert_eq!(stats.fallback_alloc_requests, 1);
544        assert_eq!(stats.fallback_recycle_requests, 1);
545
546        assert_eq!(class.alloc_requests, 2);
547        assert_eq!(class.alloc_hits, 1);
548        assert_eq!(class.malloc_fallbacks(), 1);
549        assert_eq!(class.recycle_requests, 2);
550        assert_eq!(class.recycle_hits, 2);
551        assert_eq!(class.free_fallbacks(), 0);
552        assert_eq!(class.available_buffers, 1);
553        set_thread_slab_pool(previous);
554    }
555
556    #[tokio::test(flavor = "current_thread")]
557    async fn task_local_slab_takes_precedence() {
558        let thread_pool = Arc::new(FBufSlabs::default());
559        let task_pool = Arc::new(FBufSlabs::default());
560        let previous = set_thread_slab_pool(Some(thread_pool.clone()));
561
562        TOKIO_FBUF_SLABS
563            .scope(task_pool.clone(), async {
564                let first = FBuf::with_capacity(4096);
565                let first_ptr = first.as_ptr();
566                drop(first);
567
568                tokio::task::yield_now().await;
569
570                let second = FBuf::with_capacity(3000);
571                assert_eq!(second.capacity(), 4096);
572                assert_eq!(second.as_ptr(), first_ptr);
573            })
574            .await;
575
576        assert_eq!(task_pool.cached_buffers(4096), 1);
577        assert_eq!(thread_pool.cached_buffers(4096), 0);
578
579        let stats = task_pool.stats();
580        let class = stats
581            .classes
582            .iter()
583            .find(|class| class.size == 4096)
584            .unwrap();
585
586        assert_eq!(class.alloc_requests, 2);
587        assert_eq!(class.alloc_hits, 1);
588        assert_eq!(class.recycle_requests, 2);
589        assert_eq!(class.recycle_hits, 2);
590
591        assert_eq!(thread_pool.stats().alloc_requests(), 0);
592        assert_eq!(thread_pool.stats().recycle_requests(), 0);
593
594        set_thread_slab_pool(previous);
595    }
596}