Truly independent web browser
LibGC: Let the heap be told that an object graph was abandoned
Andreas Kling50f3b30a033c
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 9c8ab4609e9..c959b165640 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -77,6 +77,11 @@ static constexpr int GC_INCREMENTAL_SWEEP_SLICE_MS = 5;// whether to proactively collect. See idle_gc_on_timer().static constexpr int GC_IDLE_GC_INTERVAL_MS = 4000;+// The shortest time from hearing of an abandoned object graph to collecting it. Whatever replaces the graph, like the+// next page, gets this long to settle, and a burst of abandoned graphs, like closing a window of tabs, shares one+// collection.+static constexpr int GC_ABANDONED_OBJECT_GRAPH_MIN_DELAY_MS = 1000;+// 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;@@ -986,6 +991,10 @@ 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);++ // Marking is synchronous, so this collection has already seen any graph the timer was waiting to collect.+ if (m_abandoned_object_graph_timer)+ m_abandoned_object_graph_timer->stop();}void Heap::update_allocation_rate()@@ -1799,6 +1808,10 @@ void Heap::finish_incremental_sweep(){update_gc_bytes_threshold(m_sweep_live_external_bytes);+ // NB: A graph abandoned during this sweep was alive when marking ran, so the threshold just set counts it.+ if (m_abandoned_object_graph_timer && m_abandoned_object_graph_timer->is_active())+ limit_gc_bytes_threshold_for_abandoned_object_graph();+dbgln_if(INCREMENTAL_SWEEP_DEBUG, "[sweep] === Sweep complete ===");dbgln_if(INCREMENTAL_SWEEP_DEBUG, "[sweep] Live cell bytes: {} ({} KiB)", m_marked_cell_bytes, m_marked_cell_bytes / KiB);dbgln_if(INCREMENTAL_SWEEP_DEBUG, "[sweep] Live external bytes: {} ({} KiB)", m_sweep_live_external_bytes, m_sweep_live_external_bytes / KiB);@@ -1920,6 +1933,45 @@ void Heap::idle_gc_on_timer()}}+void Heap::limit_gc_bytes_threshold_for_abandoned_object_graph()+{+ // The threshold came from a live size that still counts the abandoned objects. Left alone, whatever comes next+ // could allocate that whole budget on top of them.+ m_gc_bytes_threshold = min(m_gc_bytes_threshold, m_allocated_bytes_since_last_gc + GC_MIN_BYTES_THRESHOLD);+}++void Heap::did_abandon_object_graph()+{+ VERIFY(is_on_owner_thread());+ limit_gc_bytes_threshold_for_abandoned_object_graph();++ if (!m_abandoned_object_graph_timer) {+ m_abandoned_object_graph_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(GC_ABANDONED_OBJECT_GRAPH_MIN_DELAY_MS), [this] {+ collect_abandoned_object_graph_on_timer();+ });+ }+ if (m_abandoned_object_graph_timer->is_active())+ return;++ // Marking pauses everything, so a heap that is expensive to mark waits longer. After this long, one marking pause+ // makes up the share of running time we want to spend collecting.+ auto marking_cost_budget_ns = static_cast<double>(m_mark_duration_ns) * (1 - GC_TARGET_TIME_FRACTION) / GC_TARGET_TIME_FRACTION;+ m_abandoned_object_graph_timer->start(max(AK::Duration::from_milliseconds(GC_ABANDONED_OBJECT_GRAPH_MIN_DELAY_MS), AK::Duration::from_nanoseconds(static_cast<i64>(marking_cost_budget_ns))));+}++void Heap::collect_abandoned_object_graph_on_timer()+{+ // A collection now would have to finish the sweep in one go, and a deferral means now is not a safe time to+ // collect.+ if (m_incremental_sweep_active || is_gc_deferred()) {+ m_abandoned_object_graph_timer->start();+ return;+ }++ m_allocated_bytes_since_last_gc = 0;+ collect_garbage();+}+void Heap::defer_gc(){++m_gc_deferrals;diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.hindex d8f22da8a68..2c119ac2eb5 100644--- a/Libraries/LibGC/Heap.h+++ b/Libraries/LibGC/Heap.h@@ -168,6 +168,11 @@ public:void did_allocate_external_memory(size_t);void did_free_external_memory(size_t);+ // Tells the heap that a large graph of objects, such as a page that went away, has likely just become garbage.+ // Nothing about allocation shows that, so this brings the next collection forward. It never collects from here,+ // since the graph is often still on the caller's stack.+ void did_abandon_object_graph();+private:friend struct CAPI;friend class CellAllocator;@@ -259,6 +264,7 @@ private:void update_allocation_rate();double next_growth_factor(size_t live_cell_bytes);void update_gc_bytes_threshold(size_t live_external_bytes);+ void limit_gc_bytes_threshold_for_abandoned_object_graph();enum class IncludeIncomingCrossHeapMembers {No,@@ -301,6 +307,7 @@ private:void start_idle_gc_timer();void idle_gc_on_timer();+ void collect_abandoned_object_graph_on_timer();struct Stats {AK_ALLOC_WITH_KMALLOC;@@ -365,6 +372,7 @@ private:RefPtr<Core::Timer> m_incremental_sweep_timer;RefPtr<Core::Timer> m_idle_gc_timer;+ RefPtr<Core::Timer> m_abandoned_object_graph_timer;u64 m_total_allocated_bytes { 0 };// The context a heap created through LibGC/CAPI.h was created with.void* m_foreign_context { nullptr };diff --git a/Tests/LibGC/TestGCIdleCollection.cpp b/Tests/LibGC/TestGCIdleCollection.cppindex ff6be04dffa..101e32117a3 100644--- a/Tests/LibGC/TestGCIdleCollection.cpp+++ b/Tests/LibGC/TestGCIdleCollection.cpp@@ -4,11 +4,42 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <LibCore/EventLoop.h>+#include <LibGC/Cell.h>+#include <LibGC/CellAllocator.h>+#include <LibGC/Heap.h>#include <LibGC/IdleCollectionPolicy.h>+#include <LibGC/Testing.h>#include <LibTest/TestCase.h>using Decision = GC::IdleCollectionPolicy::Decision;+namespace {++bool s_abandoned_cell_was_destroyed = false;++class AbandonedCell final : public GC::Cell {+ GC_CELL(AbandonedCell, GC::Cell);+ GC_DECLARE_ALLOCATOR(AbandonedCell);++public:+ virtual ~AbandonedCell() override { s_abandoned_cell_was_destroyed = true; }++private:+ AbandonedCell() = default;++ [[maybe_unused]] FlatPtr m_room_for_a_freelist_entry[2] {};+};++GC_DEFINE_ALLOCATOR(AbandonedCell);++NEVER_INLINE void allocate_abandoned_cell(GC::Heap& heap)+{+ (void)heap.allocate<AbandonedCell>();+}++}+TEST_CASE(collects_once_the_allocation_rate_drops){GC::IdleCollectionPolicy policy;@@ -56,3 +87,16 @@ TEST_CASE(parks_when_there_is_nothing_to_collect)policy.reset(0);EXPECT(policy.evaluate(4 * MiB, 0, 8 * MiB) == Decision::Park);}++TEST_CASE(an_abandoned_object_graph_is_collected_without_further_allocation)+{+ Core::EventLoop event_loop;+ GC::Heap heap([](auto&) { }, GC::Heap::BecomeThreadDefault::No);++ s_abandoned_cell_was_destroyed = false;+ allocate_abandoned_cell(heap);+ GC::scrub_stack_for_testing();++ heap.did_abandon_object_graph();+ event_loop.spin_until([] { return s_abandoned_cell_was_destroyed; });+}