Skip to content

Truly independent web browser

LibWeb: Move the style thread pool out of the style engine

Aliaksandr Kalenik32420a01ac98
diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
index 302b17f4897..6056aaaacdb 100644
--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
@@ -1606,7 +1606,7 @@ impl StyleEngine {
live_style_may_start: crate::fork::ForkReset::original(),
cold_passes: std::sync::Arc::default(),
live_counters: Default::default(),
- style_pool: None,
+ style_layout_pool: None,
substituted_font_values: std::sync::Arc::default(),
element_declarations: Default::default(),
projection: Default::default(),
@@ -2510,7 +2510,7 @@ impl RetainedState {
cold_passes: _,
// The last pass's elements, which a reader leaves out where they departed.
live_counters: _,
- style_pool: _,
+ style_layout_pool: _,
substituted_font_values: _,
// Forgotten for departed elements in `forget_departed_elements`.
element_declarations: _,
diff --git a/Libraries/LibWeb/Rust/src/css/style/mod.rs b/Libraries/LibWeb/Rust/src/css/style/mod.rs
index 9f2ba8f9c42..0e4915e94b7 100644
--- a/Libraries/LibWeb/Rust/src/css/style/mod.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/mod.rs
@@ -336,7 +336,7 @@ pub struct RetainedState {
live_counters: pipeline::counters::Counters,
/// The threads style passes run on, which the process shares where a render state holds the
/// engine.
- style_pool: Option<std::sync::Arc<pipeline::pool::StylePool>>,
+ style_layout_pool: Option<std::sync::Arc<crate::style_layout_pool::StyleLayoutPool>>,
/// The font longhand values the engine substituted, one value per property and content: the
/// font resolver knows a family and its feature values by their values' identities.
substituted_font_values: std::sync::Arc<std::sync::Mutex<Vec<(u16, RetainedStyleValueData)>>>,
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/install.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/install.rs
index e636b0db08f..ba57dbdf27d 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/install.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/install.rs
@@ -247,7 +247,7 @@ impl RetainedState {
.filter(|&(_, &node)| self.computed_group_sets.assigned_style_record(node).is_some())
.filter_map(|(index, &node)| Some((index, live.demanded_record(node)?)))
.collect();
- let pool = self.style_pool.as_ref().and_then(|pool| pool.started());
+ let pool = self.style_layout_pool.as_ref().and_then(|pool| pool.started());
let answers: Vec<u32> = match pool.as_deref() {
Some(pool) if moving.len() > ELEMENTS_PER_TASK => {
use rayon::prelude::*;
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
index 03ea320a782..6e76cb8136d 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
@@ -166,9 +166,9 @@ struct LiveScratch {
/// The cells passes write their records to.
cells: RecordCells,
/// What a changed element matches, by thread, for the threads that followed a change.
- memos: super::pool::PerThread<FollowScratch>,
+ memos: super::per_thread::PerThread<FollowScratch>,
/// The group caches the passes keep for the next, by thread, for the threads that styled.
- groups: super::pool::PerThread<super::compute::GroupCache>,
+ groups: super::per_thread::PerThread<super::compute::GroupCache>,
/// The matched declarations cache the passes keep for the next.
matched_declarations: super::matched_declarations::MatchedDeclarationsCache,
/// The inputs of the document the entries of the matched declarations cache read, as they
@@ -1748,7 +1748,7 @@ impl Live {
}
let by_element = &*by_element;
const CHANGES_PER_TASK: usize = 8;
- let pool = state.style_pool.as_ref().and_then(|pool| pool.started());
+ let pool = state.style_layout_pool.as_ref().and_then(|pool| pool.started());
let follow_all = |chunk: &[std::ops::Range<usize>]| {
let thread = pool.as_ref().and_then(|pool| pool.current_thread_index());
let memo = self
@@ -4150,7 +4150,7 @@ impl StyleEngine {
{
return;
}
- self.start_live_style(root, super::pool::threads_from_environment(), true);
+ self.start_live_style(root, crate::style_layout_pool::threads_from_environment(), true);
}
/// Have the engine own the document under `root` from a cold pass of it, with what the cold
@@ -4183,7 +4183,7 @@ impl StyleEngine {
// NB: How many threads the machine has is asked once, as the engine starts: the answer reads the
// process's CPU affinity and quota from the kernel, which takes longer than a small pass does.
let threads = match threads {
- 0 => traversal::thread_count() as u32,
+ 0 => crate::style_layout_pool::default_thread_count() as u32,
threads => threads,
};
let index = RuleIndex::build(&self.retained.rules, self.retained.process_rule_indexes());
@@ -4463,7 +4463,7 @@ impl StyleEngine {
fn live_pass_rounds(&mut self, root: StyleNodeID, everything: bool) {
let threads = self.retained.live_style.as_ref().map_or(0, |live| live.threads);
- let pool = self.style_pool(threads);
+ let pool = self.style_layout_pool(threads);
// NB: A thread that first asks for a font resolves it there and then, under a lock, rather than leave it for a
// round between all the threads of the pass, each a barrier.
self.retained.pass_fonts = self
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs
index 3d0df82c2ab..3599f5e9c34 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs
@@ -37,7 +37,7 @@ mod matched_rules;
mod matching;
mod pending_inputs;
pub(super) use pending_inputs::HoverSealMemo;
-pub(crate) mod pool;
+pub(crate) mod per_thread;
pub(in crate::css::style) mod projection;
mod records;
mod rule_changes;
@@ -248,17 +248,17 @@ impl StyleEngine {
}
/// Has style passes run on the threads of `pool`, which the process shares.
- pub(crate) fn share_style_pool(&mut self, pool: std::sync::Arc<pool::StylePool>) {
- self.retained.style_pool = Some(pool);
+ pub(crate) fn share_style_layout_pool(&mut self, pool: std::sync::Arc<crate::style_layout_pool::StyleLayoutPool>) {
+ self.retained.style_layout_pool = Some(pool);
}
/// The pool a pass on `threads` threads runs on besides the calling thread, or on the default
/// number for the machine for none.
- fn style_pool(&mut self, threads: u32) -> Option<std::sync::Arc<rayon::ThreadPool>> {
+ fn style_layout_pool(&mut self, threads: u32) -> Option<std::sync::Arc<rayon::ThreadPool>> {
// NB: An engine no render state holds, such as a test's, starts threads of its own.
self.retained
- .style_pool
- .get_or_insert_with(|| std::sync::Arc::new(pool::StylePool::of_engine()))
+ .style_layout_pool
+ .get_or_insert_with(|| std::sync::Arc::new(crate::style_layout_pool::StyleLayoutPool::of_engine()))
.for_threads(threads)
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/per_thread.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/per_thread.rs
new file mode 100644
index 00000000000..f6dc9bed576
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/per_thread.rs
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::sync::Mutex;
+
+/// What each thread a pass runs on keeps between passes, by thread, the calling thread's last: a slot is made the first
+/// time its thread asks for it, so a document, or a fork of its render state, holds only what its threads used.
+pub(super) struct PerThread<T>([std::sync::OnceLock<Box<Mutex<T>>>; crate::style_layout_pool::MAX_THREAD_COUNT + 1]);
+
+impl<T> Default for PerThread<T> {
+ fn default() -> Self {
+ Self(std::array::from_fn(|_| std::sync::OnceLock::new()))
+ }
+}
+
+impl<T: Default> PerThread<T> {
+ /// What thread `index` keeps, made where it is not yet, or none past the last thread.
+ pub(super) fn get(&self, index: usize) -> Option<&Mutex<T>> {
+ self.0.get(index).map(|slot| &**slot.get_or_init(Box::default))
+ }
+
+ /// What the threads that asked keep.
+ pub(super) fn made(&self) -> impl Iterator<Item = &Mutex<T>> {
+ self.0.iter().filter_map(|slot| slot.get().map(|made| &**made))
+ }
+
+ /// How many threads may keep anything.
+ pub(super) fn len(&self) -> usize {
+ self.0.len()
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/self_check.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/self_check.rs
index ae0b440a58d..9e870dd19dd 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/self_check.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/self_check.rs
@@ -65,7 +65,7 @@ impl SelfCheckSettings {
/// How many threads the self-check's cold passes on several threads run on.
fn reference_thread_count() -> u32 {
- traversal::thread_count().max(4) as u32
+ crate::style_layout_pool::default_thread_count().max(4) as u32
}
/// The names of the groups, by `group_index`.
@@ -509,7 +509,7 @@ pub(super) fn reference_pass(
) -> Option<ReferencePass> {
let initial = engine.computed_initial(root)?;
// NB: A pass on one thread leaves the engine's pool as it is.
- let pool = (threads > 1).then(|| engine.style_pool(threads)).flatten();
+ let pool = (threads > 1).then(|| engine.style_layout_pool(threads)).flatten();
let started = Instant::now();
let index = RuleIndex::build(&engine.retained.rules, engine.retained.process_rule_indexes());
let index_nanoseconds = started.elapsed().as_nanos() as u64;
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
index 21b4890e307..f90e6bf879f 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
@@ -48,24 +48,6 @@ mod cache_audit;
pub(super) use cache_audit::CacheAudit;
pub(super) use cache_audit::mode_from_environment as cache_audit_mode_from_environment;
-/// The most threads the traversal runs on, however many are asked for.
-pub(super) const MAX_THREAD_COUNT: usize = 16;
-
-/// The most threads the traversal runs on where none are asked for. Beyond this many, passes over
-/// a thousand elements take no less time, while each thread more faults in pages of its own and
-/// keeps a stack and an allocator heap.
-const DEFAULT_MAX_THREAD_COUNT: usize = 8;
-
-/// How many threads the traversal runs on where none are asked for: three of every four logical
-/// processors, leaving the others to the main thread and the rest of the process, and at least one.
-pub(super) fn thread_count() -> usize {
- // NB: Each pass asks, and the answer takes system calls and reading files of the control groups.
- static THREAD_COUNT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
- *THREAD_COUNT.get_or_init(|| {
- std::thread::available_parallelism().map_or(1, |count| (count.get() * 3 / 4).clamp(1, DEFAULT_MAX_THREAD_COUNT))
- })
-}
-
/// How many elements a task hands to another at once.
const WORK_UNIT: usize = 16;
@@ -282,7 +264,7 @@ pub(super) struct PassContext<'a> {
/// The group caches of the threads, by thread, which a pass keeps for the next where it
/// keeps its caches: an element restyled in a later pass finds the groups the elements styled
/// before it built.
- pub(super) group_caches: Option<&'a super::pool::PerThread<super::compute::GroupCache>>,
+ pub(super) group_caches: Option<&'a super::per_thread::PerThread<super::compute::GroupCache>>,
/// The matched declarations cache a pass keeps for the next, where it keeps its caches.
pub(super) kept_matched_declarations: Option<&'a MatchedDeclarationsCache>,
/// The cache of a pass that keeps none for the next.
diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rs
index 8f2e62fde20..46675d36979 100644
--- a/Libraries/LibWeb/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Rust/src/lib.rs
@@ -29,6 +29,7 @@ pub(crate) mod painting;
pub(crate) mod render_state;
pub(crate) mod stage;
pub(crate) mod stage_thread;
+pub(crate) mod style_layout_pool;
pub(crate) mod svg;
// What libweb_bindings_rust, whose interfaces are implemented in Rust, uses of this crate.
diff --git a/Libraries/LibWeb/Rust/src/render_state.rs b/Libraries/LibWeb/Rust/src/render_state.rs
index bf25b26bffc..0e0e5543515 100644
--- a/Libraries/LibWeb/Rust/src/render_state.rs
+++ b/Libraries/LibWeb/Rust/src/render_state.rs
@@ -55,17 +55,17 @@ pub(crate) struct RenderState {
impl RenderState {
/// Makes the state `seed` describes, whose style engine shares `process_style` with the other documents', and whose
- /// style passes run on `style_pool`.
+ /// style passes run on `style_layout_pool`.
fn new(
seed: owner::StateSeed,
process_style: &std::sync::Arc<crate::css::style::ProcessStyle>,
- style_pool: &std::sync::Arc<crate::css::style::pipeline::pool::StylePool>,
+ style_layout_pool: &std::sync::Arc<crate::style_layout_pool::StyleLayoutPool>,
) -> Self {
let owner::StateSeed { shared } = seed;
let mut arena = Box::new(ArenaHandle::new());
let mut engine = Box::new(crate::css::style::StyleEngine::new());
engine.share_process_style(std::sync::Arc::clone(process_style));
- engine.share_style_pool(style_pool.clone());
+ engine.share_style_layout_pool(style_layout_pool.clone());
engine.share_element_random_base_values_exist(shared.element_random_base_values_exist);
engine.share_declaration_block_versions(shared.declaration_block_versions);
engine.share_container_effects_held(shared.container_effects_held);
diff --git a/Libraries/LibWeb/Rust/src/render_state/owner.rs b/Libraries/LibWeb/Rust/src/render_state/owner.rs
index 216b3bfd6fc..08a2003516d 100644
--- a/Libraries/LibWeb/Rust/src/render_state/owner.rs
+++ b/Libraries/LibWeb/Rust/src/render_state/owner.rs
@@ -79,8 +79,8 @@ struct Slot {
process_style: Arc<crate::css::style::ProcessStyle>,
/// What names the slot to ThreadSanitizer, which sees the ordering holding it gives only through it.
tsan_key: AtomicBool,
- /// The threads the style passes of every document run on besides the owner's.
- style_pool: Arc<crate::css::style::pipeline::pool::StylePool>,
+ /// The threads the style and layout passes of every document run on besides the owner's.
+ style_layout_pool: Arc<crate::style_layout_pool::StyleLayoutPool>,
}
// SAFETY: Only the thread that holds the slot reaches its states, which may cross threads, and holding it orders what
@@ -99,7 +99,7 @@ static SLOT: LazyLock<Slot> = LazyLock::new(|| Slot {
states: RefCell::new(HashMap::new()),
process_style: Arc::default(),
tsan_key: AtomicBool::new(false),
- style_pool: Arc::new(crate::css::style::pipeline::pool::StylePool::of_process()),
+ style_layout_pool: Arc::new(crate::style_layout_pool::StyleLayoutPool::of_process()),
});
/// The style data every document's style engine shares with the others, which any thread reaches without the slot: only
@@ -192,7 +192,7 @@ pub(super) fn with_state<R>(
let entry = match seed {
Some(seed) => states.entry(document).or_insert_with(|| {
Box::new(DocumentEntry {
- state: UnsafeCell::new(RenderState::new(seed, &SLOT.process_style, &SLOT.style_pool)),
+ state: UnsafeCell::new(RenderState::new(seed, &SLOT.process_style, &SLOT.style_layout_pool)),
lanes: Cell::default(),
job_runs_on_state: Cell::new(false),
})
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/pool.rs b/Libraries/LibWeb/Rust/src/style_layout_pool.rs
similarity index 64%
rename from Libraries/LibWeb/Rust/src/css/style/pipeline/pool.rs
rename to Libraries/LibWeb/Rust/src/style_layout_pool.rs
index 181ea8dec02..2830ef85f3b 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/pool.rs
+++ b/Libraries/LibWeb/Rust/src/style_layout_pool.rs
@@ -4,14 +4,32 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The threads style passes run on besides the calling thread. The owner of every document's
-//! render state holds one pool for the process and hands it to each document's style engine, so
-//! the documents of a process share their style threads, and the heaps those threads warm.
+//! The threads style and layout passes run on besides the calling thread. The owner of every document's render state
+//! holds one pool for the process and hands it to each document's style engine, so the documents of a process share
+//! these threads, and the heaps those threads warm.
use std::sync::{Arc, Mutex, PoisonError};
-/// The pool of threads style passes run on besides the calling thread.
-pub(crate) enum StylePool {
+/// The most threads a pass runs on, however many are asked for.
+pub(crate) const MAX_THREAD_COUNT: usize = 16;
+
+/// The most threads a pass runs on where none are asked for. Beyond this many, passes over
+/// a thousand elements take no less time, while each thread more faults in pages of its own and
+/// keeps a stack and an allocator heap.
+const DEFAULT_MAX_THREAD_COUNT: usize = 8;
+
+/// How many threads a pass runs on where none are asked for: three of every four logical
+/// processors, leaving the others to the main thread and the rest of the process, and at least one.
+pub(crate) fn default_thread_count() -> usize {
+ // NB: Each pass asks, and the answer takes system calls and reading files of the control groups.
+ static THREAD_COUNT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
+ *THREAD_COUNT.get_or_init(|| {
+ std::thread::available_parallelism().map_or(1, |count| (count.get() * 3 / 4).clamp(1, DEFAULT_MAX_THREAD_COUNT))
+ })
+}
+
+/// The pool of threads style and layout passes run on besides the calling thread.
+pub(crate) enum StyleLayoutPool {
/// The threads of the process, started with the owner of its render states, before any page can run script. How
/// many there are never changes after that. There are none where a pass runs on the calling thread alone.
OfProcess(Option<Arc<rayon::ThreadPool>>),
@@ -19,7 +37,7 @@ pub(crate) enum StylePool {
OfEngine(Mutex<Option<Arc<rayon::ThreadPool>>>),
}
-impl StylePool {
+impl StyleLayoutPool {
/// The threads of the process, which this starts: as many as `LIBWEB_STYLE_THREADS` asks for, or the default number
/// for the machine where it names no number of them.
pub(crate) fn of_process() -> Self {
@@ -63,7 +81,7 @@ impl StylePool {
}
/// How many threads `LIBWEB_STYLE_THREADS` asks passes to run on, or 0 where it names no number of them.
-pub(super) fn threads_from_environment() -> u32 {
+pub(crate) fn threads_from_environment() -> u32 {
std::env::var("LIBWEB_STYLE_THREADS")
.ok()
.and_then(|threads| threads.parse().ok())
@@ -74,8 +92,8 @@ pub(super) fn threads_from_environment() -> u32 {
/// number for the machine for none.
fn workers_for_threads(threads: u32) -> usize {
let threads = match threads {
- 0 => super::traversal::thread_count(),
- threads => (threads as usize).min(super::traversal::MAX_THREAD_COUNT),
+ 0 => default_thread_count(),
+ threads => (threads as usize).min(MAX_THREAD_COUNT),
};
threads.max(1) - 1
}
@@ -83,34 +101,7 @@ fn workers_for_threads(threads: u32) -> usize {
fn start_threads(workers: usize) -> rayon::ThreadPool {
rayon::ThreadPoolBuilder::new()
.num_threads(workers)
- .thread_name(|index| format!("StyleWorker {index}"))
+ .thread_name(|index| format!("StyleLayout {index}"))
.build()
- .expect("the engine thread pool starts")
-}
-
-/// What each thread a pass runs on keeps between passes, by thread, the calling thread's last: a slot is made the first
-/// time its thread asks for it, so a document, or a fork of its render state, holds only what its threads used.
-pub(super) struct PerThread<T>([std::sync::OnceLock<Box<Mutex<T>>>; super::traversal::MAX_THREAD_COUNT + 1]);
-
-impl<T> Default for PerThread<T> {
- fn default() -> Self {
- Self(std::array::from_fn(|_| std::sync::OnceLock::new()))
- }
-}
-
-impl<T: Default> PerThread<T> {
- /// What thread `index` keeps, made where it is not yet, or none past the last thread.
- pub(super) fn get(&self, index: usize) -> Option<&Mutex<T>> {
- self.0.get(index).map(|slot| &**slot.get_or_init(Box::default))
- }
-
- /// What the threads that asked keep.
- pub(super) fn made(&self) -> impl Iterator<Item = &Mutex<T>> {
- self.0.iter().filter_map(|slot| slot.get().map(|made| &**made))
- }
-
- /// How many threads may keep anything.
- pub(super) fn len(&self) -> usize {
- self.0.len()
- }
+ .expect("the style and layout thread pool starts")
}
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index 50e3f70fce5..1f853016259 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -135,7 +135,6 @@ RENDER_STATE_ALLOWED = {
"css/parser/stylesheet_cache.rs:HASHER",
"css/parser/stylesheet_cache.rs:KEYS",
"css/property_metadata.rs:SHORTHAND_LEAVES",
- "css/style/pipeline/traversal.rs:THREAD_COUNT",
"css/style_compute.rs:DIRECT",
"css/style_compute.rs:FONT_ORDER",
"css/style_compute.rs:FONT_PHASES",
@@ -145,6 +144,7 @@ RENDER_STATE_ALLOWED = {
"css/style_compute.rs:RANKS",
"css/style_compute.rs:REMAINING_ORDER",
"css/style_compute.rs:TABLE",
+ "style_layout_pool.rs:THREAD_COUNT",
],
),
**render_state_entries(