Truly independent web browser
LibGC: Track which cells of each block are allocated in its descriptor
Andreas Kling02b47436459e
diff --git a/Libraries/LibGC/BlockAllocator.cpp b/Libraries/LibGC/BlockAllocator.cppindex 7789d67a98c..6fdcb7b2832 100644--- a/Libraries/LibGC/BlockAllocator.cpp+++ b/Libraries/LibGC/BlockAllocator.cpp@@ -15,6 +15,7 @@#include <AK/Vector.h>#include <LibCore/System.h>#include <LibGC/BlockAllocator.h>+#include <LibGC/BlockDescriptor.h>#include <LibGC/HeapBlock.h>#include <LibGC/HeapRegion.h>#include <LibThreading/Thread.h>@@ -190,6 +191,9 @@ private:VERIFY(m_next_chunk_offset <= LAST_CHUNK_OFFSET);auto* chunk = m_base + m_next_chunk_offset;MUST(Core::System::commit_memory(chunk, CHUNK_SIZE, Core::System::MemoryTag::GarbageCollector));+ // NB: Conservative pointer lookups read the descriptor of any block below the committed end, see+ // allocated_cell_containing(), so the descriptors of a chunk are committed with it.+ FFI::rust_gc_block_descriptor_commit(m_next_chunk_offset / HeapBlock::BLOCK_SIZE, BLOCKS_PER_CHUNK);m_next_chunk_offset += CHUNK_SIZE;return chunk;}diff --git a/Libraries/LibGC/BlockDescriptor.h b/Libraries/LibGC/BlockDescriptor.hindex 03612639261..b20125795ce 100644--- a/Libraries/LibGC/BlockDescriptor.h+++ b/Libraries/LibGC/BlockDescriptor.h@@ -7,6 +7,7 @@#pragma once#include <AK/BitCast.h>+#include <AK/BuiltinWrappers.h>#include <AK/Platform.h>#include <AK/Types.h>#include <LibGC/HeapRegion.h>@@ -29,23 +30,25 @@ ALWAYS_INLINE FFI::BlockDescriptor& block_descriptor_for(void const* address)return g_block_descriptors[(bit_cast<FlatPtr>(address) - heap_region_base()) / HeapBlockBase::BLOCK_SIZE];}-// A cell's mark bit is its offset in its block divided by the cell size, which tells the cells apart since they are a-// cell size apart.+// A cell's bit in the bitmaps of its block's descriptor is its offset in its block divided by the cell size, which+// tells the cells apart since they are a cell size apart.// OPTIMIZATION: Dividing by the cell size is slow, so the offset is multiplied by 2^32 / cell size, rounded up, and// shifted right by 32. For offsets and cell sizes up to 2^14, the rounding error never reaches the next// whole number.-ALWAYS_INLINE size_t mark_bit_index(FFI::BlockDescriptor const& descriptor, void const* cell)+ALWAYS_INLINE size_t cell_index(FFI::BlockDescriptor const& descriptor, void const* cell){auto offset = static_cast<u64>(bit_cast<FlatPtr>(cell) & (HeapBlockBase::BLOCK_SIZE - 1));return static_cast<size_t>((offset * descriptor.cell_index_magic) >> 32);}+ALWAYS_INLINE u64 cell_bit(size_t index) { return static_cast<u64>(1) << (index % 64); }+// Marking sets mark bits from several threads at once, so every access is atomic. Outside of marking, nothing else// writes them, so relaxed accesses are enough.ALWAYS_INLINE bool is_marked(FFI::BlockDescriptor const& descriptor, void const* cell){- auto index = mark_bit_index(descriptor, cell);- return __atomic_load_n(&descriptor.marked[index / 64], __ATOMIC_RELAXED) & (static_cast<u64>(1) << (index % 64));+ auto index = cell_index(descriptor, cell);+ return __atomic_load_n(&descriptor.marked[index / 64], __ATOMIC_RELAXED) & cell_bit(index);}ALWAYS_INLINE bool is_marked(void const* cell)@@ -56,8 +59,8 @@ ALWAYS_INLINE bool is_marked(void const* cell)ALWAYS_INLINE void set_marked(void const* cell){auto& descriptor = block_descriptor_for(cell);- auto index = mark_bit_index(descriptor, cell);- __atomic_fetch_or(&descriptor.marked[index / 64], static_cast<u64>(1) << (index % 64), __ATOMIC_RELAXED);+ auto index = cell_index(descriptor, cell);+ __atomic_fetch_or(&descriptor.marked[index / 64], cell_bit(index), __ATOMIC_RELAXED);}ALWAYS_INLINE void clear_marks(FFI::BlockDescriptor& descriptor)@@ -66,6 +69,71 @@ ALWAYS_INLINE void clear_marks(FFI::BlockDescriptor& descriptor)__atomic_store_n(&word, 0, __ATOMIC_RELAXED);}+// A cell is allocated from when it is handed out until the sweep or a move frees its slot. While an allocator has taken+// the free cells of a block to hand them out itself, they all count as allocated, see HeapBlock::take_free_cells(). Only+// the thread that owns the block's heap reads and writes these bits.+ALWAYS_INLINE bool is_allocated(FFI::BlockDescriptor const& descriptor, size_t index)+{+ return descriptor.allocated[index / 64] & cell_bit(index);+}++ALWAYS_INLINE void set_allocated(FFI::BlockDescriptor& descriptor, size_t index)+{+ descriptor.allocated[index / 64] |= cell_bit(index);+}++ALWAYS_INLINE void clear_allocated(FFI::BlockDescriptor& descriptor, size_t index)+{+ descriptor.allocated[index / 64] &= ~cell_bit(index);+}++// The bits of the word of a bitmap whose first bit is at `first` that are for indices below `limit`.+ALWAYS_INLINE u64 bits_below(size_t limit, size_t first)+{+ if (limit <= first)+ return 0;+ if (limit >= first + 64)+ return ~static_cast<u64>(0);+ return cell_bit(limit - first) - 1;+}++// The cells of a block are the ones from first_cell_index on, see cell_index().+ALWAYS_INLINE void set_all_allocated(FFI::BlockDescriptor& descriptor)+{+ size_t begin = descriptor.first_cell_index;+ size_t end = begin + descriptor.cell_count;+ for (size_t word = 0; word < FFI::CELL_BITMAP_WORDS; ++word)+ descriptor.allocated[word] = bits_below(end, word * 64) & ~bits_below(begin, word * 64);+}++ALWAYS_INLINE u32 allocated_cell_count_of(FFI::BlockDescriptor const& descriptor)+{+ u32 count = 0;+ for (auto word : descriptor.allocated)+ count += popcount(word);+ return count;+}++// The cell that `address` points into, if it is an allocated cell of a block of `heap`. The address must be within the+// committed part of the heap region, where every block has a descriptor.+ALWAYS_INLINE void* allocated_cell_containing(void const* heap, FlatPtr address, size_t cells_offset)+{+ auto const& descriptor = block_descriptor_for(bit_cast<void const*>(address));+ if (__atomic_load_n(&descriptor.heap, __ATOMIC_ACQUIRE) != heap)+ return nullptr;+ auto block = address & ~(HeapBlockBase::BLOCK_SIZE - 1);+ if (address - block < cells_offset)+ return nullptr;+ auto offset_in_cells = static_cast<u64>(address - block - cells_offset);+ auto index = static_cast<size_t>((offset_in_cells * descriptor.cell_index_magic) >> 32);+ if (index >= descriptor.cell_count)+ return nullptr;+ auto cell = block + cells_offset + index * descriptor.cell_size;+ if (!is_allocated(descriptor, cell_index(descriptor, bit_cast<void const*>(cell))))+ return nullptr;+ return bit_cast<void*>(cell);+}+// Fills in the descriptor of a block that is about to hold cells, and empties it once the block goes away.void publish_block_descriptor(HeapBlock&, CellAllocator&);void retire_block_descriptor(HeapBlock&);diff --git a/Libraries/LibGC/CMakeLists.txt b/Libraries/LibGC/CMakeLists.txtindex 55c57ac9d2e..45c02ef1463 100644--- a/Libraries/LibGC/CMakeLists.txt+++ b/Libraries/LibGC/CMakeLists.txt@@ -27,7 +27,7 @@ import_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libgc_rust FEATURES atest_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})+set_property(SOURCE BlockAllocator.cpp CAPI.cpp Cell.cpp Heap.cpp HeapBlock.cpp WeakBlock.cpp APPEND PROPERTY OBJECT_DEPENDS ${_libgc_rust_lib})# The first word of a GC::ForeignCell belongs to its foreign implementation rather than holding a vtable pointer, so# UBSan's vptr checks misfire whenever LibGC handles such a cell as a GC::Cell.diff --git a/Libraries/LibGC/CellAllocator.cpp b/Libraries/LibGC/CellAllocator.cppindex 47731d82b60..76b959c2673 100644--- a/Libraries/LibGC/CellAllocator.cpp+++ b/Libraries/LibGC/CellAllocator.cpp@@ -179,7 +179,7 @@ void CellAllocator::give_back_local_free_list(Badge<Heap>)void CellAllocator::block_did_become_empty(Badge<Heap>, HeapBlock& block, DeferDecommit defer_decommit){block.m_list_node.remove();- block.heap().m_live_heap_blocks.remove(&block);+ --block.heap().m_block_count;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();diff --git a/Libraries/LibGC/CellAllocator.h b/Libraries/LibGC/CellAllocator.hindex d64e236241d..79967a51493 100644--- a/Libraries/LibGC/CellAllocator.h+++ b/Libraries/LibGC/CellAllocator.h@@ -148,6 +148,8 @@ public:void block_did_become_empty(Badge<Heap>, HeapBlock&, DeferDecommit = DeferDecommit::Yes);void block_did_become_usable(Badge<Heap>, HeapBlock&);+ bool is_local_block(HeapBlock const& block) const { return m_local_block == █ }+bool has_blocks_pending_sweep() const { return !m_blocks_pending_sweep.is_empty(); }IntrusiveListNode<CellAllocator> m_list_node;diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 1bbe36c257d..62c4dbc54d3 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -582,8 +582,8 @@ void Heap::add_stats(AK::JsonObject& values) constVERIFY(m_stats);values.set("gc.allocated_bytes_total"sv, m_total_allocated_bytes);values.set("gc.allocated_bytes_since_gc"sv, m_allocated_bytes_since_last_gc);- values.set("gc.heap_blocks"sv, m_live_heap_blocks.size());- values.set("gc.heap_block_bytes"sv, m_live_heap_blocks.size() * HeapBlock::BLOCK_SIZE);+ values.set("gc.heap_blocks"sv, m_block_count);+ values.set("gc.heap_block_bytes"sv, m_block_count * HeapBlock::BLOCK_SIZE);values.set("gc.cell_allocators"sv, m_all_cell_allocators.size_slow());values.set("gc.threshold_bytes"sv, m_gc_bytes_threshold);values.set("gc.live_cell_bytes"sv, m_stats->live_cell_bytes);@@ -608,7 +608,7 @@ void Heap::finish_stats_collection()data.set("pause_duration_ns"sv, stats.pause_duration_ns);data.set("sweep_duration_ns"sv, stats.sweep_duration_ns);data.set("bytes_before"sv, stats.bytes_before);- data.set("bytes_after"sv, m_live_heap_blocks.size() * HeapBlock::BLOCK_SIZE);+ data.set("bytes_after"sv, m_block_count * HeapBlock::BLOCK_SIZE);data.set("live_cell_bytes"sv, stats.live_cell_bytes);data.set("live_external_bytes"sv, stats.live_external_bytes);log->event("gc"sv, move(data));@@ -765,16 +765,15 @@ static void add_possible_value(PossiblePointers& possible_pointers, FlatPtr data}template<typename Callback>-static void for_each_cell_among_possible_pointers(HashTable<HeapBlock*> const& all_live_heap_blocks, PossiblePointers& possible_pointers, Callback callback)+static void for_each_cell_among_possible_pointers(Heap const& heap, PossiblePointers& possible_pointers, Callback callback){+ // NB: No block is in the low guard of the region, whose descriptors are never backed by memory.+ auto first_block = heap_region_base() + HEAP_REGION_LOW_GUARD_SIZE;auto visit = [&](HashMap<FlatPtr, HeapRoot>& candidates, bool must_be_cell_start) {for (auto possible_pointer : candidates.keys()) {- if (!possible_pointer)+ if (possible_pointer < first_block)continue;- auto* possible_heap_block = HeapBlock::from_cell(reinterpret_cast<Cell const*>(possible_pointer));- if (!all_live_heap_blocks.contains(possible_heap_block))- continue;- auto* cell = possible_heap_block->cell_from_possible_pointer(possible_pointer);+ auto* cell = static_cast<Cell*>(allocated_cell_containing(&heap, possible_pointer, HeapBlock::cells_offset()));if (!cell)continue;if (must_be_cell_start && reinterpret_cast<FlatPtr>(cell) != possible_pointer)@@ -1143,7 +1142,7 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti}if (m_stats) {++m_stats->collections;- m_stats->bytes_before = m_live_heap_blocks.size() * HeapBlock::BLOCK_SIZE;+ m_stats->bytes_before = m_block_count * HeapBlock::BLOCK_SIZE;m_stats->sweep_duration_ns = 0;}compaction_stats().active = false;@@ -1271,7 +1270,9 @@ static Vector<FFI::CompactionCandidate> compaction_candidates(CellAllocator::Liscandidates.unchecked_append({.block = &block,.allocator = allocator_index,- .live_cells = block.live_cell_count().value_or(cell_count),+ // NB: The free cells that the allocator took from its local block count as allocated, so the block+ // counts as full. Every other block knows exactly which of its cells are allocated.+ .live_cells = allocator.is_local_block(block) ? cell_count : block.allocated_cell_count(),.cell_count = cell_count,.cell_size = cell_size,.kept_by_pins = block_descriptor_for(&block).kept_by_pins,@@ -1296,7 +1297,7 @@ void Heap::schedule_compaction_if_worthwhile()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());+ auto candidates = compaction_candidates(m_all_cell_allocators, m_block_count);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) {@@ -1306,7 +1307,7 @@ void Heap::schedule_compaction_if_worthwhile()}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));+ dbgln("Scheduling a collection that compacts: {} of {} recoverable", human_readable_size(recoverable_blocks * HeapBlock::BLOCK_SIZE), human_readable_size(m_block_count * HeapBlock::BLOCK_SIZE));schedule_collection_that_moves_cells();}@@ -1340,7 +1341,7 @@ void Heap::begin_evacuation()} 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 candidates = compaction_candidates(m_all_cell_allocators, m_block_count);auto selection = FFI::rust_gc_compaction_select(candidates.data(), candidates.size(), GC_COMPACTION_BUDGET_BYTES);for (auto const& candidate : candidates) {if (candidate.selected)@@ -1461,8 +1462,7 @@ void Heap::evacuate()// 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);+ VERIFY(block.allocated_cell_count() == count + pinned.by_edge + pinned.by_root);}clear_marks(descriptor);}@@ -1511,14 +1511,12 @@ void Heap::evacuate()// 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);- });+ static_assert(cell_bitmap_words == FFI::CELL_BITMAP_WORDS);+ Array<u64, cell_bitmap_words> kept {};+ for (size_t i = 0; i < cell_bitmap_words; ++i)+ kept[i] = descriptor.allocated[i];m_cells_kept_by_pins.set(block, kept);descriptor.kept_by_pins = true;}@@ -1527,7 +1525,7 @@ void Heap::evacuate()for (auto* evacuated_block : m_evacuated_blocks) {auto& block = *evacuated_block;auto& allocator = block.cell_allocator();- if (!block.has_live_cells()) {+ if (block.allocated_cell_count() == 0) {allocator.block_did_become_empty({}, block, DeferDecommit::Yes);++stats.freed_blocks;} else if (block.is_full()) {@@ -1540,6 +1538,19 @@ void Heap::evacuate()stats.release_us = (MonotonicTime::now().nanoseconds() - release_start_ns) / 1000;}+bool Heap::is_live_cell(Cell const* cell) const+{+ VERIFY(m_collecting_garbage);+ if (!cell)+ return false;+ auto address = bit_cast<FlatPtr>(cell);+ if (address < heap_region_base() + HEAP_REGION_LOW_GUARD_SIZE || address >= BlockAllocator::heap_region_committed_end())+ return false;+ // NB: A cell that an allocator took along with the other free cells of its block counts as allocated, but it is+ // still a free cell until the allocator hands it out.+ return allocated_cell_containing(this, address, HeapBlock::cells_offset()) == cell && cell->state() == Cell::State::Live;+}+void Heap::forget_cells_kept_by_pins(HeapBlock& block){auto& descriptor = block_descriptor_for(&block);@@ -1552,7 +1563,7 @@ void Heap::forget_cells_kept_by_pins(HeapBlock& 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 index = cell_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)))@@ -2030,7 +2041,7 @@ NO_SANITIZE_ADDRESS void Heap::gather_conservative_roots(ConservativeScanOrigin{ScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.conservative_cell_lookup_us };- for_each_cell_among_possible_pointers(m_live_heap_blocks, possible_pointers, [&](Cell* cell, HashMap<FlatPtr, HeapRoot>& candidates, FlatPtr possible_pointer) {+ for_each_cell_among_possible_pointers(*this, possible_pointers, [&](Cell* cell, HashMap<FlatPtr, HeapRoot>& candidates, FlatPtr possible_pointer) {if (cell->state() == Cell::State::Live) {dbgln_if(HEAP_DEBUG, " ?-> {}", (void const*)cell);roots.set(cell, *candidates.get(possible_pointer));@@ -2104,7 +2115,7 @@ void Heap::mark_live_cells_across(ReadonlySpan<Heap* const> heaps, HashMap<Cell*for (auto* root : roots.keys())root_cells.unchecked_append(root);for (auto* heap : heaps)- heap_bytes += heap->m_live_heap_blocks.size() * HeapBlock::BLOCK_SIZE;+ heap_bytes += heap->m_block_count * HeapBlock::BLOCK_SIZE;}Vector<size_t, 1> marked_cell_bytes;@@ -2224,7 +2235,6 @@ void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measurelive_cell_bytes += block.cell_size();}});- 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.@@ -2327,7 +2337,6 @@ 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);diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.hindex bc3d24ac53e..cfa5d61128d 100644--- a/Libraries/LibGC/Heap.h+++ b/Libraries/LibGC/Heap.h@@ -201,7 +201,9 @@ public:void sweep_block(HeapBlock&);- bool is_live_heap_block(HeapBlock* block) const { return m_live_heap_blocks.contains(block); }+ // Whether `cell` points at a cell of this heap that is allocated: one that the sweep did not free yet. Code that keeps+ // pointers to cells that may have died since uses this to tell them apart from live ones.+ bool is_live_cell(Cell const*) const;template<typename Callback>void for_each_block(Callback callback)@@ -410,7 +412,7 @@ private:Vector<AK::Function<void()>> m_post_gc_tasks;Vector<AK::Function<void()>> m_sweep_callbacks;- HashTable<HeapBlock*> m_live_heap_blocks;+ size_t m_block_count { 0 };WeakBlock::List m_usable_weak_blocks;WeakBlock::List m_full_weak_blocks;diff --git a/Libraries/LibGC/HeapBlock.cpp b/Libraries/LibGC/HeapBlock.cppindex 7817d224deb..5c7bc1469f0 100644--- a/Libraries/LibGC/HeapBlock.cpp+++ b/Libraries/LibGC/HeapBlock.cpp@@ -25,15 +25,17 @@ FFI::BlockDescriptor* const g_block_descriptors = FFI::rust_gc_block_descriptor_void publish_block_descriptor(HeapBlock& block, CellAllocator& allocator){- auto index = (bit_cast<FlatPtr>(&block) - heap_region_base()) / HeapBlockBase::BLOCK_SIZE;- FFI::rust_gc_block_descriptor_commit(index);- auto& descriptor = g_block_descriptors[index];+ auto& descriptor = block_descriptor_for(&block);descriptor.type_info = &allocator.type_info();descriptor.cell_size = allocator.cell_size();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.cell_count = static_cast<u16>(block.cell_count());+ descriptor.first_cell_index = static_cast<u16>(cell_index(descriptor, bit_cast<u8 const*>(&block) + HeapBlock::cells_offset()));+ for (auto& word : descriptor.allocated)+ word = 0;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.@@ -44,6 +46,9 @@ void publish_block_descriptor(HeapBlock& block, CellAllocator& allocator)#pragma GCC diagnostic ignored "-Winvalid-offsetof"size_t HeapBlock::cells_offset(){+ static_assert(offsetof(HeapBlock, m_storage) == 112);+ // NB: A block counts its cells from its size, and the Rust core from this offset, so the two have to match.+ static_assert(sizeof(HeapBlock) == offsetof(HeapBlock, m_storage));return offsetof(HeapBlock, m_storage);}#pragma GCC diagnostic pop@@ -58,7 +63,7 @@ NonnullOwnPtr<HeapBlock> HeapBlock::create(Heap& heap, CellAllocator& cell_allocchar const* name = nullptr;auto* block = static_cast<HeapBlock*>(cell_allocator.block_allocator().allocate_block(name));new (block) HeapBlock(heap, cell_allocator);- heap.m_live_heap_blocks.set(block);+ ++heap.m_block_count;return adopt_own(*block);}@@ -79,6 +84,30 @@ HeapBlock::~HeapBlock()retire_block_descriptor(*this);}+Cell* HeapBlock::allocate()+{+ Cell* allocated_cell = nullptr;+ if (auto* head = freelist_head(); !is_end_of_freelist(head)) {+ VERIFY(is_valid_cell_pointer(head));+ m_freelist = static_cast<FreelistEntry*>(head)->next;+ allocated_cell = head;+ } else if (has_lazy_freelist()) {+ allocated_cell = cell(m_next_lazy_freelist_index++);+ }++ if (allocated_cell) {+ ASAN_UNPOISON_MEMORY_REGION(allocated_cell, m_cell_size);+ auto& descriptor = block_descriptor_for(this);+ set_allocated(descriptor, cell_index(descriptor, allocated_cell));+ }+ return allocated_cell;+}++u32 HeapBlock::allocated_cell_count() const+{+ return allocated_cell_count_of(block_descriptor_for(this));+}+HeapBlock::FreeCells HeapBlock::take_free_cells(){FreeCells free_cells {@@ -91,7 +120,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;+ set_all_allocated(block_descriptor_for(this));return free_cells;}@@ -111,6 +140,13 @@ void HeapBlock::give_back_free_cells(Cell* free_list, FlatPtr lazy_cursor)auto lazy_index = (lazy_cursor - storage) / m_cell_size;VERIFY(lazy_index <= cell_count());m_next_lazy_freelist_index = lazy_index;++ // NB: The cells that come back were never handed out, so they are not allocated after all.+ auto& descriptor = block_descriptor_for(this);+ for (auto* free_cell = freelist_head(); !is_end_of_freelist(free_cell); free_cell = next_free_cell(free_cell))+ clear_allocated(descriptor, cell_index(descriptor, free_cell));+ for (auto index = lazy_index; index < cell_count(); ++index)+ clear_allocated(descriptor, cell_index(descriptor, cell(index)));}void HeapBlock::deallocate(Cell* cell)@@ -138,8 +174,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;+ auto& descriptor = block_descriptor_for(this);+ clear_allocated(descriptor, cell_index(descriptor, cell));#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 23f24c4f02f..d593561dc1f 100644--- a/Libraries/LibGC/HeapBlock.h+++ b/Libraries/LibGC/HeapBlock.h@@ -7,8 +7,6 @@#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>@@ -37,24 +35,7 @@ public:size_t cell_count() const { return m_cell_count; }bool is_full() const { return !has_lazy_freelist() && is_end_of_freelist(freelist_head()); }- ALWAYS_INLINE Cell* allocate()- {- Cell* allocated_cell = nullptr;- if (auto* head = freelist_head(); !is_end_of_freelist(head)) {- VERIFY(is_valid_cell_pointer(head));- m_freelist = static_cast<FreelistEntry*>(head)->next;- allocated_cell = head;- } else if (has_lazy_freelist()) {- allocated_cell = cell(m_next_lazy_freelist_index++);- }-- 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;- }+ Cell* allocate();// Deallocates a cell that for_each_cell() found, which the sweep// found unmarked.@@ -113,18 +94,9 @@ 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; }+ // How many cells of the block are allocated. While an allocator has taken the block's free cells, they count as+ // allocated too, see take_free_cells().+ u32 allocated_cell_count() const;template<typename Callback>void for_each_cell(Callback callback)@@ -134,16 +106,6 @@ 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){@@ -204,7 +166,6 @@ 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/Rust/src/block.rs b/Libraries/LibGC/Rust/src/block.rsindex c3ca943272b..f8365b3d787 100644--- a/Libraries/LibGC/Rust/src/block.rs+++ b/Libraries/LibGC/Rust/src/block.rs@@ -7,7 +7,8 @@//! The descriptors of the heap's blocks.//!//! A block holds cells of one type and one size. What the collector knows about a block is in its descriptor, which-//! lives outside the heap region: the heap and the type of the block, and which of its cells are marked. So nothing that+//! lives outside the heap region: the heap and the type of the block, and which of its cells are allocated and which+//! are marked. So nothing that//! writes to a cell, or past it, can change what the collector does with the block. The descriptor of a block is at the//! block's index in the region in a table of descriptors, which is reserved once for the whole region and only backed//! by memory where blocks are.@@ -26,10 +27,11 @@ pub const BLOCK_SIZE: usize = 16 * 1024;/// The smallest cell, which has room for the link of a free cell after the header of a cell.pub const MIN_CELL_SIZE: usize = 24;-/// A cell's mark bit is its offset in its block divided by its size, which the smallest cells take the most bits for.-pub const MARK_BITMAP_WORDS: usize = 11;+/// A cell's bit in the bitmaps of its block is its offset in the block divided by its size, which the smallest cells+/// take the most bits for.+pub const CELL_BITMAP_WORDS: usize = 11;-const _: () = assert!(MARK_BITMAP_WORDS == (BLOCK_SIZE / MIN_CELL_SIZE + 1).div_ceil(64));+const _: () = assert!(CELL_BITMAP_WORDS == (BLOCK_SIZE / MIN_CELL_SIZE + 1).div_ceil(64));/// What the collector knows about a block. LibGC's C++ side fills it in when it creates the block, and empties it when/// the block goes away.@@ -49,16 +51,33 @@ pub struct BlockDescriptor {/// 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; 5],+ pub reserved: u8,+ /// How many cells fit in the block, after its header.+ pub cell_count: u16,+ /// The index of the first cell of the block, see cell_index(). Its cells have the indices from this one on.+ pub first_cell_index: u16,/// 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,/// One bit for each cell, which marking sets atomically, see mark_word().- pub marked: [UnsafeCell<u64>; MARK_BITMAP_WORDS],+ pub marked: [UnsafeCell<u64>; CELL_BITMAP_WORDS],+ /// One bit for each cell that is allocated: set when a cell is handed out, and when an allocator takes the free+ /// cells of the block to hand out itself, until it gives back the ones it did not hand out. Only the thread that+ /// owns the heap reads and writes them.+ pub allocated: [u64; CELL_BITMAP_WORDS],+ /// Where the block is in its allocator's list of blocks.+ pub list_index: u32,+ /// Whether the incremental sweep has yet to sweep the block.+ pub pending_sweep: bool,+ /// Whether a sweep is sweeping the block right now, which a destructor it calls may be in the middle of.+ pub being_swept: bool,+ /// Whether the block is on its allocator's list of blocks with free cells.+ pub usable: bool,+ /// Rounds the descriptor up to 256 bytes, four whole cache lines in the table.+ pub reserved3: [u8; 33],}-const _: () = assert!(size_of::<BlockDescriptor>() == 128);+const _: () = assert!(size_of::<BlockDescriptor>() == 256);impl BlockDescriptor {pub fn heap(&self) -> *mut c_void {@@ -144,7 +163,7 @@ impl BlockDescriptor {pub struct CellIndex(pub usize);/// The most cells a block has, and so the most bits that per-cell bitmaps of a block need.-pub const MAX_CELLS_PER_BLOCK: usize = MARK_BITMAP_WORDS * 64;+pub const MAX_CELLS_PER_BLOCK: usize = CELL_BITMAP_WORDS * 64;struct Table {descriptors: NonNull<BlockDescriptor>,@@ -250,11 +269,19 @@ pub extern "C" fn rust_gc_block_descriptor_table(region_size: usize) -> *mut Blo.as_ptr()}-/// Makes sure that the descriptor at `index` is backed by memory, before a block is created there.+/// Makes sure that the `count` descriptors from `first_index` on are backed by memory, before blocks are created there.#[unsafe(no_mangle)]-pub extern "C" fn rust_gc_block_descriptor_commit(index: usize) {+pub extern "C" fn rust_gc_block_descriptor_commit(first_index: usize, count: usize) {let table = TABLE.get().expect("the table of block descriptors exists");- assert!(index < table.count, "a block is within the heap region");- // SAFETY: The descriptor is within the reserved table.- unsafe { os::commit_reserved_zeroed(table.descriptors.add(index).cast(), size_of::<BlockDescriptor>()) };+ assert!(+ first_index + count <= table.count,+ "the blocks are within the heap region"+ );+ // SAFETY: The descriptors are within the reserved table.+ unsafe {+ os::commit_reserved_zeroed(+ table.descriptors.add(first_index).cast(),+ count * size_of::<BlockDescriptor>(),+ );+ }}diff --git a/Libraries/LibGC/Rust/src/evacuation.rs b/Libraries/LibGC/Rust/src/evacuation.rsindex 891f245c1ed..277cd00575c 100644--- a/Libraries/LibGC/Rust/src/evacuation.rs+++ b/Libraries/LibGC/Rust/src/evacuation.rs@@ -22,7 +22,7 @@ use core::ffi::c_void;use core::sync::atomic::{AtomicU32, AtomicU64, Ordering};use crate::block::{- BLOCK_SIZE, BlockDescriptor, CellIndex, MARK_BITMAP_WORDS, MAX_CELLS_PER_BLOCK, descriptor_for, descriptor_of_heap,+ BLOCK_SIZE, BlockDescriptor, CELL_BITMAP_WORDS, CellIndex, MAX_CELLS_PER_BLOCK, descriptor_for, descriptor_of_heap,set_evacuation_of_block,};use crate::identity_hash::{CompressedAddress, IDENTITY_HASH_STATE_OFFSET, identity_hashes_of};@@ -42,8 +42,8 @@ pub enum PinReason {/// What a collection that evacuates a block knows about the block's cells.pub struct Evacuation {- pinned_by_edge: [AtomicU64; MARK_BITMAP_WORDS],- pinned_by_root: [AtomicU64; MARK_BITMAP_WORDS],+ pinned_by_edge: [AtomicU64; CELL_BITMAP_WORDS],+ pinned_by_root: [AtomicU64; CELL_BITMAP_WORDS],/// The compressed address each cell that moved moved to, by cell index, and 0 for the cells that did not.forwarding: [AtomicU32; MAX_CELLS_PER_BLOCK],}@@ -51,8 +51,8 @@ pub struct Evacuation {impl Evacuation {fn new() -> Box<Self> {Box::new(Self {- pinned_by_edge: [const { AtomicU64::new(0) }; MARK_BITMAP_WORDS],- pinned_by_root: [const { AtomicU64::new(0) }; MARK_BITMAP_WORDS],+ 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],})}@@ -360,7 +360,7 @@ pub unsafe extern "C" fn rust_gc_evacuation_cells_to_move(// 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 {+ for word_index in 0..CELL_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;diff --git a/Libraries/LibWeb/DOM/HTMLCollection.cpp b/Libraries/LibWeb/DOM/HTMLCollection.cppindex 72d37629d7e..5594852b8cf 100644--- a/Libraries/LibWeb/DOM/HTMLCollection.cpp+++ b/Libraries/LibWeb/DOM/HTMLCollection.cpp@@ -60,13 +60,11 @@ GC::Cell const& HTMLCollection::owner_cell(Badge<GC::Heap>) constvoid HTMLCollection::remove_dead_cells(Badge<GC::Heap>){m_cached_elements.remove_all_matching([&](GC::RawPtr<Element> const& element) {- auto* block = GC::HeapBlock::from_cell(element.ptr());- return !heap().is_live_heap_block(block) || element->state() != Cell::State::Live || !element->is_marked();+ return !heap().is_live_cell(element.ptr()) || !element->is_marked();});if (m_cached_name_to_element_mappings) {m_cached_name_to_element_mappings->remove_all_matching([&](Utf16FlyString const&, GC::RawPtr<Element> const& element) {- auto* block = GC::HeapBlock::from_cell(element.ptr());- return !heap().is_live_heap_block(block) || element->state() != Cell::State::Live || !element->is_marked();+ return !heap().is_live_cell(element.ptr()) || !element->is_marked();});}}diff --git a/Libraries/LibWeb/DOM/LiveNodeList.cpp b/Libraries/LibWeb/DOM/LiveNodeList.cppindex 0e95d1b6bac..fff7311198b 100644--- a/Libraries/LibWeb/DOM/LiveNodeList.cpp+++ b/Libraries/LibWeb/DOM/LiveNodeList.cpp@@ -48,8 +48,7 @@ GC::Cell const& LiveNodeList::owner_cell(Badge<GC::Heap>) constvoid LiveNodeList::remove_dead_cells(Badge<GC::Heap>){m_cached_nodes.remove_all_matching([&](GC::RawPtr<Node> const& node) {- auto* block = GC::HeapBlock::from_cell(node.ptr());- return !heap().is_live_heap_block(block) || node->state() != Cell::State::Live || !node->is_marked();+ return !heap().is_live_cell(node.ptr()) || !node->is_marked();});}diff --git a/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp b/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cppindex b420612d5f1..e438ff04e0d 100644--- a/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp+++ b/Libraries/LibWeb/HTML/CrossOrigin/AbstractOperations.cpp@@ -8,7 +8,6 @@#include <AK/Variant.h>#include <AK/Vector.h>#include <LibGC/CellAllocator.h>-#include <LibGC/HeapBlock.h>#include <LibJS/Runtime/AbstractOperations.h>#include <LibJS/Runtime/Completion.h>#include <LibJS/Runtime/Error.h>@@ -216,8 +215,7 @@ void CrossOriginPropertyDescriptorMap::remove_dead_cells(Badge<GC::Heap>){m_descriptors.remove_all_matching([&](CrossOriginKey const& key, JS::PropertyDescriptor const&) {auto const& current_settings_object = *key.current_settings_object;- auto* block = GC::HeapBlock::from_cell(¤t_settings_object);- return !heap().is_live_heap_block(block) || current_settings_object.state() != Cell::State::Live || !current_settings_object.is_marked();+ return !heap().is_live_cell(¤t_settings_object) || !current_settings_object.is_marked();});}