#[cfg(target_os = "linux")]
use core::any::type_name;
use core::cell::Cell;
use core::marker::PhantomData;
use core::num::{NonZeroU32, NonZeroUsize};
use core::ptr::{NonNull, null_mut};
use core::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering};
#[cfg(target_os = "linux")]
use core::time::Duration;
#[cfg(target_os = "linux")]
use std::io;
#[cfg(target_os = "linux")]
use std::fs::File;
#[cfg(target_os = "linux")]
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use crossbeam_deque::{Injector, Steal};
use crossbeam_utils::{Backoff, CachePadded};
use crate::{Gc, Trace};
use crate::handle::{GcInternal, Invariant, RawSlot, RootTable};
#[cfg(target_os = "linux")]
use crate::handle::{EdgeMap, Public, PublicBrand, PublicGc, PublicGcInternal, PublicInternal, Shared};
use crate::layout::{BLOCK, Block, Pages, LINE, EVACUATE_LIVE, EVACUATE_MAX, EVACUATE_MIN, GRANULE, GROWTH, HEADER, Header, LARGE, MAX_EPOCH, MIN_SPARE_BLOCKS, MIN_TRIGGER, OVERFLOW_TRIES, FRAG_NUM, FRAG_DEN, YOUNG_PER_FULL, YOUNG_PER_FULL_RC};
#[cfg(target_os = "linux")]
use crate::layout::{Core, State};
#[cfg(target_os = "linux")]
use crate::layout::{ATTACH_CAP, ATTACH_OFF, Attachment, BlockState, Entry, Kind, MAP_CAP, PAGE, PHEADER, PHeader, Segment, Super, TYPE_CAP, TypeEntry, WindowLayout};
use crate::mark::Marking;
#[cfg(target_os = "linux")]
use crate::mark::{Marker, Member};
#[cfg(target_os = "linux")]
use crate::shm::{Liveness, Process, Region, Registry, Space, WINDOW, WINDOWS};
use crate::sweep::{Large, Outcome, Releaser, Sink, Sweeper};
use crate::sync::{Pool, SegVec};
#[cfg(target_os = "linux")]
use crate::sync::{FutexWord, Retry, Stack};
pub struct Heap {
threads: NonZeroUsize,
pool: OnceLock<Pool>,
epoch: u32,
marking: AtomicU32,
gate: CachePadded<AtomicU64>,
grey: Injector<usize>,
remembered: Injector<usize>,
rc_log: Injector<usize>,
decs: Injector<usize>,
dirty: Injector<Block>,
rc_valid: AtomicBool,
rc_parity: AtomicBool,
black: Injector<usize>,
rc_roots: Vec<usize>,
young_since_full: usize,
young_collections: u64,
collections: u64,
blocks: SegVec<Block>,
available: Injector<Block>,
large: SegVec<Large>,
sweeper: Sweeper,
parallel_drop: AtomicBool,
young_evacuation: AtomicU8,
shrinking: AtomicBool,
pages: Pages,
roots: Arc<RootTable>,
weaks: Arc<RootTable>,
allocated: AtomicUsize,
evacuated: (usize, usize),
spare: AtomicPtr<Tlab>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(u8)]
pub enum YoungEvacuation {
Off,
#[default]
SkipRemembered,
Full,
}
impl From<u8> for YoungEvacuation {
fn from(v: u8) -> Self {
match v {
0 => Self::Off,
2 => Self::Full,
_ => Self::SkipRemembered,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Stats {
pub live: usize,
pub allocated: usize,
pub blocks: usize,
pub large: usize,
pub collections: u64,
pub young_collections: u64,
pub evacuated_blocks: usize,
pub evacuated_bytes: usize,
}
impl Default for Heap {
fn default() -> Self {
Self::new(std::thread::available_parallelism().unwrap_or(NonZeroUsize::MIN))
}
}
impl Heap {
pub fn new(threads: NonZeroUsize) -> Self {
Self {
threads,
pool: OnceLock::new(),
epoch: 1,
marking: AtomicU32::new(0),
gate: CachePadded::new(AtomicU64::new(0)),
grey: Injector::new(),
remembered: Injector::new(),
rc_log: Injector::new(),
decs: Injector::new(),
dirty: Injector::new(),
rc_valid: AtomicBool::new(false),
rc_parity: AtomicBool::new(false),
black: Injector::new(),
rc_roots: Vec::new(),
young_since_full: 0,
young_collections: 0,
collections: 0,
blocks: SegVec::default(),
available: Injector::new(),
large: SegVec::default(),
sweeper: Sweeper::default(),
parallel_drop: AtomicBool::new(true),
young_evacuation: AtomicU8::new(YoungEvacuation::default() as u8),
shrinking: AtomicBool::new(false),
pages: Pages::default(),
roots: Arc::default(),
weaks: Arc::default(),
allocated: AtomicUsize::new(0),
evacuated: (0, 0),
spare: AtomicPtr::new(null_mut()),
}
}
pub fn mutate<R>(&self, f: impl for<'gc> FnOnce(&Mutator<'gc>) -> R) -> R {
let spare = self.spare.swap(null_mut(), Ordering::AcqRel);
let mut tlab = if spare.is_null() {
Box::default()
} else {
unsafe { Box::from_raw(spare) }
};
let r = self.mutate_in(&mut tlab, f);
let tlab = Box::into_raw(tlab);
if self.spare.compare_exchange(null_mut(), tlab, Ordering::AcqRel, Ordering::Relaxed).is_err() {
drop(unsafe { Box::from_raw(tlab) });
}
r
}
pub fn mutate_in<R>(&self, tlab: &mut Tlab, f: impl for<'gc> FnOnce(&Mutator<'gc>) -> R) -> R {
let _inside = Inside::enter(self);
tlab.adopt((self.id(), self.collections));
let marking = NonZeroU32::new(self.marking.load(Ordering::Acquire));
f(&Mutator { heap: self, tlab, marking, _brand: PhantomData })
}
fn pool(&self) -> &Pool {
self.pool.get_or_init(|| Pool::new(self.threads))
}
pub fn mark_concurrently(&self) -> bool {
self.sweep_concurrently();
let epoch = self.next_epoch();
if self.gate.fetch_or(REQUEST, Ordering::AcqRel) & REQUEST != 0 {
return false;
}
if self.marking.load(Ordering::Acquire) != 0 {
self.gate.fetch_and(!REQUEST, Ordering::AcqRel);
return false;
}
let backoff = Backoff::new();
while self.gate.load(Ordering::Acquire) & !REQUEST != 0 {
backoff.snooze();
}
self.marking.store(epoch, Ordering::Release);
let parity = !self.rc_parity.fetch_xor(true, Ordering::AcqRel);
self.rc_valid.store(false, Ordering::Release);
drop(Self::drain(&self.rc_log));
let roots = unsafe { self.roots.settle() };
Marking::seed(&self.grey, &roots, epoch);
self.gate.fetch_and(!REQUEST, Ordering::AcqRel);
let pool = self.pool();
Marking::new(pool.threads(), epoch, &self.grey).counting(Some(parity)).logging(&self.rc_log).run(pool);
true
}
fn settle_concurrent_log(&mut self, epoch: u32) {
let parity = *self.rc_parity.get_mut();
for addr in Self::drain(&self.rc_log) {
let slot = unsafe { &*core::ptr::with_exposed_provenance::<RawSlot>(addr) };
let (cur, prev) = slot.recount();
if let Some(cur) = cur {
unsafe { &*cur }.rc_inc(parity);
}
if let Some(prev) = prev
&& unsafe { &*prev }.is_marked(epoch)
{
self.decs.push(prev.expose_provenance());
}
}
}
fn next_epoch(&self) -> u32 {
self.epoch.checked_add(1).filter(|&e| e <= MAX_EPOCH).expect("纪元用完了")
}
fn pick_evacuation(available: &[Block], targets: &Injector<Block>) -> usize {
let live = |b: &Block| b.live_since_sweep().filter(|&live| live > 0 && live < EVACUATE_LIVE);
let mut sparse: Vec<(usize, Block)> = available.iter().filter_map(|b| live(b).map(|l| (l, *b))).collect();
sparse.sort_unstable_by_key(|&(l, _)| l);
sparse.truncate(EVACUATE_MAX);
if sparse.len() < EVACUATE_MIN {
sparse.clear();
}
for &(_, b) in &sparse {
b.set_evacuate();
}
for &b in available {
if !b.is_evacuating() {
targets.push(b);
}
}
sparse.len()
}
fn remember(&self, old: *const Header, epoch: u32) {
let h = unsafe { &*old };
if h.mark(epoch) {
if !h.is_large() {
Block::containing(old.cast()).mark_lines(old.cast(), h.bytes(), epoch);
}
self.grey.push(old.expose_provenance());
}
}
fn acquire(&self) -> Block {
self.allocated.fetch_add(BLOCK, Ordering::Relaxed);
loop {
match self.available.steal() {
Steal::Success(b) => {
b.unlist();
b.reused();
return b;
}
Steal::Retry => continue,
Steal::Empty => {}
}
match self.sweeper.sweep_next_block() {
Some(Outcome::Usable(b)) => {
b.reused();
self.blocks.push(b);
self.sweeper.finished();
return b;
}
Some(other) => {
self.block(other);
self.sweeper.finished();
}
None => break,
}
}
self.fresh()
}
fn acquire_for(&self, bytes: usize) -> Block {
self.allocated.fetch_add(BLOCK, Ordering::Relaxed);
let mut rejected = Vec::new();
let mut found = None;
while rejected.len() < OVERFLOW_TRIES {
match self.available.steal() {
Steal::Success(b) if b.has_hole(bytes, self.epoch) => {
found = Some(b);
break;
}
Steal::Success(b) => rejected.push(b),
Steal::Retry => {}
Steal::Empty => break,
}
}
for b in rejected {
self.available.push(b);
}
match found {
Some(b) => {
b.unlist();
b.reused();
b
}
None => self.fresh(),
}
}
fn fresh(&self) -> Block {
let b = Block::new(&self.pages);
self.blocks.push(b);
b
}
pub fn set_young_evacuation(&self, mode: YoungEvacuation) {
self.young_evacuation.store(mode as u8, Ordering::Relaxed);
}
pub fn set_parallel_drop(&self, on: bool) {
self.parallel_drop.store(on, Ordering::Relaxed);
}
pub fn is_sweeping(&self) -> bool {
!self.sweeper.is_done()
}
pub fn sweep_concurrently(&self) {
let pool = self.pool();
if !self.decs.is_empty() {
Releaser::new(&self.decs, &self.dirty, pool.threads(), self.epoch, self.rc_parity.load(Ordering::Acquire), self.parallel_drop.load(Ordering::Relaxed)).run(pool);
}
self.sweeper.finish(pool, self, self.parallel_drop.load(Ordering::Relaxed));
}
fn alloc_large(&self, bytes: usize) -> *mut u8 {
let p = unsafe { NonNull::new_unchecked(Large::alloc(bytes)) };
self.large.push(Large(p.cast()));
self.allocated.fetch_add(bytes, Ordering::Relaxed);
p.as_ptr()
}
pub fn stats(&self) -> Stats {
Stats {
live: self.sweeper.live(),
allocated: self.allocated.load(Ordering::Relaxed),
blocks: self.blocks.len(),
large: self.large.len(),
collections: self.collections,
young_collections: self.young_collections,
evacuated_blocks: self.evacuated.0,
evacuated_bytes: self.evacuated.1,
}
}
pub fn collect_if_needed(&mut self) -> bool {
let live = self.sweeper.live().max(MIN_TRIGGER);
let due = *self.allocated.get_mut() >= live * GROWTH;
if due {
let every = if *self.rc_valid.get_mut() { YOUNG_PER_FULL_RC } else { YOUNG_PER_FULL };
let fragmented = self.blocks.len() * BLOCK * FRAG_DEN > live * (1 + GROWTH) * FRAG_NUM;
if self.young_since_full < every && !fragmented {
self.collect_young();
} else {
self.collect();
}
}
due
}
pub fn collect_young(&mut self) {
self.finish_young();
self.sweep_concurrently();
}
pub fn finish_young(&mut self) {
if *self.marking.get_mut() != 0 {
self.finish_marking();
return;
}
self.sweep_concurrently();
let epoch = self.epoch;
let mut dirty = Self::drain(&self.dirty);
dirty.sort_unstable_by_key(|b| b.line(0).addr());
dirty.dedup();
for b in dirty {
if unsafe { b.recompute_lines(epoch) } && b.list() {
self.available.push(b);
}
}
let epoch = self.epoch;
let remembered = Self::drain(&self.remembered);
let counting = *self.rc_valid.get_mut();
let parity = *self.rc_parity.get_mut();
let pool = self.pool.get_or_init(|| Pool::new(self.threads));
let workers = pool.sized(self.blocks.len() + self.large.len());
let mode = YoungEvacuation::from(*self.young_evacuation.get_mut());
let mark = Marking::new(workers, epoch, &self.grey).counting(counting.then_some(parity));
let moved = AtomicUsize::new(0);
if mode == YoungEvacuation::Off {
Marking::seed(&self.grey, &unsafe { self.roots.settle() }, epoch);
Marking::seed_slots(&self.grey, &remembered, epoch);
mark.run(pool);
} else {
let young: Vec<Block> = self.blocks.take();
for &b in &young {
if b.live_since_sweep().is_none() {
b.set_evacuate();
}
}
self.blocks.extend(young);
let mut pinned = Vec::new();
unsafe { self.roots.pinned(|h| pinned.push(h)) };
Marking::seed(&self.grey, &pinned, epoch);
let slots: &[usize] = if mode == YoungEvacuation::Full { &remembered } else {
Marking::seed_slots(&self.grey, &remembered, epoch);
&[]
};
mark.evacuating(&self.roots, &self.available, &self.blocks, &self.pages, &moved, epoch).relocating_slots(slots).run(pool);
}
let roots = unsafe { self.roots.settle() };
let mut decs = Vec::new();
if counting {
for &root in &roots {
unsafe { &*root }.rc_inc(parity);
}
decs.append(&mut self.rc_roots);
} else {
self.rc_roots.clear();
}
for addr in Self::drain(&self.rc_log) {
let slot = unsafe { &*core::ptr::with_exposed_provenance::<RawSlot>(addr) };
if counting {
let (cur, prev) = slot.recount();
if let Some(cur) = cur {
unsafe { &*cur }.rc_inc(parity);
}
decs.extend(prev.map(<*const Header>::expose_provenance));
} else {
slot.unlog();
}
}
if counting {
self.rc_roots = roots.iter().map(|r| r.expose_provenance()).collect();
for addr in decs {
self.decs.push(addr);
}
}
unsafe { self.weaks.clear_unreached(epoch, parity) };
let (young, old): (Vec<Block>, Vec<Block>) = self.blocks.take().into_iter().partition(|b| b.live_since_sweep().is_none());
self.blocks.extend(old);
let large = self.large.take();
let spare = (*self.allocated.get_mut() / BLOCK).max(MIN_SPARE_BLOCKS);
self.sweeper.start(epoch, young, large, spare, false);
self.evacuated = (0, moved.into_inner());
*self.allocated.get_mut() = 0;
self.collections += 1;
self.young_collections += 1;
self.young_since_full += 1;
}
fn drain<T>(queue: &Injector<T>) -> Vec<T> {
let mut out = Vec::new();
loop {
match queue.steal() {
Steal::Success(v) => out.push(v),
Steal::Retry => {}
Steal::Empty => return out,
}
}
}
pub fn collect(&mut self) {
self.finish_marking();
self.sweep_concurrently();
}
pub fn shrink(&mut self) {
*self.shrinking.get_mut() = true;
self.collect();
*self.shrinking.get_mut() = false;
}
pub fn finish_marking(&mut self) {
self.sweep_concurrently();
let concurrent = *self.marking.get_mut() != 0;
self.begin_full(concurrent);
let count = Some(*self.rc_parity.get_mut());
let roots = unsafe { self.roots.settle() };
let marking = *self.marking.get_mut();
let epoch = if marking == 0 { self.next_epoch() } else { marking };
let pool = self.pool.get_or_init(|| Pool::new(self.threads));
let workers = pool.sized(self.blocks.len() + self.large.len());
let available = self.take_available();
let targets = Injector::new();
let mut evacuate = if marking == 0 { Self::pick_evacuation(&available, &targets) } else { 0 };
if evacuate > 0 {
let pin = |h: *const Header| {
if !unsafe { &*h }.is_large() && Block::containing(h.cast()).pin() {
evacuate -= 1;
targets.push(Block::containing(h.cast()));
}
};
unsafe { self.roots.pinned(pin) };
}
for addr in Self::drain(&self.black) {
self.grey.push(addr);
}
let mark = Marking::new(workers, epoch, &self.grey).counting(count);
let moved = AtomicUsize::new(0);
if evacuate > 0 {
mark.evacuating(&self.roots, &targets, &self.blocks, &self.pages, &moved, self.epoch).run(pool);
} else {
if marking == 0 {
Marking::seed(&self.grey, &roots, epoch);
}
mark.run(pool);
}
if concurrent {
self.settle_concurrent_log(epoch);
}
unsafe { self.weaks.clear_unreached(epoch, *self.rc_parity.get_mut()) };
self.end_full(epoch, (evacuate, moved.into_inner()));
}
fn begin_full(&mut self, concurrent: bool) {
drop(Self::drain(&self.dirty));
drop(Self::drain(&self.remembered));
self.young_since_full = 0;
if !concurrent {
drop(Self::drain(&self.rc_log));
let parity = self.rc_parity.get_mut();
*parity = !*parity;
}
self.rc_roots.clear();
}
fn take_available(&self) -> Vec<Block> {
let available = Self::drain(&self.available);
for b in &available {
b.unlist();
}
available
}
fn end_full(&mut self, epoch: u32, evacuated: (usize, usize)) {
*self.rc_valid.get_mut() = true;
let blocks = self.blocks.take();
let large = self.large.take();
let shrinking = *self.shrinking.get_mut();
let spare = if shrinking { 0 } else { (*self.allocated.get_mut() / BLOCK).max(MIN_SPARE_BLOCKS) };
self.sweeper.start(epoch, blocks, large, spare, shrinking);
self.evacuated = evacuated;
self.epoch = epoch;
*self.marking.get_mut() = 0;
*self.allocated.get_mut() = 0;
self.collections += 1;
}
pub fn collect_group(heaps: &mut [&mut Heap]) {
for h in heaps.iter_mut() {
if *h.marking.get_mut() != 0 {
h.finish_marking();
}
h.sweep_concurrently();
}
let ids: Vec<usize> = heaps.iter().map(|h| h.id()).collect();
let inside = |holder: usize| ids.contains(&holder);
let mut epochs = Vec::with_capacity(heaps.len());
for h in heaps.iter_mut() {
h.begin_full(false);
drop(h.take_available());
let epoch = h.next_epoch();
let roots = unsafe { h.roots.settle_outside(inside) };
Marking::seed(&h.grey, &roots, epoch);
epochs.push(epoch);
}
let found = Injector::new();
loop {
for (h, &epoch) in heaps.iter().zip(&epochs) {
if h.grey.is_empty() {
continue;
}
let pool = h.pool();
let workers = pool.sized(h.blocks.len() + h.large.len());
Marking::new(workers, epoch, &h.grey).counting(Some(h.rc_parity.load(Ordering::Acquire))).grouping(&found).run(pool);
}
for (table, header) in Self::drain(&found) {
if let Some(j) = ids.iter().position(|&id| id == table) {
Marking::seed(&heaps[j].grey, &[core::ptr::with_exposed_provenance(header)], epochs[j]);
}
}
if heaps.iter().all(|h| h.grey.is_empty()) {
break;
}
}
for (h, &epoch) in heaps.iter_mut().zip(&epochs) {
unsafe { h.roots.clear_dead(inside, epoch) };
unsafe { h.weaks.clear_unreached(epoch, *h.rc_parity.get_mut()) };
h.end_full(epoch, (0, 0));
}
for h in heaps.iter() {
h.sweep_concurrently();
}
}
}
pub trait HeapInternal {
fn roots(&self) -> &Arc<RootTable>;
fn weaks(&self) -> &Arc<RootTable>;
fn id(&self) -> usize;
}
impl HeapInternal for Heap {
fn roots(&self) -> &Arc<RootTable> {
&self.roots
}
fn weaks(&self) -> &Arc<RootTable> {
&self.weaks
}
fn id(&self) -> usize {
Arc::as_ptr(&self.roots).addr()
}
}
impl Sink for Heap {
fn block(&self, outcome: Outcome) {
match outcome {
Outcome::Usable(b) => {
self.blocks.push(b);
if b.list() {
self.available.push(b);
}
}
Outcome::Full(b) => {
self.blocks.push(b);
}
Outcome::Release(b) => unsafe { b.release(&self.pages) },
}
}
fn large(&self, survivor: Large) {
self.large.push(survivor);
}
}
impl Drop for Heap {
fn drop(&mut self) {
let pool = self.pool.take().unwrap_or_else(|| Pool::new(NonZeroUsize::MIN));
let parallel_drop = *self.parallel_drop.get_mut();
self.sweeper.finish(&pool, self, parallel_drop);
let epoch = self.epoch.max(*self.marking.get_mut()).wrapping_add(1);
let blocks = self.blocks.take();
let large = self.large.take();
while !matches!(self.available.steal(), Steal::Empty) {}
self.sweeper.start(epoch, blocks, large, 0, false);
self.sweeper.finish(&pool, self, parallel_drop);
debug_assert!(self.blocks.is_empty() && self.large.is_empty());
let spare = *self.spare.get_mut();
if !spare.is_null() {
drop(unsafe { Box::from_raw(spare) });
}
}
}
#[derive(Default)]
pub struct Tlab {
owner: Cell<(usize, u64)>,
main: Bump,
overflow: Bump,
last: Cell<Option<(usize, u32)>>,
}
unsafe impl Send for Tlab {}
impl Tlab {
fn adopt(&mut self, owner: (usize, u64)) {
if self.owner.get() != owner {
let last = if self.owner.get().0 == owner.0 { self.last.get() } else { None };
*self = Self { owner: Cell::new(owner), last: Cell::new(last), ..Self::default() };
}
}
fn bump(&self, bytes: usize, epoch: u32, acquire: impl Fn() -> Block, roomy: impl Fn(usize) -> Block) -> *mut u8 {
if let Some(p) = self.main.fit(bytes) {
return p;
}
if bytes > LINE {
return self.overflow.take(bytes, epoch, &|| roomy(bytes));
}
self.main.take(bytes, epoch, &acquire)
}
}
struct Bump {
block: Cell<Option<Block>>,
line: Cell<usize>,
cursor: Cell<*mut u8>,
limit: Cell<*mut u8>,
}
impl Default for Bump {
fn default() -> Self {
Self { block: Cell::default(), line: Cell::default(), cursor: Cell::new(null_mut()), limit: Cell::new(null_mut()) }
}
}
impl Bump {
fn fit(&self, bytes: usize) -> Option<*mut u8> {
let cursor = self.cursor.get();
(self.limit.get().addr() - cursor.addr() >= bytes).then(|| {
self.cursor.set(cursor.wrapping_add(bytes));
cursor
})
}
fn take(&self, bytes: usize, epoch: u32, acquire: &impl Fn() -> Block) -> *mut u8 {
loop {
if let Some(p) = self.fit(bytes) {
return p;
}
if let Some(b) = self.block.get()
&& let Some((start, end)) = b.hole(self.line.get(), epoch)
{
self.line.set(end);
self.cursor.set(b.line(start));
self.limit.set(b.line(end));
continue;
}
self.block.set(Some(acquire()));
self.line.set(Block::FIRST_LINE);
self.cursor.set(null_mut());
self.limit.set(null_mut());
}
}
}
const YOUNG: u32 = 0;
const REQUEST: u64 = 1 << 63;
struct Inside<'h>(&'h Heap);
impl<'h> Inside<'h> {
fn enter(heap: &'h Heap) -> Self {
let backoff = Backoff::new();
let mut word = heap.gate.load(Ordering::Acquire);
loop {
if word & REQUEST != 0 {
backoff.snooze();
word = heap.gate.load(Ordering::Acquire);
continue;
}
match heap.gate.compare_exchange_weak(word, word + 1, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => return Self(heap),
Err(now) => word = now,
}
}
}
}
impl Drop for Inside<'_> {
fn drop(&mut self) {
self.0.gate.fetch_sub(1, Ordering::AcqRel);
}
}
pub struct Mutator<'gc> {
heap: &'gc Heap,
tlab: &'gc Tlab,
marking: Option<NonZeroU32>,
_brand: Invariant<'gc>,
}
impl<'gc> Mutator<'gc> {
pub fn is_marking(&self) -> bool {
self.marking.is_some()
}
pub fn alloc<T: Trace + 'gc>(&self, value: T) -> Gc<'gc, T> {
const { assert!(align_of::<T>() <= GRANULE, "对象数据的对齐不能超过 8 字节") };
let bytes = (HEADER + size_of::<T>()).next_multiple_of(GRANULE);
let large = bytes > LARGE;
let p = if large { self.heap.alloc_large(bytes) } else { self.alloc_small(bytes) };
let mark = self.marking.map_or(YOUNG, NonZeroU32::get);
if self.marking.is_some() {
if !large {
Block::containing(p).mark_lines(p, bytes, mark);
}
self.heap.black.push(p.expose_provenance());
}
unsafe {
p.cast::<Header>().write(Header::new::<T>(bytes, large, mark));
let data = Header::data(p.cast()).cast::<T>();
data.write(value);
Gc::from_data(data)
}
}
fn alloc_small(&self, bytes: usize) -> *mut u8 {
let p = self.tlab.bump(bytes, self.heap.epoch, || self.heap.acquire(), |need| self.heap.acquire_for(need));
Block::containing(p).set_start(p);
p
}
}
pub trait MutatorInternal<'gc> {
fn heap(&self) -> &'gc Heap;
fn written(&self, slot: &RawSlot, old: Option<*const Header>, new: Option<*const Header>);
fn reached(&self, h: *const Header);
}
impl<'gc> MutatorInternal<'gc> for Mutator<'gc> {
fn heap(&self) -> &'gc Heap {
self.heap
}
fn written(&self, slot: &RawSlot, old: Option<*const Header>, new: Option<*const Header>) {
let addr = (&raw const *slot).expose_provenance();
if let Some(epoch) = self.marking {
if let Some(old) = old {
self.heap.remember(old, epoch.get());
}
} else if !slot.is_young()
&& let Some(new) = new
&& !unsafe { &*new }.is_marked(self.heap.epoch)
{
self.heap.remembered.push(addr);
}
if slot.log() {
self.heap.rc_log.push(addr);
}
}
fn reached(&self, h: *const Header) {
if let Some(epoch) = self.marking {
self.heap.remember(h, epoch.get());
}
}
}
#[cfg(target_os = "linux")]
const POLL: Duration = Duration::from_millis(10);
#[cfg(target_os = "linux")]
const REAPING: u32 = u32::MAX;
#[cfg(target_os = "linux")]
const YIELD_ROUNDS: usize = 10;
#[cfg(target_os = "linux")]
const PATIENCE: Duration = Duration::from_millis(50);
#[cfg(target_os = "linux")]
pub const HEAP_HOLDER: u32 = 1 << 31;
#[cfg(target_os = "linux")]
pub const SAME_DIR: u32 = 1 << 30;
#[cfg(target_os = "linux")]
const HOLDER_INDEX: u32 = SAME_DIR - 1;
#[cfg(target_os = "linux")]
const ALIVE_RECHECK: Duration = Duration::from_millis(10);
#[cfg(target_os = "linux")]
const SWEEP_BATCH: usize = 16;
#[cfg(target_os = "linux")]
pub enum Backing {
File { file: File, path: PathBuf, owner: bool },
Anonymous,
}
#[cfg(target_os = "linux")]
impl Backing {
fn commit(&self, offset: usize, len: usize) {
if let Self::File { file, .. } = self {
Region::commit(file, offset, len).expect("公开堆所在的文件系统满了");
}
}
}
#[cfg(target_os = "linux")]
struct Fnv(u64);
#[cfg(target_os = "linux")]
impl Fnv {
const PRIME: u64 = 0x0000_0100_0000_01b3;
const SEEDS: [u64; 2] = [0xcbf2_9ce4_8422_2325, 0x6c62_272e_07bb_0142];
fn write(&mut self, bytes: &[u8]) {
for &b in bytes {
self.0 = (self.0 ^ u64::from(b)).wrapping_mul(Self::PRIME);
}
}
fn of<T: Shared>() -> (EdgeMap, [u64; 2]) {
let mut map = EdgeMap::default();
T::edges(&mut map, 0);
let key = Self::key(type_name::<T>(), size_of::<T>(), map.as_slice());
(map, key)
}
fn key(name: &str, size: usize, edges: &[u32]) -> [u64; 2] {
Self::SEEDS.map(|seed| {
let mut h = Self(seed);
h.write(name.as_bytes());
h.write(&size.to_le_bytes());
for e in edges {
h.write(&e.to_le_bytes());
}
h.0
})
}
}
#[cfg(target_os = "linux")]
pub struct Inner {
space: Arc<Space>,
index: usize,
window: NonNull<u8>,
layout: WindowLayout,
backing: Backing,
threads: NonZeroUsize,
pool: OnceLock<Pool>,
types: SegVec<(usize, u32)>,
spare: AtomicPtr<Tlab>,
slot: usize,
born: std::time::Instant,
checked: AtomicU64,
}
#[cfg(target_os = "linux")]
unsafe impl Send for Inner {}
#[cfg(target_os = "linux")]
unsafe impl Sync for Inner {}
#[cfg(target_os = "linux")]
impl Inner {
pub fn new(space: Arc<Space>, index: usize, backing: Backing, threads: NonZeroUsize, fresh: bool) -> io::Result<Self> {
let window = NonNull::new(space.region().window(index)).expect("窗口地址非空");
let mut me = Self { space, index, window, layout: WindowLayout::new(), backing, threads, pool: OnceLock::new(), types: SegVec::default(), spare: AtomicPtr::new(null_mut()), slot: ATTACH_CAP, born: std::time::Instant::now(), checked: AtomicU64::new(0) };
if fresh {
me.backing.commit(0, PAGE);
let incarnation = std::hash::BuildHasher::hash_one(&std::collections::hash_map::RandomState::new(), (index, Process::current().pid));
unsafe { me.window.as_ptr().cast::<Super>().write(Super::new(index as u64, incarnation, Process::current())) };
} else if me.sup().heap.load(Ordering::Acquire) != index as u64 {
return Err(io::Error::new(io::ErrorKind::InvalidData, "超级块里的堆号与窗口不符"));
}
me.slot = me.attach().ok_or_else(|| io::Error::new(io::ErrorKind::OutOfMemory, "这个公开堆的挂接表满了"))?;
Ok(me)
}
fn attach(&self) -> Option<usize> {
let me = Process::current();
let claim = || (0..ATTACH_CAP).find(|&i| self.attachment(i).pid.compare_exchange(0, me.pid, Ordering::AcqRel, Ordering::Relaxed).is_ok());
let slot = claim().or_else(|| {
self.reap_dead();
claim()
})?;
let a = self.attachment(slot);
a.inside.store(0, Ordering::Relaxed);
a.waiting.store(0, Ordering::Relaxed);
a.start.store(me.start, Ordering::Release);
Some(slot)
}
fn attachment(&self, i: usize) -> &Attachment {
unsafe { &*self.at::<Attachment>(ATTACH_OFF).add(i) }
}
fn alive(&self, i: usize) -> bool {
let a = self.attachment(i);
let pid = a.pid.load(Ordering::Acquire);
pid != 0 && pid != REAPING && Process { pid, start: a.start.load(Ordering::Acquire) }.alive()
}
fn reap_dead(&self) {
let owner = self.sup().request.load(Ordering::SeqCst) as usize;
for i in 0..ATTACH_CAP {
let pid = self.attachment(i).pid.load(Ordering::Acquire);
if pid != 0 && pid != REAPING && i + 1 != owner && !self.alive(i) {
self.reap(i, pid);
}
}
}
fn reap(&self, i: usize, pid: u32) {
let a = self.attachment(i);
if a.pid.compare_exchange(pid, REAPING, Ordering::AcqRel, Ordering::Relaxed).is_err() {
return;
}
let holder = u32::try_from(i + 1).expect("挂接槽号");
for j in 0..self.sup().entries.load(Ordering::Acquire) {
if self.entry(j).holder.load(Ordering::Acquire) == holder {
self.release_entry(j);
}
}
a.inside.store(0, Ordering::Release);
a.waiting.store(0, Ordering::Release);
a.start.store(0, Ordering::Relaxed);
a.pid.store(0, Ordering::Release);
}
fn yield_to_waiting(&self) {
for _ in 0..YIELD_ROUNDS {
let Some(i) = (0..ATTACH_CAP).find(|&i| self.attachment(i).waiting.load(Ordering::SeqCst) != 0 && self.alive(i)) else {
return;
};
let waiting = &self.attachment(i).waiting;
waiting.wait(waiting.load(Ordering::SeqCst), POLL);
}
}
fn claim_collection(&self, done_by_other: bool) -> bool {
let sup = self.sup();
let me = u32::try_from(self.slot + 1).expect("挂接槽号");
loop {
let owner = sup.request.load(Ordering::SeqCst);
if owner == 0 {
self.yield_to_waiting();
if sup.request.compare_exchange(0, me, Ordering::SeqCst, Ordering::SeqCst).is_ok() {
return true;
}
} else if self.alive(owner as usize - 1) {
sup.request.wait(owner, POLL);
if done_by_other && sup.request.load(Ordering::SeqCst) != owner {
return false;
}
} else if sup.request.compare_exchange(owner, me, Ordering::SeqCst, Ordering::SeqCst).is_ok() {
sup.takeovers.fetch_add(1, Ordering::Relaxed);
return true;
}
}
}
fn drain(&self) -> bool {
let start = std::time::Instant::now();
for i in 0..ATTACH_CAP {
let inside = &self.attachment(i).inside;
loop {
let n = inside.load(Ordering::SeqCst);
if n == 0 || !self.alive(i) {
break;
}
if start.elapsed() >= PATIENCE {
return false;
}
inside.wait(n, POLL);
}
}
true
}
fn release(&self) {
let sup = self.sup();
sup.request.store(0, Ordering::SeqCst);
sup.request.wake_all();
}
fn collect(&self) {
let mut retry = Retry::new();
loop {
if !self.claim_collection(true) {
return;
}
if self.drain() {
break;
}
self.release();
retry.pause();
}
self.reap_dead();
Self::collect_members(&[self]);
self.release();
}
fn collect_group(members: &[&Self]) {
let mut retry = Retry::new();
'retry: loop {
for (k, m) in members.iter().enumerate() {
m.claim_collection(false);
if !m.drain() {
for held in members[..=k].iter().rev() {
held.release();
}
retry.pause();
continue 'retry;
}
}
break;
}
for m in members {
m.reap_dead();
}
Self::collect_members(members);
for m in members.iter().rev() {
m.release();
}
}
pub fn index(&self) -> usize {
self.index
}
pub fn heap_of(off: u64) -> Option<usize> {
usize::try_from(off).ok().map(|o| o / WINDOW).filter(|&k| k < WINDOWS)
}
pub fn incarnation(&self) -> u64 {
self.sup().incarnation.load(Ordering::Acquire)
}
fn path(&self) -> Option<&std::path::Path> {
match &self.backing {
Backing::File { path, .. } => Some(path),
Backing::Anonymous => None,
}
}
pub fn holder_word(&self, target: &Self) -> u32 {
let same_dir = self.path().zip(target.path()).is_some_and(|(a, b)| Registry::of(a).dir() == Registry::of(b).dir());
HEAP_HOLDER | if same_dir { SAME_DIR } else { 0 } | u32::try_from(self.index).expect("堆号")
}
pub fn is_alive(&self) -> bool {
let sup = self.sup();
if sup.dead.load(Ordering::Acquire) != 0 {
return false;
}
let Some(path) = self.path() else { return true };
let owner = Process { pid: sup.owner_pid.load(Ordering::Acquire), start: sup.owner_start.load(Ordering::Acquire) };
if sup.persist.load(Ordering::Acquire) != 0 || owner.alive() {
return true;
}
sup.dead.store(1, Ordering::Release);
Registry::of(path).bury(path, self.index, self.incarnation());
false
}
fn alive_cached(&self) -> bool {
if self.sup().dead.load(Ordering::Acquire) != 0 {
return false;
}
let now = u64::try_from(self.born.elapsed().as_nanos()).unwrap_or(u64::MAX);
let last = self.checked.load(Ordering::Relaxed);
if u128::from(now.saturating_sub(last)) < ALIVE_RECHECK.as_nanos() {
return true;
}
let alive = self.is_alive();
if alive {
self.checked.store(now, Ordering::Relaxed);
}
alive
}
fn held_by(members: &[&Self], holder: u32, incarnation: u64) -> bool {
holder & HEAP_HOLDER != 0 && members.iter().any(|m| m.index == (holder & HOLDER_INDEX) as usize && m.incarnation() == incarnation)
}
fn release_dead_holders(&self) {
let Some(path) = self.path() else { return };
let registry = Registry::of(path);
let mut verdicts: Vec<((usize, u64), Liveness)> = Vec::new();
for i in 0..self.sup().entries.load(Ordering::Acquire) {
let e = self.entry(i);
let holder = e.holder.load(Ordering::Acquire);
if e.ptr.load(Ordering::Acquire) == 0 || holder & (HEAP_HOLDER | SAME_DIR) != HEAP_HOLDER | SAME_DIR {
continue;
}
let key = ((holder & HOLDER_INDEX) as usize, e.holder_incarnation.load(Ordering::Acquire));
let verdict = if let Some(&(_, v)) = verdicts.iter().find(|(k, _)| *k == key) {
v
} else {
let v = registry.liveness(key.0, Some(key.1));
verdicts.push((key, v));
v
};
if matches!(verdict, Liveness::Dead | Liveness::Gone) {
self.release_entry(i);
}
}
}
pub fn sup(&self) -> &Super {
unsafe { &*self.window.as_ptr().cast() }
}
fn at<T>(&self, offset: usize) -> *mut T {
self.window.as_ptr().wrapping_add(offset).cast()
}
pub fn ptr(&self, off: u64) -> *mut u8 {
self.space.region().base().as_ptr().wrapping_add(usize::try_from(off).expect("公开偏移"))
}
pub fn owns(&self, off: u64) -> bool {
usize::try_from(off).is_ok_and(|o| o / WINDOW == self.index)
}
fn pool(&self) -> &Pool {
self.pool.get_or_init(|| Pool::new(self.threads))
}
fn commit(&self, segment: Segment, end: usize) {
let committed = &self.sup().committed[segment.index()];
let have = usize::try_from(committed.load(Ordering::Acquire)).expect("窗口内偏移");
if have >= end {
return;
}
let (start, limit) = self.layout.segment(segment);
let to = end.next_multiple_of(PAGE).min(limit);
let from = have.max(start);
if to <= from {
return;
}
self.backing.commit(from, to - from);
committed.fetch_max(to as u64, Ordering::AcqRel);
}
fn type_entry(&self, ty: u32) -> &TypeEntry {
unsafe { &*self.at::<TypeEntry>(self.layout.types).add(ty as usize) }
}
pub fn edges(&self, ty: u32) -> &[u32] {
let e = self.type_entry(ty);
let (map, n) = (e.map.load(Ordering::Relaxed) as usize, e.edges.load(Ordering::Relaxed) as usize);
unsafe { core::slice::from_raw_parts(self.at::<u32>(self.layout.map).add(map), n) }
}
pub fn has_edges(&self, ty: u32) -> bool {
self.type_entry(ty).edges.load(Ordering::Relaxed) != 0
}
fn type_of<T: Shared>(&self, tlab: &Tlab) -> u32 {
let tag = type_name::<T>().as_ptr().addr();
if let Some((t, ty)) = tlab.last.get()
&& t == tag
{
return ty;
}
let ty = self.types.iter().find(|(t, _)| *t == tag).map_or_else(
|| {
let ty = self.register::<T>();
self.types.push((tag, ty));
ty
},
|&(_, ty)| ty,
);
tlab.last.set(Some((tag, ty)));
ty
}
fn register<T: Shared>(&self) -> u32 {
let (map, key) = Fnv::of::<T>();
let sup = self.sup();
let known = (sup.types.load(Ordering::Acquire) as usize).min(TYPE_CAP);
if let Some(ty) = (0..u32::try_from(known).expect("类型表容量")).find(|&ty| self.type_entry(ty).has_key(key)) {
return ty;
}
let ty = sup.types.fetch_add(1, Ordering::AcqRel);
assert!((ty as usize) < TYPE_CAP, "公开堆的类型表满了");
let edges = map.as_slice();
let n = u32::try_from(edges.len()).expect("指针槽个数");
let start = sup.map.fetch_add(n, Ordering::AcqRel);
assert!((start + n) as usize <= MAP_CAP, "公开堆的指针图满了");
self.commit(Segment::Types, self.layout.types + (ty as usize + 1) * size_of::<TypeEntry>());
self.commit(Segment::Map, self.layout.map + (start + n) as usize * size_of::<u32>());
unsafe { self.at::<u32>(self.layout.map).add(start as usize).copy_from_nonoverlapping(edges.as_ptr(), edges.len()) };
let e = self.type_entry(ty);
e.edges.store(n, Ordering::Relaxed);
e.map.store(start, Ordering::Relaxed);
e.size.store(u32::try_from(size_of::<T>()).expect("对象不超过 4 GiB"), Ordering::Relaxed);
for (k, v) in e.key.iter().zip(key) {
k.store(v, Ordering::Relaxed);
}
e.ready.store(1, Ordering::Release);
ty
}
fn same_type<T: Shared>(&self, ty: u32) -> bool {
let (_, key) = Fnv::of::<T>();
self.type_entry(ty).has_key(key)
}
fn entry(&self, i: u32) -> &Entry {
unsafe { &*self.at::<Entry>(self.layout.entries).add(i as usize) }
}
pub fn claim_entry(&self, off: u64) -> u32 {
self.claim_entry_for(off, u32::try_from(self.slot + 1).expect("挂接槽号"), 0)
}
pub fn claim_entry_for(&self, off: u64, holder: u32, incarnation: u64) -> u32 {
let sup = self.sup();
let i = Stack::on(&sup.free_entries).pop(|i| &self.entry(i).next).unwrap_or_else(|| {
let i = sup.entries.fetch_add(1, Ordering::AcqRel);
assert!((i as usize) < self.layout.entry_cap, "公开堆的入口表满了");
self.commit(Segment::Entries, self.layout.entries + (i as usize + 1) * size_of::<Entry>());
i
});
let e = self.entry(i);
e.holder.store(holder, Ordering::Relaxed);
e.holder_incarnation.store(incarnation, Ordering::Relaxed);
e.ptr.store(off, Ordering::Release);
i
}
pub fn disown_entry(&self, i: u32) {
self.entry(i).holder.store(0, Ordering::Release);
}
pub fn release_entry(&self, i: u32) {
let e = self.entry(i);
e.holder.store(0, Ordering::Release);
e.ptr.store(0, Ordering::Release);
Stack::on(&self.sup().free_entries).push(i, &e.next);
}
fn state(&self, i: u32) -> &BlockState {
unsafe { &*self.at::<BlockState>(self.layout.states).add(i as usize) }
}
fn block(&self, i: u32) -> Block {
unsafe { Block::at(self.at(self.layout.blocks + i as usize * BLOCK)) }
}
fn open_blocks(&self, n: usize) -> u32 {
let count = u32::try_from(n).expect("块数");
let i = self.sup().blocks.fetch_add(count, Ordering::AcqRel);
assert!(i as usize + n <= self.layout.max_blocks, "公开堆的窗口用完了");
self.commit(Segment::States, self.layout.states + (i as usize + n) * size_of::<BlockState>());
self.backing.commit(self.layout.blocks + i as usize * BLOCK, n * BLOCK);
i
}
fn acquire(&self) -> Block {
let sup = self.sup();
sup.allocated.fetch_add(BLOCK as u64, Ordering::Relaxed);
let i = Stack::on(&sup.available).pop(|i| &self.state(i).next).unwrap_or_else(|| {
let i = self.open_blocks(1);
self.state(i).kind.store(Kind::Small as u32, Ordering::Release);
i
});
let b = self.block(i);
b.reused();
b
}
fn alloc_large(&self, bytes: usize) -> (*mut u8, u32, u32) {
let n = bytes.div_ceil(BLOCK);
let i = self.open_blocks(n);
self.sup().allocated.fetch_add((n * BLOCK) as u64, Ordering::Relaxed);
(self.block(i).line(0), i, u32::try_from(n).expect("块数"))
}
fn publish_large(&self, first: u32, n: u32) {
for j in first + 1..first + n {
self.state(j).kind.store(Kind::LargeTail as u32, Ordering::Release);
}
self.state(first).kind.store(Kind::LargeHead as u32, Ordering::Release);
}
fn collect_members(members: &[&Self]) {
let in_group = |e: &Entry| members.len() > 1 && Self::held_by(members, e.holder.load(Ordering::Acquire), e.holder_incarnation.load(Ordering::Acquire));
let mut epochs = Vec::with_capacity(members.len());
let mut roots = Vec::new();
let mut blocks = 0;
for (m, heap) in members.iter().enumerate() {
let sup = heap.sup();
let last = sup.epoch.load(Ordering::Acquire).max(sup.marking.load(Ordering::Acquire));
let epoch = last.checked_add(1).filter(|&e| e <= MAX_EPOCH).expect("纪元用完了");
sup.marking.store(epoch, Ordering::Release);
epochs.push(epoch);
let n = sup.blocks.load(Ordering::Acquire) as usize;
blocks += n;
heap.commit(Segment::States, heap.layout.states + n * size_of::<BlockState>());
heap.commit(Segment::Entries, heap.layout.entries + sup.entries.load(Ordering::Acquire) as usize * size_of::<Entry>());
heap.release_dead_holders();
for i in 0..sup.entries.load(Ordering::Acquire) {
let e = heap.entry(i);
let off = e.ptr.load(Ordering::Acquire);
if off != 0 && !in_group(e) {
roots.push((m, PHeader::of(heap.ptr(off)).expose_provenance()));
}
}
}
let marked: Vec<Member<'_>> = members.iter().zip(&epochs).map(|(&heap, &epoch)| Member { heap, epoch }).collect();
let found = Injector::new();
let pool = members[0].pool();
let grey = Injector::new();
Marker::new(&marked, (members.len() > 1).then_some(&found), &grey, pool.sized(blocks)).run(pool, &roots);
if members.len() > 1 {
Self::reregister(members, &found);
}
for (heap, epoch) in members.iter().zip(epochs) {
heap.sweep_all(epoch);
}
}
fn reregister(members: &[&Self], found: &Injector<(usize, u64)>) {
let old: Vec<Vec<u32>> = members
.iter()
.map(|heap| {
(0..heap.sup().entries.load(Ordering::Acquire))
.filter(|&i| {
let e = heap.entry(i);
e.ptr.load(Ordering::Acquire) != 0 && Self::held_by(members, e.holder.load(Ordering::Acquire), e.holder_incarnation.load(Ordering::Acquire))
})
.collect()
})
.collect();
let mut edges = Vec::new();
loop {
match found.steal() {
Steal::Success(e) => edges.push(e),
Steal::Retry => {}
Steal::Empty => break,
}
}
edges.sort_unstable();
edges.dedup();
for (source, off) in edges {
let target = members.iter().find(|m| m.owns(off)).expect("找到的边都指向组里的堆");
target.claim_entry_for(off, members[source].holder_word(target), members[source].incarnation());
}
for (heap, old) in members.iter().zip(old) {
for i in old {
heap.release_entry(i);
}
}
}
fn sweep_all(&self, epoch: u32) {
let sup = self.sup();
let blocks = sup.blocks.load(Ordering::Acquire) as usize;
let pool = self.pool();
let workers = pool.sized(blocks);
sup.available.store(0, Ordering::Release);
let cursor = AtomicUsize::new(0);
let swept = pool.run(workers, |_| self.sweep_some(&cursor, blocks, epoch));
let mut live = 0;
for (bytes, dead) in swept {
live += bytes;
for head in dead {
self.free_large(head);
}
}
sup.live.store(live as u64, Ordering::Relaxed);
sup.allocated.store(0, Ordering::Relaxed);
sup.collections.fetch_add(1, Ordering::AcqRel);
sup.epoch.store(epoch, Ordering::Release);
}
fn sweep_some(&self, cursor: &AtomicUsize, blocks: usize, epoch: u32) -> (usize, Vec<u32>) {
let (mut live, mut dead) = (0, Vec::new());
loop {
let start = cursor.fetch_add(SWEEP_BATCH, Ordering::AcqRel);
if start >= blocks {
return (live, dead);
}
for i in start..(start + SWEEP_BATCH).min(blocks) {
let i = u32::try_from(i).expect("块序号");
match Kind::from(self.state(i).kind.load(Ordering::Acquire)) {
Kind::Small => {
let (state, bytes) = unsafe { self.block(i).sweep::<PHeader>(epoch, None) };
live += bytes;
if !matches!(state, State::Full) {
Stack::on(&self.sup().available).push(i, &self.state(i).next);
}
}
Kind::LargeHead => {
let h = unsafe { &*self.block(i).line(0).cast::<Core>() };
if h.is_marked(epoch) {
live += h.bytes();
} else {
dead.push(i);
}
}
Kind::LargeTail | Kind::Unused => {}
}
}
}
}
fn free_large(&self, head: u32) {
let n = unsafe { &*self.block(head).line(0).cast::<Core>() }.bytes().div_ceil(BLOCK);
let tails = head + 1..head + u32::try_from(n).expect("块数");
for j in tails.filter(|&j| Kind::from(self.state(j).kind.load(Ordering::Acquire)) == Kind::LargeTail).chain([head]) {
let b = self.block(j);
unsafe { b.reset() };
b.reused();
self.state(j).kind.store(Kind::Small as u32, Ordering::Release);
Stack::on(&self.sup().available).push(j, &self.state(j).next);
}
}
}
#[cfg(target_os = "linux")]
impl Drop for Inner {
fn drop(&mut self) {
if self.slot < ATTACH_CAP {
let a = self.attachment(self.slot);
a.start.store(0, Ordering::Relaxed);
a.pid.store(0, Ordering::Release);
}
if let Backing::File { path, owner: true, .. } = &self.backing
&& self.sup().persist.load(Ordering::Acquire) == 0
{
self.sup().dead.store(1, Ordering::Release);
Registry::of(path).bury(path, self.index, self.incarnation());
}
unsafe { self.space.region().unmap(self.index) };
self.space.release(self.index);
let spare = *self.spare.get_mut();
if !spare.is_null() {
drop(unsafe { Box::from_raw(spare) });
}
}
}
#[cfg(target_os = "linux")]
pub struct PublicHeap(Arc<Inner>);
#[cfg(target_os = "linux")]
impl From<Inner> for PublicHeap {
fn from(inner: Inner) -> Self {
Self(Arc::new(inner))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg(target_os = "linux")]
pub struct HeapDead;
#[cfg(target_os = "linux")]
impl core::fmt::Display for HeapDead {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("公开堆已经死了(建它的进程不在了)")
}
}
#[cfg(target_os = "linux")]
impl std::error::Error for HeapDead {}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg(target_os = "linux")]
pub struct PublicStats {
pub live: usize,
pub allocated: usize,
pub blocks: usize,
pub collections: u64,
pub takeovers: u64,
}
#[cfg(target_os = "linux")]
impl PublicHeap {
pub fn id(&self) -> usize {
self.0.index
}
pub fn persist(&self) {
self.0.sup().persist.store(1, Ordering::Release);
}
pub fn is_alive(&self) -> bool {
self.0.is_alive()
}
pub fn mutate_with<R>(&self, other: &PublicHeap, f: impl for<'a, 'b> FnOnce(&PublicMutator<'a>, &PublicMutator<'b>) -> R) -> R {
assert!(self.id() != other.id(), "两个不同的公开堆");
if self.id() < other.id() { self.mutate(|ma| other.mutate(|mb| f(ma, mb))) } else { other.mutate(|mb| self.mutate(|ma| f(ma, mb))) }
}
pub fn try_mutate<R>(&self, f: impl for<'p> FnOnce(&PublicMutator<'p>) -> R) -> Result<R, HeapDead> {
if !self.0.alive_cached() {
return Err(HeapDead);
}
Ok(self.mutate(f))
}
pub fn attached(&self) -> usize {
(0..ATTACH_CAP).filter(|&i| self.0.attachment(i).pid.load(Ordering::Acquire) != 0).count()
}
pub fn mutate<R>(&self, f: impl for<'p> FnOnce(&PublicMutator<'p>) -> R) -> R {
let spare = self.0.spare.swap(null_mut(), Ordering::AcqRel);
let mut tlab = if spare.is_null() {
Box::default()
} else {
unsafe { Box::from_raw(spare) }
};
let r = {
let _gate = Gate::enter(&self.0);
tlab.adopt((Arc::as_ptr(&self.0).addr(), self.0.sup().collections.load(Ordering::Acquire)));
let epoch = self.0.sup().epoch.load(Ordering::Acquire);
f(&PublicMutator { heap: &self.0, tlab: &tlab, epoch, _brand: PhantomData })
};
let tlab = Box::into_raw(tlab);
if self.0.spare.compare_exchange(null_mut(), tlab, Ordering::AcqRel, Ordering::Relaxed).is_err() {
drop(unsafe { Box::from_raw(tlab) });
}
r
}
pub fn collect(&self) {
self.0.collect();
}
pub fn collect_group(heaps: &[&PublicHeap]) {
let mut members: Vec<&Inner> = heaps.iter().map(|h| &*h.0).filter(|m| m.is_alive()).collect();
members.sort_by_key(|m| m.index);
assert!(members.windows(2).all(|w| w[0].index != w[1].index), "同一个公开堆不能在组里出现两次");
if !members.is_empty() {
Inner::collect_group(&members);
}
}
pub fn incarnation(&self) -> u64 {
self.0.incarnation()
}
pub fn stats(&self) -> PublicStats {
let sup = self.0.sup();
PublicStats {
live: usize::try_from(sup.live.load(Ordering::Relaxed)).unwrap_or(usize::MAX),
allocated: usize::try_from(sup.allocated.load(Ordering::Relaxed)).unwrap_or(usize::MAX),
blocks: sup.blocks.load(Ordering::Relaxed) as usize,
collections: sup.collections.load(Ordering::Relaxed),
takeovers: sup.takeovers.load(Ordering::Relaxed),
}
}
}
#[cfg(target_os = "linux")]
pub trait PublicHeapInternal {
fn is(&self, inner: &Arc<Inner>) -> bool;
}
#[cfg(target_os = "linux")]
impl PublicHeapInternal for PublicHeap {
fn is(&self, inner: &Arc<Inner>) -> bool {
Arc::ptr_eq(&self.0, inner)
}
}
#[cfg(target_os = "linux")]
struct Gate<'h> {
inside: &'h AtomicU32,
request: &'h AtomicU32,
}
#[cfg(target_os = "linux")]
impl<'h> Gate<'h> {
fn enter(heap: &'h Inner) -> Self {
let request = &heap.sup().request;
let a = heap.attachment(heap.slot);
let (inside, waiting) = (&a.inside, &a.waiting);
let mut queued = false;
let leave_queue = |queued: &mut bool| {
if core::mem::take(queued) && waiting.fetch_sub(1, Ordering::SeqCst) == 1 {
waiting.wake_all();
}
};
loop {
let owner = request.load(Ordering::SeqCst);
if owner != 0 {
if heap.alive(owner as usize - 1) {
if !queued {
waiting.fetch_add(1, Ordering::SeqCst);
queued = true;
}
request.wait(owner, POLL);
} else {
leave_queue(&mut queued);
heap.collect();
}
continue;
}
inside.fetch_add(1, Ordering::SeqCst);
if request.load(Ordering::SeqCst) == 0 {
leave_queue(&mut queued);
return Self { inside, request };
}
inside.fetch_sub(1, Ordering::SeqCst);
inside.wake_all();
}
}
}
#[cfg(target_os = "linux")]
impl Drop for Gate<'_> {
fn drop(&mut self) {
self.inside.fetch_sub(1, Ordering::SeqCst);
if self.request.load(Ordering::SeqCst) != 0 {
self.inside.wake_all();
}
}
}
#[cfg(target_os = "linux")]
pub struct PublicMutator<'p> {
heap: &'p Arc<Inner>,
tlab: &'p Tlab,
epoch: u32,
_brand: Invariant<'p>,
}
#[cfg(target_os = "linux")]
impl<'p> PublicMutator<'p> {
pub fn alloc<T: Shared>(&self, value: T) -> PublicGc<'p, T> {
const {
assert!(!core::mem::needs_drop::<T>(), "公开堆的对象不能有析构");
assert!(align_of::<T>() <= GRANULE, "对象数据的对齐不能超过 8 字节");
};
let bytes = (PHEADER + size_of::<T>()).next_multiple_of(GRANULE);
let ty = self.heap.type_of::<T>(self.tlab);
let large = bytes > LARGE;
let (p, run) = if large {
let (p, first, n) = self.heap.alloc_large(bytes);
(p, Some((first, n)))
} else {
(self.alloc_small(bytes), None)
};
let gc = unsafe {
p.cast::<PHeader>().write(PHeader::new(bytes, large, ty));
let data = PHeader::data(p.cast());
data.cast::<T>().write(value);
PublicGc::from_data(data)
};
match run {
Some((first, n)) => self.heap.publish_large(first, n),
None => Block::containing(p).set_start(p),
}
gc
}
pub fn root<B: PublicBrand>(&self, gc: PublicGc<'p, B::Of<'p>>) -> Public<B> {
let entry = self.heap.claim_entry(gc.offset());
Public::new(self.heap.clone(), entry, unsafe { NonNull::new_unchecked(gc.as_ptr().cast_mut().cast()) })
}
pub fn find<B: PublicBrand>(&self, index: u32) -> Option<Public<B>> {
let sup = self.heap.sup();
if index >= sup.entries.load(Ordering::Acquire) {
return None;
}
let off = self.heap.entry(index).ptr.load(Ordering::Acquire);
if off == 0 || !self.heap.owns(off) {
return None;
}
let data = self.heap.ptr(off);
let ty = unsafe { (*PHeader::of(data)).ty };
if !self.heap.same_type::<B::Of<'p>>(ty) {
return None;
}
let entry = self.heap.claim_entry(off);
Some(Public::new(self.heap.clone(), entry, NonNull::new(data).expect("对象地址非空")))
}
pub fn release(&self, index: u32) -> bool {
let heap = self.heap;
if index >= heap.sup().entries.load(Ordering::Acquire) {
return false;
}
let e = heap.entry(index);
if e.ptr.load(Ordering::Acquire) == 0 || e.holder.load(Ordering::Acquire) != 0 {
return false;
}
heap.release_entry(index);
true
}
fn alloc_small(&self, bytes: usize) -> *mut u8 {
self.tlab.bump(bytes, self.epoch, || self.heap.acquire(), |_| self.heap.acquire())
}
}
#[cfg(target_os = "linux")]
pub trait PublicMutatorInternal {
fn is(&self, inner: &Arc<Inner>) -> bool;
fn at(&self, off: u64) -> *mut u8;
fn index(&self) -> usize;
fn register(&self, off: u64, holder: &PublicMutator<'_>);
fn incarnation(&self) -> u64;
}
#[cfg(target_os = "linux")]
impl PublicMutatorInternal for PublicMutator<'_> {
fn is(&self, inner: &Arc<Inner>) -> bool {
Arc::ptr_eq(self.heap, inner)
}
fn at(&self, off: u64) -> *mut u8 {
self.heap.ptr(off)
}
fn index(&self) -> usize {
self.heap.index
}
fn register(&self, off: u64, holder: &PublicMutator<'_>) {
self.heap.claim_entry_for(off, holder.heap.holder_word(self.heap), holder.heap.incarnation());
}
fn incarnation(&self) -> u64 {
self.heap.incarnation()
}
}