Truly independent web browser
LibGC: Compact fragmented heaps once they go quiet
Andreas Kling5b7679e905cc
diff --git a/Libraries/LibGC/CMakeLists.txt b/Libraries/LibGC/CMakeLists.txtindex 1eb571996cf..55c57ac9d2e 100644--- a/Libraries/LibGC/CMakeLists.txt+++ b/Libraries/LibGC/CMakeLists.txt@@ -24,6 +24,7 @@ target_link_libraries(LibGC PUBLIC LibThreading)# The collector's core: the descriptors of blocks, and marking.import_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libgc_rust FEATURES allocator FFI_HEADER RustFFI.h)+test_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libgc_rust)target_link_libraries(LibGC PRIVATE libgc_rust)get_target_property(_libgc_rust_lib libgc_rust IMPORTED_LOCATION)set_property(SOURCE CAPI.cpp Cell.cpp Heap.cpp HeapBlock.cpp WeakBlock.cpp APPEND PROPERTY OBJECT_DEPENDS ${_libgc_rust_lib})diff --git a/Libraries/LibGC/CellAllocator.cpp b/Libraries/LibGC/CellAllocator.cppindex 3ed560d5e51..47731d82b60 100644--- a/Libraries/LibGC/CellAllocator.cpp+++ b/Libraries/LibGC/CellAllocator.cpp@@ -180,6 +180,7 @@ void CellAllocator::block_did_become_empty(Badge<Heap>, HeapBlock& block, DeferD{block.m_list_node.remove();block.heap().m_live_heap_blocks.remove(&block);+ block.heap().forget_cells_kept_by_pins(block);// NOTE: HeapBlocks are managed by the BlockAllocator, so we don't want to `delete` the block here.block.~HeapBlock();m_block_allocator.deallocate_block(&block, defer_decommit);diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 5ab12bb9bbf..1bbe36c257d 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -102,6 +102,19 @@ static constexpr int GC_ABANDONED_OBJECT_GRAPH_MIN_DELAY_MS = 1000;// busy, and leaves time for the work that a collection starts on other threads, like compressing source text.static constexpr int GC_ALLOCATOR_MEMORY_RELEASE_DELAY_MS = 5000;+// Compaction moves at most this many bytes of cells per collection. Moving cells out of nearly empty blocks costs about+// 3 ms per MiB on a desktop machine, half of it to copy the cells and take their new slots, and half to rewrite what+// points at them. Only a heap that went quiet compacts, so nobody waits for the pause, and as the emptiest blocks go+// first, a budget like this one frees most of what can be freed in one collection.+static constexpr size_t GC_COMPACTION_BUDGET_BYTES { 8 * MiB };++// A heap that went quiet compacts in collections of their own, one after another, as long as each frees at least this+// much and at least this much is left to recover.+// NB: While a page is busy, the holes that compaction would close are the room that the page fills again before the+// next collection, which comes after GC_MIN_BYTES_THRESHOLD of allocation at least. Compacting then frees blocks+// that the page needs again a few seconds later. Once the page is quiet, the heap would keep its holes for good.+static constexpr size_t GC_COMPACTION_MIN_RECOVERABLE_BYTES { 1 * MiB };+// Every thread that runs a VM has a heap of its own, and all but the main thread may come and go.AK_TLS_INITIAL_EXEC static thread_local constinit Heap* s_the = nullptr;@@ -140,6 +153,19 @@ bool libgc_move_everything()return value;}+// LIBGC_COMPACT=0 turns compaction off, so that collections never move cells unless LIBGC_MOVE_EVERYTHING asks them to.+bool read_libgc_compact()+{+ char const* env = getenv("LIBGC_COMPACT");+ return !env || !*env || atoi(env) != 0;+}++bool libgc_compact()+{+ static bool const value = read_libgc_compact();+ return value;+}+// What a collection that moves cells did, for its report.struct CompactionStats {enum PinReason : u8 {@@ -164,13 +190,20 @@ struct CompactionStats {size_t evacuated_blocks { 0 };size_t new_blocks { 0 };size_t freed_blocks { 0 };+ // What selection expected to recover and move, see rust_gc_compaction_select().+ size_t recoverable_bytes { 0 };+ size_t bytes_to_move { 0 };+ // The blocks that compaction could have freed as well, but that would have gone over the budget.+ size_t blocks_left_by_budget { 0 };Counts moved;Array<Counts, PinReasonCount> pinned;size_t recorded_slots { 0 };size_t rewritten_slots { 0 };+ i64 select_us { 0 };i64 sweep_us { 0 };i64 copy_us { 0 };i64 fix_up_us { 0 };+ i64 release_us { 0 };HashMap<ByteString, Array<Counts, PinReasonCount>> pinned_by_type;};@@ -260,11 +293,45 @@ IncrementalSweepStats& incremental_sweep_stats()thread_local bool g_next_incremental_sweep_should_report { false };+// What started the collection in progress, for its report.+thread_local CollectionTrigger g_collection_trigger { CollectionTrigger::Explicit };++StringView collection_trigger_name(CollectionTrigger trigger)+{+ switch (trigger) {+ case CollectionTrigger::Explicit:+ return "explicit"sv;+ case CollectionTrigger::Allocation:+ return "allocation"sv;+ case CollectionTrigger::IdlePolicy:+ return "idle policy"sv;+ case CollectionTrigger::AbandonedObjectGraph:+ return "abandoned object graph"sv;+ case CollectionTrigger::Compaction:+ return "compaction"sv;+ case CollectionTrigger::DeferralEnded:+ return "deferral ended"sv;+ }+ VERIFY_NOT_REACHED();+}+// Set by collect_garbage() while a reported collection is in flight. Used by// the GC's helpers to decide whether they should record subphase timings.thread_local bool g_recording_phase_timings { false };-void print_gc_report(i64 total_us, size_t live_block_count)+void print_compaction_summary()+{+ auto const& c = compaction_stats();+ auto pinned_bytes = [&](CompactionStats::PinReason reason) { return human_readable_size(c.pinned[reason].bytes); };+ dbgln("Compaction: {} source blocks, {} freed, {} new; moved {} of {} expected; pinned {} by edge, {} by root, {} non-movable; {} recoverable before; {} slots recorded, {} rewritten; select {} us, sweep {} us, compaction {} us (copy {}, fix up {}, release {})",+ c.evacuated_blocks, c.freed_blocks, c.new_blocks, human_readable_size(c.moved.bytes), human_readable_size(c.bytes_to_move),+ pinned_bytes(CompactionStats::ByValueEdge), pinned_bytes(CompactionStats::ByValueRoot),+ pinned_bytes(CompactionStats::NonMovableAllocator),+ human_readable_size(c.recoverable_bytes), c.recorded_slots, c.rewritten_slots, c.select_us, c.sweep_us,+ c.select_us + c.copy_us + c.fix_up_us + c.release_us, c.copy_us, c.fix_up_us, c.release_us);+}++void print_gc_report(i64 total_us, size_t live_block_count, bool scan_stack, size_t marked_cell_bytes, u64 allocated_bytes){auto const& t = g_phase_timings;auto const& s = g_sweep_stats;@@ -279,6 +346,10 @@ void print_gc_report(i64 total_us, size_t live_block_count)dbgln("=================================================================");dbgln("Totals:");dbgln(" Time spent: {} us", total_us);+ dbgln(" Stack scanned: {}", scan_stack ? "yes"sv : "no"sv);+ dbgln(" Trigger: {}", collection_trigger_name(g_collection_trigger));+ dbgln(" Marked cells: {}", human_readable_size(marked_cell_bytes));+ dbgln(" Allocated since: {}", human_readable_size(allocated_bytes));dbgln(" Live cells: {} ({})", s.live_cells, human_readable_size(s.live_cell_bytes));dbgln(" Live external: {}", human_readable_size(s.live_external_bytes));dbgln(" Collected cells: {} ({})", s.collected_cells, human_readable_size(s.collected_cell_bytes));@@ -324,9 +395,11 @@ void print_gc_report(i64 total_us, size_t live_block_count)print_counts("pinned: non-movable type"sv, c.pinned[CompactionStats::NonMovableAllocator]);dbgln(" recorded slots {:>10}", c.recorded_slots);dbgln(" rewritten slots {:>10}", c.rewritten_slots);+ dbgln(" select {:>10} us", c.select_us);dbgln(" sweep for compaction {:>10} us", c.sweep_us);dbgln(" copy {:>10} us", c.copy_us);dbgln(" fix up {:>10} us", c.fix_up_us);+ dbgln(" release {:>10} us", c.release_us);if (!c.pinned_by_type.is_empty()) {struct Entry {ByteString name;@@ -554,11 +627,13 @@ void Heap::will_allocate(size_t size, TriggersCollection triggers_collection)// may collect starts. Otherwise a program that allocates mostly storage (as one making large arrays does) would// keep gigabytes of dead storage before its few other allocations reached the threshold.if (m_block_sweeps_in_progress == 0 && triggers_collection == TriggersCollection::Yes) {- if (should_collect_on_every_allocation()) {- m_allocated_bytes_since_last_gc = 0;- collect_garbage();- } else if (m_allocated_bytes_since_last_gc + size > m_gc_bytes_threshold) {+ if (should_collect_on_every_allocation() || m_allocated_bytes_since_last_gc + size > m_gc_bytes_threshold) {m_allocated_bytes_since_last_gc = 0;+ // NB: A heap that allocates this much is not quiet.+ m_reducing_memory = false;+ m_compacted_since_activity = false;+ m_should_compact = false;+ TemporaryChange trigger { g_collection_trigger, CollectionTrigger::Allocation };collect_garbage();}}@@ -1078,8 +1153,12 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, CollectiScopedPhaseTimer timer { report, g_phase_timings.gather_roots_us };gather_roots(origin, roots);}- if (should_move_cells(collection_type, scan_stack))+ if (should_move_cells(collection_type, scan_stack)) {+ // NB: This collection may compact, which is what a scheduled one would be for.+ if (m_moving_collection_timer)+ m_moving_collection_timer->stop();begin_evacuation();+ }{ScopedPhaseTimer timer { report, g_phase_timings.mark_live_cells_us };mark_live_cells(roots);@@ -1108,6 +1187,10 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecticompaction_stats().sweep_us = g_phase_timings.sweep_dead_cells_us;evacuate();end_evacuation();+ // NB: The blocks this freed go back to the system once the decommit worker gets to them.+ BlockAllocator::wake_decommit_worker_async();+ if (libgc_log_level() >= 1)+ print_compaction_summary();}if (report) {@@ -1116,7 +1199,7 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti++live_block_count;return IterationDecision::Continue;});- print_gc_report(collection_measurement_timer.elapsed_time().to_microseconds(), live_block_count);+ print_gc_report(collection_measurement_timer.elapsed_time().to_microseconds(), live_block_count, scan_stack, m_marked_cell_bytes, m_total_allocated_bytes - m_total_allocated_bytes_at_last_collection);if (dump_allocators_too)dump_allocators();}@@ -1146,6 +1229,7 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti// A collection just happened: restart the idle policy's episode (peak rate and watchdog tick count) from here, so// a threshold-driven GC mid-episode doesn't leave it comparing against stale state.m_idle_collection_policy.reset(m_total_allocated_bytes);+ m_idle_collection_postponed = false;// Marking is synchronous, so this collection has already seen any graph the timer was waiting to collect.if (m_abandoned_object_graph_state == AbandonedObjectGraphState::WaitingToCollect) {@@ -1159,6 +1243,8 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collectiif (scan_stack && m_moves_everything)schedule_collection_that_moves_cells();+ else if (collection_type == CollectionType::CollectGarbage && !m_incremental_sweep_active)+ schedule_compaction_if_worthwhile();}bool Heap::should_move_cells(CollectionType collection_type, bool scan_stack) const@@ -1167,8 +1253,61 @@ bool Heap::should_move_cells(CollectionType collection_type, bool scan_stack) co// stack moves cells.if (collection_type != CollectionType::CollectGarbage || scan_stack)return false;- // FIXME: Choose blocks worth evacuating. For now, only the stress mode moves cells.- return m_moves_everything;+ return m_moves_everything || m_should_compact;+}++// The blocks of the movable allocators, as candidates for compaction, see rust_gc_compaction_select().+static Vector<FFI::CompactionCandidate> compaction_candidates(CellAllocator::List& allocators, size_t block_count)+{+ Vector<FFI::CompactionCandidate> candidates;+ candidates.ensure_capacity(block_count);+ u32 allocator_index = 0;+ for (auto& allocator : allocators) {+ if (!allocator.descriptor().is_movable())+ continue;+ auto cell_size = static_cast<u32>(allocator.cell_size());+ auto cell_count = static_cast<u32>((HeapBlock::BLOCK_SIZE - sizeof(HeapBlock)) / cell_size);+ allocator.for_each_block([&](HeapBlock& block) {+ candidates.unchecked_append({+ .block = &block,+ .allocator = allocator_index,+ .live_cells = block.live_cell_count().value_or(cell_count),+ .cell_count = cell_count,+ .cell_size = cell_size,+ .kept_by_pins = block_descriptor_for(&block).kept_by_pins,+ .selected = false,+ });+ return IterationDecision::Continue;+ });+ ++allocator_index;+ }+ return candidates;+}++void Heap::schedule_compaction_if_worthwhile()+{+ if (!m_reducing_memory)+ return;+ // After a collection that compacted, what is left is what went over its budget. A compaction that freed little+ // means that its blocks hold pinned cells or that the counts were off, and the next one would not do better.+ auto const& last = compaction_stats();+ size_t recoverable_blocks = 0;+ if (last.active) {+ if (last.freed_blocks * HeapBlock::BLOCK_SIZE >= GC_COMPACTION_MIN_RECOVERABLE_BYTES)+ recoverable_blocks = last.blocks_left_by_budget;+ } else {+ auto candidates = compaction_candidates(m_all_cell_allocators, m_live_heap_blocks.size());+ recoverable_blocks = FFI::rust_gc_compaction_select(candidates.data(), candidates.size(), 0).fitting_blocks;+ }+ if (recoverable_blocks * HeapBlock::BLOCK_SIZE < GC_COMPACTION_MIN_RECOVERABLE_BYTES) {+ m_reducing_memory = false;+ m_compacted_since_activity = true;+ return;+ }+ m_should_compact = true;+ if (libgc_log_level() >= 1)+ dbgln("Scheduling a collection that compacts: {} of {} recoverable", human_readable_size(recoverable_blocks * HeapBlock::BLOCK_SIZE), human_readable_size(m_live_heap_blocks.size() * HeapBlock::BLOCK_SIZE));+ schedule_collection_that_moves_cells();}bool Heap::moves_everything()@@ -1176,12 +1315,48 @@ bool Heap::moves_everything()return libgc_move_everything();}+// Picks the blocks this collection evacuates, before it marks: the blocks that compaction selects, or every block of+// cells defined outside of C++ in the stress mode.void Heap::begin_evacuation(){VERIFY(!m_evacuation);+ // NB: A pending sweep is finished before a collection, so every block knows how many cells it holds.+ VERIFY(!m_incremental_sweep_active);auto& stats = compaction_stats();stats = {};++ Vector<HeapBlock*> blocks;+ if (m_moves_everything) {+ for (auto& allocator : m_all_cell_allocators) {+ // NB: Cells defined in C++ never move. Blocks of cells defined elsewhere are evacuated whether or not+ // their allocator is movable, which tells what keeps cells from moving.+ if (!allocator.foreign_type())+ continue;+ allocator.for_each_block([&](HeapBlock& block) {+ blocks.append(&block);+ return IterationDecision::Continue;+ });+ }+ } else {+ m_should_compact = false;+ auto select_start_ns = MonotonicTime::now().nanoseconds();+ auto candidates = compaction_candidates(m_all_cell_allocators, m_live_heap_blocks.size());+ auto selection = FFI::rust_gc_compaction_select(candidates.data(), candidates.size(), GC_COMPACTION_BUDGET_BYTES);+ for (auto const& candidate : candidates) {+ if (candidate.selected)+ blocks.append(static_cast<HeapBlock*>(candidate.block));+ }+ stats.recoverable_bytes = selection.recoverable_bytes;+ stats.bytes_to_move = selection.bytes_to_move;+ stats.blocks_left_by_budget = selection.fitting_blocks - selection.selected_blocks;+ stats.select_us = (MonotonicTime::now().nanoseconds() - select_start_ns) / 1000;+ }+ if (blocks.is_empty())+ return;++ m_evacuated_blocks = move(blocks);stats.active = true;+ stats.evacuated_blocks = m_evacuated_blocks.size();m_evacuation = FFI::rust_gc_evacuation_create({.heap_region_base = heap_region_base(),@@ -1190,17 +1365,8 @@ void Heap::begin_evacuation().value_offset_mask = HEAP_REGION_OFFSET_MASK,},this);- for (auto& allocator : m_all_cell_allocators) {- // NB: Cells defined in C++ never move. Blocks of cells defined elsewhere are evacuated whether or not their- // allocator is movable, which tells what keeps cells from moving.- if (!allocator.foreign_type())- continue;- allocator.for_each_block([&](HeapBlock& block) {- FFI::rust_gc_evacuation_add_block(m_evacuation, &block);- ++stats.evacuated_blocks;- return IterationDecision::Continue;- });- }+ for (auto* block : m_evacuated_blocks)+ FFI::rust_gc_evacuation_add_block(m_evacuation, block);}Cell* Heap::allocate_destination_for_moved_cell(CellAllocator& allocator)@@ -1220,9 +1386,10 @@ Cell* Heap::allocate_destination_for_moved_cell(CellAllocator& allocator)}}-// Moves the live cells of the evacuated blocks that nothing pinned to free slots of their allocator, then rewrites the-// slots that marking recorded and the weak pointers, and frees the old slots without destroying their cells. The dead-// cells are swept already, so their slots are free to take, and no destructor of a dead cell sees a cell that moved.+// Moves the live cells of the evacuated blocks that nothing pinned to free slots of other blocks of their allocator:+// takes their new slots, rewrites the slots that marking recorded and the weak pointers, copies the cells, and frees+// the old slots without destroying their cells. The dead cells are swept already, so their slots are free to take, and+// no destructor of a dead cell sees a cell that moved.void Heap::evacuate(){auto& stats = compaction_stats();@@ -1235,41 +1402,70 @@ void Heap::evacuate()stats.pinned_by_type.ensure(class_name_of(*cell))[reason].add(cell_size);};+ // NB: The free cells of a block have to be back in their block before the slots of cells that move are freed.+ // Nothing has allocated since the collection gave them back, see allocate_cell(), so this only makes sure.+ give_back_local_free_lists();+struct AllocatorMoves {CellAllocator* allocator;Vector<FFI::CellMove> moves;};Vector<AllocatorMoves> all_moves;+ Array<void*, FFI::MAX_CELLS_PER_BLOCK> cells;+ // NB: The evacuated blocks wait here while cells move, so that no cell moves into one of them.+ CellAllocator::BlockList blocks_being_evacuated;+ Vector<HeapBlock*> blocks_kept_by_pins;auto copy_start_ns = MonotonicTime::now().nanoseconds();- for (auto& allocator : m_all_cell_allocators) {- if (!allocator.foreign_type())- continue;+ // NB: The sweep let go of the evacuated blocks whose cells all died, and a block it let go of may have come back+ // since, which publishes it again without an evacuation.+ m_evacuated_blocks.remove_all_matching([this](HeapBlock* block) {+ auto const& descriptor = block_descriptor_for(block);+ return descriptor.heap != this || !descriptor.evacuation;+ });+ // NB: The blocks of an allocator come one after another, see begin_evacuation().+ for (size_t first_block_of_allocator = 0; first_block_of_allocator < m_evacuated_blocks.size();) {+ auto& allocator = m_evacuated_blocks[first_block_of_allocator]->cell_allocator();auto cell_size = allocator.cell_size();+ auto end = first_block_of_allocator;+ while (end < m_evacuated_blocks.size() && &m_evacuated_blocks[end]->cell_allocator() == &allocator)+ ++end;+Vector<Cell*> cells_to_move;- allocator.for_each_block([&](HeapBlock& block) {- if (!block_descriptor_for(&block).evacuation)- return IterationDecision::Continue;- block.for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {- if (!allocator.descriptor().is_movable()) {- count_pinned(cell, cell_size, CompactionStats::NonMovableAllocator);- return;- }- switch (FFI::rust_gc_evacuation_pin_reason(m_evacuation, cell)) {- case FFI::PinReason::Root:- count_pinned(cell, cell_size, CompactionStats::ByValueRoot);- return;- case FFI::PinReason::Edge:- count_pinned(cell, cell_size, CompactionStats::ByValueEdge);- return;- case FFI::PinReason::Unpinned:- cells_to_move.append(cell);- return;- }- VERIFY_NOT_REACHED();- });- return IterationDecision::Continue;- });+ for (size_t i = exchange(first_block_of_allocator, end); i < end; ++i) {+ auto& block = *m_evacuated_blocks[i];+ blocks_being_evacuated.append(block);+ auto& descriptor = block_descriptor_for(&block);+ if (count_by_type || !allocator.descriptor().is_movable()) {+ block.for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {+ if (!allocator.descriptor().is_movable())+ count_pinned(cell, cell_size, CompactionStats::NonMovableAllocator);+ else if (auto reason = FFI::rust_gc_evacuation_pin_reason(m_evacuation, cell); reason != FFI::PinReason::Unpinned)+ stats.pinned_by_type.ensure(class_name_of(*cell))[reason == FFI::PinReason::Root ? CompactionStats::ByValueRoot : CompactionStats::ByValueEdge].add(cell_size);+ });+ }+ 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);+ for (size_t j = 0; j < count; ++j)+ cells_to_move.unchecked_append(static_cast<Cell*>(cells[j]));+ auto& by_edge = stats.pinned[CompactionStats::ByValueEdge];+ by_edge.cells += pinned.by_edge;+ by_edge.bytes += pinned.by_edge * cell_size;+ auto& by_root = stats.pinned[CompactionStats::ByValueRoot];+ by_root.cells += pinned.by_root;+ by_root.bytes += pinned.by_root * cell_size;+ if (pinned.by_edge + pinned.by_root > 0)+ blocks_kept_by_pins.append(&block);+ // NB: Nothing allocates during a collection (see allocate_cell()), and the sweep freed every cell that+ // marking did not reach, so every cell left in the block is marked, and either moves or is pinned.+ // A cell allocated after marking would hold slots that marking never recorded.+ if (auto live_cells = block.live_cell_count(); live_cells.has_value())+ VERIFY(live_cells.value() == count + pinned.by_edge + pinned.by_root);+ }+ clear_marks(descriptor);+ }if (cells_to_move.is_empty())continue;@@ -1280,12 +1476,14 @@ void Heap::evacuate()moves.unchecked_append({ .from = cell, .to = allocate_destination_for_moved_cell(allocator) });stats.moved.add(cell_size);}- FFI::rust_gc_evacuation_move_cells(m_evacuation, moves.data(), moves.size(), cell_size);+ FFI::rust_gc_evacuation_forward_cells(m_evacuation, moves.data(), moves.size(), cell_size);all_moves.append({ &allocator, move(moves) });}auto fix_up_start_ns = MonotonicTime::now().nanoseconds();stats.copy_us = (fix_up_start_ns - copy_start_ns) / 1000;+ // NB: The slots are rewritten where they are, before any cell is copied, so a cell that moves takes its rewritten+ // slots along.if (!all_moves.is_empty()) {stats.rewritten_slots = FFI::rust_gc_evacuation_fix_up_slots(m_evacuation);auto forwarding_address = [this](void* cell) {@@ -1296,40 +1494,76 @@ void Heap::evacuate()for (auto& weak_block : m_full_weak_blocks)weak_block.update_moved_cells(forwarding_address);}+ auto copy_start_again_ns = MonotonicTime::now().nanoseconds();+ stats.fix_up_us = (copy_start_again_ns - fix_up_start_ns) / 1000;++ for (auto& [allocator, moves] : all_moves)+ FFI::rust_gc_evacuation_move_cells(m_evacuation, moves.data(), moves.size(), allocator->cell_size());auto release_start_ns = MonotonicTime::now().nanoseconds();- stats.fix_up_us = (release_start_ns - fix_up_start_ns) / 1000;+ stats.copy_us += (release_start_ns - copy_start_again_ns) / 1000;for (auto& [allocator, moves] : all_moves) {for (auto& cell_move : moves) {auto* cell = static_cast<Cell*>(cell_move.from);HeapBlock::from_cell(cell)->release_moved_cell(cell);}+ }- // Sorts the blocks of the allocator into full and usable ones again, and lets go of the empty ones.- Vector<HeapBlock*> blocks;- allocator->for_each_block([&](HeapBlock& block) {- blocks.append(&block);- return IterationDecision::Continue;+ // NB: What is left in these blocks is what pins kept there, and evacuating them again would not free them, see+ // rust_gc_compaction_select().+ static_assert(cell_bitmap_words == FFI::MARK_BITMAP_WORDS);+ for (auto* block : blocks_kept_by_pins) {+ Array<u64, cell_bitmap_words> kept {};+ auto& descriptor = block_descriptor_for(block);+ block->for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {+ auto index = mark_bit_index(descriptor, cell);+ kept[index / 64] |= static_cast<u64>(1) << (index % 64);});- for (auto* block : blocks) {- bool has_live_cells = false;- block->for_each_cell_in_state<Cell::State::Live>([&](Cell*) { has_live_cells = true; });- if (!has_live_cells) {- allocator->block_did_become_empty({}, *block, DeferDecommit::No);- ++stats.freed_blocks;- } else if (block->is_full()) {- allocator->m_full_blocks.append(*block);- } else {- allocator->m_usable_blocks.append(*block);- }+ m_cells_kept_by_pins.set(block, kept);+ descriptor.kept_by_pins = true;+ }++ // Puts the evacuated blocks back with their allocators, and lets go of the ones that are empty now.+ for (auto* evacuated_block : m_evacuated_blocks) {+ auto& block = *evacuated_block;+ auto& allocator = block.cell_allocator();+ if (!block.has_live_cells()) {+ allocator.block_did_become_empty({}, block, DeferDecommit::Yes);+ ++stats.freed_blocks;+ } else if (block.is_full()) {+ allocator.m_full_blocks.append(block);+ } else {+ allocator.m_usable_blocks.append(block);}}+ VERIFY(blocks_being_evacuated.is_empty());+ stats.release_us = (MonotonicTime::now().nanoseconds() - release_start_ns) / 1000;+}++void Heap::forget_cells_kept_by_pins(HeapBlock& block)+{+ auto& descriptor = block_descriptor_for(&block);+ if (!descriptor.kept_by_pins)+ return;+ descriptor.kept_by_pins = false;+ m_cells_kept_by_pins.remove(&block);+}++void Heap::cell_in_block_kept_by_pins_died(HeapBlock& block, Cell const* cell)+{+ auto& descriptor = block_descriptor_for(&block);+ auto index = mark_bit_index(descriptor, cell);+ auto kept = m_cells_kept_by_pins.get(&block);+ VERIFY(kept.has_value());+ if (kept.value()[index / 64] & (static_cast<u64>(1) << (index % 64)))+ forget_cells_kept_by_pins(block);}void Heap::end_evacuation(){FFI::rust_gc_evacuation_destroy(m_evacuation);m_evacuation = nullptr;+ m_evacuated_blocks.clear();}void Heap::schedule_collection_that_moves_cells()@@ -1341,13 +1575,28 @@ void Heap::schedule_collection_that_moves_cells()return;if (!m_moving_collection_timer) {m_moving_collection_timer = Core::Timer::create_single_shot(AK::Duration::zero(), [this] {- if (is_gc_deferred() || Core::ThreadEventQueue::current().is_processing_nested())+ if (!m_moves_everything && !m_should_compact)+ return;+ // NB: Only an outermost turn of the event loop that is not deferring GC can collect without scanning the+ // stack, so try again later rather than spin while a nested loop runs.+ if (is_gc_deferred() || Core::ThreadEventQueue::current().is_processing_nested()) {+ m_moving_collection_timer->start(AK::Duration::from_milliseconds(GC_IDLE_GC_INTERVAL_MS));+ return;+ }+ // NB: Whatever the event loop has queued goes first, for one turn at most, so that a queue that is never+ // empty does not hold off the collection for good, as in idle_gc_on_timer().+ if (!m_moving_collection_postponed && Core::ThreadEventQueue::current().has_pending_events()) {+ m_moving_collection_postponed = true;+ m_moving_collection_timer->start(AK::Duration::zero());return;- collect_garbage_from_timer();+ }+ m_moving_collection_postponed = false;+ collect_garbage_from_timer(CollectionTrigger::Compaction);});}- if (!m_moving_collection_timer->is_active())- m_moving_collection_timer->start();+ // NB: This replaces a retry that waits for a nested event loop or a GC deferral to end.+ m_moving_collection_postponed = false;+ m_moving_collection_timer->restart(AK::Duration::zero());}void Heap::update_allocation_rate()@@ -1958,22 +2207,29 @@ void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measure{ScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.sweep_block_iteration_us };for_each_block([&](auto& block) {- bool block_has_live_cells = false;+ u32 block_live_cells = 0;bool block_was_full = block.is_full();auto& descriptor = block_descriptor_for(&block);block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {if (!is_marked(descriptor, cell)) {dbgln_if(HEAP_DEBUG, " ~ {}", cell);+ if (descriptor.kept_by_pins)+ cell_in_block_kept_by_pins_died(block, cell);block.deallocate(cell);++collected_cells;collected_cell_bytes += block.cell_size();} else {- block_has_live_cells = true;+ ++block_live_cells;++live_cells;live_cell_bytes += block.cell_size();}});- clear_marks(descriptor);+ block.set_live_cell_count(block_live_cells);+ bool block_has_live_cells = block_live_cells > 0;+ // NB: An evacuated block keeps its marks until its cells have moved, which tells the cells that marking+ // knows about from the ones allocated since.+ if (!descriptor.evacuation)+ clear_marks(descriptor);if (!block_has_live_cells)empty_blocks.append(&block);else if (block_was_full != block.is_full())@@ -1984,9 +2240,15 @@ void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measure{ScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.sweep_block_reclassify_us };+ // NB: A collection that moves cells is an ordinary one that sweeps synchronously, and gives its empty blocks+ // back to the system like the incremental sweep does. Only the collection of a heap that goes away keeps+ // them for whoever comes next.+ auto defer_decommit = m_evacuation ? DeferDecommit::Yes : DeferDecommit::No;for (auto* block : empty_blocks) {dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", block, block->cell_size());- block->cell_allocator().block_did_become_empty({}, *block, DeferDecommit::No);+ if (block_descriptor_for(block).evacuation)+ clear_marks(block_descriptor_for(block));+ block->cell_allocator().block_did_become_empty({}, *block, defer_decommit);}for (auto* block : full_blocks_that_became_usable) {@@ -2055,6 +2317,8 @@ void Heap::sweep_block(HeapBlock& block)block.for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {if (!is_marked(descriptor, cell)) {dbgln_if(HEAP_DEBUG, " ~ {}", cell);+ if (descriptor.kept_by_pins)+ cell_in_block_kept_by_pins_died(block, cell);block.deallocate(cell);++collected_cells;} else {@@ -2063,6 +2327,7 @@ void Heap::sweep_block(HeapBlock& block)}});block.set_being_swept(false);+ block.set_live_cell_count(static_cast<u32>(live_cells));// NB: This also clears the marks of the cells that were allocated in the block while it was swept.clear_marks(descriptor);@@ -2167,6 +2432,7 @@ void Heap::finish_incremental_sweep()if (m_abandoned_object_graph_state == AbandonedObjectGraphState::WaitingToReleaseMemory)schedule_release_of_abandoned_object_graph_memory();schedule_release_of_allocator_memory();+ schedule_compaction_if_worthwhile();}void Heap::finish_pending_incremental_sweep()@@ -2284,16 +2550,36 @@ void Heap::idle_gc_on_timer()if (m_incremental_sweep_active || is_gc_deferred())return;+ bool may_reduce_memory = libgc_compact() && !m_moves_everything;switch (m_idle_collection_policy.evaluate(m_total_allocated_bytes, m_allocated_bytes_since_last_gc, m_gc_bytes_threshold)) {case IdleCollectionPolicy::Decision::KeepWaiting:+ // NB: A heap that went quiet with little garbage still has the holes that its last sweep left, which+ // compacting collections close.+ if (may_reduce_memory && !m_compacted_since_activity && m_idle_collection_policy.last_tick_was_quiet()+ && !Core::ThreadEventQueue::current().has_pending_events()) {+ m_reducing_memory = true;+ schedule_compaction_if_worthwhile();+ }return;case IdleCollectionPolicy::Decision::Park:// Nothing left to collect; the next allocation will re-arm the timer.m_idle_gc_timer->stop();return;case IdleCollectionPolicy::Decision::Collect:+ // NB: Whatever the event loop has queued, like input or a task, goes first, and the next tick looks again.+ // What has not reached the queue yet, like a message still in its socket, waits for the collection. It+ // waits for one tick at most, so that a queue that is never empty does not hold off the collection and the+ // watchdog for good.+ if (!m_idle_collection_postponed && Core::ThreadEventQueue::current().has_pending_events()) {+ m_idle_collection_postponed = true;+ return;+ }+ // A heap that went quiet gives back what it can, compacting after this collection, see+ // schedule_compaction_if_worthwhile().+ m_reducing_memory = may_reduce_memory && m_idle_collection_policy.last_tick_was_quiet();+ m_compacted_since_activity = false;m_allocated_bytes_since_last_gc = 0;- collect_garbage_from_timer();+ collect_garbage_from_timer(CollectionTrigger::IdlePolicy);m_idle_gc_timer->stop();return;}@@ -2343,11 +2629,12 @@ void Heap::on_abandoned_object_graph_timer()}m_allocated_bytes_since_last_gc = 0;- collect_garbage_from_timer();+ collect_garbage_from_timer(CollectionTrigger::AbandonedObjectGraph);}-void Heap::collect_garbage_from_timer()+void Heap::collect_garbage_from_timer(CollectionTrigger trigger){+ TemporaryChange trigger_change { g_collection_trigger, trigger };// A timer fires from the event loop. In its outermost turn the only frames on the stack are the event loop's and the// embedder's, so if the embedder vouches for its own, there is no root to find there. Words that only look like a// cell pointer are still there, and some never change, so scanning them could keep a cell alive for good. A nested@@ -2416,6 +2703,7 @@ void Heap::undefer_gc(){TemporaryChange change { m_is_returning_memory_to_system, m_should_return_memory_when_deferral_ends };+ TemporaryChange trigger { g_collection_trigger, CollectionTrigger::DeferralEnded };collect_garbage();}m_should_gc_when_deferral_ends = false;diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.hindex 8d0c7aa7f42..bc3d24ac53e 100644--- a/Libraries/LibGC/Heap.h+++ b/Libraries/LibGC/Heap.h@@ -6,6 +6,7 @@#pragma once+#include <AK/Array.h>#include <AK/Badge.h>#include <AK/Function.h>#include <AK/HashTable.h>@@ -36,6 +37,16 @@namespace GC {+// What started a collection, for its report.+enum class CollectionTrigger : u8 {+ Explicit,+ Allocation,+ IdlePolicy,+ AbandonedObjectGraph,+ Compaction,+ DeferralEnded,+};+namespace FFI {struct EvacuationSet;@@ -321,6 +332,7 @@ private:void end_evacuation();Cell* allocate_destination_for_moved_cell(CellAllocator&);void schedule_collection_that_moves_cells();+ void schedule_compaction_if_worthwhile();static void mark_live_cells_across(ReadonlySpan<Heap* const>, HashMap<Cell*, HeapRoot>& roots);void clear_weak_pointers_to_dead_cells(bool report);void run_post_mark_phases(bool report);@@ -414,14 +426,32 @@ private:RefPtr<Core::Timer> m_idle_gc_timer;RefPtr<Core::Timer> m_moving_collection_timer;+ // Whether the moving collection timer already let queued events go, see schedule_collection_that_moves_cells().+ bool m_moving_collection_postponed { false };bool m_outermost_event_loop_turn_holds_no_cells { false };// The blocks the collection in progress evacuates and the slots it found, while it may move cells.FFI::EvacuationSet* m_evacuation { nullptr };+ // The blocks it evacuates, those of an allocator one after another.+ Vector<HeapBlock*> m_evacuated_blocks;+ // The cells that pins kept in the blocks that a collection could not empty, one bit per cell, see+ // FFI::BlockDescriptor::kept_by_pins. A sweep that frees one of them lets compaction take the block again.+ static constexpr size_t cell_bitmap_words = 11;+ HashMap<HeapBlock*, Array<u64, cell_bitmap_words>> m_cells_kept_by_pins;+ void forget_cells_kept_by_pins(HeapBlock&);+ void cell_in_block_kept_by_pins_died(HeapBlock&, Cell const*);// The identity hashes of the cells that moved since they were hashed, see identity_hash().FFI::IdentityHashes* m_identity_hashes { nullptr };bool m_moves_everything { moves_everything() };- void collect_garbage_from_timer();+ // Whether the heap went quiet and compacts until there is little left to recover, whether it did so since it was+ // last busy, and whether the next collection that does not scan the stack compacts, see+ // schedule_compaction_if_worthwhile().+ bool m_reducing_memory { false };+ bool m_compacted_since_activity { false };+ bool m_should_compact { false };+ // Whether the idle timer already let queued events go before a collection it decided on, see idle_gc_on_timer().+ bool m_idle_collection_postponed { false };+ void collect_garbage_from_timer(CollectionTrigger);enum class AbandonedObjectGraphState : u8 {None,WaitingToCollect,diff --git a/Libraries/LibGC/HeapBlock.cpp b/Libraries/LibGC/HeapBlock.cppindex aa843ac7f2c..7817d224deb 100644--- a/Libraries/LibGC/HeapBlock.cpp+++ b/Libraries/LibGC/HeapBlock.cpp@@ -33,6 +33,7 @@ void publish_block_descriptor(HeapBlock& block, CellAllocator& allocator)descriptor.cell_index_magic = static_cast<u32>(((static_cast<u64>(1) << 32) + descriptor.cell_size - 1) / descriptor.cell_size);descriptor.traced_on_owner_thread_only = allocator.descriptor().trace_thread() == TraceThread::OwnerThreadOnly;descriptor.movable = allocator.descriptor().is_movable();+ descriptor.kept_by_pins = false;descriptor.evacuation = nullptr;clear_marks(descriptor);// NB: Markers of other heaps read the heap of any block their cells point into, to leave it alone if it is not theirs.@@ -90,6 +91,7 @@ HeapBlock::FreeCells HeapBlock::take_free_cells()VERIFY(free_cells.lazy_end <= bit_cast<FlatPtr>(this) + BLOCK_SIZE);m_freelist = 0;m_next_lazy_freelist_index = cell_count();+ m_live_cell_count = unknown_live_cell_count;return free_cells;}@@ -136,6 +138,8 @@ void HeapBlock::free_slot(Cell* cell)freelist_entry->set_state(Cell::State::Dead);freelist_entry->next = m_freelist;m_freelist = bit_cast<FlatPtr>(freelist_entry);+ if (m_live_cell_count != unknown_live_cell_count)+ --m_live_cell_count;#ifdef HAS_ADDRESS_SANITIZERauto dword_after_freelist = round_up_to_power_of_two(reinterpret_cast<uintptr_t>(freelist_entry) + sizeof(FreelistEntry), 8);diff --git a/Libraries/LibGC/HeapBlock.h b/Libraries/LibGC/HeapBlock.hindex 6429acc419c..23f24c4f02f 100644--- a/Libraries/LibGC/HeapBlock.h+++ b/Libraries/LibGC/HeapBlock.h@@ -7,6 +7,8 @@#pragma once#include <AK/IntrusiveList.h>+#include <AK/NumericLimits.h>+#include <AK/Optional.h>#include <AK/Platform.h>#include <AK/StringView.h>#include <AK/Types.h>@@ -48,6 +50,8 @@ public:if (allocated_cell) {ASAN_UNPOISON_MEMORY_REGION(allocated_cell, m_cell_size);+ if (m_live_cell_count != unknown_live_cell_count)+ ++m_live_cell_count;}return allocated_cell;}@@ -109,6 +113,19 @@ public:bool is_being_swept() const { return m_is_being_swept; }void set_being_swept(bool being_swept) { m_is_being_swept = being_swept; }+ // How many cells of the block are allocated, as the sweep counted them and the block's own allocations and frees+ // kept up since. Once an allocator takes the block's free cells, it allocates them without the block's knowledge,+ // and the count is unknown until the next sweep. Compaction picks blocks by this count, and nothing depends on it+ // being right.+ static constexpr u32 unknown_live_cell_count = NumericLimits<u32>::max();+ Optional<u32> live_cell_count() const+ {+ if (m_live_cell_count == unknown_live_cell_count)+ return {};+ return m_live_cell_count;+ }+ void set_live_cell_count(u32 count) { m_live_cell_count = count; }+template<typename Callback>void for_each_cell(Callback callback){@@ -117,6 +134,16 @@ public:callback(cell(i));}+ bool has_live_cells()+ {+ auto end = has_lazy_freelist() ? m_next_lazy_freelist_index : cell_count();+ for (size_t i = 0; i < end; ++i) {+ if (cell(i)->state() == Cell::State::Live)+ return true;+ }+ return false;+ }+template<Cell::State state, typename Callback>void for_each_cell_in_state(Callback callback){@@ -177,6 +204,7 @@ private:u32 m_next_lazy_freelist_index { 0 };// NB: Computed once, since dividing by the cell size is slow.u32 m_cell_count { 0 };+ u32 m_live_cell_count { 0 };bool m_is_being_swept { false };// See follow_freelist_link().diff --git a/Libraries/LibGC/IdleCollectionPolicy.h b/Libraries/LibGC/IdleCollectionPolicy.hindex 8417e9b6d21..6d6aceeca23 100644--- a/Libraries/LibGC/IdleCollectionPolicy.h+++ b/Libraries/LibGC/IdleCollectionPolicy.h@@ -17,8 +17,11 @@ namespace GC {// small allocation trickle going even on an idle page. So instead of waiting for zero allocation, we watch for the// mutator transitioning out of an active phase: a tick whose allocation rate has dropped below 1/low_rate_divisor of// the peak rate seen so far this episode. The rate-drop trigger is gated on enough uncollected garbage having piled up-// to be worth marking the whole live heap. The watchdog bounds how long garbage can sit when the rate-drop trigger-// never fires, e.g. on a heap that allocates too steadily to show a drop or too slowly to clear the gate.+// to be worth marking the whole live heap. A tick that allocates next to nothing is a quiet one, which collects once+// a few MiB of garbage are there, however large the heap and its threshold: nobody waits for a quiet heap, and what+// the garbage holds goes back to the system long before the threshold would have come. The watchdog bounds how long+// garbage can sit when neither trigger fires, e.g. on a heap that allocates too steadily to show a drop or too+// slowly to clear the gates.class IdleCollectionPolicy {public:enum class Decision : u8 {@@ -33,6 +36,7 @@ public:m_total_allocated_at_last_check = total_allocated_bytes;m_peak_delta = 0;m_tick_count = 0;+ m_last_tick_was_quiet = false;}// Evaluates one idle-timer tick. `total_allocated_bytes` is the monotonic allocation counter, `garbage_bytes` is@@ -47,18 +51,26 @@ public:m_peak_delta = max(m_peak_delta, delta);bool rate_dropped = delta * low_rate_divisor < m_peak_delta;+ m_last_tick_was_quiet = delta <= quiet_tick_bytes;bool watchdog_elapsed = ++m_tick_count >= watchdog_ticks;bool enough_garbage = garbage_bytes >= gc_threshold / min_garbage_divisor;+ bool enough_garbage_for_a_quiet_heap = garbage_bytes >= quiet_min_garbage_bytes;- if ((rate_dropped && enough_garbage) || watchdog_elapsed)+ if ((rate_dropped && enough_garbage) || (m_last_tick_was_quiet && enough_garbage_for_a_quiet_heap) || watchdog_elapsed)return Decision::Collect;return Decision::KeepWaiting;}+ // Whether the last tick that was evaluated allocated next to nothing.+ bool last_tick_was_quiet() const { return m_last_tick_was_quiet; }+// A tick counts as a rate drop when its allocation is below 1/low_rate_divisor of the episode's peak.static constexpr u64 low_rate_divisor = 4;// The rate-drop trigger only fires once garbage reaches gc_threshold / min_garbage_divisor.static constexpr size_t min_garbage_divisor = 16;+ // A tick that allocates at most this much is a quiet one, and a quiet tick collects once this much is garbage.+ static constexpr u64 quiet_tick_bytes = 1 * MiB;+ static constexpr size_t quiet_min_garbage_bytes = 2 * MiB;// The watchdog forces a collection after this many ticks regardless of the rate or the gate.static constexpr u32 watchdog_ticks = 15;@@ -66,6 +78,7 @@ private:u64 m_total_allocated_at_last_check { 0 };u64 m_peak_delta { 0 };u32 m_tick_count { 0 };+ bool m_last_tick_was_quiet { false };};}diff --git a/Libraries/LibGC/Rust/src/block.rs b/Libraries/LibGC/Rust/src/block.rsindex 10e64e6b27c..c3ca943272b 100644--- a/Libraries/LibGC/Rust/src/block.rs+++ b/Libraries/LibGC/Rust/src/block.rs@@ -46,8 +46,11 @@ pub struct BlockDescriptor {pub traced_on_owner_thread_only: bool,/// Whether a collection may move the block's cells to other blocks of their allocator.pub movable: bool,+ /// Whether a collection evacuated the block and could not empty it because something pinned some of its cells.+ /// Compaction leaves the block alone until one of the cells it kept dies.+ pub kept_by_pins: bool,/// Rounds the descriptor up to 128 bytes, two whole cache lines in the table.- pub reserved: [u8; 6],+ pub reserved: [u8; 5],/// What a collection that evacuates the block knows about its cells, and null in every other collection. Marking/// reads it for every cell it visits, to pin the cells of evacuated blocks that something visits by value.pub evacuation: *mut Evacuation,diff --git a/Libraries/LibGC/Rust/src/compaction.rs b/Libraries/LibGC/Rust/src/compaction.rsnew file mode 100644index 00000000000..834c3428942--- /dev/null+++ b/Libraries/LibGC/Rust/src/compaction.rs@@ -0,0 +1,196 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Compaction policy: which blocks a collection that may move cells evacuates.+//!+//! Cells only move within their allocator, so each allocator is looked at on its own. Its blocks are taken emptiest+//! first, as long as the live cells of the blocks taken still fit into the free slots of the blocks left. Then every+//! block that fits is a block that the collection frees, unless something pins one of its cells. Of the blocks that fit+//! in all allocators, the ones that move the fewest bytes go first, since each frees one block, until moving the next+//! one would go over the budget. A block that an earlier collection could not empty because something pinned some of+//! its cells is not taken again until one of the cells it kept dies, since evacuating it again would only move the+//! cells that moved into it since.++use crate::block::BLOCK_SIZE;+use crate::rust_panic::abort_on_panic;++/// A block of a movable allocator, as the allocator knows it before the collection marks.+#[repr(C)]+#[derive(Clone, Copy, Debug)]+pub struct CompactionCandidate {+ pub block: *mut core::ffi::c_void,+ /// Which allocator the block belongs to. The blocks of an allocator come one after another.+ pub allocator: u32,+ /// The cells of the block that are allocated: at least the ones that are alive. A block whose count the allocator+ /// does not know counts as full.+ pub live_cells: u32,+ pub cell_count: u32,+ pub cell_size: u32,+ /// Whether an earlier collection could not empty the block because of pinned cells, see+ /// BlockDescriptor::kept_by_pins. Its free slots still take the cells of other blocks.+ pub kept_by_pins: bool,+ /// Set for the blocks the collection evacuates.+ pub selected: bool,+}++/// What selection found.+#[repr(C)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct CompactionSelection {+ /// How many bytes of blocks compaction could free in these allocators if it moved every cell it had to, which is+ /// the blocks each allocator has beyond the fewest that its live cells fit in.+ pub recoverable_bytes: usize,+ /// The blocks whose live cells fit into the free slots of their allocator's other blocks, which compaction frees+ /// unless something pins their cells. The ones over the budget are left for another collection.+ pub fitting_blocks: usize,+ pub selected_blocks: usize,+ /// The bytes of the live cells of the selected blocks, which move unless pinned.+ pub bytes_to_move: usize,+}++/// Selects the blocks to evacuate, moving at most `budget_bytes` of cells, and says how much could be recovered.+fn select(candidates: &mut [CompactionCandidate], budget_bytes: usize) -> CompactionSelection {+ let mut selection = CompactionSelection::default();+ // The blocks that fit, of all allocators, by index into the candidates.+ let mut fitting = Vec::new();+ let mut start = 0;+ while start < candidates.len() {+ let allocator = candidates[start].allocator;+ let end = start+ + candidates[start..]+ .iter()+ .take_while(|candidate| candidate.allocator == allocator)+ .count();+ let blocks = &candidates[start..end];+ debug_assert!(blocks.iter().all(|block| block.cell_count == blocks[0].cell_count));+ let cell_count = blocks[0].cell_count as usize;++ let live_cells: usize = blocks.iter().map(|block| block.live_cells as usize).sum();+ let fewest_blocks = live_cells.div_ceil(cell_count);+ selection.recoverable_bytes += (blocks.len() - fewest_blocks) * BLOCK_SIZE;++ let mut by_live_cells: Vec<usize> = (start..end).collect();+ by_live_cells.sort_by_key(|&index| candidates[index].live_cells);+ let mut free_cells_elsewhere = blocks.len() * cell_count - live_cells;+ let mut cells_to_move = 0;+ for index in by_live_cells {+ let block = &candidates[index];+ let live = block.live_cells as usize;+ // NB: A full block frees nothing that its cells would not take elsewhere.+ if live >= cell_count {+ break;+ }+ if block.kept_by_pins {+ continue;+ }+ let free = cell_count - live;+ if cells_to_move + live > free_cells_elsewhere - free {+ break;+ }+ cells_to_move += live;+ free_cells_elsewhere -= free;+ fitting.push(index);+ }+ start = end;+ }++ let bytes_of = |candidate: &CompactionCandidate| candidate.live_cells as usize * candidate.cell_size as usize;+ selection.fitting_blocks = fitting.len();+ if budget_bytes == 0 {+ return selection;+ }+ // NB: A stable sort keeps the blocks of an allocator emptiest first, so the ones within budget fit as well.+ fitting.sort_by_key(|&index| bytes_of(&candidates[index]));+ for index in fitting {+ let bytes = bytes_of(&candidates[index]);+ if selection.bytes_to_move + bytes > budget_bytes {+ break;+ }+ selection.bytes_to_move += bytes;+ selection.selected_blocks += 1;+ candidates[index].selected = true;+ }+ selection+}++/// Selects the blocks of `candidates` that a collection evacuates, as the module comment says, moving at most+/// `budget_bytes` of cells. A budget of 0 only tells how much could be recovered.+///+/// # Safety+///+/// `candidates` must point to `count` candidates, the blocks of each allocator one after another.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_compaction_select(+ candidates: *mut CompactionCandidate,+ count: usize,+ budget_bytes: usize,+) -> CompactionSelection {+ abort_on_panic(|| {+ if count == 0 {+ return CompactionSelection::default();+ }+ // SAFETY: The caller passes count candidates.+ select(unsafe { ak::slice_from_raw_parts_mut(candidates, count) }, budget_bytes)+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn candidate(allocator: u32, live_cells: u32) -> CompactionCandidate {+ CompactionCandidate {+ block: core::ptr::null_mut(),+ allocator,+ live_cells,+ cell_count: 100,+ cell_size: 64,+ kept_by_pins: false,+ selected: false,+ }+ }++ #[test]+ fn selects_the_emptiest_blocks_whose_cells_fit_elsewhere() {+ let mut candidates = [candidate(0, 10), candidate(0, 50), candidate(0, 20), candidate(0, 90)];+ let selection = select(&mut candidates, usize::MAX);+ // 170 live cells fit in 2 blocks of 4. The blocks with 10 and 20 fit into the free slots of the others.+ assert_eq!(selection.recoverable_bytes, 2 * BLOCK_SIZE);+ assert_eq!(selection.fitting_blocks, 2);+ assert_eq!(selection.selected_blocks, 2);+ let selected: Vec<bool> = candidates.iter().map(|candidate| candidate.selected).collect();+ assert_eq!(selected, [true, false, true, false]);+ }++ #[test]+ fn selects_nothing_from_full_allocators() {+ let mut candidates = [candidate(0, 100), candidate(0, 95), candidate(1, 100)];+ let selection = select(&mut candidates, usize::MAX);+ assert_eq!(selection.recoverable_bytes, 0);+ assert_eq!(selection.selected_blocks, 0);+ }++ #[test]+ fn skips_blocks_kept_by_pins_but_fills_them() {+ let mut candidates = [candidate(0, 10), candidate(0, 20), candidate(0, 50)];+ candidates[0].kept_by_pins = true;+ let selection = select(&mut candidates, usize::MAX);+ assert_eq!(selection.fitting_blocks, 2);+ let selected: Vec<bool> = candidates.iter().map(|candidate| candidate.selected).collect();+ assert_eq!(selected, [false, true, true]);+ }++ #[test]+ fn keeps_to_the_budget_with_the_cheapest_blocks_first() {+ let mut candidates = [candidate(0, 30), candidate(0, 5), candidate(1, 10), candidate(1, 10)];+ let selection = select(&mut candidates, 15 * 64);+ assert_eq!(selection.fitting_blocks, 2);+ assert_eq!(selection.selected_blocks, 2);+ assert_eq!(selection.bytes_to_move, 15 * 64);+ let selected: Vec<bool> = candidates.iter().map(|candidate| candidate.selected).collect();+ assert_eq!(selected, [false, true, true, false]);+ }+}diff --git a/Libraries/LibGC/Rust/src/evacuation.rs b/Libraries/LibGC/Rust/src/evacuation.rsindex e1f72d57df4..891f245c1ed 100644--- a/Libraries/LibGC/Rust/src/evacuation.rs+++ b/Libraries/LibGC/Rust/src/evacuation.rs@@ -10,9 +10,9 @@//! An edge that marking visits through its slot can be updated once its target moves, while an edge visited by value//! pins its target. Marking pins the cells of evacuated blocks that something visits by value, or that are roots, and//! records the slots that point into evacuated blocks. After marking, a cell of an evacuated block moves if its-//! allocator is movable and nothing pinned it: it is copied bytewise to its new slot, and its old slot is freed without-//! being destroyed. Then every recorded slot that points at a moved cell is rewritten, after the slot itself is found-//! in the copy of its cell if that moved too.+//! allocator is movable and nothing pinned it. Each cell that moves gets a free slot of another block first, then every+//! recorded slot that points at one is rewritten where it is, and only then is each cell copied bytewise to its new+//! slot, with its slots rewritten already, and its old slot freed without being destroyed.//!//! The collector finds slots only in cells, in the heap region: a slot elsewhere, like in malloc memory that a cell//! owns, could be freed or moved by the finalizers and destructors that run between marking and moving, so the visit@@ -73,6 +73,17 @@ impl Evacuation {}}+ /// Whether the cell at `address` of the block this evacuates is pinned, for whatever reason.+ #[inline(always)]+ pub fn is_pinned(&self, descriptor: &BlockDescriptor, address: usize) -> bool {+ let index = descriptor.cell_index(address).0;+ let bit = 1u64 << (index % 64);+ (self.pinned_by_root[index / 64].load(Ordering::Relaxed)+ | self.pinned_by_edge[index / 64].load(Ordering::Relaxed))+ & bit+ != 0+ }+pub fn pin_reason(&self, index: CellIndex) -> PinReason {let bit = 1u64 << (index.0 % 64);if self.pinned_by_root[index.0 / 64].load(Ordering::Relaxed) & bit != 0 {@@ -189,28 +200,17 @@ impl EvacuationSet {.map(|to| self.decompress(to))}- /// Where the byte at `address` is now: in the copy of its cell if that moved.- #[inline(always)]- fn relocate(&self, address: usize) -> usize {- let Some((descriptor, evacuation)) = self.evacuation_of(address) else {- return address;- };- let cell = descriptor.cell_containing(address, self.layout.block_cells_offset as usize);- match evacuation.forwarding(descriptor.cell_index(cell)) {- Some(to) => self.decompress(to) + (address - cell),- None => address,- }- }-- /// Rewrites a slot that marking recorded to point where its target moved, and returns whether it did.+ /// Rewrites a slot that marking recorded to point where its target moves, and returns whether it did. Cells are only+ /// copied once their slots are rewritten, so the slot is still where marking found it, and the copy of a cell that+ /// moves gets the rewritten slots.////// # Safety///- /// The slot must be in a live cell, and hold what its kind says.+ /// The slot must be in a live cell that has not moved yet, and hold what its kind says.unsafe fn fix_up(&self, slot: RecordedSlot) -> bool {let base = self.layout.heap_region_base;- let address = self.relocate(slot.address());- // SAFETY: The caller passes a slot of a live cell, which is now at `address`.+ let address = slot.address();+ // SAFETY: The caller passes a slot of a live cell.unsafe {match slot.kind() {SlotKind::Member => {@@ -249,10 +249,10 @@ impl EvacuationSet {slot.write(to + (pointer - cell));}SlotKind::SelfPointer => {- let Some((descriptor, _)) = self.evacuation_of(slot.address()) else {+ let Some((descriptor, _)) = self.evacuation_of(address) else {return false;};- let holder = descriptor.cell_containing(slot.address(), self.layout.block_cells_offset as usize);+ let holder = descriptor.cell_containing(address, self.layout.block_cells_offset as usize);let Some(to) = self.forwarding_address(holder) else {return false;};@@ -322,6 +322,65 @@ pub unsafe extern "C" fn rust_gc_evacuation_pin_reason(set: *const EvacuationSetevacuation.pin_reason(descriptor.cell_index(cell.addr()))}+/// How many marked cells of an evacuated block were pinned, by reason.+#[repr(C)]+#[derive(Clone, Copy, Debug, Default)]+pub struct PinnedCells {+ pub by_edge: usize,+ pub by_root: usize,+}++/// Finds the cells of an evacuated block that move once marking is done: the marked ones that nothing pinned. Writes+/// their addresses to `cells`, returns how many there are, and adds the marked cells that are pinned to `pinned`. Only+/// the mark bits are read, so the dead cells and the free slots of the block are never touched.+///+/// # Safety+///+/// `set` must be live, `block` one of its blocks whose cells start `block_cells_offset` bytes into it and whose marks+/// are the ones marking left, and `cells` must have room for MAX_CELLS_PER_BLOCK addresses.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_evacuation_cells_to_move(+ set: *const EvacuationSet,+ block: *const c_void,+ cells: *mut *mut c_void,+ pinned: *mut PinnedCells,+) -> usize {+ abort_on_panic(|| {+ // SAFETY: The caller passes a live set, room for the cells, and a live count.+ let (set, cells, pinned) = unsafe {+ (+ &*set,+ ak::slice_from_raw_parts_mut(cells, MAX_CELLS_PER_BLOCK),+ &mut *pinned,+ )+ };+ let (descriptor, evacuation) = set.evacuation_of(block.addr()).expect("the block is evacuated");+ let cell_size = descriptor.cell_size as usize;+ let cells_offset = set.layout.block_cells_offset as usize;+ // NB: A cell's mark bit is its offset in the block divided by the cell size, see BlockDescriptor::cell_index().+ let first_bit = cells_offset / cell_size;+ let mut count = 0;+ for word_index in 0..MARK_BITMAP_WORDS {+ let mut bits = descriptor.mark_word(word_index).load(Ordering::Relaxed);+ while bits != 0 {+ let bit = word_index * 64 + bits.trailing_zeros() as usize;+ bits &= bits - 1;+ let cell = block.addr() + cells_offset + (bit - first_bit) * cell_size;+ debug_assert!(descriptor.cell_index(cell).0 == bit);+ match evacuation.pin_reason(CellIndex(bit)) {+ PinReason::Unpinned => {+ cells[count] = block.with_addr(cell).cast_mut();+ count += 1;+ }+ PinReason::Edge => pinned.by_edge += 1,+ PinReason::Root => pinned.by_root += 1,+ }+ }+ }+ count+ })+}+/// A cell to move, from its slot to a free slot of another block of its allocator.#[repr(C)]pub struct CellMove {@@ -329,14 +388,14 @@ pub struct CellMove {pub to: *mut c_void,}-/// Copies each cell to its new slot, and notes where it went. Both slots are `cell_size` bytes.+/// Notes where each cell moves to, before anything moves. The slots of both are `cell_size` bytes.////// # Safety///-/// `set` must be live, and the moves name live, unpinned cells of its blocks and free slots of the same allocators,-/// each once.+/// `set` must be live, and the moves name live, unpinned cells of its blocks and free slots of the same allocators+/// outside its blocks, each once.#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_gc_evacuation_move_cells(+pub unsafe extern "C" fn rust_gc_evacuation_forward_cells(set: *mut EvacuationSet,moves: *const CellMove,count: usize,@@ -344,14 +403,38 @@ pub unsafe extern "C" fn rust_gc_evacuation_move_cells() {abort_on_panic(|| {// SAFETY: The caller passes a live set, and count moves.- let (set, moves) = unsafe { (&mut *set, ak::slice_from_raw_parts(moves, count)) };- let mut identity_hashes = None;+ let (set, moves) = unsafe { (&*set, ak::slice_from_raw_parts(moves, count)) };for cell_move in moves {let (from, to) = (cell_move.from.addr(), cell_move.to.addr());let (descriptor, evacuation) = set.evacuation_of(from).expect("the cell is in an evacuated block");debug_assert!(descriptor.cell_size as usize == cell_size);+ debug_assert!(set.evacuation_of(to).is_none(), "no cell moves into an evacuated block");let index = descriptor.cell_index(from);debug_assert!(evacuation.forwarding(index).is_none());+ evacuation.forwarding[index.0].store((to >> COMPRESSED_POINTER_SHIFT) as u32, Ordering::Relaxed);+ }+ });+}++/// Copies each cell to the slot it moves to, once its slots and the slots that point at it are rewritten. Both slots+/// are `cell_size` bytes.+///+/// # Safety+///+/// As for rust_gc_evacuation_forward_cells(), with the same moves.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_evacuation_move_cells(+ set: *mut EvacuationSet,+ moves: *const CellMove,+ count: usize,+ cell_size: usize,+) {+ abort_on_panic(|| {+ // SAFETY: The caller passes a live set, and count moves.+ let (set, moves) = unsafe { (&mut *set, ak::slice_from_raw_parts(moves, count)) };+ let mut identity_hashes = None;+ for cell_move in moves {+ let (from, to) = (cell_move.from.addr(), cell_move.to.addr());// SAFETY: The caller passes a live cell and a free slot of the same size, which do not overlap.unsafe {core::ptr::copy_nonoverlapping(cell_move.from.cast::<u8>(), cell_move.to.cast::<u8>(), cell_size);@@ -365,16 +448,16 @@ pub unsafe extern "C" fn rust_gc_evacuation_move_cells());}}- evacuation.forwarding[index.0].store((to >> COMPRESSED_POINTER_SHIFT) as u32, Ordering::Relaxed);}});}-/// Rewrites every slot that marking recorded and that points at a cell that moved, and returns how many it rewrote.+/// Rewrites every slot that marking recorded and that points at a cell that moves, and returns how many it rewrote.////// # Safety///-/// `set` must be live, every cell has to be moved already, and the cells that held recorded slots must still be live.+/// `set` must be live, every cell that moves has to be forwarded and none copied yet, and the cells that held recorded+/// slots must still be live.#[unsafe(no_mangle)]pub unsafe extern "C" fn rust_gc_evacuation_fix_up_slots(set: *mut EvacuationSet) -> usize {abort_on_panic(|| {@@ -383,7 +466,7 @@ pub unsafe extern "C" fn rust_gc_evacuation_fix_up_slots(set: *mut EvacuationSetlet mut rewritten = 0;for slots in &set.slots {for &slot in slots {- // SAFETY: Marking recorded the slot in a live cell, as the caller makes sure it still is.+ // 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) } {rewritten += 1;}diff --git a/Libraries/LibGC/Rust/src/lib.rs b/Libraries/LibGC/Rust/src/lib.rsindex 249c18b4fc2..57fef3df98c 100644--- a/Libraries/LibGC/Rust/src/lib.rs+++ b/Libraries/LibGC/Rust/src/lib.rs@@ -16,6 +16,7 @@ mod rust_demangle;mod rust_panic;mod block;+mod compaction;mod evacuation;mod identity_hash;mod marker;@@ -23,9 +24,11 @@ mod os;mod pool;pub use block::{BlockDescriptor, rust_gc_block_descriptor_commit, rust_gc_block_descriptor_table};+pub use compaction::{CompactionCandidate, CompactionSelection, rust_gc_compaction_select};pub use evacuation::{- CellMove, EvacuationLayout, EvacuationSet, PinReason, rust_gc_evacuation_add_block, rust_gc_evacuation_create,- rust_gc_evacuation_destroy, rust_gc_evacuation_fix_up_slots, rust_gc_evacuation_forwarding_address,+ CellMove, EvacuationLayout, EvacuationSet, PinReason, PinnedCells, rust_gc_evacuation_add_block,+ rust_gc_evacuation_cells_to_move, rust_gc_evacuation_create, rust_gc_evacuation_destroy,+ rust_gc_evacuation_fix_up_slots, rust_gc_evacuation_forward_cells, rust_gc_evacuation_forwarding_address,rust_gc_evacuation_move_cells, rust_gc_evacuation_pin_reason, rust_gc_evacuation_recorded_slot_count,rust_gc_evacuation_will_move,};diff --git a/Libraries/LibGC/Rust/src/marker.rs b/Libraries/LibGC/Rust/src/marker.rsindex a4b81df84cc..3cb721d5611 100644--- a/Libraries/LibGC/Rust/src/marker.rs+++ b/Libraries/LibGC/Rust/src/marker.rs@@ -203,14 +203,17 @@ impl Marker {}/// Marks the cell at `address`, which a slot at `slot` points to. If the cell's block is evacuated, the slot is- /// recorded, so that it can be rewritten once the cell moves, or the cell pinned if the slot is not in a cell.+ /// recorded, so that it can be rewritten once the cell moves, or the cell pinned if the slot is not in a cell. A+ /// cell that is pinned already, as roots are before marking starts, stays where it is, so its slots are left out.#[inline(always)]fn mark_through_slot(&self, slot: RecordedSlot, address: usize) {let job = self.job();let Some((_, descriptor)) = job.descriptor_in_domain(address) else {return;};- if let Some(evacuation) = descriptor.evacuation() {+ if let Some(evacuation) = descriptor.evacuation()+ && !evacuation.is_pinned(descriptor, address)+ {if job.is_in_heap_region(slot.address()) {// SAFETY: Only this marker's thread touches its recorded slots while it marks.unsafe { &mut *self.recorded_slots.get() }.push(slot);diff --git a/Tests/LibGC/TestGCIdleCollection.cpp b/Tests/LibGC/TestGCIdleCollection.cppindex 101e32117a3..b4b2600b302 100644--- a/Tests/LibGC/TestGCIdleCollection.cpp+++ b/Tests/LibGC/TestGCIdleCollection.cpp@@ -64,6 +64,20 @@ TEST_CASE(rate_drop_is_gated_on_having_enough_garbage)EXPECT(policy.evaluate(64 * KiB, 64 * KiB, 8 * MiB) == Decision::KeepWaiting);}+TEST_CASE(a_quiet_tick_collects_a_few_mib_of_garbage_below_the_rate_drop_gate)+{+ GC::IdleCollectionPolicy policy;+ policy.reset(0);++ // A burst far below the rate-drop gate of a large heap (threshold / 16, i.e. 16 MiB here).+ EXPECT(policy.evaluate(3 * MiB, 3 * MiB, 256 * MiB) == Decision::KeepWaiting);+ EXPECT(!policy.last_tick_was_quiet());++ // Next to no allocation since: the heap went quiet, and a few MiB of garbage are enough.+ EXPECT(policy.evaluate(3 * MiB + 64 * KiB, 3 * MiB + 64 * KiB, 256 * MiB) == Decision::Collect);+ EXPECT(policy.last_tick_was_quiet());+}+TEST_CASE(watchdog_collects_when_the_rate_never_drops){GC::IdleCollectionPolicy policy;