use core::ptr::NonNull;
use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::alloc::{Layout, alloc_zeroed, dealloc, handle_alloc_error};
use crate::header::Header;
use crate::layout::{BITS, BLOCK, GRANULE, GRANULES, LINE, LINES};
#[repr(C)]
struct Meta {
lines: [AtomicU32; LINES],
starts: [AtomicU64; GRANULES / BITS],
live: AtomicU32,
evacuate: AtomicBool,
listed: AtomicBool,
}
const REUSED: u32 = u32::MAX;
pub(crate) enum State {
Empty,
Recyclable,
Full,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct Block(NonNull<Meta>);
unsafe impl Send for Block {}
unsafe impl Sync for Block {}
impl Block {
const LAYOUT: Layout = match Layout::from_size_align(BLOCK, BLOCK) {
Ok(layout) => layout,
Err(_) => panic!("块的大小 / 对齐不合法"),
};
pub(crate) const FIRST_LINE: usize = size_of::<Meta>().div_ceil(LINE);
pub(crate) fn new() -> Self {
let p = unsafe { alloc_zeroed(Self::LAYOUT) };
let b = Self(NonNull::new(p.cast()).unwrap_or_else(|| handle_alloc_error(Self::LAYOUT)));
b.reused();
b
}
pub(crate) fn reused(self) {
self.meta().live.store(REUSED, Ordering::Relaxed);
}
pub(crate) fn live_since_sweep(self) -> Option<usize> {
let live = self.meta().live.load(Ordering::Relaxed);
(live != REUSED).then_some(live as usize)
}
pub(crate) fn list(self) -> bool {
!self.meta().listed.swap(true, Ordering::AcqRel)
}
pub(crate) fn unlist(self) {
self.meta().listed.store(false, Ordering::Release);
}
pub(crate) fn clear_start(self, p: *const u8) {
let g = self.offset(p) / GRANULE;
self.meta().starts[g / BITS].fetch_and(!(1 << (g % BITS)), Ordering::Relaxed);
}
pub(crate) unsafe fn recompute_lines(self, epoch: u32) -> bool {
let meta = self.meta();
let reused = meta.live.load(Ordering::Relaxed) == REUSED;
for line in &meta.lines {
line.store(0, Ordering::Relaxed);
}
let mut live = 0;
for (w, word) in meta.starts.iter().enumerate() {
let mut bits = word.load(Ordering::Relaxed);
while bits != 0 {
let bit = bits.trailing_zeros() as usize;
bits &= bits - 1;
let p = self.base().wrapping_add((w * BITS + bit) * GRANULE);
let h = unsafe { &*p.cast::<Header>() };
if h.is_marked(epoch) {
self.mark_lines(p, h.bytes(), epoch);
live += h.bytes();
}
}
}
if reused {
return false;
}
meta.live.store(u32::try_from(live).unwrap_or(REUSED - 1), Ordering::Relaxed);
meta.lines[Self::FIRST_LINE..].iter().any(|l| l.load(Ordering::Relaxed) != epoch)
}
pub(crate) fn set_evacuate(self) {
self.meta().evacuate.store(true, Ordering::Relaxed);
}
pub(crate) fn is_evacuating(self) -> bool {
self.meta().evacuate.load(Ordering::Relaxed)
}
pub(crate) unsafe fn release(self) {
unsafe { dealloc(self.0.as_ptr().cast(), Self::LAYOUT) };
}
pub(crate) fn containing(p: *const u8) -> Self {
let base = p.map_addr(|a| a & !(BLOCK - 1)).cast_mut().cast::<Meta>();
Self(unsafe { NonNull::new_unchecked(base) })
}
fn meta(&self) -> &Meta {
unsafe { self.0.as_ref() }
}
fn base(self) -> *mut u8 {
self.0.as_ptr().cast()
}
pub(crate) fn line(self, i: usize) -> *mut u8 {
self.base().wrapping_add(i * LINE)
}
fn offset(self, p: *const u8) -> usize {
p.addr() - self.base().addr()
}
pub(crate) fn mark_lines(self, p: *const u8, bytes: usize, epoch: u32) {
let first = self.offset(p) / LINE;
let last = (self.offset(p) + bytes - 1) / LINE;
for line in &self.meta().lines[first..=last] {
line.store(epoch, Ordering::Relaxed);
}
}
pub(crate) fn set_start(self, p: *const u8) {
let g = self.offset(p) / GRANULE;
self.meta().starts[g / BITS].fetch_or(1 << (g % BITS), Ordering::Relaxed);
}
pub(crate) fn hole(self, from: usize, epoch: u32) -> Option<(usize, usize)> {
let lines = &self.meta().lines;
let free = |i: usize| lines[i].load(Ordering::Relaxed) < epoch;
let start = (from..LINES).find(|&i| free(i))?;
let end = (start..LINES).find(|&i| !free(i)).unwrap_or(LINES);
Some((start, end))
}
pub(crate) unsafe fn sweep(self, epoch: u32) -> (State, usize) {
let mut live = 0;
for (w, word) in self.meta().starts.iter().enumerate() {
let mut bits = word.load(Ordering::Relaxed);
let mut dead = 0u64;
while bits != 0 {
let bit = bits.trailing_zeros() as usize;
bits &= bits - 1;
let header = self.base().wrapping_add((w * BITS + bit) * GRANULE).cast::<Header>().cast_const();
let h = unsafe { &*header };
if h.is_forwarded() {
dead |= 1 << bit;
} else if h.is_marked(epoch) {
live += h.bytes();
} else {
unsafe { Header::finalize(header) };
dead |= 1 << bit;
}
}
if dead != 0 {
word.fetch_and(!dead, Ordering::Relaxed);
}
}
let lines = &self.meta().lines[Self::FIRST_LINE..];
let used = lines.iter().filter(|l| l.load(Ordering::Relaxed) == epoch).count();
let state = match used {
0 => State::Empty,
n if n == lines.len() => State::Full,
_ => State::Recyclable,
};
self.meta().live.store(u32::try_from(live).unwrap_or(REUSED - 1), Ordering::Relaxed);
self.meta().evacuate.store(false, Ordering::Relaxed);
(state, live)
}
}