ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
//! A reference-counted buffer of elements whose memory is recycled by the
//! thread that frees it: the native backend allocates a buffer for every
//! array of more than a few elements (an observation grid, for example), and
//! a step of an environment would otherwise spend much of its time in the
//! allocator.

use std::alloc::{Layout, alloc_zeroed, dealloc, handle_alloc_error};
use std::cell::RefCell;
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicUsize, Ordering, fence};

use ruxla_kernels::{DType, Element};

/// The header before the elements.
#[repr(C)]
struct Header {
    count: AtomicUsize,
    len: usize,
    /// The size class of the allocation (see [`class_bytes`]), or
    /// [`UNPOOLED`].
    class: usize,
}

/// The alignment of allocations, enough for any element type.
const ALIGN: usize = 16;
/// The offset of the elements from the start of the allocation.
const DATA_OFFSET: usize = 32;
/// The number of size classes: allocations of 64 bytes to 64 << 13 = 512 KiB
/// (with the header) are recycled.
const CLASSES: usize = 14;
/// The number of free buffers a thread keeps per size class.
const KEEP: usize = 32;
/// The class of allocations that are not recycled.
const UNPOOLED: usize = usize::MAX;

const _: () = assert!(std::mem::size_of::<Header>() <= DATA_OFFSET);
const _: () = assert!(DATA_OFFSET.is_multiple_of(ALIGN));

/// The size in bytes of the allocations of a class.
const fn class_bytes(class: usize) -> usize {
    64 << class
}

/// The smallest class that holds `bytes`, or [`UNPOOLED`].
#[inline]
fn class_of(bytes: usize) -> usize {
    // The exponent of the next power of two of `bytes / 64`.
    let class = bytes
        .saturating_sub(1)
        .checked_ilog2()
        .map_or(0, |b| b as usize + 1)
        .saturating_sub(6);
    if class < CLASSES { class } else { UNPOOLED }
}

fn layout(bytes: usize) -> Layout {
    Layout::from_size_align(bytes, ALIGN).expect("a buffer size that fits in memory")
}

/// The free buffers of a thread, by size class.
struct Pool {
    free: [Vec<NonNull<u8>>; CLASSES],
}

impl Drop for Pool {
    fn drop(&mut self) {
        for (class, buffers) in self.free.iter_mut().enumerate() {
            for p in buffers.drain(..) {
                // SAFETY: the buffer was allocated with the layout of its
                // class and is owned by the pool.
                unsafe { dealloc(p.as_ptr(), layout(class_bytes(class))) };
            }
        }
    }
}

thread_local! {
    static POOL: RefCell<Pool> = const {
        RefCell::new(Pool {
            free: [const { Vec::new() }; CLASSES],
        })
    };
}

/// Allocates `bytes` (at least [`DATA_OFFSET`]) of class `class`.
fn allocate(class: usize, bytes: usize) -> NonNull<u8> {
    if class != UNPOOLED {
        let recycled = POOL
            .try_with(|p| p.borrow_mut().free[class].pop())
            .ok()
            .flatten();
        if let Some(p) = recycled {
            return p;
        }
    }
    let size = if class == UNPOOLED {
        bytes
    } else {
        class_bytes(class)
    };
    let layout = layout(size);
    // Zeroed, so that every byte of an allocation is initialized (which
    // `Shared::new_overwrite` relies on when the buffer is recycled).
    // SAFETY: the layout has a nonzero size (at least the header).
    let p = unsafe { alloc_zeroed(layout) };
    NonNull::new(p).unwrap_or_else(|| handle_alloc_error(layout))
}

/// Returns an allocation of class `class` (and `bytes` if unpooled) to the
/// thread's pool, or to the allocator.
///
/// # Safety
///
/// `p` must come from [`allocate`] with the same class and size, and must
/// not be used afterwards.
unsafe fn release(p: NonNull<u8>, class: usize, bytes: usize) {
    if class != UNPOOLED {
        let kept = POOL
            .try_with(|pool| {
                let mut pool = pool.borrow_mut();
                let free = &mut pool.free[class];
                if free.len() < KEEP {
                    free.push(p);
                    true
                } else {
                    false
                }
            })
            .unwrap_or(false);
        if kept {
            return;
        }
    }
    let size = if class == UNPOOLED {
        bytes
    } else {
        class_bytes(class)
    };
    // SAFETY: the caller's contract: `p` was allocated with this layout.
    unsafe { dealloc(p.as_ptr(), layout(size)) };
}

/// A shared buffer of `len` elements (like `Arc<[T]>`).
pub(crate) struct Shared<T: Element> {
    header: NonNull<Header>,
    _elements: PhantomData<[T]>,
}

// SAFETY: the elements are `Send + Sync` (`Element`), the reference count is
// atomic, and a buffer is mutated only through `get_mut`, which requires it
// to be unique.
unsafe impl<T: Element> Send for Shared<T> {}
// SAFETY: see above.
unsafe impl<T: Element> Sync for Shared<T> {}

impl<T: Element> Shared<T> {
    /// A new buffer of `len` elements, written by `init` (which gets them
    /// filled with `T::default()`, whose bits are zero for every element
    /// type).
    #[inline]
    pub(crate) fn new(len: usize, init: impl FnOnce(&mut [T])) -> Self {
        Self::with_init(len, true, init)
    }

    /// A new buffer of `len` elements, all of which `init` must write: it
    /// gets them with unspecified (but valid) values, so that the buffer
    /// need not be cleared first.
    #[inline]
    pub(crate) fn new_overwrite(len: usize, init: impl FnOnce(&mut [T])) -> Self {
        // Every bit pattern is a valid value of the other element types.
        Self::with_init(len, T::DTYPE == DType::Bool, init)
    }

    #[inline]
    fn with_init(len: usize, clear: bool, init: impl FnOnce(&mut [T])) -> Self {
        let bytes = DATA_OFFSET + len * std::mem::size_of::<T>();
        let class = class_of(bytes);
        let p = allocate(class, bytes);
        let header = p.cast::<Header>();
        // SAFETY: the allocation is large enough and aligned for the header
        // and `len` elements after `DATA_OFFSET`. Its bytes are initialized
        // (allocations are zeroed and then hold only elements), and they
        // are cleared unless every bit pattern is a valid `T`.
        unsafe {
            header.as_ptr().write(Header {
                count: AtomicUsize::new(1),
                len,
                class,
            });
            let data = p.as_ptr().add(DATA_OFFSET).cast::<T>();
            if clear {
                // `T::default()` is zero bits for every element type.
                std::ptr::write_bytes(data, 0, len);
            }
            init(std::slice::from_raw_parts_mut(data, len));
        }
        Self {
            header,
            _elements: PhantomData,
        }
    }

    /// `len` copies of `v`.
    #[inline]
    pub(crate) fn filled(len: usize, v: T) -> Self {
        // All bytes zero (`to_bits` holds the bits of the types of up to 8
        // bytes; `c128` is compared by its bytes).
        let zero = if T::DTYPE.size_in_bytes() <= 8 {
            v.to_bits() == 0
        } else {
            let mut bytes = Vec::with_capacity(16);
            v.write_bytes(&mut bytes);
            bytes.iter().all(|&b| b == 0)
        };
        if zero {
            return Self::new(len, |_| {});
        }
        Self::new_overwrite(len, |out| out.fill(v))
    }

    /// A copy of `v`.
    #[inline]
    pub(crate) fn from_slice(v: &[T]) -> Self {
        Self::new_overwrite(v.len(), |out| out.copy_from_slice(v))
    }

    fn header(&self) -> &Header {
        // SAFETY: the header is live while `self` holds a reference.
        unsafe { self.header.as_ref() }
    }

    fn data(&self) -> *mut T {
        // SAFETY: the elements start at `DATA_OFFSET` in the allocation.
        unsafe {
            self.header
                .as_ptr()
                .cast::<u8>()
                .add(DATA_OFFSET)
                .cast::<T>()
        }
    }

    /// The elements, mutable, if the buffer is not shared.
    #[inline]
    pub(crate) fn get_mut(&mut self) -> Option<&mut [T]> {
        if self.header().count.load(Ordering::Acquire) != 1 {
            return None;
        }
        let len = self.header().len;
        // SAFETY: the buffer is unique (count 1, and `&mut self`), so no
        // other reference to the elements exists.
        Some(unsafe { std::slice::from_raw_parts_mut(self.data(), len) })
    }
}

impl<T: Element> std::ops::Deref for Shared<T> {
    type Target = [T];
    #[inline]
    fn deref(&self) -> &[T] {
        // SAFETY: the `len` elements are initialized and live while `self`
        // holds a reference; they are not mutated while shared.
        unsafe { std::slice::from_raw_parts(self.data(), self.header().len) }
    }
}

impl<T: Element> Clone for Shared<T> {
    #[inline]
    fn clone(&self) -> Self {
        let old = self.header().count.fetch_add(1, Ordering::Relaxed);
        // As `Arc` does: abort before the count could overflow.
        if old > isize::MAX as usize {
            std::process::abort();
        }
        Self {
            header: self.header,
            _elements: PhantomData,
        }
    }
}

impl<T: Element> Drop for Shared<T> {
    #[inline]
    fn drop(&mut self) {
        // A count of 1 means that `self` is the only reference, which no
        // other thread can clone, so the buffer is freed without the atomic
        // decrement (the load synchronizes with the releases of the other
        // references, as the fence below does).
        if self.header().count.load(Ordering::Acquire) != 1 {
            if self.header().count.fetch_sub(1, Ordering::Release) != 1 {
                return;
            }
            // Synchronizes with the other references' releases, as `Arc`
            // does.
            fence(Ordering::Acquire);
        }
        let (class, len) = (self.header().class, self.header().len);
        let bytes = DATA_OFFSET + len * std::mem::size_of::<T>();
        // SAFETY: this was the last reference; the elements are `Copy` and
        // need no drop, and the allocation came from `allocate` with this
        // class and size.
        unsafe { release(self.header.cast::<u8>(), class, bytes) };
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classes_are_the_smallest_that_fit() {
        for bytes in 1..(1 << 20) {
            let expected = (0..CLASSES)
                .find(|&c| class_bytes(c) >= bytes)
                .unwrap_or(UNPOOLED);
            assert_eq!(class_of(bytes), expected, "{bytes}");
        }
    }

    #[test]
    fn element_defaults_are_zero_bits() {
        use ruxla_kernels::{bf16, f16};
        assert_eq!(f32::default().to_bits(), 0);
        assert_eq!(f64::default().to_bits(), 0);
        assert_eq!(f16::default().to_bits(), 0);
        assert_eq!(bf16::default().to_bits(), 0);
        assert_eq!(bool::default().to_bits(), 0);
        assert_eq!(i8::default().to_bits(), 0);
        assert_eq!(u64::default().to_bits(), 0);
    }

    #[test]
    fn overwritten_buffers_reuse_any_element_type() {
        // A recycled buffer that held `f32`s is handed to `u32` and `bool`
        // elements; `bool`s are cleared first (other bit patterns are not
        // valid), and the others see the old bits until `init` writes them.
        let a = Shared::<f32>::new_overwrite(20, |o| o.fill(1.5));
        drop(a);
        let b = Shared::<u32>::new_overwrite(20, |o| {
            assert!(o.iter().all(|&x| x == 1.5f32.to_bits()));
            o.fill(3);
        });
        assert!(b.iter().all(|&x| x == 3));
        drop(b);
        let c = Shared::<bool>::new_overwrite(80, |o| {
            assert!(o.iter().all(|&x| !x));
            o[7] = true;
        });
        assert!(c[7] && !c[6]);
        // A fresh allocation is zeroed beyond the elements too.
        let d = Shared::<u8>::new_overwrite(3, |o| o.fill(9));
        assert_eq!(&d[..], [9, 9, 9]);
    }

    #[test]
    fn buffers_are_shared_copied_and_recycled() {
        let a = Shared::<f32>::new(50, |o| o[3] = 1.5);
        assert_eq!(a.len(), 50);
        assert_eq!(a[3], 1.5);
        let mut b = a.clone();
        assert!(b.get_mut().is_none());
        drop(a);
        b.get_mut().unwrap()[0] = 2.0;
        assert_eq!(b[0], 2.0);
        let p = b.header;
        drop(b);
        // The same class reuses the freed buffer, filled anew.
        let c = Shared::<f32>::new(40, |_| {});
        assert_eq!(c.header, p);
        assert!(c.iter().all(|&x| x == 0.0));
        // Large buffers go to the allocator.
        let d = Shared::<u8>::new(1 << 20, |o| o[12345] = 7);
        assert_eq!(d[12345], 7);
        // Buffers freed on another thread are recycled there.
        let e = Shared::<f64>::from_slice(&[1.0, 2.0, 3.0]);
        let f = e.clone();
        std::thread::spawn(move || assert_eq!(f[2], 3.0))
            .join()
            .unwrap();
        assert_eq!(&e[..], [1.0, 2.0, 3.0]);
    }
}