use core::mem::needs_drop;
use core::ptr::NonNull;
use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::alloc::{Layout, handle_alloc_error};
#[cfg(any(not(target_os = "linux"), miri))]
use std::alloc::{alloc, dealloc};
#[cfg(all(target_os = "linux", not(miri)))]
use crossbeam_deque::{Injector, Steal};
use crossbeam_utils::Backoff;
use crate::Trace;
use crate::mark::{Tracer, TracerInternal};
#[cfg(target_os = "linux")]
use crate::shm::WINDOW;
pub const BLOCK: usize = 32 * 1024;
pub const LINE: usize = 256;
pub const LINES: usize = BLOCK / LINE;
pub const GRANULE: usize = 8;
pub const GRANULES: usize = BLOCK / GRANULE;
pub const BITS: usize = u64::BITS as usize;
pub const START_SPAN: usize = BITS * GRANULE;
pub const LARGE: usize = BLOCK / 2;
#[cfg(all(target_os = "linux", not(miri)))]
pub const LARGE_MMAP: usize = 64 * 1024;
pub const UNITS_PER_WORKER: usize = 8;
pub const MIN_TRIGGER: usize = 4 * 1024 * 1024;
pub const GROWTH: usize = 2;
pub const YOUNG_PER_FULL: usize = 4;
pub const YOUNG_PER_FULL_RC: usize = 16;
pub const EVACUATE_LIVE: usize = BLOCK / 2;
pub const EVACUATE_MIN: usize = 4;
pub const EVACUATE_MAX: usize = usize::MAX;
pub const FRAG_NUM: usize = 3;
pub const FRAG_DEN: usize = 2;
pub const MIN_SPARE_BLOCKS: usize = 4;
pub const OVERFLOW_TRIES: usize = 8;
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 rc_stick(&self, parity: bool) {
let parity = if parity { PARITY_BIT } else { 0 };
self.info.fetch_update(Ordering::AcqRel, Ordering::Relaxed, |word| Some((word & !(RC_MASK | PARITY_BIT)) | parity | RC_MASK)).ok();
}
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);
}
pub fn survivor(this: *const Self, epoch: u32) -> Option<*const Self> {
let h = unsafe { &*this };
if h.is_forwarded() {
Some(h.forwardee())
} else {
h.is_marked(epoch).then_some(this)
}
}
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)) };
}
}
}
#[repr(C)]
struct Meta {
lines: [AtomicU32; LINES],
starts: [AtomicU64; GRANULES / BITS],
live: AtomicU32,
evacuate: AtomicBool,
listed: AtomicBool,
}
pub trait Finalize {
unsafe fn finalize(object: *const Core);
}
impl Finalize for Header {
unsafe fn finalize(object: *const Core) {
unsafe { Header::finalize(object.cast()) };
}
}
const REUSED: u32 = u32::MAX;
#[derive(Clone, Copy)]
pub enum State {
Empty,
Recyclable,
Full,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub 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 const FIRST_LINE: usize = size_of::<Meta>().div_ceil(LINE);
pub fn new(pages: &Pages) -> Self {
let b = Self(pages.take());
unsafe { b.0.as_ptr().write_bytes(0, 1) };
b.reused();
b
}
#[cfg(target_os = "linux")]
pub unsafe fn at(p: *mut u8) -> Self {
Self(unsafe { NonNull::new_unchecked(p.cast()) })
}
#[cfg(target_os = "linux")]
pub unsafe fn reset(self) {
unsafe { self.0.as_ptr().write_bytes(0, 1) };
}
pub fn reused(self) {
self.meta().live.store(REUSED, Ordering::Relaxed);
}
pub fn live_since_sweep(self) -> Option<usize> {
let live = self.meta().live.load(Ordering::Relaxed);
(live != REUSED).then_some(live as usize)
}
pub fn list(self) -> bool {
!self.meta().listed.swap(true, Ordering::AcqRel)
}
pub fn unlist(self) {
self.meta().listed.store(false, Ordering::Release);
}
pub 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 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::<Core>() };
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 fn set_evacuate(self) {
self.meta().evacuate.store(true, Ordering::Relaxed);
}
pub fn pin(self) -> bool {
self.meta().evacuate.swap(false, Ordering::Relaxed)
}
pub fn is_evacuating(self) -> bool {
self.meta().evacuate.load(Ordering::Relaxed)
}
pub unsafe fn release(self, pages: &Pages) {
unsafe { pages.give(self.0) };
}
pub 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 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 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 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 fn set_start_owned(self, p: *const u8) {
let g = self.offset(p) / GRANULE;
let word = &self.meta().starts[g / BITS];
word.store(word.load(Ordering::Relaxed) | 1 << (g % BITS), Ordering::Relaxed);
}
pub unsafe fn discard_free_lines(self, epoch: u32) {
#[cfg(all(target_os = "linux", not(miri)))]
{
const PER_PAGE: usize = PAGE / LINE;
let mut from = PER_PAGE.max(Self::FIRST_LINE);
while let Some((start, end)) = self.hole(from, epoch) {
let first = start.next_multiple_of(PER_PAGE);
let last = end / PER_PAGE * PER_PAGE;
if first < last {
unsafe { libc::madvise(self.line(first).cast(), (last - first) * LINE, libc::MADV_DONTNEED) };
}
from = end;
}
}
#[cfg(not(all(target_os = "linux", not(miri))))]
let _ = (self, epoch);
}
pub fn has_hole(self, bytes: usize, epoch: u32) -> bool {
let need = bytes.div_ceil(LINE);
let mut from = Self::FIRST_LINE;
while let Some((start, end)) = self.hole(from, epoch) {
if end - start >= need {
return true;
}
from = end;
}
false
}
pub 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 unsafe fn sweep<K: Finalize>(self, epoch: u32, mut deferred: Option<&mut Vec<usize>>) -> (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::<Core>().cast_const();
let h = unsafe { &*header };
if h.is_forwarded() {
dead |= 1 << bit;
} else if h.is_marked(epoch) {
live += h.bytes();
} else {
match deferred.as_deref_mut() {
Some(list) => list.push(header.expose_provenance()),
None => unsafe { K::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)
}
}
#[cfg(all(target_os = "linux", not(miri)))]
const CHUNK: usize = 2 * 1024 * 1024;
#[derive(Default)]
pub struct Pages {
#[cfg(all(target_os = "linux", not(miri)))]
free: Injector<usize>,
#[cfg(all(target_os = "linux", not(miri)))]
chunks: Injector<usize>,
}
impl Pages {
#[cfg(all(target_os = "linux", not(miri)))]
fn take(&self) -> NonNull<Meta> {
loop {
match self.free.steal() {
Steal::Success(addr) => return unsafe { NonNull::new_unchecked(core::ptr::with_exposed_provenance_mut(addr)) },
Steal::Retry => {}
Steal::Empty => break,
}
}
let base = self.map_chunk();
for i in 1..CHUNK / BLOCK {
self.free.push(base.wrapping_add(i * BLOCK).expose_provenance());
}
unsafe { NonNull::new_unchecked(base.cast()) }
}
#[cfg(all(target_os = "linux", not(miri)))]
fn map_chunk(&self) -> *mut u8 {
let len = CHUNK + BLOCK;
let raw = unsafe { libc::mmap(core::ptr::null_mut(), len, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE, -1, 0) };
if raw == libc::MAP_FAILED {
handle_alloc_error(Block::LAYOUT);
}
let raw = raw.cast::<u8>();
let head = raw.align_offset(BLOCK);
let base = raw.wrapping_add(head);
unsafe {
if head > 0 {
libc::munmap(raw.cast(), head);
}
let tail = BLOCK - head;
if tail > 0 {
libc::munmap(base.wrapping_add(CHUNK).cast(), tail);
}
}
self.chunks.push(base.expose_provenance());
base
}
#[cfg(all(target_os = "linux", not(miri)))]
unsafe fn give(&self, p: NonNull<Meta>) {
unsafe { libc::madvise(p.as_ptr().cast(), BLOCK, libc::MADV_DONTNEED) };
self.free.push(p.as_ptr().expose_provenance());
}
#[cfg(any(not(target_os = "linux"), miri))]
#[expect(clippy::unused_self, reason = "与 Linux 版同签名")]
fn take(&self) -> NonNull<Meta> {
let p = unsafe { alloc(Block::LAYOUT) };
NonNull::new(p.cast()).unwrap_or_else(|| handle_alloc_error(Block::LAYOUT))
}
#[cfg(any(not(target_os = "linux"), miri))]
#[expect(clippy::unused_self, reason = "与 Linux 版同签名")]
unsafe fn give(&self, p: NonNull<Meta>) {
unsafe { dealloc(p.as_ptr().cast(), Block::LAYOUT) };
}
}
#[cfg(all(target_os = "linux", not(miri)))]
impl Drop for Pages {
fn drop(&mut self) {
loop {
match self.chunks.steal() {
Steal::Success(addr) => unsafe {
libc::munmap(core::ptr::with_exposed_provenance_mut::<libc::c_void>(addr), CHUNK);
},
Steal::Retry => {}
Steal::Empty => return,
}
}
}
}
#[cfg(target_os = "linux")]
pub const MAGIC: u64 = u64::from_le_bytes(*b"paragcP4");
#[cfg(target_os = "linux")]
pub const PAGE: usize = 4096;
#[cfg(target_os = "linux")]
pub const TYPE_CAP: usize = 1024;
#[cfg(target_os = "linux")]
pub const MAP_CAP: usize = 64 * 1024;
#[cfg(target_os = "linux")]
pub const BYTES_PER_ENTRY: usize = 16 * 1024;
#[cfg(target_os = "linux")]
pub const ATTACH_CAP: usize = 32;
#[cfg(target_os = "linux")]
pub const ATTACH_OFF: usize = 1024;
#[repr(C)]
#[cfg(target_os = "linux")]
pub struct Super {
pub magic: AtomicU64,
pub window: AtomicU64,
pub heap: AtomicU64,
pub request: AtomicU32,
pub marking: AtomicU32,
pub epoch: AtomicU32,
pub blocks: AtomicU32,
pub collections: AtomicU64,
pub takeovers: AtomicU64,
pub available: AtomicU64,
pub types: AtomicU32,
pub map: AtomicU32,
pub entries: AtomicU32,
_pad: u32,
pub free_entries: AtomicU64,
pub committed: [AtomicU64; Segment::COUNT],
pub live: AtomicU64,
pub allocated: AtomicU64,
pub incarnation: AtomicU64,
pub owner_pid: AtomicU32,
pub persist: AtomicU32,
pub owner_start: AtomicU64,
pub dead: AtomicU32,
_pad_dead: u32,
}
#[cfg(target_os = "linux")]
impl Super {
pub fn new(heap: u64, incarnation: u64, owner: crate::shm::Process) -> Self {
Self {
magic: AtomicU64::new(MAGIC),
window: AtomicU64::new(WINDOW as u64),
heap: AtomicU64::new(heap),
request: AtomicU32::new(0),
marking: AtomicU32::new(0),
epoch: AtomicU32::new(1),
blocks: AtomicU32::new(0),
collections: AtomicU64::new(0),
takeovers: AtomicU64::new(0),
available: AtomicU64::new(0),
types: AtomicU32::new(0),
map: AtomicU32::new(0),
entries: AtomicU32::new(0),
_pad: 0,
free_entries: AtomicU64::new(0),
committed: core::array::from_fn(|_| AtomicU64::new(0)),
live: AtomicU64::new(0),
allocated: AtomicU64::new(0),
incarnation: AtomicU64::new(incarnation),
owner_pid: AtomicU32::new(owner.pid),
persist: AtomicU32::new(0),
owner_start: AtomicU64::new(owner.start),
dead: AtomicU32::new(0),
_pad_dead: 0,
}
}
}
#[repr(C, align(64))]
#[cfg(target_os = "linux")]
pub struct Attachment {
pub pid: AtomicU32,
pub inside: AtomicU32,
pub start: AtomicU64,
pub waiting: AtomicU32,
}
#[cfg(target_os = "linux")]
const _: () = assert!(size_of::<Super>() <= ATTACH_OFF && ATTACH_OFF + ATTACH_CAP * size_of::<Attachment>() <= PAGE, "挂接表放在超级块那一页里");
#[derive(Clone, Copy)]
#[cfg(target_os = "linux")]
pub enum Segment {
Types,
Map,
Entries,
States,
}
#[cfg(target_os = "linux")]
impl Segment {
pub const COUNT: usize = 4;
pub fn index(self) -> usize {
self as usize
}
}
#[repr(C)]
#[cfg(target_os = "linux")]
pub struct TypeEntry {
pub ready: AtomicU32,
pub edges: AtomicU32,
pub map: AtomicU32,
pub size: AtomicU32,
pub key: [AtomicU64; 2],
}
#[cfg(target_os = "linux")]
impl TypeEntry {
pub fn has_key(&self, key: [u64; 2]) -> bool {
self.ready.load(core::sync::atomic::Ordering::Acquire) == 1 && self.key.iter().zip(key).all(|(k, v)| k.load(core::sync::atomic::Ordering::Relaxed) == v)
}
}
#[repr(C)]
#[cfg(target_os = "linux")]
pub struct Entry {
pub ptr: AtomicU64,
pub holder: AtomicU32,
pub next: AtomicU32,
pub holder_incarnation: AtomicU64,
}
#[repr(C)]
#[cfg(target_os = "linux")]
pub struct BlockState {
pub kind: AtomicU32,
pub next: AtomicU32,
}
#[repr(u32)]
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg(target_os = "linux")]
pub enum Kind {
Unused = 0,
Small = 1,
LargeHead = 2,
LargeTail = 3,
}
#[cfg(target_os = "linux")]
impl From<u32> for Kind {
fn from(v: u32) -> Self {
match v {
1 => Self::Small,
2 => Self::LargeHead,
3 => Self::LargeTail,
_ => Self::Unused,
}
}
}
#[derive(Clone, Copy)]
#[cfg(target_os = "linux")]
pub struct WindowLayout {
pub types: usize,
pub map: usize,
pub entries: usize,
pub entry_cap: usize,
pub states: usize,
pub blocks: usize,
pub max_blocks: usize,
}
#[cfg(target_os = "linux")]
impl WindowLayout {
pub fn new() -> Self {
let types = size_of::<Super>().next_multiple_of(PAGE);
let map = types + TYPE_CAP * size_of::<TypeEntry>();
let entries = (map + MAP_CAP * size_of::<u32>()).next_multiple_of(PAGE);
let entry_cap = WINDOW / BYTES_PER_ENTRY;
let states = (entries + entry_cap * size_of::<Entry>()).next_multiple_of(PAGE);
let blocks = (states + WINDOW / BLOCK * size_of::<BlockState>()).next_multiple_of(BLOCK);
let max_blocks = (WINDOW - blocks) / BLOCK;
assert!(max_blocks > 0, "窗口放不下任何块");
Self { types, map, entries, entry_cap, states, blocks, max_blocks }
}
pub fn segment(&self, s: Segment) -> (usize, usize) {
match s {
Segment::Types => (self.types, self.map),
Segment::Map => (self.map, self.entries),
Segment::Entries => (self.entries, self.states),
Segment::States => (self.states, self.blocks),
}
}
}
#[repr(C)]
#[cfg(target_os = "linux")]
pub struct PHeader {
pub core: Core,
pub ty: u32,
_pad: u32,
}
#[cfg(target_os = "linux")]
pub const PHEADER: usize = size_of::<PHeader>();
#[cfg(target_os = "linux")]
const _: () = assert!(PHEADER == 16, "公开堆的对象头是 16 字节");
#[cfg(target_os = "linux")]
impl PHeader {
pub fn new(bytes: usize, large: bool, ty: u32) -> Self {
Self { core: Core::new(bytes, large, 0), ty, _pad: 0 }
}
pub fn data(this: *const Self) -> *mut u8 {
this.cast::<u8>().cast_mut().wrapping_add(PHEADER)
}
pub fn of(data: *const u8) -> *const Self {
data.wrapping_sub(PHEADER).cast()
}
}
#[cfg(target_os = "linux")]
impl Finalize for PHeader {
unsafe fn finalize(_: *const Core) {}
}