Truly independent web browser
LibWeb: Give back the memory of idle stage and style threads
Andreas Klingb73497b99d67
diff --git a/Libraries/LibWeb/Rust/src/paint_stage.rs b/Libraries/LibWeb/Rust/src/paint_stage.rsindex cb0eb9e7396..e3213af43b0 100644--- a/Libraries/LibWeb/Rust/src/paint_stage.rs+++ b/Libraries/LibWeb/Rust/src/paint_stage.rs@@ -49,7 +49,10 @@ struct PaintStage {fn the_paint_thread() -> &'static PaintThread {static PAINT_THREAD: OnceLock<PaintThread> = OnceLock::new();PAINT_THREAD.get_or_init(|| PaintThread {- thread: StageThread::spawn("Paint"),+ thread: StageThread::spawn(+ "Paint",+ crate::render_state::release_unused_memory_of_style_layout_threads,+ ),stage: StageCell(RefCell::default()),})}diff --git a/Libraries/LibWeb/Rust/src/render_state.rs b/Libraries/LibWeb/Rust/src/render_state.rsindex 510d7e1af6f..de2b68e9508 100644--- a/Libraries/LibWeb/Rust/src/render_state.rs+++ b/Libraries/LibWeb/Rust/src/render_state.rs@@ -20,7 +20,7 @@ mod clock;mod devtools;mod document_host;mod owner;-pub(crate) use owner::process_style;+pub(crate) use owner::{process_style, release_unused_memory_of_style_layout_threads};mod wait;pub use clock::FfiPlannedScrollTimeline;diff --git a/Libraries/LibWeb/Rust/src/render_state/owner.rs b/Libraries/LibWeb/Rust/src/render_state/owner.rsindex aecf5e30ee6..a3eb00bc77a 100644--- a/Libraries/LibWeb/Rust/src/render_state/owner.rs+++ b/Libraries/LibWeb/Rust/src/render_state/owner.rs@@ -137,6 +137,20 @@ static SLOT: LazyLock<Slot> = LazyLock::new(|| Slot {style_layout_pool: Arc::new(crate::style_layout_pool::StyleLayoutPool::of_process()),});+/// Has the style and layout threads of the process give back the memory they freed, which they keep until they+/// allocate again. Each does so between its jobs, and this does not wait for them. The Paint and Render threads both+/// ask for this when they go idle, as either can stay busy for long while the workers have nothing to do.+#[cfg(feature = "allocator")]+pub(crate) fn release_unused_memory_of_style_layout_threads() {+ if let Some(pool) = SLOT.style_layout_pool.started() {+ pool.spawn_broadcast(|_| ak::release_unused_allocator_memory());+ }+}++/// Standalone Rust tests do not link the C++ allocator, so there is nothing to release.+#[cfg(not(feature = "allocator"))]+pub(crate) fn release_unused_memory_of_style_layout_threads() {}+/// The style data every document's style engine shares with the others, which any thread reaches without the slot: only/// what it guards itself is written once it is made.pub(crate) fn process_style() -> &'static Arc<crate::css::style::ProcessStyle> {diff --git a/Libraries/LibWeb/Rust/src/stage_thread.rs b/Libraries/LibWeb/Rust/src/stage_thread.rsindex e40d853f094..e9481329d8f 100644--- a/Libraries/LibWeb/Rust/src/stage_thread.rs+++ b/Libraries/LibWeb/Rust/src/stage_thread.rs@@ -28,6 +28,7 @@ use std::ptr::NonNull;use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU8, AtomicUsize, Ordering};use std::sync::{Arc, Mutex, OnceLock, PoisonError};use std::thread::Thread;+use std::time::{Duration, Instant};// This crate is not instrumented by ThreadSanitizer, so TSan cannot see the ordering the hand-off gives between the// host's thread and a stage thread. Tell it explicitly, or every access a stage thread makes to what the host wrote@@ -121,9 +122,13 @@ pub extern "C" fn stage_thread_set_flight_finished(finished: extern "C" fn()) {// not committed, so the larger size costs address space only.pub(crate) const STAGE_THREAD_STACK_SIZE: usize = 64 * 1024 * 1024;+/// How long a stage thread waits for a job before it gives back the memory it freed.+const IDLE_MEMORY_RELEASE_DELAY: Duration = Duration::from_secs(1);+impl StageThread {- /// Spawns a thread named `name`, which lives as long as the process.- pub(crate) fn spawn(name: &str) -> Self {+ /// Spawns a thread named `name`, which lives as long as the process, and which calls `release_more` once it has+ /// given back the memory it freed.+ pub(crate) fn spawn(name: &str, release_more: fn()) -> Self {let shared: &'static Shared = Box::leak(Box::new(Shared {handed: AtomicPtr::new(std::ptr::null_mut()),tsan_key: AtomicBool::new(false),@@ -135,8 +140,30 @@ impl StageThread {if let Some(setup) = THREAD_SETUP.get() {setup();}+ let mut release_memory_at = None;loop {- let last = wait_for(|| NonNull::new(shared.handed.swap(std::ptr::null_mut(), Ordering::Acquire)));+ let last = loop {+ if let Some(last) = NonNull::new(shared.handed.swap(std::ptr::null_mut(), Ordering::Acquire)) {+ break last;+ }+ let Some(deadline) = release_memory_at else {+ std::thread::park();+ continue;+ };+ // NB: An unpark this thread did not wait for makes the next park return at once, so this+ // goes by the clock.+ let now = Instant::now();+ if now < deadline {+ std::thread::park_timeout(deadline - now);+ continue;+ }+ // NB: The allocator keeps what a thread freed until the thread allocates again, which an idle+ // thread does not do. Standalone Rust tests do not link the C++ allocator.+ #[cfg(feature = "allocator")]+ ak::release_unused_allocator_memory();+ release_more();+ release_memory_at = None;+ };tsan::acquire(&shared.tsan_key);let mut next = Some(in_handed_order(last));while let Some(job) = next {@@ -148,6 +175,7 @@ impl StageThread {(job.as_ref().run)(job, shared);}}+ release_memory_at = Some(Instant::now() + IDLE_MEMORY_RELEASE_DELAY);}}).expect("a stage thread could not be started");@@ -886,7 +914,12 @@ static RENDER_THREAD: OnceLock<StageThread> = OnceLock::new();/// The Render thread, which runs the jobs on every document's render state that the host does not run itself.pub(crate) fn render_thread() -> &'static StageThread {- RENDER_THREAD.get_or_init(|| StageThread::spawn("Render"))+ RENDER_THREAD.get_or_init(|| {+ StageThread::spawn(+ "Render",+ crate::render_state::release_unused_memory_of_style_layout_threads,+ )+ })}#[cfg(test)]@@ -896,7 +929,7 @@ mod tests {fn test_thread() -> &'static StageThread {static THREAD: OnceLock<StageThread> = OnceLock::new();- THREAD.get_or_init(|| StageThread::spawn("Test"))+ THREAD.get_or_init(|| StageThread::spawn("Test", || {}))}impl Flown for std::thread::ThreadId {