Truly independent web browser
LibGC: Give the memory that collections use back to the system
Andreas Kling757403990c1a
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 0d4fbc7e0c1..79c93bc6cc4 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -1376,7 +1376,7 @@ void Heap::begin_evacuation().value_is_cell_pattern = SHIFTED_IS_CELL_PATTERN,.value_offset_mask = HEAP_REGION_OFFSET_MASK,},- this);+ this, m_evacuated_blocks.size());for (auto* block : m_evacuated_blocks)FFI::rust_gc_evacuation_add_block(m_evacuation, block);}@@ -1431,7 +1431,7 @@ void Heap::evacuate()while (end < m_evacuated_blocks.size() && &m_evacuated_blocks[end]->cell_allocator() == &allocator)++end;- Vector<Cell*> cells_to_move;+ Vector<FFI::CellMove> moves;for (size_t i = exchange(first_block_of_allocator, end); i < end; ++i) {auto& block = *m_evacuated_blocks[i];auto& descriptor = block_descriptor_for(&block);@@ -1446,9 +1446,9 @@ void Heap::evacuate()if (allocator.descriptor().is_movable()) {FFI::PinnedCells pinned {};auto count = FFI::rust_gc_evacuation_cells_to_move(m_evacuation, &block, cells.data(), &pinned);- cells_to_move.ensure_capacity(cells_to_move.size() + count);+ moves.grow_capacity(moves.size() + count);for (size_t j = 0; j < count; ++j)- cells_to_move.unchecked_append(static_cast<Cell*>(cells[j]));+ moves.unchecked_append({ .from = cells[j], .to = nullptr });auto& by_edge = stats.pinned[CompactionStats::ByValueEdge];by_edge.cells += pinned.by_edge;by_edge.bytes += pinned.by_edge * cell_size;@@ -1464,14 +1464,12 @@ void Heap::evacuate()}clear_marks(descriptor);}- if (cells_to_move.is_empty())+ if (moves.is_empty())continue;// NB: Every destination is taken before any cell moves, so no cell moves twice, and no old slot is free yet.- Vector<FFI::CellMove> moves;- moves.ensure_capacity(cells_to_move.size());- for (auto* cell : cells_to_move) {- moves.unchecked_append({ .from = cell, .to = allocate_destination_for_moved_cell(allocator) });+ for (auto& cell_move : moves) {+ cell_move.to = allocate_destination_for_moved_cell(allocator);stats.moved.add(cell_size);}FFI::rust_gc_evacuation_forward_cells(m_evacuation, moves.data(), moves.size(), cell_size);@@ -2564,6 +2562,7 @@ void Heap::schedule_release_of_allocator_memory()if (!m_allocator_memory_release_timer) {m_allocator_memory_release_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(GC_ALLOCATOR_MEMORY_RELEASE_DELAY_MS), [] {ak_kmalloc_collect();+ FFI::rust_gc_marker_release_unused_helper_memory();});}m_allocator_memory_release_timer->restart();diff --git a/Libraries/LibGC/Rust/src/evacuation.rs b/Libraries/LibGC/Rust/src/evacuation.rsindex 277cd00575c..2b511d48d6d 100644--- a/Libraries/LibGC/Rust/src/evacuation.rs+++ b/Libraries/LibGC/Rust/src/evacuation.rs@@ -19,6 +19,7 @@//! of such a slot pins its target instead.use core::ffi::c_void;+use core::ptr::NonNull;use core::sync::atomic::{AtomicU32, AtomicU64, Ordering};use crate::block::{@@ -27,8 +28,118 @@ use crate::block::{};use crate::identity_hash::{CompressedAddress, IDENTITY_HASH_STATE_OFFSET, identity_hashes_of};use crate::marker::COMPRESSED_POINTER_SHIFT;+use crate::os;use crate::rust_panic::abort_on_panic;+/// Zero-filled room for `capacity` values of `T`, mapped from the system and given back to it as a whole when dropped,+/// for what a collection that moves cells keeps until it is over. Only the pages that are written to take memory.+///+/// NB: A compacting collection needs a burst of memory that it frees all at once. Malloc would keep those pages for+/// later and hand them out among long-lived allocations, which then keep them in the process.+struct MappedArray<T> {+ pointer: NonNull<T>,+ capacity: usize,+}++impl<T> MappedArray<T> {+ /// # Safety+ ///+ /// All-zero bytes must be a valid `T`.+ unsafe fn new_zeroed(capacity: usize) -> Self {+ let capacity = capacity.max(1);+ let size = capacity * size_of::<T>();+ let pointer = os::reserve_zeroed(size).expect("map memory for a collection that moves cells");+ // SAFETY: The range is all of what reserve_zeroed() just returned.+ unsafe { os::commit_reserved_zeroed(pointer, size) };+ Self {+ pointer: pointer.cast(),+ capacity,+ }+ }++ fn get(&self, index: usize) -> &T {+ assert!(index < self.capacity);+ // SAFETY: The index is in bounds, and every value is valid from the start, as new_zeroed() requires.+ unsafe { self.pointer.add(index).as_ref() }+ }+}++impl<T> Drop for MappedArray<T> {+ fn drop(&mut self) {+ // SAFETY: The range is all of the reservation, which goes away with this.+ unsafe { os::release(self.pointer.cast(), self.capacity * size_of::<T>()) };+ }+}++/// How many slots a chunk of recorded slots has room for: 1 MiB of address space.+const RECORDED_SLOTS_PER_CHUNK: usize = 128 * 1024;++/// The slots one marker records, in chunks of mapped memory (see MappedArray).+pub struct RecordedSlots {+ /// The chunks, the one being filled last.+ chunks: Vec<MappedArray<RecordedSlot>>,+ /// Where the next slot goes in the last chunk, and the end of that chunk; both null before the first chunk.+ next: *mut RecordedSlot,+ end: *mut RecordedSlot,+}++impl Default for RecordedSlots {+ fn default() -> Self {+ Self {+ chunks: Vec::new(),+ next: core::ptr::null_mut(),+ end: core::ptr::null_mut(),+ }+ }+}++impl RecordedSlots {+ #[inline(always)]+ pub fn push(&mut self, slot: RecordedSlot) {+ if self.next == self.end {+ self.add_chunk();+ }+ // SAFETY: The last chunk has room at next, which stays within it.+ unsafe {+ self.next.write(slot);+ self.next = self.next.add(1);+ }+ }++ #[cold]+ fn add_chunk(&mut self) {+ // SAFETY: A RecordedSlot is an integer.+ let chunk = unsafe { MappedArray::<RecordedSlot>::new_zeroed(RECORDED_SLOTS_PER_CHUNK) };+ self.next = chunk.pointer.as_ptr();+ // SAFETY: The chunk has room for its capacity.+ self.end = unsafe { self.next.add(chunk.capacity) };+ self.chunks.push(chunk);+ }++ pub fn is_empty(&self) -> bool {+ self.chunks.is_empty()+ }++ /// The recorded slots, chunk by chunk.+ fn slices(&self) -> impl Iterator<Item = &[RecordedSlot]> {+ let last = self.chunks.len().wrapping_sub(1);+ self.chunks.iter().enumerate().map(move |(index, chunk)| {+ let length = if index == last {+ // SAFETY: next is in the last chunk.+ unsafe { self.next.offset_from(chunk.pointer.as_ptr()) as usize }+ } else {+ chunk.capacity+ };+ // SAFETY: The first length slots of the chunk were written.+ unsafe { ak::slice_from_raw_parts(chunk.pointer.as_ptr(), length) }+ })+ }++ fn len(&self) -> usize {+ self.slices().map(<[RecordedSlot]>::len).sum()+ }+}+/// Why a cell of an evacuated block stays where it is.#[derive(Clone, Copy, Debug, PartialEq, Eq)]#[repr(u8)]@@ -40,7 +151,7 @@ pub enum PinReason {Root = 2,}-/// What a collection that evacuates a block knows about the block's cells.+/// What a collection that evacuates a block knows about the block's cells. All zeros is nothing pinned or moved yet.pub struct Evacuation {pinned_by_edge: [AtomicU64; CELL_BITMAP_WORDS],pinned_by_root: [AtomicU64; CELL_BITMAP_WORDS],@@ -49,14 +160,6 @@ pub struct Evacuation {}impl Evacuation {- fn new() -> Box<Self> {- Box::new(Self {- pinned_by_edge: [const { AtomicU64::new(0) }; CELL_BITMAP_WORDS],- pinned_by_root: [const { AtomicU64::new(0) }; CELL_BITMAP_WORDS],- forwarding: [const { AtomicU32::new(0) }; MAX_CELLS_PER_BLOCK],- })- }-/// Pins the cell at `address` of the block this evacuates, which markers may do from several threads at once.#[inline(always)]pub fn pin(&self, descriptor: &BlockDescriptor, address: usize, reason: PinReason) {@@ -159,12 +262,14 @@ pub struct EvacuationLayout {pub struct EvacuationSet {layout: EvacuationLayout,heap: *mut c_void,- blocks: Vec<(usize, Box<Evacuation>)>,- slots: Vec<Vec<RecordedSlot>>,+ /// The evacuated blocks, and their evacuations at the same indices.+ blocks: Vec<usize>,+ evacuations: MappedArray<Evacuation>,+ slots: Vec<RecordedSlots>,}impl EvacuationSet {- pub(crate) fn add_recorded_slots(&mut self, slots: Vec<RecordedSlot>) {+ pub(crate) fn add_recorded_slots(&mut self, slots: RecordedSlots) {if !slots.is_empty() {self.slots.push(slots);}@@ -270,13 +375,20 @@ impl EvacuationSet {}}-/// Starts the evacuation state of a collection of `heap`, which owns the evacuations of the blocks it adds.+/// Starts the evacuation state of a collection of `heap`, which evacuates up to `block_count` blocks that it adds, and+/// owns their evacuations.#[unsafe(no_mangle)]-pub extern "C" fn rust_gc_evacuation_create(layout: EvacuationLayout, heap: *mut c_void) -> *mut EvacuationSet {+pub extern "C" fn rust_gc_evacuation_create(+ layout: EvacuationLayout,+ heap: *mut c_void,+ block_count: usize,+) -> *mut EvacuationSet {Box::into_raw(Box::new(EvacuationSet {layout,heap,- blocks: Vec::new(),+ blocks: Vec::with_capacity(block_count),+ // SAFETY: All zeros is an evacuation that pinned and moved nothing.+ evacuations: unsafe { MappedArray::new_zeroed(block_count) },slots: Vec::new(),}))}@@ -285,7 +397,8 @@ pub extern "C" fn rust_gc_evacuation_create(layout: EvacuationLayout, heap: *mut////// # Safety///-/// `set` must be live, and `block` a live block of its heap that the set does not have yet.+/// `set` must be live, and `block` a live block of its heap that the set does not have yet. The set must have room for+/// it, see rust_gc_evacuation_create().#[unsafe(no_mangle)]pub unsafe extern "C" fn rust_gc_evacuation_add_block(set: *mut EvacuationSet, block: *mut c_void) {// SAFETY: The caller passes a live set.@@ -295,16 +408,16 @@ pub unsafe extern "C" fn rust_gc_evacuation_add_block(set: *mut EvacuationSet, b// SAFETY: The caller passes a live block.let descriptor = unsafe { descriptor_for(set.layout.heap_region_base, address) };debug_assert!(descriptor.heap() == set.heap && descriptor.evacuation().is_none());- let evacuation = Evacuation::new();+ let evacuation = set.evacuations.get(set.blocks.len());// SAFETY: The caller passes a live block, and no marker runs yet.unsafe {set_evacuation_of_block(set.layout.heap_region_base,address,- core::ptr::from_ref(&*evacuation).cast_mut(),+ core::ptr::from_ref(evacuation).cast_mut(),);}- set.blocks.push((address, evacuation));+ set.blocks.push(address);}/// Why a live cell of an evacuated block was pinned.@@ -464,7 +577,7 @@ pub unsafe extern "C" fn rust_gc_evacuation_fix_up_slots(set: *mut EvacuationSet// SAFETY: The caller passes a live set.let set = unsafe { &*set };let mut rewritten = 0;- for slots in &set.slots {+ for slots in set.slots.iter().flat_map(RecordedSlots::slices) {for &slot in slots {// SAFETY: Marking recorded the slot in a live cell, which the caller makes sure is still live and where it was.if unsafe { set.fix_up(slot) } {@@ -484,7 +597,7 @@ pub unsafe extern "C" fn rust_gc_evacuation_fix_up_slots(set: *mut EvacuationSet#[unsafe(no_mangle)]pub unsafe extern "C" fn rust_gc_evacuation_recorded_slot_count(set: *const EvacuationSet) -> usize {// SAFETY: The caller passes a live set.- unsafe { &*set }.slots.iter().map(Vec::len).sum()+ unsafe { &*set }.slots.iter().map(RecordedSlots::len).sum()}/// Where the cell at `cell` moved to, or null if it did not move.@@ -514,13 +627,13 @@ pub unsafe extern "C" fn rust_gc_evacuation_forwarding_address(pub unsafe extern "C" fn rust_gc_evacuation_destroy(set: *mut EvacuationSet) {// SAFETY: The caller passes a live set, which it gives up.let set = unsafe { Box::from_raw(set) };- for (block, evacuation) in &set.blocks {+ for (index, block) in set.blocks.iter().enumerate() {// SAFETY: Every block of the set was in the region, where descriptors stay backed by memory.let descriptor = unsafe { descriptor_for(set.layout.heap_region_base, *block) };// NB: A block that went away and came back since has a fresh descriptor, which may not be cleared.if descriptor.evacuation()- .is_some_and(|current| core::ptr::eq(current, &raw const **evacuation))+ .is_some_and(|current| core::ptr::eq(current, set.evacuations.get(index))){// SAFETY: The block is in the region, and no marker runs.unsafe { set_evacuation_of_block(set.layout.heap_region_base, *block, core::ptr::null_mut()) };diff --git a/Libraries/LibGC/Rust/src/lib.rs b/Libraries/LibGC/Rust/src/lib.rsindex e90b100cd5f..f3646b10256 100644--- a/Libraries/LibGC/Rust/src/lib.rs+++ b/Libraries/LibGC/Rust/src/lib.rs@@ -55,7 +55,8 @@ pub use identity_hash::{rust_gc_identity_hashes_destroy,};pub use marker::{- MarkRequest, Marker, MarkerLayout, rust_gc_marker_mark, rust_gc_marker_pin_cell, rust_gc_marker_visit_cell,- rust_gc_marker_visit_ephemeron, rust_gc_marker_visit_interior_pointer, rust_gc_marker_visit_member,- rust_gc_marker_visit_self_pointer, rust_gc_marker_visit_values,+ MarkRequest, Marker, MarkerLayout, rust_gc_marker_mark, rust_gc_marker_pin_cell,+ rust_gc_marker_release_unused_helper_memory, rust_gc_marker_visit_cell, rust_gc_marker_visit_ephemeron,+ rust_gc_marker_visit_interior_pointer, rust_gc_marker_visit_member, rust_gc_marker_visit_self_pointer,+ rust_gc_marker_visit_values,};diff --git a/Libraries/LibGC/Rust/src/marker.rs b/Libraries/LibGC/Rust/src/marker.rsindex 111d668e574..b5e393d14dc 100644--- a/Libraries/LibGC/Rust/src/marker.rs+++ b/Libraries/LibGC/Rust/src/marker.rs@@ -25,7 +25,7 @@ use std::sync::Barrier;use crossbeam_deque::{Injector, Steal, Stealer, Worker};use crate::block::{BLOCK_SIZE, BlockDescriptor, descriptor_table, heap_of_descriptor};-use crate::evacuation::{EvacuationSet, PinReason, RecordedSlot, SlotKind};+use crate::evacuation::{EvacuationSet, PinReason, RecordedSlot, RecordedSlots, SlotKind};use crate::pool::{Pool, PoolGuard};use crate::rust_panic::abort_on_panic;@@ -128,7 +128,7 @@ pub struct Marker {/// Ephemerons whose key was not marked yet when they were visited, as (key, value).pending_ephemerons: UnsafeCell<Vec<(u32, u32)>>,/// The slots that point into evacuated blocks, which a collection that moves cells rewrites.- recorded_slots: UnsafeCell<Vec<RecordedSlot>>,+ recorded_slots: UnsafeCell<RecordedSlots>,}impl Job<'_> {@@ -600,6 +600,16 @@ pub unsafe extern "C" fn rust_gc_marker_visit_ephemeron(marker: *mut Marker, keyunsafe { &*marker }.visit_ephemeron(key.addr(), value.addr());}+/// Has the threads that help mark give back the memory they no longer use, see Pool::release_unused_memory().+#[unsafe(no_mangle)]+pub extern "C" fn rust_gc_marker_release_unused_helper_memory() {+ abort_on_panic(|| {+ if let Some(pool) = Pool::the() {+ pool.release_unused_memory();+ }+ });+}+/// Marks every cell of the heaps that the roots reach, and adds up the bytes they take.////// # Safety@@ -649,7 +659,7 @@ fn mark(request: &mut MarkRequest, heaps: &[*const c_void], roots: &[*const c_vomarked_cell_bytes: (0..heaps.len()).map(|_| Cell::new(0)).collect(),marked_external_bytes: (0..heaps.len()).map(|_| Cell::new(0)).collect(),pending_ephemerons: UnsafeCell::new(Vec::new()),- recorded_slots: UnsafeCell::new(Vec::new()),+ recorded_slots: UnsafeCell::new(RecordedSlots::default()),});}// NB: The job lives on this stack until every marker is done with it, so the markers may point at it as if it liveddiff --git a/Libraries/LibGC/Rust/src/os.rs b/Libraries/LibGC/Rust/src/os.rsindex 14e00ce376a..76e9c49c620 100644--- a/Libraries/LibGC/Rust/src/os.rs+++ b/Libraries/LibGC/Rust/src/os.rs@@ -38,6 +38,15 @@ mod platform {NonNull::new(address.cast())}+ /// # Safety+ ///+ /// The range must be all of a reservation that reserve_zeroed() returned, which nothing uses any more.+ pub unsafe fn release(address: NonNull<u8>, size: usize) {+ // SAFETY: The caller passes a whole reservation that nothing uses.+ let result = unsafe { libc::munmap(address.as_ptr().cast(), size) };+ assert_eq!(result, 0, "munmap() failed");+ }+/// # Safety////// The range must be within memory that reserve_zeroed() returned.@@ -162,7 +171,8 @@ mod platform {mod platform {use core::ptr::NonNull;use windows_sys::Win32::System::Memory::{- MEM_COMMIT, MEM_RESERVE, MEM_RESET, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualUnlock,+ MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, MEM_RESET, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree,+ VirtualUnlock,};pub fn reserve_zeroed(size: usize) -> Option<NonNull<u8>> {@@ -173,6 +183,15 @@ mod platform {NonNull::new(address.cast())}+ /// # Safety+ ///+ /// The range must be all of a reservation that reserve_zeroed() returned, which nothing uses any more.+ pub unsafe fn release(address: NonNull<u8>, _size: usize) {+ // SAFETY: The caller passes a whole reservation that nothing uses.+ let released = unsafe { VirtualFree(address.as_ptr().cast(), 0, MEM_RELEASE) };+ assert!(released != 0, "VirtualFree(MEM_RELEASE) failed");+ }+/// # Safety////// The range must be within memory that reserve_zeroed() returned.@@ -235,6 +254,16 @@ pub fn reserve_zeroed(size: usize) -> Option<NonNull<u8>> {platform::reserve_zeroed(size)}+/// Gives back all of a reservation that reserve_zeroed() returned.+///+/// # Safety+///+/// The range must be all of a reservation that reserve_zeroed() returned, which nothing uses any more.+pub unsafe fn release(address: NonNull<u8>, size: usize) {+ // SAFETY: Forwarded from the caller.+ unsafe { platform::release(address, size) }+}+/// Backs a range of memory that reserve_zeroed() returned with memory, if it was not already.////// # Safetydiff --git a/Libraries/LibGC/Rust/src/pool.rs b/Libraries/LibGC/Rust/src/pool.rsindex dfd6c671418..b35232d22ce 100644--- a/Libraries/LibGC/Rust/src/pool.rs+++ b/Libraries/LibGC/Rust/src/pool.rs@@ -7,7 +7,7 @@//! The threads that help the thread that owns a heap mark it. They live as long as the process, and wait for the next//! collection in between, so a collection does not pay for creating them.-use core::sync::atomic::{AtomicUsize, Ordering};+use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Condvar, Mutex, MutexGuard, OnceLock, PoisonError};/// The most threads that mark a heap, the thread that owns it included, unless LIBGC_MARKER_THREADS asks for another@@ -56,6 +56,8 @@ pub(crate) struct Pool {helpers_done: Condvar,/// Held while a collection uses the helpers. Heaps of other threads collect on their own meanwhile.in_use: Mutex<()>,+ /// Whether the helpers ran a task since they last gave their unused memory back, see release_unused_memory().+ ran_since_release: AtomicBool,}fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {@@ -81,6 +83,7 @@ impl Pool {task_available: Condvar::new(),helpers_done: Condvar::new(),in_use: Mutex::new(()),+ ran_since_release: AtomicBool::new(false),}));// NB: A helper that cannot start, as when the process has as many threads as it may, leaves marking to the// ones that did, or to the thread that owns the heap alone.@@ -113,6 +116,26 @@ impl Pool {})}+ /// Has the helpers give back the memory they freed, unless another heap uses them now, which does the same once it is+ /// done. What a helper allocates while it marks, such as room in its queue, is freed by the thread that collects+ /// once the collection is over, and the allocator keeps it for the helper until the helper allocates again, which an+ /// idle helper never does.+ pub(crate) fn release_unused_memory(&'static self) {+ if !self.ran_since_release.load(Ordering::Relaxed) {+ return;+ }+ let Some(helpers) = self.try_acquire() else {+ return;+ };+ unsafe fn release(_: *const (), _: usize) {+ ak::release_unused_allocator_memory();+ }+ // SAFETY: release() takes nothing, and any thread may call it.+ unsafe { helpers.run(release, core::ptr::null(), || {}) };+ // NB: Running this task set the flag as well. No other task runs while the helpers are taken.+ self.ran_since_release.store(false, Ordering::Relaxed);+ }+fn run_helper(&self, index: usize) {// NB: The pool starts at generation 0, so a helper that starts after the first task was handed out still sees it.let mut seen_generation = 0;@@ -157,6 +180,7 @@ impl PoolGuard {owner: impl FnOnce(),) {let pool = self.pool;+ pool.ran_since_release.store(true, Ordering::Relaxed);{let mut state = lock(&pool.state);state.generation += 1;