use crate::{cache::CacheLine, size_class::Class};
use core::{cell::Cell, ptr};
#[derive(Debug)]
#[repr(C)]
pub(crate) struct Block {
pub(crate) next: *mut Self,
}
const MAX_BLOCKS: usize = 4096;
const BITMAP_WORDS: usize = MAX_BLOCKS / 64;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum List {
None = 0,
Active = 1,
Full = 2,
}
pub(crate) struct Slab {
_line: [CacheLine; 0],
next: Cell<*const Self>,
prev: Cell<*const Self>,
start: Cell<*mut u8>,
free_len: Cell<u32>,
capacity: Cell<u32>,
cursor: Cell<u16>,
zero_from: Cell<u16>,
class: Cell<u8>,
list: Cell<List>,
filled: Cell<bool>,
bits: [Cell<u64>; BITMAP_WORDS],
}
impl core::fmt::Debug for Slab {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Slab").finish_non_exhaustive()
}
}
unsafe impl Sync for Slab {}
impl Slab {
#[cfg(any(test, feature = "testing"))]
pub(crate) const fn new() -> Self {
Self {
_line: [],
next: Cell::new(ptr::null()),
prev: Cell::new(ptr::null()),
start: Cell::new(ptr::null_mut()),
free_len: Cell::new(0),
capacity: Cell::new(0),
cursor: Cell::new(0),
zero_from: Cell::new(0),
class: Cell::new(0),
list: Cell::new(List::None),
filled: Cell::new(false),
bits: [const { Cell::new(0) }; BITMAP_WORDS],
}
}
pub(crate) const unsafe fn owned(&self) -> Owned<'_> {
Owned(self)
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Owned<'a>(&'a Slab);
impl<'a> Owned<'a> {
pub(crate) const fn slab(self) -> &'a Slab {
self.0
}
pub(crate) unsafe fn init(self, class: Class, start: *mut u8, zeroed: bool) {
let slab = self.0;
let capacity = class.blocks_per_slab();
debug_assert!(capacity <= MAX_BLOCKS);
slab.next.set(ptr::null());
slab.prev.set(ptr::null());
slab.start.set(start);
slab.free_len.set(capacity as u32);
slab.capacity.set(capacity as u32);
slab.cursor.set(0);
slab.zero_from.set(if zeroed { 0 } else { capacity as u16 });
slab.class.set(class.index() as u8);
slab.list.set(List::None);
slab.filled.set(false);
for (index, word) in slab.bits.iter().enumerate() {
let below = capacity.saturating_sub(index * 64);
word.set(if below >= 64 { u64::MAX } else { (1 << below) - 1 });
}
}
pub(crate) fn class(self) -> Class {
Class::from_index(usize::from(self.0.class.get()))
}
pub(crate) const fn start(self) -> *mut u8 {
self.0.start.get()
}
pub(crate) const fn used(self) -> u32 {
self.0.capacity.get() - self.0.free_len.get()
}
pub(crate) const fn is_exhausted(self) -> bool {
self.0.free_len.get() == 0
}
pub(crate) const fn mark_filled(self) -> bool {
!self.0.filled.replace(true)
}
pub(crate) const fn was_filled(self) -> bool {
self.0.filled.get()
}
pub(crate) const fn list(self) -> List {
self.0.list.get()
}
pub(crate) fn set_list(self, list: List) {
self.0.list.set(list);
}
pub(crate) const fn next(self) -> *const Slab {
self.0.next.get()
}
pub(crate) fn set_next(self, next: *const Slab) {
self.0.next.set(next);
}
pub(crate) const fn prev(self) -> *const Slab {
self.0.prev.get()
}
pub(crate) fn set_prev(self, prev: *const Slab) {
self.0.prev.set(prev);
}
pub(crate) unsafe fn push(self, block: *mut Block) {
let mut returns = Returns::new(self);
unsafe { returns.add(block) };
returns.finish();
}
pub(crate) fn take(self, max: usize, mut out: impl FnMut(*mut u8)) -> usize {
let slab = self.0;
let want = max.min(slab.free_len.get() as usize);
let (start, size) = (slab.start.get(), self.class().block_size());
let mut word = usize::from(slab.cursor.get());
let mut taken = 0;
let mut last = 0;
while taken < want {
let mut bits = slab.bits[word].get();
if bits == u64::MAX && want - taken >= 64 {
let mut block = unsafe { start.add(word * 64 * size) };
for _ in 0..64 {
out(block);
block = block.wrapping_add(size);
}
slab.bits[word].set(0);
taken += 64;
last = word * 64 + 63;
word += 1;
continue;
}
while bits != 0 && taken < want {
let index = word * 64 + bits.trailing_zeros() as usize;
out(unsafe { start.add(index * size) });
bits &= bits - 1;
taken += 1;
last = index;
}
slab.bits[word].set(bits);
if bits == 0 {
word += 1;
}
}
slab.cursor.set(word.min(BITMAP_WORDS - 1) as u16);
slab.free_len.set(slab.free_len.get() - taken as u32);
if taken != 0 {
slab.zero_from.set(slab.zero_from.get().max(last as u16 + 1));
}
taken
}
pub(crate) fn take_one(self) -> Option<(*mut u8, bool)> {
let zero_from = usize::from(self.0.zero_from.get());
let mut block = None;
self.take(1, |taken| block = Some(taken));
let block = block?;
let index = (block.addr() - self.start().addr()) / self.class().block_size();
Some((block, index >= zero_from))
}
#[cfg(any(test, feature = "testing"))]
pub(crate) fn check(self) -> usize {
let slab = self.0;
let capacity = slab.capacity.get() as usize;
let mut count = 0;
for (word, bits) in slab.bits.iter().enumerate() {
let bits = bits.get();
assert!(
bits == 0 || word >= usize::from(slab.cursor.get()),
"a free block sits below the cursor"
);
let valid = capacity.saturating_sub(word * 64);
if valid < 64 {
assert_eq!(bits >> valid, 0, "a bit past the last block is set");
}
count += bits.count_ones() as usize;
}
assert_eq!(count, slab.free_len.get() as usize, "free blocks disagree with the counter");
count
}
#[cfg(any(test, feature = "testing"))]
pub(crate) fn is_free(self, block: *mut u8) -> bool {
let index = self.class().index_of(block.addr() - self.0.start.get().addr());
self.0.bits[index / 64].get() & 1 << (index % 64) != 0
}
}
pub(crate) struct Returns<'a> {
slab: Owned<'a>,
start: usize,
class: Class,
word: usize,
mask: u64,
count: u32,
lowest: usize,
}
impl<'a> Returns<'a> {
#[inline(always)]
pub(crate) fn new(slab: Owned<'a>) -> Self {
let lowest = usize::from(slab.0.cursor.get());
Self {
slab,
start: slab.start().addr(),
class: slab.class(),
word: 0,
mask: 0,
count: 0,
lowest,
}
}
pub(crate) const fn slab(&self) -> Owned<'a> {
self.slab
}
#[inline(always)]
pub(crate) unsafe fn add(&mut self, block: *mut Block) {
let index = self.class.index_of(block.addr() - self.start);
let word = index / 64;
if word != self.word {
self.store();
self.word = word;
}
debug_assert_eq!(self.mask & 1 << (index % 64), 0, "a block came back twice");
self.mask |= 1 << (index % 64);
self.count += 1;
}
#[inline(always)]
fn store(&mut self) {
if self.mask != 0 {
let bits = &self.slab.0.bits[self.word];
debug_assert_eq!(bits.get() & self.mask, 0, "a block came back twice");
bits.set(bits.get() | self.mask);
self.lowest = self.lowest.min(self.word);
self.mask = 0;
}
}
#[inline(always)]
pub(crate) fn finish(mut self) -> Owned<'a> {
self.store();
let slab = self.slab.0;
slab.free_len.set(slab.free_len.get() + self.count);
slab.cursor.set(self.lowest as u16);
self.slab
}
}
#[cfg(all(test, not(loom)))]
mod test {
use super::*;
use crate::testing::Buffer;
use core::mem::{align_of, size_of};
use std::vec::Vec;
#[test]
fn a_descriptor_fills_whole_cache_lines() {
let line = align_of::<CacheLine>();
assert_eq!(align_of::<Slab>(), line);
assert_eq!(size_of::<Slab>() % line, 0);
}
#[test]
fn the_bitmap_covers_the_fullest_slab() {
for index in 0..crate::size_class::CLASSES {
assert!(Class::from_index(index).blocks_per_slab() <= MAX_BLOCKS);
}
}
struct Fixture {
slab: Slab,
_memory: Buffer,
}
impl Fixture {
fn new(size: usize) -> Self {
let class = Class::for_size(size);
let memory = Buffer::new(class.slab_chunks() << crate::chunks::CHUNK_SHIFT);
let slab = Slab::new();
unsafe { slab.owned().init(class, memory.as_ptr(), true) };
Self { slab, _memory: memory }
}
const fn owned(&self) -> Owned<'_> {
unsafe { self.slab.owned() }
}
fn take(&self, max: usize) -> Vec<*mut u8> {
let mut blocks = Vec::new();
assert_eq!(self.owned().take(max, |block| blocks.push(block)), blocks.len());
blocks
}
}
#[test]
fn a_fresh_slab_yields_every_block_once_in_address_order() {
for size in [16, 48, 1024, 3000, 60_000] {
let fixture = Fixture::new(size);
let capacity = Class::for_size(size).blocks_per_slab();
let blocks = fixture.take(usize::MAX);
assert_eq!(blocks.len(), capacity);
assert!(blocks.windows(2).all(|pair| pair[0] < pair[1]), "{size}");
assert!(fixture.owned().is_exhausted());
assert_eq!(fixture.owned().used(), capacity as u32);
assert!(fixture.take(1).is_empty());
assert_eq!(fixture.owned().check(), 0);
}
}
#[test]
fn returned_blocks_come_back_lowest_first() {
let fixture = Fixture::new(256);
let first = fixture.take(200);
unsafe {
fixture.owned().push(first[150].cast());
fixture.owned().push(first[3].cast());
}
assert_eq!(fixture.owned().used(), 198);
let again = fixture.take(3);
assert_eq!(again[..2], [first[3], first[150]]);
assert!(!first.contains(&again[2]), "then fresh blocks follow");
}
#[test]
fn an_all_zero_descriptor_is_an_unused_one() {
let zeroed: Slab = unsafe { core::mem::zeroed() };
let owned = Owned(&zeroed);
assert_eq!(owned.list(), List::None);
assert_eq!(owned.used(), 0);
assert!(owned.next().is_null() && owned.prev().is_null());
}
}