
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#1201 · main · 9 min 57 s
1Étoiles
0Forks
0Issues
| 1 | //! Block allocation and reference counting (Perceus runtime side). |
| 2 | //! |
| 3 | //! The compiler inserts `tl_dup`/`tl_drop`; their fast paths are inline in |
| 4 | //! the C header. This module implements the slow paths: freeing, which is |
| 5 | //! iterative so dropping a long list cannot overflow a small fiber stack, |
| 6 | //! and shared (atomic) counts. |
| 7 | //! |
| 8 | //! Blocks come from [`blocks`]: mimalloc with the `mimalloc` feature (the |
| 9 | //! default), the system allocator without it. Only blocks: the runtime's |
| 10 | //! own Rust allocations (queues, mailboxes, worklists) keep Rust's global |
| 11 | //! allocator. A block may be freed on another thread than the one that |
| 12 | //! allocated it (actors migrate, messages move); both allocators allow it. |
| 13 | //! Sanitizer builds link a runtime built without the feature, so ASan sees |
| 14 | //! every block (`scripts/ci.sh`). |
| 15 | |
| 16 | use std::alloc::{Layout, handle_alloc_error}; |
| 17 | use std::sync::atomic::{AtomicI32, Ordering}; |
| 18 | |
| 19 | use crate::abi::{ |
| 20 | Block, Ctx, Header, SCAN_LARGE, TAG_ARRAY, TAG_BYTES, TAG_CLOSURE, TAG_FLOAT, TAG_REF, |
| 21 | TAG_RUNTIME_MIN, TAG_STRING, Value, int_get, is_ptr, |
| 22 | }; |
| 23 | |
| 24 | /// Blocks whose count reached zero, waiting for their children to be |
| 25 | /// released. Owned by each actor so draining never touches shared state. |
| 26 | /// |
| 27 | /// A drop drains it a step at a time (issue #158): at most [`DRAIN_BLOCKS`] |
| 28 | /// blocks, then the rest waits for the actor's next safe point |
| 29 | /// ([`continue_drain`]), so freeing a large structure doesn't hold its |
| 30 | /// thread. Everything left is freed when the actor ends. |
| 31 | #[derive(Default)] |
| 32 | pub struct DropStack { |
| 33 | pending: Vec<*mut Block>, |
| 34 | /// Large blocks being released from their end: each with the number |
| 35 | /// of its scanned fields still to release. |
| 36 | partial: Vec<(*mut Block, usize)>, |
| 37 | draining: bool, |
| 38 | } |
| 39 | |
| 40 | /// The blocks one step of a drain frees: about 40–60 µs (a list of 4,096 |
| 41 | /// cells takes 45 µs). |
| 42 | const DRAIN_BLOCKS: u32 = 4096; |
| 43 | |
| 44 | /// A block with more scanned fields than this is set aside and released |
| 45 | /// a step at a time, from its end: [`DRAIN_FIELDS`] fields per step. |
| 46 | const LARGE: usize = 4096; |
| 47 | const DRAIN_FIELDS: usize = 65536; |
| 48 | |
| 49 | impl DropStack { |
| 50 | /// Whether dead blocks wait to be freed. |
| 51 | pub(crate) fn has_pending(&self) -> bool { |
| 52 | !self.pending.is_empty() || !self.partial.is_empty() |
| 53 | } |
| 54 | |
| 55 | /// Set `b` aside to release in steps if it is large (more than |
| 56 | /// [`LARGE`] fields, and nothing to run when freed); whether it was. |
| 57 | /// |
| 58 | /// # Safety |
| 59 | /// `b` must be dead, with `scan_fsize` [`SCAN_LARGE`]. |
| 60 | #[cold] |
| 61 | #[inline(never)] |
| 62 | unsafe fn set_aside(&mut self, b: *mut Block) -> bool { |
| 63 | // SAFETY: forwarded caller guarantee. |
| 64 | let (n, _) = unsafe { scanned(b) }; |
| 65 | // SAFETY: as above. |
| 66 | if n > LARGE && plain(unsafe { (*b).header.tag }) { |
| 67 | self.partial.push((b, n)); |
| 68 | return true; |
| 69 | } |
| 70 | false |
| 71 | } |
| 72 | |
| 73 | /// Free up to `blocks` dead blocks; whether it stopped there (more |
| 74 | /// may be left). Large blocks are only set aside here. |
| 75 | /// |
| 76 | /// # Safety |
| 77 | /// Only blocks whose last reference was released are queued. |
| 78 | #[inline(always)] |
| 79 | unsafe fn free_some(&mut self, mut blocks: u32) -> bool { |
| 80 | while let Some(b) = self.pending.pop() { |
| 81 | // SAFETY: `b` is dead, and live until freed. |
| 82 | unsafe { |
| 83 | if (*b).header.scan_fsize == SCAN_LARGE && self.set_aside(b) { |
| 84 | continue; |
| 85 | } |
| 86 | free_block(b, &mut self.pending); |
| 87 | } |
| 88 | blocks -= 1; |
| 89 | if blocks == 0 { |
| 90 | return true; |
| 91 | } |
| 92 | } |
| 93 | false |
| 94 | } |
| 95 | |
| 96 | /// One step of a drain: [`DRAIN_BLOCKS`] blocks, or else |
| 97 | /// [`DRAIN_FIELDS`] fields of the large block set aside last. Whether |
| 98 | /// nothing is left. |
| 99 | /// |
| 100 | /// # Safety |
| 101 | /// As [`DropStack::free_some`]. |
| 102 | #[cold] |
| 103 | #[inline(never)] |
| 104 | unsafe fn step(&mut self) -> bool { |
| 105 | // SAFETY: forwarded caller guarantee. |
| 106 | if unsafe { self.free_some(DRAIN_BLOCKS) } { |
| 107 | return !self.has_pending(); |
| 108 | } |
| 109 | if let Some((b, left)) = self.partial.last_mut() { |
| 110 | let (b, end) = (*b, *left); |
| 111 | let start = end.saturating_sub(DRAIN_FIELDS); |
| 112 | // SAFETY: `b` is dead; its fields `start..end` were not |
| 113 | // released yet. |
| 114 | unsafe { |
| 115 | let (fields, _) = scanned_fields(b); |
| 116 | for i in start..end { |
| 117 | release_into(*fields.add(i), &mut self.pending); |
| 118 | } |
| 119 | } |
| 120 | *left = start; |
| 121 | if start == 0 { |
| 122 | self.partial.pop(); |
| 123 | // SAFETY: every field was released; nothing else refers |
| 124 | // to `b`. |
| 125 | unsafe { blocks::free(b) }; |
| 126 | stats::free(); |
| 127 | } |
| 128 | } |
| 129 | !self.has_pending() |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | impl Drop for DropStack { |
| 134 | fn drop(&mut self) { |
| 135 | debug_assert!( |
| 136 | !self.has_pending(), |
| 137 | "louise: an actor ended with blocks left to free" |
| 138 | ); |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | /// Continue freeing what an earlier drop left (a step), at a safe point |
| 143 | /// of the running actor: when it was preempted or woken. If more is left, |
| 144 | /// its next function entry yields again (`reductions` 0). |
| 145 | /// |
| 146 | /// # Safety |
| 147 | /// `ctx` must be the running actor's context. |
| 148 | #[inline(always)] |
| 149 | pub(crate) unsafe fn continue_drain(ctx: *mut Ctx) { |
| 150 | // SAFETY: forwarded caller guarantee. |
| 151 | unsafe { |
| 152 | let stack = crate::sched::drop_stack(ctx); |
| 153 | if stack.has_pending() && !stack.draining { |
| 154 | drain_step(ctx, stack); |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | /// # Safety |
| 160 | /// `ctx` must be the running actor's context, `stack` its drop stack. |
| 161 | #[cold] |
| 162 | #[inline(never)] |
| 163 | unsafe fn drain_step(ctx: *mut Ctx, stack: &mut DropStack) { |
| 164 | stack.draining = true; |
| 165 | // SAFETY: only dead blocks are queued. |
| 166 | let done = unsafe { stack.step() }; |
| 167 | stack.draining = false; |
| 168 | if !done { |
| 169 | // SAFETY: the running actor's context. |
| 170 | unsafe { (*ctx).reductions = 0 }; |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// Free what an actor's drops left when its body returned, a step at a |
| 175 | /// time, yielding to other actors between steps: its exit is recorded |
| 176 | /// after. On the actor's own stack. |
| 177 | /// |
| 178 | /// # Safety |
| 179 | /// `ctx` must be the running actor's context, on its own stack. |
| 180 | pub(crate) unsafe fn drain_before_exit(ctx: *mut Ctx) { |
| 181 | // SAFETY: forwarded caller guarantee. |
| 182 | unsafe { |
| 183 | while crate::sched::drop_stack(ctx).has_pending() { |
| 184 | let stack = crate::sched::drop_stack(ctx); |
| 185 | stack.draining = true; |
| 186 | let done = stack.step(); |
| 187 | stack.draining = false; |
| 188 | if !done { |
| 189 | crate::sched::preempt_root(ctx); |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | /// Free everything left when an actor ends (after |
| 196 | /// [`drain_before_exit`], what releasing its mailbox dropped), at once. |
| 197 | /// |
| 198 | /// # Safety |
| 199 | /// `ctx` must be the ending actor's context. |
| 200 | pub(crate) unsafe fn finish_drain(ctx: *mut Ctx) { |
| 201 | // SAFETY: forwarded caller guarantee. |
| 202 | unsafe { |
| 203 | let stack = crate::sched::drop_stack(ctx); |
| 204 | stack.draining = true; |
| 205 | while !stack.step() {} |
| 206 | stack.draining = false; |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | /// The allocator of blocks (see the module documentation). |
| 211 | /// |
| 212 | /// mimalloc is called directly: its `GlobalAlloc` (the `mimalloc` crate) |
| 213 | /// always takes the aligned allocation path, and blocks need no more than |
| 214 | /// the 8-byte alignment every mimalloc allocation has. Freeing needs no |
| 215 | /// size, so the free path skips computing the block's layout (issue #61). |
| 216 | #[cfg(feature = "mimalloc")] |
| 217 | mod blocks { |
| 218 | use std::alloc::Layout; |
| 219 | |
| 220 | /// # Safety |
| 221 | /// `layout.size()` must be non-zero. |
| 222 | pub(super) unsafe fn alloc(layout: Layout) -> *mut u8 { |
| 223 | // SAFETY: mimalloc returns 16-byte aligned memory, or null. |
| 224 | unsafe { libmimalloc_sys::mi_malloc(layout.size()) }.cast() |
| 225 | } |
| 226 | |
| 227 | /// # Safety |
| 228 | /// `b` must be a live block, from [`alloc`]. |
| 229 | pub(super) unsafe fn free(b: *mut crate::abi::Block) { |
| 230 | // SAFETY: forwarded caller guarantee. |
| 231 | unsafe { libmimalloc_sys::mi_free(b.cast()) } |
| 232 | } |
| 233 | |
| 234 | /// # Safety |
| 235 | /// `b` must be a live block from [`alloc`] of layout `old`, and `size` |
| 236 | /// non-zero. |
| 237 | pub(super) unsafe fn realloc(b: *mut u8, old: Layout, size: usize) -> *mut u8 { |
| 238 | let _ = old; |
| 239 | // SAFETY: forwarded caller guarantee; the result keeps mimalloc's |
| 240 | // alignment. |
| 241 | unsafe { libmimalloc_sys::mi_realloc(b.cast(), size) }.cast() |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | #[cfg(not(feature = "mimalloc"))] |
| 246 | mod blocks { |
| 247 | use std::alloc::{GlobalAlloc, Layout, System}; |
| 248 | |
| 249 | /// # Safety |
| 250 | /// `layout.size()` must be non-zero. |
| 251 | pub(super) unsafe fn alloc(layout: Layout) -> *mut u8 { |
| 252 | // SAFETY: forwarded caller guarantee. |
| 253 | unsafe { System.alloc(layout) } |
| 254 | } |
| 255 | |
| 256 | /// # Safety |
| 257 | /// `b` must be a live block, from [`alloc`]. |
| 258 | pub(super) unsafe fn free(b: *mut crate::abi::Block) { |
| 259 | // SAFETY: forwarded caller guarantee; the layout is the block's. |
| 260 | unsafe { System.dealloc(b.cast(), super::layout_of(b)) } |
| 261 | } |
| 262 | |
| 263 | /// # Safety |
| 264 | /// `b` must be a live block from [`alloc`] of layout `old`, and `size` |
| 265 | /// non-zero. |
| 266 | pub(super) unsafe fn realloc(b: *mut u8, old: Layout, size: usize) -> *mut u8 { |
| 267 | // SAFETY: forwarded caller guarantee. |
| 268 | unsafe { System.realloc(b, old, size) } |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | const HEADER_SIZE: usize = size_of::<Header>(); |
| 273 | const WORD: usize = size_of::<Value>(); |
| 274 | |
| 275 | /// Number of scanned fields and the offset (in words) of the first one. |
| 276 | /// |
| 277 | /// # Safety |
| 278 | /// `b` must point to a live block. |
| 279 | unsafe fn scanned(b: *mut Block) -> (usize, usize) { |
| 280 | // SAFETY: caller guarantees `b` is live. |
| 281 | let scan = unsafe { (*b).header.scan_fsize }; |
| 282 | if scan == SCAN_LARGE { |
| 283 | // SAFETY: large blocks store their count as an int in fields[0]. |
| 284 | let n = unsafe { *Block::fields_ptr(b) }; |
| 285 | (int_get(n) as usize, 1) |
| 286 | } else { |
| 287 | (scan as usize, 0) |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | /// Size of the raw area that follows the scanned fields, by tag. |
| 292 | /// |
| 293 | /// # Safety |
| 294 | /// `raw` must point at the raw area of a live block with tag `tag`. |
| 295 | unsafe fn raw_size(tag: u16, raw: *const u8) -> usize { |
| 296 | // SAFETY: these kinds start their raw area with an i64 count (a big |
| 297 | // integer's is signed). |
| 298 | let first = || unsafe { raw.cast::<i64>().read() }; |
| 299 | let len = || first() as usize; |
| 300 | match tag { |
| 301 | TAG_STRING => WORD + len() + 1, |
| 302 | TAG_BYTES => WORD + len(), |
| 303 | // The spare count, then that many unused slots. |
| 304 | TAG_ARRAY => WORD * (1 + len()), |
| 305 | // The signed limb count, then the limbs. |
| 306 | crate::abi::TAG_BIGINT => WORD * (1 + first().unsigned_abs() as usize), |
| 307 | // The length and the capacity, then the capacity's bytes. |
| 308 | crate::abi::TAG_BUILDER => { |
| 309 | // SAFETY: the capacity is the second word. |
| 310 | 2 * WORD + unsafe { raw.cast::<i64>().add(1).read() } as usize |
| 311 | } |
| 312 | TAG_FLOAT | crate::abi::TAG_U64 | crate::abi::TAG_REGION | crate::abi::TAG_FRAME => WORD, |
| 313 | // The owned entry's and the borrowed entry's code pointers |
| 314 | // (ADR 0068). |
| 315 | TAG_CLOSURE => 2 * WORD, |
| 316 | crate::abi::TAG_RESOURCE | crate::abi::TAG_DEC => 2 * WORD, |
| 317 | TAG_REF | crate::abi::TAG_CAP => 0, |
| 318 | t if t < TAG_RUNTIME_MIN => 0, |
| 319 | t => panic!("louise: unknown runtime tag {t:#x}"), |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | /// # Safety |
| 324 | /// `b` must point to a live block. |
| 325 | unsafe fn layout_of(b: *mut Block) -> Layout { |
| 326 | // SAFETY: caller guarantees `b` is live; the raw area follows the fields. |
| 327 | unsafe { |
| 328 | let (n, offset) = scanned(b); |
| 329 | let words = n + offset; |
| 330 | let raw = Block::fields_ptr(b).add(words).cast::<u8>(); |
| 331 | let size = HEADER_SIZE + words * WORD + raw_size((*b).header.tag, raw); |
| 332 | Layout::from_size_align_unchecked(size, WORD) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | /// Size in bytes of a live block, header included. |
| 337 | /// |
| 338 | /// # Safety |
| 339 | /// `b` must point to a live block. |
| 340 | pub(crate) unsafe fn block_size(b: *mut Block) -> usize { |
| 341 | // SAFETY: forwarded caller guarantee. |
| 342 | unsafe { layout_of(b) }.size() |
| 343 | } |
| 344 | |
| 345 | /// The scanned fields of a live block: a pointer to the first, and their |
| 346 | /// number. |
| 347 | /// |
| 348 | /// # Safety |
| 349 | /// `b` must point to a live block. |
| 350 | pub(crate) unsafe fn scanned_fields(b: *mut Block) -> (*mut Value, usize) { |
| 351 | // SAFETY: forwarded caller guarantee. |
| 352 | unsafe { |
| 353 | let (n, offset) = scanned(b); |
| 354 | (Block::fields_ptr(b).add(offset), n) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | /// Allocate `size` uninitialised bytes for a block (counted by the leak |
| 359 | /// oracle); the caller writes the header and fields. |
| 360 | pub(crate) fn alloc_bytes(_ctx: *mut Ctx, size: usize) -> *mut Block { |
| 361 | let layout = Layout::from_size_align(size, WORD).expect("louise: block too large"); |
| 362 | // SAFETY: layout has non-zero size (at least the header). |
| 363 | let b = unsafe { blocks::alloc(layout) }.cast::<Block>(); |
| 364 | if b.is_null() { |
| 365 | handle_alloc_error(layout); |
| 366 | } |
| 367 | stats::alloc(); |
| 368 | b |
| 369 | } |
| 370 | |
| 371 | /// Resize the unique block `b`, of `old_size` bytes, to `size` bytes (its |
| 372 | /// contents up to the smaller size are kept). Returns the block's new |
| 373 | /// address; `b` is no longer valid. The live count does not change. |
| 374 | /// `old_size` is passed because a caller may have rewritten the block |
| 375 | /// (`bytes.build` turns a builder into `Bytes`) before shrinking it. |
| 376 | /// |
| 377 | /// # Safety |
| 378 | /// `b` must be live and unique, `old_size` the size it was allocated (or |
| 379 | /// last resized) with, and no other pointer to it may be used afterwards. |
| 380 | pub(crate) unsafe fn realloc_block(b: *mut Block, old_size: usize, size: usize) -> *mut Block { |
| 381 | let old = Layout::from_size_align(old_size, WORD).expect("louise: block too large"); |
| 382 | // SAFETY: forwarded caller guarantee. |
| 383 | let new = unsafe { blocks::realloc(b.cast(), old, size) }.cast::<Block>(); |
| 384 | if new.is_null() { |
| 385 | handle_alloc_error(Layout::from_size_align(size, WORD).expect("louise: block too large")); |
| 386 | } |
| 387 | new |
| 388 | } |
| 389 | |
| 390 | /// A block's count, read atomically. A shared block's count changes on |
| 391 | /// other threads (any number of actors may hold one, `std/table` makes |
| 392 | /// that common), so even the test that tells a local count from a shared |
| 393 | /// one must not be a plain read: it would race with their atomic updates. |
| 394 | /// A relaxed load costs a plain load on x86-64 and aarch64. Writes stay |
| 395 | /// plain: only a local count is written that way, by its one owner. The C |
| 396 | /// fast paths read it the same way (`tl_rc`, louise_rt.h). |
| 397 | /// |
| 398 | /// # Safety |
| 399 | /// `b` must point to a live block. |
| 400 | #[inline(always)] |
| 401 | pub(crate) unsafe fn rc(b: *mut Block) -> i32 { |
| 402 | // SAFETY: caller guarantees `b` is live; the count is an aligned i32. |
| 403 | unsafe { AtomicI32::from_ptr(&raw mut (*b).header.rc) }.load(Ordering::Relaxed) |
| 404 | } |
| 405 | |
| 406 | /// Add a reference to `v` from Rust code (the C `tl_dup`); returns `v`. |
| 407 | /// |
| 408 | /// # Safety |
| 409 | /// `v` must be live. |
| 410 | pub(crate) unsafe fn dup_value(v: Value) -> Value { |
| 411 | if !is_ptr(v) { |
| 412 | return v; |
| 413 | } |
| 414 | let b = v as *mut Block; |
| 415 | // SAFETY: caller guarantees `v` is live. |
| 416 | unsafe { |
| 417 | let rc = rc(b); |
| 418 | if (1..RC_STUCK).contains(&rc) { |
| 419 | (*b).header.rc = rc + 1; |
| 420 | } else { |
| 421 | tl_dup_shared(b); |
| 422 | } |
| 423 | } |
| 424 | v |
| 425 | } |
| 426 | |
| 427 | /// A local count stops here instead of overflowing (issue #217): no dup |
| 428 | /// or drop moves it again, and the block is never freed. A bounded leak |
| 429 | /// replaces a use after free. |
| 430 | pub(crate) const RC_STUCK: i32 = i32::MAX; |
| 431 | |
| 432 | /// A shared count at or past this is saturated: every dup or drop that |
| 433 | /// sees it puts it back to [`SHARED_STUCK`]. The gap between the two |
| 434 | /// absorbs the dups and drops other threads have in flight, so the count |
| 435 | /// never reaches -1 again, nor wraps, without a compare-and-swap loop. |
| 436 | pub(crate) const SHARED_SATURATED: i32 = -(1 << 29); |
| 437 | |
| 438 | /// Where a saturated shared count is held. |
| 439 | pub(crate) const SHARED_STUCK: i32 = -(1 << 30); |
| 440 | |
| 441 | /// Say once that a count saturated: the program now leaks that block. |
| 442 | fn saturated() { |
| 443 | static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); |
| 444 | if !SAID.swap(true, Ordering::Relaxed) { |
| 445 | eprintln!( |
| 446 | "louise: a value has too many references to count; it will never be freed (issue #217)" |
| 447 | ); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | /// Allocate a block with `rc = 1`. Scanned fields are initialised to unit so |
| 452 | /// a block dropped before the caller fills it is still well formed. |
| 453 | /// |
| 454 | /// `ctx` is not read, and may be null. The safe helpers that build values |
| 455 | /// (`values::cell`, `values::string`, ...) rely on this: if allocation |
| 456 | /// ever reads the context, they must become `unsafe`. |
| 457 | #[unsafe(no_mangle)] |
| 458 | pub extern "C" fn tl_alloc( |
| 459 | _ctx: *mut Ctx, |
| 460 | tag: u16, |
| 461 | scan_fsize: u8, |
| 462 | raw_bytes: usize, |
| 463 | ) -> *mut Block { |
| 464 | assert!( |
| 465 | scan_fsize != SCAN_LARGE, |
| 466 | "louise: large blocks (arrays) are allocated by the runtime only" |
| 467 | ); |
| 468 | let b = alloc_bytes(_ctx, HEADER_SIZE + scan_fsize as usize * WORD + raw_bytes); |
| 469 | // SAFETY: `b` is a fresh allocation large enough for header and fields. |
| 470 | unsafe { |
| 471 | b.cast::<Header>().write(Header { |
| 472 | rc: 1, |
| 473 | tag, |
| 474 | scan_fsize, |
| 475 | flags: 0, |
| 476 | }); |
| 477 | let fields = Block::fields_ptr(b); |
| 478 | for i in 0..scan_fsize as usize { |
| 479 | fields.add(i).write(crate::abi::UNIT); |
| 480 | } |
| 481 | } |
| 482 | b |
| 483 | } |
| 484 | |
| 485 | /// Increment the count of a shared (negative rc) block, or of one whose |
| 486 | /// count saturated, which stays as it is. |
| 487 | /// |
| 488 | /// # Safety |
| 489 | /// `b` must point to a live block. |
| 490 | #[unsafe(no_mangle)] |
| 491 | pub unsafe extern "C" fn tl_dup_shared(b: *mut Block) { |
| 492 | // SAFETY: caller guarantees `b` is live. Immortal blocks (rc 0, static |
| 493 | // literals) are never counted. |
| 494 | let local = unsafe { rc(b) }; |
| 495 | if local == 0 { |
| 496 | return; |
| 497 | } |
| 498 | if local == RC_STUCK { |
| 499 | saturated(); |
| 500 | return; |
| 501 | } |
| 502 | // SAFETY: shared blocks are only ever accessed atomically. |
| 503 | let rc = unsafe { AtomicI32::from_ptr(&raw mut (*b).header.rc) }; |
| 504 | if rc.fetch_sub(1, Ordering::Relaxed) <= SHARED_SATURATED { |
| 505 | rc.store(SHARED_STUCK, Ordering::Relaxed); |
| 506 | saturated(); |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | /// Returns true when this call released the last reference to `b`. |
| 511 | /// |
| 512 | /// # Safety |
| 513 | /// `b` must point to a live block whose count is <= 1 or shared. |
| 514 | unsafe fn release(b: *mut Block) -> bool { |
| 515 | // SAFETY: caller guarantees `b` is live. |
| 516 | let local = unsafe { rc(b) }; |
| 517 | if local == 0 || local == RC_STUCK { |
| 518 | return false; // immortal (a static literal), or saturated |
| 519 | } |
| 520 | if local > 0 { |
| 521 | debug_assert_eq!(local, 1, "louise: release on a block with rc > 1"); |
| 522 | return true; |
| 523 | } |
| 524 | // SAFETY: shared blocks are only ever accessed atomically. |
| 525 | let rc = unsafe { AtomicI32::from_ptr(&raw mut (*b).header.rc) }; |
| 526 | let old = rc.fetch_add(1, Ordering::Release); |
| 527 | if old == -1 { |
| 528 | // ThreadSanitizer does not model fences, so under it an acquire |
| 529 | // load of the count does the fence's job, as `Arc` does: every |
| 530 | // other holder's release must happen before the block is freed. |
| 531 | #[cfg(not(louise_rt_tsan))] |
| 532 | std::sync::atomic::fence(Ordering::Acquire); |
| 533 | #[cfg(louise_rt_tsan)] |
| 534 | rc.load(Ordering::Acquire); |
| 535 | return true; |
| 536 | } |
| 537 | if old <= SHARED_SATURATED { |
| 538 | rc.store(SHARED_STUCK, Ordering::Relaxed); |
| 539 | } |
| 540 | false |
| 541 | } |
| 542 | |
| 543 | /// Drop a block whose local count is 1, which is shared, or whose count |
| 544 | /// saturated (left as it is). |
| 545 | /// |
| 546 | /// # Safety |
| 547 | /// `ctx` must be the running actor's context and `b` a live block. |
| 548 | #[unsafe(no_mangle)] |
| 549 | pub unsafe extern "C" fn tl_drop_slow(ctx: *mut Ctx, b: *mut Block) { |
| 550 | // SAFETY: caller guarantees `b` is live. |
| 551 | if !unsafe { release(b) } { |
| 552 | return; |
| 553 | } |
| 554 | // A block without children or finalizer (a Float, a String, a |
| 555 | // nullary-free leaf) is freed at once, without the worklist: half the |
| 556 | // drops of numeric code. |
| 557 | // SAFETY: `b` is live until freed. |
| 558 | unsafe { |
| 559 | let (scan, tag) = ((*b).header.scan_fsize, (*b).header.tag); |
| 560 | if scan == 0 && plain(tag) { |
| 561 | blocks::free(b); |
| 562 | stats::free(); |
| 563 | return; |
| 564 | } |
| 565 | } |
| 566 | // SAFETY: forwarded caller guarantee; `b` is dead. |
| 567 | unsafe { drop_queued(ctx, b) } |
| 568 | } |
| 569 | |
| 570 | /// Free the dead block `b` and what dies with it, through the actor's |
| 571 | /// worklist, [`DRAIN_BLOCKS`] at most. Out of line, so that the leaf case |
| 572 | /// above stays small enough to inline into callers (issue #158). |
| 573 | /// |
| 574 | /// # Safety |
| 575 | /// `ctx` must be the running actor's context; `b` dead. |
| 576 | #[inline(never)] |
| 577 | unsafe fn drop_queued(ctx: *mut Ctx, b: *mut Block) { |
| 578 | // SAFETY: the running actor's context always has a live actor. |
| 579 | let stack = unsafe { crate::sched::drop_stack(ctx) }; |
| 580 | stack.pending.push(b); |
| 581 | if stack.draining { |
| 582 | return; // An outer tl_drop_slow on this actor is already draining. |
| 583 | } |
| 584 | stack.draining = true; |
| 585 | // SAFETY: only blocks whose last reference was released are pushed. |
| 586 | let stopped = unsafe { stack.free_some(DRAIN_BLOCKS) }; |
| 587 | stack.draining = false; |
| 588 | if stopped || !stack.partial.is_empty() { |
| 589 | // The rest at the next safe point: the next function entry yields, |
| 590 | // and the actor continues when it runs again (`continue_drain`). |
| 591 | // SAFETY: the running actor's context. |
| 592 | unsafe { (*ctx).reductions = 0 }; |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | /// Deallocate a unique block whose children were moved out by the caller |
| 597 | /// (Perceus drop specialisation: matching on a unique cell). |
| 598 | /// |
| 599 | /// # Safety |
| 600 | /// `b` must be live with local rc 1, and its fields must not be used again. |
| 601 | #[unsafe(no_mangle)] |
| 602 | pub unsafe extern "C" fn tl_free(_ctx: *mut Ctx, b: *mut Block) { |
| 603 | // SAFETY: caller guarantees `b` is live and unique. |
| 604 | unsafe { |
| 605 | debug_assert_eq!((*b).header.rc, 1, "louise: tl_free on a shared block"); |
| 606 | blocks::free(b); |
| 607 | } |
| 608 | stats::free(); |
| 609 | } |
| 610 | |
| 611 | /// Whether freeing a block with this tag needs nothing but its children |
| 612 | /// released: not a region, a handler frame or a resource. |
| 613 | fn plain(tag: u16) -> bool { |
| 614 | !matches!( |
| 615 | tag, |
| 616 | crate::abi::TAG_REGION | crate::abi::TAG_FRAME | crate::abi::TAG_RESOURCE |
| 617 | ) |
| 618 | } |
| 619 | |
| 620 | /// Release `b`'s children (queuing those that die) and deallocate `b`. |
| 621 | /// |
| 622 | /// # Safety |
| 623 | /// `b` must be live and unreachable. |
| 624 | unsafe fn free_block(b: *mut Block, pending: &mut Vec<*mut Block>) { |
| 625 | // SAFETY: `b` is live until the dealloc at the end. |
| 626 | unsafe { |
| 627 | match (*b).header.tag { |
| 628 | crate::abi::TAG_REGION => crate::region::free_region(b, pending), |
| 629 | crate::abi::TAG_FRAME => crate::handlers::free_frame(b, pending), |
| 630 | crate::abi::TAG_RESOURCE => crate::resource::finalize_resource(b), |
| 631 | _ => {} |
| 632 | } |
| 633 | let (fields, n) = scanned_fields(b); |
| 634 | // A reuse token's kept fields are dead: their values are owned by |
| 635 | // the bindings they were moved to (ADR 0040 Revision 2, issue |
| 636 | // #193; the flag is set at the release, cleared at the reuse). |
| 637 | if (*b).header.flags & crate::abi::FLAG_TOKEN == 0 { |
| 638 | for i in 0..n { |
| 639 | release_into(*fields.add(i), pending); |
| 640 | } |
| 641 | } |
| 642 | blocks::free(b); |
| 643 | } |
| 644 | stats::free(); |
| 645 | } |
| 646 | |
| 647 | /// Release a value from Rust code (the C `tl_drop`). |
| 648 | /// |
| 649 | /// # Safety |
| 650 | /// `ctx` must be the running actor's context; `v` must be owned. |
| 651 | pub unsafe fn drop_value(ctx: *mut Ctx, v: Value) { |
| 652 | if !is_ptr(v) { |
| 653 | return; |
| 654 | } |
| 655 | let b = v as *mut Block; |
| 656 | // SAFETY: an owned pointer value refers to a live block. |
| 657 | unsafe { |
| 658 | let rc = rc(b); |
| 659 | if (2..RC_STUCK).contains(&rc) { |
| 660 | (*b).header.rc = rc - 1; |
| 661 | } else { |
| 662 | tl_drop_slow(ctx, b); |
| 663 | } |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | /// Release a value outside any actor's context (the scheduler freeing a |
| 668 | /// message it made, whose receiver is gone). Iterative, with its own |
| 669 | /// worklist. |
| 670 | /// |
| 671 | /// # Safety |
| 672 | /// `v` must be an owned value. |
| 673 | pub(crate) unsafe fn drop_detached(v: Value) { |
| 674 | let mut pending = Vec::new(); |
| 675 | // SAFETY: caller guarantees `v` is owned; blocks pushed are dead. |
| 676 | unsafe { |
| 677 | release_into(v, &mut pending); |
| 678 | while let Some(b) = pending.pop() { |
| 679 | free_block(b, &mut pending); |
| 680 | } |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | /// Live block accounting: the leak oracle for Perceus tests; and, from |
| 685 | /// the same per-thread counts, the total of blocks ever allocated (the |
| 686 | /// `LOUISE_STATS` measurement, `docs/runtime-abi.md`). |
| 687 | /// |
| 688 | /// Each thread counts the blocks it allocates and frees; the number of |
| 689 | /// live blocks is the sum. A shared counter would make every allocation |
| 690 | /// and free an atomic read-modify-write, which cost 20–30% of the run |
| 691 | /// time of allocation-heavy programs. A block freed on another thread |
| 692 | /// than the one that allocated it makes one count go up and another down; |
| 693 | /// the sum stays right. The total only ever goes up: a free on another |
| 694 | /// thread does not lower it. |
| 695 | pub mod stats { |
| 696 | #[cfg(feature = "stats")] |
| 697 | mod counts { |
| 698 | use std::cell::Cell; |
| 699 | use std::sync::atomic::{AtomicI64, Ordering}; |
| 700 | use std::sync::{Mutex, PoisonError}; |
| 701 | |
| 702 | /// A thread's counts: the blocks it has live (`allocated − freed`) |
| 703 | /// and the blocks it ever allocated. |
| 704 | pub struct Counts { |
| 705 | live: AtomicI64, |
| 706 | allocs: AtomicI64, |
| 707 | } |
| 708 | |
| 709 | /// The counts of every thread that ever allocated or freed a block |
| 710 | /// (one leaked struct per thread, so a count outlives its thread). |
| 711 | static ALL: Mutex<Vec<&'static Counts>> = Mutex::new(Vec::new()); |
| 712 | |
| 713 | thread_local! { |
| 714 | // No destructor: usable while thread-locals are destroyed. |
| 715 | static MINE: Cell<Option<&'static Counts>> = const { Cell::new(None) }; |
| 716 | } |
| 717 | |
| 718 | /// Inlined into every allocation and free, on actor fibers that |
| 719 | /// move between threads: see the `Fiber` safety comment in |
| 720 | /// `sched` for why that is sound today, and what is left to |
| 721 | /// review (`docs/code-health.md`, M7). |
| 722 | #[inline] |
| 723 | fn mine() -> &'static Counts { |
| 724 | MINE.get().unwrap_or_else(register) |
| 725 | } |
| 726 | |
| 727 | #[cold] |
| 728 | fn register() -> &'static Counts { |
| 729 | let counts = Box::leak(Box::new(Counts { |
| 730 | live: AtomicI64::new(0), |
| 731 | allocs: AtomicI64::new(0), |
| 732 | })); |
| 733 | ALL.lock() |
| 734 | .unwrap_or_else(PoisonError::into_inner) |
| 735 | .push(counts); |
| 736 | MINE.set(Some(counts)); |
| 737 | counts |
| 738 | } |
| 739 | |
| 740 | #[inline] |
| 741 | pub fn alloc() { |
| 742 | let counts = mine(); |
| 743 | // Only this thread writes its counts: no read-modify-write. |
| 744 | counts |
| 745 | .live |
| 746 | .store(counts.live.load(Ordering::Relaxed) + 1, Ordering::Relaxed); |
| 747 | counts |
| 748 | .allocs |
| 749 | .store(counts.allocs.load(Ordering::Relaxed) + 1, Ordering::Relaxed); |
| 750 | } |
| 751 | |
| 752 | #[inline] |
| 753 | pub fn free() { |
| 754 | let counts = mine(); |
| 755 | counts |
| 756 | .live |
| 757 | .store(counts.live.load(Ordering::Relaxed) - 1, Ordering::Relaxed); |
| 758 | } |
| 759 | |
| 760 | fn sum(of: fn(&Counts) -> &AtomicI64) -> i64 { |
| 761 | ALL.lock() |
| 762 | .unwrap_or_else(PoisonError::into_inner) |
| 763 | .iter() |
| 764 | .map(|c| of(c).load(Ordering::Relaxed)) |
| 765 | .sum() |
| 766 | } |
| 767 | |
| 768 | pub fn live() -> i64 { |
| 769 | sum(|c| &c.live) |
| 770 | } |
| 771 | |
| 772 | pub fn allocs() -> i64 { |
| 773 | sum(|c| &c.allocs) |
| 774 | } |
| 775 | } |
| 776 | |
| 777 | #[inline] |
| 778 | pub fn alloc() { |
| 779 | #[cfg(feature = "stats")] |
| 780 | counts::alloc(); |
| 781 | } |
| 782 | |
| 783 | #[inline] |
| 784 | pub fn free() { |
| 785 | #[cfg(feature = "stats")] |
| 786 | counts::free(); |
| 787 | } |
| 788 | |
| 789 | /// The number of live blocks; meaningful when no other thread is |
| 790 | /// allocating or freeing (at exit, say). -1 without the `stats` |
| 791 | /// feature. |
| 792 | #[unsafe(no_mangle)] |
| 793 | pub extern "C" fn tl_stats_live_blocks() -> i64 { |
| 794 | #[cfg(feature = "stats")] |
| 795 | return counts::live(); |
| 796 | #[cfg(not(feature = "stats"))] |
| 797 | return -1; |
| 798 | } |
| 799 | |
| 800 | /// The number of blocks ever allocated, summed over threads; |
| 801 | /// meaningful when no other thread is allocating (at exit, say). -1 |
| 802 | /// without the `stats` feature. |
| 803 | #[unsafe(no_mangle)] |
| 804 | pub extern "C" fn tl_stats_allocations() -> i64 { |
| 805 | #[cfg(feature = "stats")] |
| 806 | return counts::allocs(); |
| 807 | #[cfg(not(feature = "stats"))] |
| 808 | return -1; |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | /// Release one count of `v` while the drop worklist is being drained |
| 813 | /// (freeing a block that owns `v`). |
| 814 | /// |
| 815 | /// # Safety |
| 816 | /// `v` must be an owned value. |
| 817 | pub(crate) unsafe fn release_into(v: Value, pending: &mut Vec<*mut Block>) { |
| 818 | if !is_ptr(v) { |
| 819 | return; |
| 820 | } |
| 821 | let b = v as *mut Block; |
| 822 | // SAFETY: caller guarantees `v` is live. |
| 823 | unsafe { |
| 824 | let rc = rc(b); |
| 825 | if (2..RC_STUCK).contains(&rc) { |
| 826 | (*b).header.rc = rc - 1; |
| 827 | } else if release(b) { |
| 828 | pending.push(b); |
| 829 | } |
| 830 | } |
| 831 | } |
| 832 | |
| 833 | #[cfg(test)] |
| 834 | mod tests { |
| 835 | use super::*; |
| 836 | use crate::abi::UNIT; |
| 837 | use crate::abi::int; |
| 838 | use crate::values::{list, string}; |
| 839 | |
| 840 | /// Run `continue_drain` until nothing is left; the number of steps. |
| 841 | unsafe fn steps(ctx: *mut Ctx) -> usize { |
| 842 | // SAFETY: forwarded caller guarantee. |
| 843 | unsafe { |
| 844 | let stack = crate::sched::drop_stack(ctx); |
| 845 | let mut steps = 1; |
| 846 | while stack.has_pending() { |
| 847 | assert_eq!((*ctx).reductions, 0, "the next function entry yields"); |
| 848 | (*ctx).reductions = crate::sched::REDUCTIONS; |
| 849 | continue_drain(ctx); |
| 850 | steps += 1; |
| 851 | } |
| 852 | steps |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | /// Large structures are freed a step at a time (issue #158), and what |
| 857 | /// is left when the actor ends is freed then. |
| 858 | unsafe extern "C" fn drops_in_steps(ctx: *mut Ctx) -> Value { |
| 859 | // SAFETY: `ctx` is the root actor's; every value built is owned. |
| 860 | unsafe { |
| 861 | let before = stats::tl_stats_live_blocks(); |
| 862 | // A million cells: about 3,600 per step. |
| 863 | drop_value(ctx, list(ctx, (0..1_000_000).map(int))); |
| 864 | let n = steps(ctx); |
| 865 | assert!((200..400).contains(&n), "{n} steps"); |
| 866 | assert_eq!(stats::tl_stats_live_blocks(), before); |
| 867 | // An array of 100,000 strings, released from its end (its |
| 868 | // fields cost one each, its strings 16), after the list it was |
| 869 | // made from (cells cost 18). |
| 870 | let strings = list(ctx, (0..100_000).map(|i| string(ctx, &i.to_string()))); |
| 871 | let array = crate::array::tl_array_from_list(ctx, strings); |
| 872 | drop_value(ctx, strings); |
| 873 | drop_value(ctx, array); |
| 874 | let n = steps(ctx); |
| 875 | assert!((40..80).contains(&n), "{n} steps"); |
| 876 | assert_eq!(stats::tl_stats_live_blocks(), before); |
| 877 | // Small drops take one step. |
| 878 | drop_value(ctx, list(ctx, (0..1000).map(int))); |
| 879 | assert!(!crate::sched::drop_stack(ctx).has_pending()); |
| 880 | // Left over: the actor's end frees it (`finish_drain`; the |
| 881 | // stack's `Drop` checks). |
| 882 | drop_value(ctx, list(ctx, (0..1_000_000).map(int))); |
| 883 | assert!(crate::sched::drop_stack(ctx).has_pending()); |
| 884 | } |
| 885 | UNIT |
| 886 | } |
| 887 | |
| 888 | /// An actor's `proc` capability is immortal, as `clock`'s is: every |
| 889 | /// actor gets the same block, and its release frees nothing and queues |
| 890 | /// nothing. Built per actor, its 17 closures were allocated at each |
| 891 | /// start and queued on the drop worklist at each exit (#422 made that |
| 892 | /// one more doubling of the worklist: 10% of `tests/bench/churn`). |
| 893 | unsafe extern "C" fn proc_capabilities_are_shared(ctx: *mut Ctx) -> Value { |
| 894 | // SAFETY: `ctx` is the root actor's; the capabilities are owned here. |
| 895 | unsafe { |
| 896 | let before = stats::tl_stats_live_blocks(); |
| 897 | let a = crate::process::root_cap(crate::process::RootCap::Proc); |
| 898 | let b = crate::process::root_cap(crate::process::RootCap::Proc); |
| 899 | assert_eq!(a, b, "one capability for every actor"); |
| 900 | assert_eq!(stats::tl_stats_live_blocks(), before, "allocated"); |
| 901 | drop_value(ctx, a); |
| 902 | drop_value(ctx, b); |
| 903 | assert!(!crate::sched::drop_stack(ctx).has_pending(), "queued"); |
| 904 | assert_eq!(stats::tl_stats_live_blocks(), before); |
| 905 | } |
| 906 | UNIT |
| 907 | } |
| 908 | |
| 909 | #[test] |
| 910 | fn a_proc_capability_is_immortal() { |
| 911 | // SAFETY: the entry follows the generated-code convention. |
| 912 | let status = unsafe { crate::sched::run_test_actor(proc_capabilities_are_shared) }; |
| 913 | assert_eq!(status, 0); |
| 914 | } |
| 915 | |
| 916 | #[test] |
| 917 | fn large_drops_are_freed_in_steps() { |
| 918 | // SAFETY: `drops_in_steps` follows the generated-code convention. |
| 919 | assert_eq!(unsafe { crate::sched::run_test_actor(drops_in_steps) }, 0); |
| 920 | } |
| 921 | |
| 922 | /// A count that would overflow sticks instead (issue #217): no dup or |
| 923 | /// drop moves it again, and the block is never freed. |
| 924 | unsafe extern "C" fn saturating_counts(ctx: *mut Ctx) -> Value { |
| 925 | // SAFETY: `ctx` is the root actor's; the blocks are owned here. |
| 926 | unsafe { |
| 927 | let local = string(ctx, "local"); |
| 928 | let b = local as *mut Block; |
| 929 | (*b).header.rc = RC_STUCK - 1; |
| 930 | dup_value(local); |
| 931 | assert_eq!((*b).header.rc, RC_STUCK); |
| 932 | dup_value(local); |
| 933 | for _ in 0..3 { |
| 934 | drop_value(ctx, local); |
| 935 | } |
| 936 | assert_eq!((*b).header.rc, RC_STUCK); |
| 937 | |
| 938 | let shared = string(ctx, "shared"); |
| 939 | let s = shared as *mut Block; |
| 940 | (*s).header.rc = SHARED_SATURATED; |
| 941 | dup_value(shared); |
| 942 | assert_eq!((*s).header.rc, SHARED_STUCK); |
| 943 | for _ in 0..1000 { |
| 944 | drop_value(ctx, shared); |
| 945 | } |
| 946 | assert_eq!((*s).header.rc, SHARED_STUCK); |
| 947 | |
| 948 | // Back to one reference each, so the actor ends without leaks. |
| 949 | (*b).header.rc = 1; |
| 950 | drop_value(ctx, local); |
| 951 | (*s).header.rc = -1; |
| 952 | drop_value(ctx, shared); |
| 953 | } |
| 954 | UNIT |
| 955 | } |
| 956 | |
| 957 | #[test] |
| 958 | fn counts_saturate_instead_of_wrapping() { |
| 959 | // SAFETY: `saturating_counts` follows the generated-code convention. |
| 960 | let leaked = unsafe { crate::sched::run_test_actor(saturating_counts) }; |
| 961 | assert_eq!(leaked, 0); |
| 962 | } |
| 963 | } |