use core::mem::needs_drop;
use core::sync::atomic::{AtomicU32, Ordering};
use crossbeam_utils::Backoff;
use crate::trace::TracerInternal;
use crate::Trace;
use crate::layout::GRANULE;
use crate::trace::Tracer;
const SIZE_BITS: u32 = 24;
const SIZE_MASK: u32 = (1 << SIZE_BITS) - 1;
const RC_BITS: u32 = 6;
const RC_SHIFT: u32 = SIZE_BITS;
const RC_MAX: u32 = (1 << RC_BITS) - 1;
const RC_MASK: u32 = RC_MAX << RC_SHIFT;
const PARITY_BIT: u32 = 1 << (RC_SHIFT + RC_BITS);
const LARGE_BIT: u32 = 1 << 31;
const FORWARDED: u32 = 1 << 31;
const BUSY: u32 = 1 << 30;
pub const MAX_EPOCH: u32 = BUSY - 1;
#[repr(C)]
pub struct Core {
mark: AtomicU32,
info: AtomicU32,
}
#[repr(C)]
pub struct Header {
core: Core,
visit: unsafe fn(*mut u8, &mut Tracer<'_>),
drop: Option<unsafe fn(*mut u8)>,
}
pub const HEADER: usize = size_of::<Header>();
const _: () = assert!(HEADER.is_multiple_of(GRANULE), "对象数据要按粒度对齐");
const _: () = assert!(size_of::<Option<unsafe fn(*mut u8)>>() == size_of::<*const Header>(), "转发地址要放得进 drop 那个字");
pub enum Claim {
Mine,
Moved(*const Header),
}
impl core::ops::Deref for Header {
type Target = Core;
fn deref(&self) -> &Core {
&self.core
}
}
impl Header {
pub fn new<T: Trace>(bytes: usize, large: bool, mark: u32) -> Self {
Self {
core: Core::new(bytes, large, mark),
visit: Self::visit_as::<T>,
drop: needs_drop::<T>().then_some(Self::drop_as::<T> as unsafe fn(*mut u8)),
}
}
unsafe fn visit_as<T: Trace>(data: *mut u8, t: &mut Tracer<'_>) {
if t.relocating() {
unsafe { &mut *data.cast::<T>() }.relocate(t);
} else {
unsafe { &*data.cast::<T>() }.trace(t);
}
}
unsafe fn drop_as<T>(data: *mut u8) {
unsafe { data.cast::<T>().drop_in_place() };
}
pub fn data(this: *const Self) -> *mut u8 {
this.cast::<u8>().cast_mut().wrapping_add(HEADER)
}
pub fn of(data: *const u8) -> *const Self {
data.wrapping_sub(HEADER).cast()
}
}
impl Core {
pub fn new(bytes: usize, large: bool, mark: u32) -> Self {
let granules = u32::try_from(bytes / GRANULE).expect("对象太大");
assert!(granules <= SIZE_MASK, "对象太大(单个对象至多 128 MiB)");
Self { mark: AtomicU32::new(mark), info: AtomicU32::new(granules | if large { LARGE_BIT } else { 0 }) }
}
pub fn bytes(&self) -> usize {
(self.info.load(Ordering::Relaxed) & SIZE_MASK) as usize * GRANULE
}
pub fn is_large(&self) -> bool {
self.info.load(Ordering::Relaxed) & LARGE_BIT != 0
}
pub fn mark(&self, epoch: u32) -> bool {
self.mark.load(Ordering::Relaxed) != epoch && self.mark.swap(epoch, Ordering::AcqRel) != epoch
}
pub fn is_marked(&self, epoch: u32) -> bool {
self.mark.load(Ordering::Acquire) == epoch
}
pub fn rc_inc(&self, parity: bool) {
let parity = if parity { PARITY_BIT } else { 0 };
let mut word = self.info.load(Ordering::Relaxed);
loop {
let rc = if word & PARITY_BIT == parity { (word & RC_MASK) >> RC_SHIFT } else { 0 };
if rc == RC_MAX {
return;
}
let new = (word & !(RC_MASK | PARITY_BIT)) | parity | ((rc + 1) << RC_SHIFT);
match self.info.compare_exchange_weak(word, new, Ordering::AcqRel, Ordering::Relaxed) {
Ok(_) => return,
Err(now) => word = now,
}
}
}
pub fn rc_inc_exclusive(&self, parity: bool) {
let parity = if parity { PARITY_BIT } else { 0 };
let word = self.info.load(Ordering::Relaxed);
let rc = if word & PARITY_BIT == parity { (word & RC_MASK) >> RC_SHIFT } else { 0 };
if rc < RC_MAX {
self.info.store((word & !(RC_MASK | PARITY_BIT)) | parity | ((rc + 1) << RC_SHIFT), Ordering::Relaxed);
}
}
pub fn rc_dec(&self, parity: bool) -> bool {
let parity = if parity { PARITY_BIT } else { 0 };
let mut word = self.info.load(Ordering::Relaxed);
loop {
if word & PARITY_BIT != parity {
return false;
}
let rc = (word & RC_MASK) >> RC_SHIFT;
if rc == RC_MAX || rc == 0 {
return false;
}
let new = (word & !RC_MASK) | ((rc - 1) << RC_SHIFT);
match self.info.compare_exchange_weak(word, new, Ordering::AcqRel, Ordering::Relaxed) {
Ok(_) => return rc == 1,
Err(now) => word = now,
}
}
}
pub fn is_forwarded(&self) -> bool {
self.mark.load(Ordering::Acquire) & FORWARDED != 0
}
pub fn set_mark(&self, epoch: u32) {
self.mark.store(epoch, Ordering::Release);
}
}
impl Header {
pub fn claim(&self) -> Claim {
let backoff = Backoff::new();
loop {
let word = self.mark.load(Ordering::Acquire);
if word & FORWARDED != 0 {
return Claim::Moved(self.forwardee());
}
if word & BUSY != 0 {
backoff.snooze();
continue;
}
if self.mark.compare_exchange_weak(word, BUSY, Ordering::AcqRel, Ordering::Acquire).is_ok() {
return Claim::Mine;
}
}
}
pub unsafe fn forward(this: *const Self, to: *const Self) {
unsafe { (&raw const (*this).drop).cast_mut().cast::<*const Self>().write(to) };
unsafe { &*this }.core.mark.store(FORWARDED, Ordering::Release);
}
fn forwardee(&self) -> *const Self {
unsafe { (&raw const self.drop).cast::<*const Self>().read() }
}
pub unsafe fn visit(this: *const Self, t: &mut Tracer<'_>) {
unsafe { ((*this).visit)(Self::data(this), t) };
}
pub unsafe fn finalize(this: *const Self) {
if let Some(drop) = unsafe { (*this).drop } {
unsafe { drop(Self::data(this)) };
}
}
}