//! Block allocation and reference counting (Perceus runtime side). //! //! The compiler inserts `tl_dup`/`tl_drop`; their fast paths are inline in //! the C header. This module implements the slow paths: freeing, which is //! iterative so dropping a long list cannot overflow a small fiber stack, //! and shared (atomic) counts. //! //! Blocks come from [`blocks`]: mimalloc with the `mimalloc` feature (the //! default), the system allocator without it. Only blocks: the runtime's //! own Rust allocations (queues, mailboxes, worklists) keep Rust's global //! allocator. A block may be freed on another thread than the one that //! allocated it (actors migrate, messages move); both allocators allow it. //! Sanitizer builds link a runtime built without the feature, so ASan sees //! every block (`scripts/ci.sh`). use std::alloc::{Layout, handle_alloc_error}; use std::sync::atomic::{AtomicI32, Ordering}; use crate::abi::{ Block, Ctx, Header, SCAN_LARGE, TAG_ARRAY, TAG_BYTES, TAG_CLOSURE, TAG_FLOAT, TAG_REF, TAG_RUNTIME_MIN, TAG_STRING, Value, int_get, is_ptr, }; /// Blocks whose count reached zero, waiting for their children to be /// released. Owned by each actor so draining never touches shared state. /// /// A drop drains it a step at a time (issue #158): at most [`DRAIN_BLOCKS`] /// blocks, then the rest waits for the actor's next safe point /// ([`continue_drain`]), so freeing a large structure doesn't hold its /// thread. Everything left is freed when the actor ends. #[derive(Default)] pub struct DropStack { pending: Vec<*mut Block>, /// Large blocks being released from their end: each with the number /// of its scanned fields still to release. partial: Vec<(*mut Block, usize)>, draining: bool, } /// The blocks one step of a drain frees: about 40–60 µs (a list of 4,096 /// cells takes 45 µs). const DRAIN_BLOCKS: u32 = 4096; /// A block with more scanned fields than this is set aside and released /// a step at a time, from its end: [`DRAIN_FIELDS`] fields per step. const LARGE: usize = 4096; const DRAIN_FIELDS: usize = 65536; impl DropStack { /// Whether dead blocks wait to be freed. pub(crate) fn has_pending(&self) -> bool { !self.pending.is_empty() || !self.partial.is_empty() } /// Set `b` aside to release in steps if it is large (more than /// [`LARGE`] fields, and nothing to run when freed); whether it was. /// /// # Safety /// `b` must be dead, with `scan_fsize` [`SCAN_LARGE`]. #[cold] #[inline(never)] unsafe fn set_aside(&mut self, b: *mut Block) -> bool { // SAFETY: forwarded caller guarantee. let (n, _) = unsafe { scanned(b) }; // SAFETY: as above. if n > LARGE && plain(unsafe { (*b).header.tag }) { self.partial.push((b, n)); return true; } false } /// Free up to `blocks` dead blocks; whether it stopped there (more /// may be left). Large blocks are only set aside here. /// /// # Safety /// Only blocks whose last reference was released are queued. #[inline(always)] unsafe fn free_some(&mut self, mut blocks: u32) -> bool { while let Some(b) = self.pending.pop() { // SAFETY: `b` is dead, and live until freed. unsafe { if (*b).header.scan_fsize == SCAN_LARGE && self.set_aside(b) { continue; } free_block(b, &mut self.pending); } blocks -= 1; if blocks == 0 { return true; } } false } /// One step of a drain: [`DRAIN_BLOCKS`] blocks, or else /// [`DRAIN_FIELDS`] fields of the large block set aside last. Whether /// nothing is left. /// /// # Safety /// As [`DropStack::free_some`]. #[cold] #[inline(never)] unsafe fn step(&mut self) -> bool { // SAFETY: forwarded caller guarantee. if unsafe { self.free_some(DRAIN_BLOCKS) } { return !self.has_pending(); } if let Some((b, left)) = self.partial.last_mut() { let (b, end) = (*b, *left); let start = end.saturating_sub(DRAIN_FIELDS); // SAFETY: `b` is dead; its fields `start..end` were not // released yet. unsafe { let (fields, _) = scanned_fields(b); for i in start..end { release_into(*fields.add(i), &mut self.pending); } } *left = start; if start == 0 { self.partial.pop(); // SAFETY: every field was released; nothing else refers // to `b`. unsafe { blocks::free(b) }; stats::free(); } } !self.has_pending() } } impl Drop for DropStack { fn drop(&mut self) { debug_assert!( !self.has_pending(), "louise: an actor ended with blocks left to free" ); } } /// Continue freeing what an earlier drop left (a step), at a safe point /// of the running actor: when it was preempted or woken. If more is left, /// its next function entry yields again (`reductions` 0). /// /// # Safety /// `ctx` must be the running actor's context. #[inline(always)] pub(crate) unsafe fn continue_drain(ctx: *mut Ctx) { // SAFETY: forwarded caller guarantee. unsafe { let stack = crate::sched::drop_stack(ctx); if stack.has_pending() && !stack.draining { drain_step(ctx, stack); } } } /// # Safety /// `ctx` must be the running actor's context, `stack` its drop stack. #[cold] #[inline(never)] unsafe fn drain_step(ctx: *mut Ctx, stack: &mut DropStack) { stack.draining = true; // SAFETY: only dead blocks are queued. let done = unsafe { stack.step() }; stack.draining = false; if !done { // SAFETY: the running actor's context. unsafe { (*ctx).reductions = 0 }; } } /// Free what an actor's drops left when its body returned, a step at a /// time, yielding to other actors between steps: its exit is recorded /// after. On the actor's own stack. /// /// # Safety /// `ctx` must be the running actor's context, on its own stack. pub(crate) unsafe fn drain_before_exit(ctx: *mut Ctx) { // SAFETY: forwarded caller guarantee. unsafe { while crate::sched::drop_stack(ctx).has_pending() { let stack = crate::sched::drop_stack(ctx); stack.draining = true; let done = stack.step(); stack.draining = false; if !done { crate::sched::preempt_root(ctx); } } } } /// Free everything left when an actor ends (after /// [`drain_before_exit`], what releasing its mailbox dropped), at once. /// /// # Safety /// `ctx` must be the ending actor's context. pub(crate) unsafe fn finish_drain(ctx: *mut Ctx) { // SAFETY: forwarded caller guarantee. unsafe { let stack = crate::sched::drop_stack(ctx); stack.draining = true; while !stack.step() {} stack.draining = false; } } /// The allocator of blocks (see the module documentation). /// /// mimalloc is called directly: its `GlobalAlloc` (the `mimalloc` crate) /// always takes the aligned allocation path, and blocks need no more than /// the 8-byte alignment every mimalloc allocation has. Freeing needs no /// size, so the free path skips computing the block's layout (issue #61). #[cfg(feature = "mimalloc")] mod blocks { use std::alloc::Layout; /// # Safety /// `layout.size()` must be non-zero. pub(super) unsafe fn alloc(layout: Layout) -> *mut u8 { // SAFETY: mimalloc returns 16-byte aligned memory, or null. unsafe { libmimalloc_sys::mi_malloc(layout.size()) }.cast() } /// # Safety /// `b` must be a live block, from [`alloc`]. pub(super) unsafe fn free(b: *mut crate::abi::Block) { // SAFETY: forwarded caller guarantee. unsafe { libmimalloc_sys::mi_free(b.cast()) } } /// # Safety /// `b` must be a live block from [`alloc`] of layout `old`, and `size` /// non-zero. pub(super) unsafe fn realloc(b: *mut u8, old: Layout, size: usize) -> *mut u8 { let _ = old; // SAFETY: forwarded caller guarantee; the result keeps mimalloc's // alignment. unsafe { libmimalloc_sys::mi_realloc(b.cast(), size) }.cast() } } #[cfg(not(feature = "mimalloc"))] mod blocks { use std::alloc::{GlobalAlloc, Layout, System}; /// # Safety /// `layout.size()` must be non-zero. pub(super) unsafe fn alloc(layout: Layout) -> *mut u8 { // SAFETY: forwarded caller guarantee. unsafe { System.alloc(layout) } } /// # Safety /// `b` must be a live block, from [`alloc`]. pub(super) unsafe fn free(b: *mut crate::abi::Block) { // SAFETY: forwarded caller guarantee; the layout is the block's. unsafe { System.dealloc(b.cast(), super::layout_of(b)) } } /// # Safety /// `b` must be a live block from [`alloc`] of layout `old`, and `size` /// non-zero. pub(super) unsafe fn realloc(b: *mut u8, old: Layout, size: usize) -> *mut u8 { // SAFETY: forwarded caller guarantee. unsafe { System.realloc(b, old, size) } } } const HEADER_SIZE: usize = size_of::
(); const WORD: usize = size_of::(); /// Number of scanned fields and the offset (in words) of the first one. /// /// # Safety /// `b` must point to a live block. unsafe fn scanned(b: *mut Block) -> (usize, usize) { // SAFETY: caller guarantees `b` is live. let scan = unsafe { (*b).header.scan_fsize }; if scan == SCAN_LARGE { // SAFETY: large blocks store their count as an int in fields[0]. let n = unsafe { *Block::fields_ptr(b) }; (int_get(n) as usize, 1) } else { (scan as usize, 0) } } /// Size of the raw area that follows the scanned fields, by tag. /// /// # Safety /// `raw` must point at the raw area of a live block with tag `tag`. unsafe fn raw_size(tag: u16, raw: *const u8) -> usize { // SAFETY: these kinds start their raw area with an i64 count (a big // integer's is signed). let first = || unsafe { raw.cast::().read() }; let len = || first() as usize; match tag { TAG_STRING => WORD + len() + 1, TAG_BYTES => WORD + len(), // The spare count, then that many unused slots. TAG_ARRAY => WORD * (1 + len()), // The signed limb count, then the limbs. crate::abi::TAG_BIGINT => WORD * (1 + first().unsigned_abs() as usize), // The length and the capacity, then the capacity's bytes. crate::abi::TAG_BUILDER => { // SAFETY: the capacity is the second word. 2 * WORD + unsafe { raw.cast::().add(1).read() } as usize } TAG_FLOAT | crate::abi::TAG_U64 | crate::abi::TAG_REGION | crate::abi::TAG_FRAME => WORD, // The owned entry's and the borrowed entry's code pointers // (ADR 0068). TAG_CLOSURE => 2 * WORD, crate::abi::TAG_RESOURCE | crate::abi::TAG_DEC => 2 * WORD, TAG_REF | crate::abi::TAG_CAP => 0, t if t < TAG_RUNTIME_MIN => 0, t => panic!("louise: unknown runtime tag {t:#x}"), } } /// # Safety /// `b` must point to a live block. unsafe fn layout_of(b: *mut Block) -> Layout { // SAFETY: caller guarantees `b` is live; the raw area follows the fields. unsafe { let (n, offset) = scanned(b); let words = n + offset; let raw = Block::fields_ptr(b).add(words).cast::(); let size = HEADER_SIZE + words * WORD + raw_size((*b).header.tag, raw); Layout::from_size_align_unchecked(size, WORD) } } /// Size in bytes of a live block, header included. /// /// # Safety /// `b` must point to a live block. pub(crate) unsafe fn block_size(b: *mut Block) -> usize { // SAFETY: forwarded caller guarantee. unsafe { layout_of(b) }.size() } /// The scanned fields of a live block: a pointer to the first, and their /// number. /// /// # Safety /// `b` must point to a live block. pub(crate) unsafe fn scanned_fields(b: *mut Block) -> (*mut Value, usize) { // SAFETY: forwarded caller guarantee. unsafe { let (n, offset) = scanned(b); (Block::fields_ptr(b).add(offset), n) } } /// Allocate `size` uninitialised bytes for a block (counted by the leak /// oracle); the caller writes the header and fields. pub(crate) fn alloc_bytes(_ctx: *mut Ctx, size: usize) -> *mut Block { let layout = Layout::from_size_align(size, WORD).expect("louise: block too large"); // SAFETY: layout has non-zero size (at least the header). let b = unsafe { blocks::alloc(layout) }.cast::(); if b.is_null() { handle_alloc_error(layout); } stats::alloc(); b } /// Resize the unique block `b`, of `old_size` bytes, to `size` bytes (its /// contents up to the smaller size are kept). Returns the block's new /// address; `b` is no longer valid. The live count does not change. /// `old_size` is passed because a caller may have rewritten the block /// (`bytes.build` turns a builder into `Bytes`) before shrinking it. /// /// # Safety /// `b` must be live and unique, `old_size` the size it was allocated (or /// last resized) with, and no other pointer to it may be used afterwards. pub(crate) unsafe fn realloc_block(b: *mut Block, old_size: usize, size: usize) -> *mut Block { let old = Layout::from_size_align(old_size, WORD).expect("louise: block too large"); // SAFETY: forwarded caller guarantee. let new = unsafe { blocks::realloc(b.cast(), old, size) }.cast::(); if new.is_null() { handle_alloc_error(Layout::from_size_align(size, WORD).expect("louise: block too large")); } new } /// A block's count, read atomically. A shared block's count changes on /// other threads (any number of actors may hold one, `std/table` makes /// that common), so even the test that tells a local count from a shared /// one must not be a plain read: it would race with their atomic updates. /// A relaxed load costs a plain load on x86-64 and aarch64. Writes stay /// plain: only a local count is written that way, by its one owner. The C /// fast paths read it the same way (`tl_rc`, louise_rt.h). /// /// # Safety /// `b` must point to a live block. #[inline(always)] pub(crate) unsafe fn rc(b: *mut Block) -> i32 { // SAFETY: caller guarantees `b` is live; the count is an aligned i32. unsafe { AtomicI32::from_ptr(&raw mut (*b).header.rc) }.load(Ordering::Relaxed) } /// Add a reference to `v` from Rust code (the C `tl_dup`); returns `v`. /// /// # Safety /// `v` must be live. pub(crate) unsafe fn dup_value(v: Value) -> Value { if !is_ptr(v) { return v; } let b = v as *mut Block; // SAFETY: caller guarantees `v` is live. unsafe { let rc = rc(b); if (1..RC_STUCK).contains(&rc) { (*b).header.rc = rc + 1; } else { tl_dup_shared(b); } } v } /// A local count stops here instead of overflowing (issue #217): no dup /// or drop moves it again, and the block is never freed. A bounded leak /// replaces a use after free. pub(crate) const RC_STUCK: i32 = i32::MAX; /// A shared count at or past this is saturated: every dup or drop that /// sees it puts it back to [`SHARED_STUCK`]. The gap between the two /// absorbs the dups and drops other threads have in flight, so the count /// never reaches -1 again, nor wraps, without a compare-and-swap loop. pub(crate) const SHARED_SATURATED: i32 = -(1 << 29); /// Where a saturated shared count is held. pub(crate) const SHARED_STUCK: i32 = -(1 << 30); /// Say once that a count saturated: the program now leaks that block. fn saturated() { static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !SAID.swap(true, Ordering::Relaxed) { eprintln!( "louise: a value has too many references to count; it will never be freed (issue #217)" ); } } /// Allocate a block with `rc = 1`. Scanned fields are initialised to unit so /// a block dropped before the caller fills it is still well formed. /// /// `ctx` is not read, and may be null. The safe helpers that build values /// (`values::cell`, `values::string`, ...) rely on this: if allocation /// ever reads the context, they must become `unsafe`. #[unsafe(no_mangle)] pub extern "C" fn tl_alloc( _ctx: *mut Ctx, tag: u16, scan_fsize: u8, raw_bytes: usize, ) -> *mut Block { assert!( scan_fsize != SCAN_LARGE, "louise: large blocks (arrays) are allocated by the runtime only" ); let b = alloc_bytes(_ctx, HEADER_SIZE + scan_fsize as usize * WORD + raw_bytes); // SAFETY: `b` is a fresh allocation large enough for header and fields. unsafe { b.cast::
().write(Header { rc: 1, tag, scan_fsize, flags: 0, }); let fields = Block::fields_ptr(b); for i in 0..scan_fsize as usize { fields.add(i).write(crate::abi::UNIT); } } b } /// Increment the count of a shared (negative rc) block, or of one whose /// count saturated, which stays as it is. /// /// # Safety /// `b` must point to a live block. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_dup_shared(b: *mut Block) { // SAFETY: caller guarantees `b` is live. Immortal blocks (rc 0, static // literals) are never counted. let local = unsafe { rc(b) }; if local == 0 { return; } if local == RC_STUCK { saturated(); return; } // SAFETY: shared blocks are only ever accessed atomically. let rc = unsafe { AtomicI32::from_ptr(&raw mut (*b).header.rc) }; if rc.fetch_sub(1, Ordering::Relaxed) <= SHARED_SATURATED { rc.store(SHARED_STUCK, Ordering::Relaxed); saturated(); } } /// Returns true when this call released the last reference to `b`. /// /// # Safety /// `b` must point to a live block whose count is <= 1 or shared. unsafe fn release(b: *mut Block) -> bool { // SAFETY: caller guarantees `b` is live. let local = unsafe { rc(b) }; if local == 0 || local == RC_STUCK { return false; // immortal (a static literal), or saturated } if local > 0 { debug_assert_eq!(local, 1, "louise: release on a block with rc > 1"); return true; } // SAFETY: shared blocks are only ever accessed atomically. let rc = unsafe { AtomicI32::from_ptr(&raw mut (*b).header.rc) }; let old = rc.fetch_add(1, Ordering::Release); if old == -1 { // ThreadSanitizer does not model fences, so under it an acquire // load of the count does the fence's job, as `Arc` does: every // other holder's release must happen before the block is freed. #[cfg(not(louise_rt_tsan))] std::sync::atomic::fence(Ordering::Acquire); #[cfg(louise_rt_tsan)] rc.load(Ordering::Acquire); return true; } if old <= SHARED_SATURATED { rc.store(SHARED_STUCK, Ordering::Relaxed); } false } /// Drop a block whose local count is 1, which is shared, or whose count /// saturated (left as it is). /// /// # Safety /// `ctx` must be the running actor's context and `b` a live block. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_drop_slow(ctx: *mut Ctx, b: *mut Block) { // SAFETY: caller guarantees `b` is live. if !unsafe { release(b) } { return; } // A block without children or finalizer (a Float, a String, a // nullary-free leaf) is freed at once, without the worklist: half the // drops of numeric code. // SAFETY: `b` is live until freed. unsafe { let (scan, tag) = ((*b).header.scan_fsize, (*b).header.tag); if scan == 0 && plain(tag) { blocks::free(b); stats::free(); return; } } // SAFETY: forwarded caller guarantee; `b` is dead. unsafe { drop_queued(ctx, b) } } /// Free the dead block `b` and what dies with it, through the actor's /// worklist, [`DRAIN_BLOCKS`] at most. Out of line, so that the leaf case /// above stays small enough to inline into callers (issue #158). /// /// # Safety /// `ctx` must be the running actor's context; `b` dead. #[inline(never)] unsafe fn drop_queued(ctx: *mut Ctx, b: *mut Block) { // SAFETY: the running actor's context always has a live actor. let stack = unsafe { crate::sched::drop_stack(ctx) }; stack.pending.push(b); if stack.draining { return; // An outer tl_drop_slow on this actor is already draining. } stack.draining = true; // SAFETY: only blocks whose last reference was released are pushed. let stopped = unsafe { stack.free_some(DRAIN_BLOCKS) }; stack.draining = false; if stopped || !stack.partial.is_empty() { // The rest at the next safe point: the next function entry yields, // and the actor continues when it runs again (`continue_drain`). // SAFETY: the running actor's context. unsafe { (*ctx).reductions = 0 }; } } /// Deallocate a unique block whose children were moved out by the caller /// (Perceus drop specialisation: matching on a unique cell). /// /// # Safety /// `b` must be live with local rc 1, and its fields must not be used again. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_free(_ctx: *mut Ctx, b: *mut Block) { // SAFETY: caller guarantees `b` is live and unique. unsafe { debug_assert_eq!((*b).header.rc, 1, "louise: tl_free on a shared block"); blocks::free(b); } stats::free(); } /// Whether freeing a block with this tag needs nothing but its children /// released: not a region, a handler frame or a resource. fn plain(tag: u16) -> bool { !matches!( tag, crate::abi::TAG_REGION | crate::abi::TAG_FRAME | crate::abi::TAG_RESOURCE ) } /// Release `b`'s children (queuing those that die) and deallocate `b`. /// /// # Safety /// `b` must be live and unreachable. unsafe fn free_block(b: *mut Block, pending: &mut Vec<*mut Block>) { // SAFETY: `b` is live until the dealloc at the end. unsafe { match (*b).header.tag { crate::abi::TAG_REGION => crate::region::free_region(b, pending), crate::abi::TAG_FRAME => crate::handlers::free_frame(b, pending), crate::abi::TAG_RESOURCE => crate::resource::finalize_resource(b), _ => {} } let (fields, n) = scanned_fields(b); // A reuse token's kept fields are dead: their values are owned by // the bindings they were moved to (ADR 0040 Revision 2, issue // #193; the flag is set at the release, cleared at the reuse). if (*b).header.flags & crate::abi::FLAG_TOKEN == 0 { for i in 0..n { release_into(*fields.add(i), pending); } } blocks::free(b); } stats::free(); } /// Release a value from Rust code (the C `tl_drop`). /// /// # Safety /// `ctx` must be the running actor's context; `v` must be owned. pub unsafe fn drop_value(ctx: *mut Ctx, v: Value) { if !is_ptr(v) { return; } let b = v as *mut Block; // SAFETY: an owned pointer value refers to a live block. unsafe { let rc = rc(b); if (2..RC_STUCK).contains(&rc) { (*b).header.rc = rc - 1; } else { tl_drop_slow(ctx, b); } } } /// Release a value outside any actor's context (the scheduler freeing a /// message it made, whose receiver is gone). Iterative, with its own /// worklist. /// /// # Safety /// `v` must be an owned value. pub(crate) unsafe fn drop_detached(v: Value) { let mut pending = Vec::new(); // SAFETY: caller guarantees `v` is owned; blocks pushed are dead. unsafe { release_into(v, &mut pending); while let Some(b) = pending.pop() { free_block(b, &mut pending); } } } /// Live block accounting: the leak oracle for Perceus tests; and, from /// the same per-thread counts, the total of blocks ever allocated (the /// `LOUISE_STATS` measurement, `docs/runtime-abi.md`). /// /// Each thread counts the blocks it allocates and frees; the number of /// live blocks is the sum. A shared counter would make every allocation /// and free an atomic read-modify-write, which cost 20–30% of the run /// time of allocation-heavy programs. A block freed on another thread /// than the one that allocated it makes one count go up and another down; /// the sum stays right. The total only ever goes up: a free on another /// thread does not lower it. pub mod stats { #[cfg(feature = "stats")] mod counts { use std::cell::Cell; use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::{Mutex, PoisonError}; /// A thread's counts: the blocks it has live (`allocated − freed`) /// and the blocks it ever allocated. pub struct Counts { live: AtomicI64, allocs: AtomicI64, } /// The counts of every thread that ever allocated or freed a block /// (one leaked struct per thread, so a count outlives its thread). static ALL: Mutex> = Mutex::new(Vec::new()); thread_local! { // No destructor: usable while thread-locals are destroyed. static MINE: Cell> = const { Cell::new(None) }; } /// Inlined into every allocation and free, on actor fibers that /// move between threads: see the `Fiber` safety comment in /// `sched` for why that is sound today, and what is left to /// review (`docs/code-health.md`, M7). #[inline] fn mine() -> &'static Counts { MINE.get().unwrap_or_else(register) } #[cold] fn register() -> &'static Counts { let counts = Box::leak(Box::new(Counts { live: AtomicI64::new(0), allocs: AtomicI64::new(0), })); ALL.lock() .unwrap_or_else(PoisonError::into_inner) .push(counts); MINE.set(Some(counts)); counts } #[inline] pub fn alloc() { let counts = mine(); // Only this thread writes its counts: no read-modify-write. counts .live .store(counts.live.load(Ordering::Relaxed) + 1, Ordering::Relaxed); counts .allocs .store(counts.allocs.load(Ordering::Relaxed) + 1, Ordering::Relaxed); } #[inline] pub fn free() { let counts = mine(); counts .live .store(counts.live.load(Ordering::Relaxed) - 1, Ordering::Relaxed); } fn sum(of: fn(&Counts) -> &AtomicI64) -> i64 { ALL.lock() .unwrap_or_else(PoisonError::into_inner) .iter() .map(|c| of(c).load(Ordering::Relaxed)) .sum() } pub fn live() -> i64 { sum(|c| &c.live) } pub fn allocs() -> i64 { sum(|c| &c.allocs) } } #[inline] pub fn alloc() { #[cfg(feature = "stats")] counts::alloc(); } #[inline] pub fn free() { #[cfg(feature = "stats")] counts::free(); } /// The number of live blocks; meaningful when no other thread is /// allocating or freeing (at exit, say). -1 without the `stats` /// feature. #[unsafe(no_mangle)] pub extern "C" fn tl_stats_live_blocks() -> i64 { #[cfg(feature = "stats")] return counts::live(); #[cfg(not(feature = "stats"))] return -1; } /// The number of blocks ever allocated, summed over threads; /// meaningful when no other thread is allocating (at exit, say). -1 /// without the `stats` feature. #[unsafe(no_mangle)] pub extern "C" fn tl_stats_allocations() -> i64 { #[cfg(feature = "stats")] return counts::allocs(); #[cfg(not(feature = "stats"))] return -1; } } /// Release one count of `v` while the drop worklist is being drained /// (freeing a block that owns `v`). /// /// # Safety /// `v` must be an owned value. pub(crate) unsafe fn release_into(v: Value, pending: &mut Vec<*mut Block>) { if !is_ptr(v) { return; } let b = v as *mut Block; // SAFETY: caller guarantees `v` is live. unsafe { let rc = rc(b); if (2..RC_STUCK).contains(&rc) { (*b).header.rc = rc - 1; } else if release(b) { pending.push(b); } } } #[cfg(test)] mod tests { use super::*; use crate::abi::UNIT; use crate::abi::int; use crate::values::{list, string}; /// Run `continue_drain` until nothing is left; the number of steps. unsafe fn steps(ctx: *mut Ctx) -> usize { // SAFETY: forwarded caller guarantee. unsafe { let stack = crate::sched::drop_stack(ctx); let mut steps = 1; while stack.has_pending() { assert_eq!((*ctx).reductions, 0, "the next function entry yields"); (*ctx).reductions = crate::sched::REDUCTIONS; continue_drain(ctx); steps += 1; } steps } } /// Large structures are freed a step at a time (issue #158), and what /// is left when the actor ends is freed then. unsafe extern "C" fn drops_in_steps(ctx: *mut Ctx) -> Value { // SAFETY: `ctx` is the root actor's; every value built is owned. unsafe { let before = stats::tl_stats_live_blocks(); // A million cells: about 3,600 per step. drop_value(ctx, list(ctx, (0..1_000_000).map(int))); let n = steps(ctx); assert!((200..400).contains(&n), "{n} steps"); assert_eq!(stats::tl_stats_live_blocks(), before); // An array of 100,000 strings, released from its end (its // fields cost one each, its strings 16), after the list it was // made from (cells cost 18). let strings = list(ctx, (0..100_000).map(|i| string(ctx, &i.to_string()))); let array = crate::array::tl_array_from_list(ctx, strings); drop_value(ctx, strings); drop_value(ctx, array); let n = steps(ctx); assert!((40..80).contains(&n), "{n} steps"); assert_eq!(stats::tl_stats_live_blocks(), before); // Small drops take one step. drop_value(ctx, list(ctx, (0..1000).map(int))); assert!(!crate::sched::drop_stack(ctx).has_pending()); // Left over: the actor's end frees it (`finish_drain`; the // stack's `Drop` checks). drop_value(ctx, list(ctx, (0..1_000_000).map(int))); assert!(crate::sched::drop_stack(ctx).has_pending()); } UNIT } /// An actor's `proc` capability is immortal, as `clock`'s is: every /// actor gets the same block, and its release frees nothing and queues /// nothing. Built per actor, its 17 closures were allocated at each /// start and queued on the drop worklist at each exit (#422 made that /// one more doubling of the worklist: 10% of `tests/bench/churn`). unsafe extern "C" fn proc_capabilities_are_shared(ctx: *mut Ctx) -> Value { // SAFETY: `ctx` is the root actor's; the capabilities are owned here. unsafe { let before = stats::tl_stats_live_blocks(); let a = crate::process::root_cap(crate::process::RootCap::Proc); let b = crate::process::root_cap(crate::process::RootCap::Proc); assert_eq!(a, b, "one capability for every actor"); assert_eq!(stats::tl_stats_live_blocks(), before, "allocated"); drop_value(ctx, a); drop_value(ctx, b); assert!(!crate::sched::drop_stack(ctx).has_pending(), "queued"); assert_eq!(stats::tl_stats_live_blocks(), before); } UNIT } #[test] fn a_proc_capability_is_immortal() { // SAFETY: the entry follows the generated-code convention. let status = unsafe { crate::sched::run_test_actor(proc_capabilities_are_shared) }; assert_eq!(status, 0); } #[test] fn large_drops_are_freed_in_steps() { // SAFETY: `drops_in_steps` follows the generated-code convention. assert_eq!(unsafe { crate::sched::run_test_actor(drops_in_steps) }, 0); } /// A count that would overflow sticks instead (issue #217): no dup or /// drop moves it again, and the block is never freed. unsafe extern "C" fn saturating_counts(ctx: *mut Ctx) -> Value { // SAFETY: `ctx` is the root actor's; the blocks are owned here. unsafe { let local = string(ctx, "local"); let b = local as *mut Block; (*b).header.rc = RC_STUCK - 1; dup_value(local); assert_eq!((*b).header.rc, RC_STUCK); dup_value(local); for _ in 0..3 { drop_value(ctx, local); } assert_eq!((*b).header.rc, RC_STUCK); let shared = string(ctx, "shared"); let s = shared as *mut Block; (*s).header.rc = SHARED_SATURATED; dup_value(shared); assert_eq!((*s).header.rc, SHARED_STUCK); for _ in 0..1000 { drop_value(ctx, shared); } assert_eq!((*s).header.rc, SHARED_STUCK); // Back to one reference each, so the actor ends without leaks. (*b).header.rc = 1; drop_value(ctx, local); (*s).header.rc = -1; drop_value(ctx, shared); } UNIT } #[test] fn counts_saturate_instead_of_wrapping() { // SAFETY: `saturating_counts` follows the generated-code convention. let leaked = unsafe { crate::sched::run_test_actor(saturating_counts) }; assert_eq!(leaked, 0); } }