Skip to content

Truly independent web browser

LibWeb: Let the runs of a layout pass share it across threads

Aliaksandr Kalenik55eaad5a0a73
diff --git a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
index afceb73a3aa..27c0508561c 100644
--- a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
@@ -2190,9 +2190,9 @@ fn execute_formatting_context_run(
};
let fragments = builds_fragments.then(|| {
fragment_tree::RunFragmentBuilder::new(
+ &callbacks,
box_,
(!root_containing_block.is_invalid()).then_some(root_containing_block),
- &callbacks,
)
});
let (outputs, root_cells_left_by_run) = RunState::with_root_building_fragments(
@@ -3681,7 +3681,7 @@ fn compute_root_layout(input: LayoutStageInput<'_>, should_collect_devtools_layo
Node::INVALID,
None,
Some(fragment_tree::RunFragmentBuilder::new_entry_accumulator(
- root, &callbacks,
+ &callbacks, root,
)),
|entry_run_state, callbacks| {
let _trace = scratch.layout_trace.pass(None);
@@ -3844,7 +3844,7 @@ fn compute_subtree_layout_fragments(input: LayoutStageInput<'_>, containing_bloc
entry_root_containing_block,
None,
Some(fragment_tree::RunFragmentBuilder::new_entry_accumulator(
- entry_root, &callbacks,
+ &callbacks, entry_root,
)),
|entry_run_state, callbacks| {
let _trace = scratch.layout_trace.pass(Some(root));
diff --git a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
index 5704e0079e0..aad179e488e 100644
--- a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
+++ b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
@@ -491,7 +491,7 @@ impl Default for PlacedBoxSlot {
}
#[derive(Default)]
-struct FragmentBuilderBuffers {
+pub(super) struct FragmentBuilderBuffers {
pending_fragments: HashMap<u32, PendingFragment>,
placed_boxes: PlacedBoxes,
}
@@ -499,8 +499,21 @@ struct FragmentBuilderBuffers {
#[derive(Default)]
pub(crate) struct FragmentBuilderScratch {
placed_box_slots: super::pass_column::PassColumn<PlacedBoxSlot>,
- builders_created: std::cell::Cell<u64>,
- spare_buffers: std::cell::RefCell<Vec<FragmentBuilderBuffers>>,
+}
+
+fn next_unique_identity(worker: &super::layout_pass::WorkerScratch) -> u64 {
+ const IDENTITIES_PER_RESERVATION: u64 = 1024;
+ static NEXT_UNRESERVED_IDENTITY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+ let reserved = &worker.reserved_unique_identities;
+ let mut identities = reserved.replace(0..0);
+ if identities.is_empty() {
+ let first =
+ NEXT_UNRESERVED_IDENTITY.fetch_add(IDENTITIES_PER_RESERVATION, std::sync::atomic::Ordering::Relaxed);
+ identities = first..first + IDENTITIES_PER_RESERVATION;
+ }
+ let identity = identities.start;
+ reserved.set(identity + 1..identities.end);
+ identity
}
impl FragmentBuilderScratch {
@@ -530,20 +543,18 @@ impl FragmentBuilderScratch {
pub(super) fn cover_slots(&mut self, slot_count: usize) {
self.placed_box_slots.cover_slots(slot_count);
}
+}
- fn next_builder_id(&self) -> u64 {
- let builder = self.builders_created.get() + 1;
- self.builders_created.set(builder);
- builder
- }
-
- fn take_spare_buffers(&self) -> FragmentBuilderBuffers {
- self.spare_buffers.borrow_mut().pop().unwrap_or_default()
- }
+fn take_spare_fragment_builder_buffers(worker: &super::layout_pass::WorkerScratch) -> FragmentBuilderBuffers {
+ worker
+ .spare_fragment_builder_buffers
+ .borrow_mut()
+ .pop()
+ .unwrap_or_default()
+}
- fn return_spare_buffers(&self, buffers: FragmentBuilderBuffers) {
- self.spare_buffers.borrow_mut().push(buffers);
- }
+fn return_spare_fragment_builder_buffers(worker: &super::layout_pass::WorkerScratch, buffers: FragmentBuilderBuffers) {
+ worker.spare_fragment_builder_buffers.borrow_mut().push(buffers);
}
pub(crate) struct PlacementsOfBuilder<'scratch> {
@@ -697,7 +708,6 @@ fn snapshot_fragment(
fragment_facts: run_state::FragmentFactsDecidedByParent,
payloads: Option<Box<FragmentPayloads>>,
) -> std::sync::Arc<Fragment> {
- static NEXT_IDENTITY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let FragmentGeometry { cells, line_data } = geometry;
let FragmentPayloads {
collapsed_table_borders,
@@ -759,7 +769,7 @@ fn snapshot_fragment(
}
return std::sync::Arc::new(previous.with_scrollable_overflow(fragment.scrollable_overflow));
}
- fragment.identity = NEXT_IDENTITY.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ fragment.identity = next_unique_identity(callbacks.worker_scratch());
std::sync::Arc::new(fragment)
}
@@ -1120,36 +1130,36 @@ impl RunFragmentBuilderInner {
impl RunFragmentBuilder {
pub(crate) fn new(
+ callbacks: &LayoutPass<'_>,
root_node: crate::layout::node_data::NodeSlotId,
root_containing_block: Option<crate::layout::node_data::NodeSlotId>,
- callbacks: &LayoutPass<'_>,
) -> Self {
- Self::with_scratch(
+ Self::with_spare_buffers(
+ callbacks.worker_scratch(),
root_node,
root_containing_block.map(|node| node.slot_index()),
false,
- callbacks,
)
}
pub(crate) fn new_entry_accumulator(
- root_node: crate::layout::node_data::NodeSlotId,
callbacks: &LayoutPass<'_>,
+ root_node: crate::layout::node_data::NodeSlotId,
) -> Self {
- Self::with_scratch(root_node, None, true, callbacks)
+ Self::with_spare_buffers(callbacks.worker_scratch(), root_node, None, true)
}
- fn with_scratch(
+ fn with_spare_buffers(
+ worker: &super::layout_pass::WorkerScratch,
root_node: crate::layout::node_data::NodeSlotId,
root_containing_block_slot: Option<u32>,
is_entry_accumulator: bool,
- callbacks: &LayoutPass<'_>,
) -> Self {
- let builder = callbacks.fragment_builder_scratch().next_builder_id();
+ let builder = next_unique_identity(worker);
let FragmentBuilderBuffers {
pending_fragments,
placed_boxes,
- } = callbacks.fragment_builder_scratch().take_spare_buffers();
+ } = take_spare_fragment_builder_buffers(worker);
Self {
root_node,
root_containing_block_slot,
@@ -1991,12 +2001,13 @@ impl RunFragmentBuilder {
let mut placed_boxes = std::mem::take(&mut inner.placed_boxes);
placed_boxes.placed_slots.clear();
placed_boxes.cells_of_abspos_containing_blocks.clear();
- callbacks
- .fragment_builder_scratch()
- .return_spare_buffers(FragmentBuilderBuffers {
+ return_spare_fragment_builder_buffers(
+ callbacks.worker_scratch(),
+ FragmentBuilderBuffers {
pending_fragments,
placed_boxes,
- });
+ },
+ );
RunContents {
node: self.root_node,
scoped_descendants: inner.top_scope_links,
diff --git a/Libraries/LibWeb/Rust/src/layout/layout_pass.rs b/Libraries/LibWeb/Rust/src/layout/layout_pass.rs
index e58a149b133..41c8247d7ae 100644
--- a/Libraries/LibWeb/Rust/src/layout/layout_pass.rs
+++ b/Libraries/LibWeb/Rust/src/layout/layout_pass.rs
@@ -43,6 +43,60 @@ pub(crate) struct LayoutPass<'arena> {
/// The innermost of the position options the boxes this pass view lays out are laid out with.
position_option_styles: Option<&'arena PositionOptionStyle<'arena>>,
records_trace: bool,
+ worker_scratch: WorkerScratchOfThisThread,
+}
+
+const _: () = {
+ const fn assert_send_and_sync<T: Send + Sync>() {}
+ assert_send_and_sync::<LayoutPass<'static>>();
+};
+
+#[derive(Default)]
+pub(crate) struct WorkerScratch {
+ pub(super) spare_fragment_builder_buffers: std::cell::RefCell<Vec<super::fragment_tree::FragmentBuilderBuffers>>,
+ pub(super) reserved_unique_identities: std::cell::Cell<std::ops::Range<u64>>,
+ inline_content_preparation_buffers:
+ std::cell::Cell<super::prepared_inline_content::InlineContentPreparationBuffers>,
+}
+
+thread_local! {
+ static WORKER_SCRATCH_OF_THIS_THREAD: WorkerScratch = WorkerScratch::default();
+}
+
+#[derive(Clone, Copy)]
+struct WorkerScratchOfThisThread {
+ scratch: std::ptr::NonNull<WorkerScratch>,
+ #[cfg(debug_assertions)]
+ thread: std::thread::ThreadId,
+}
+
+// SAFETY: A pass view reaches the worker scratch of the thread it was pointed at only on that thread: a pass view
+// handed to a task on another thread is first pointed at the scratch of that thread (debug builds check the thread on
+// every use).
+unsafe impl Send for WorkerScratchOfThisThread {}
+// SAFETY: As above.
+unsafe impl Sync for WorkerScratchOfThisThread {}
+
+impl WorkerScratchOfThisThread {
+ fn get() -> Self {
+ WORKER_SCRATCH_OF_THIS_THREAD.with(|scratch| Self {
+ scratch: std::ptr::NonNull::from(scratch),
+ #[cfg(debug_assertions)]
+ thread: std::thread::current().id(),
+ })
+ }
+
+ #[inline]
+ fn scratch(&self) -> &WorkerScratch {
+ #[cfg(debug_assertions)]
+ assert_eq!(
+ self.thread,
+ std::thread::current().id(),
+ "a pass view reaches the worker scratch of another thread"
+ );
+ // SAFETY: The scratch lives as long as its thread, on which alone it is reached (see the Send impl).
+ unsafe { self.scratch.as_ref() }
+ }
}
/// The style a box is laid out with in place of the style of its row: that of one of its position options. It links to
@@ -76,9 +130,15 @@ impl<'arena> LayoutPass<'arena> {
reads_no_memoized_layout: false,
position_option_styles: None,
records_trace: scratch.layout_trace.is_recording(),
+ worker_scratch: WorkerScratchOfThisThread::get(),
}
}
+ #[inline]
+ pub(super) fn worker_scratch(&self) -> &WorkerScratch {
+ self.worker_scratch.scratch()
+ }
+
/// A pass over `arena` and `scratch` with no viewport, in no-quirks mode.
#[cfg(test)]
pub(crate) fn for_test(
@@ -268,14 +328,14 @@ impl<'arena> LayoutPass<'arena> {
pub(crate) fn take_inline_content_preparation_buffers(
&self,
) -> super::prepared_inline_content::InlineContentPreparationBuffers {
- self.scratch.inline_content_preparation_buffers().take()
+ self.worker_scratch().inline_content_preparation_buffers.take()
}
pub(crate) fn return_inline_content_preparation_buffers(
&self,
buffers: super::prepared_inline_content::InlineContentPreparationBuffers,
) {
- self.scratch.inline_content_preparation_buffers().set(buffers);
+ self.worker_scratch().inline_content_preparation_buffers.set(buffers);
}
/// Runs `read` with the grapheme segmenter of the text row `node`.
diff --git a/Libraries/LibWeb/Rust/src/layout/pass_column.rs b/Libraries/LibWeb/Rust/src/layout/pass_column.rs
index 4002685b94b..402752f140b 100644
--- a/Libraries/LibWeb/Rust/src/layout/pass_column.rs
+++ b/Libraries/LibWeb/Rust/src/layout/pass_column.rs
@@ -54,6 +54,24 @@ pub(crate) struct PassColumn<T> {
chunks: Vec<OwnedChunk<T>>,
}
+// SAFETY: A pass writes a row only from the run that lays out the row's box. The runs laid out at once on several
+// threads lay out disjoint subtrees, and outside their own subtree they only read the rows of their ancestors, whose
+// runs wait for them. So no row is written while another thread reaches it, and rows several threads read at once are
+// Sync. Debug builds check that no row is written while it is reached otherwise.
+unsafe impl<T: Send + Sync> Sync for PassColumn<T> {}
+
+#[derive(Default)]
+pub(crate) struct ExclusiveRow<T>(T);
+
+// SAFETY: An ExclusiveRow hands out its contents only through a mutable reference, so threads never share them.
+unsafe impl<T: Send> Sync for ExclusiveRow<T> {}
+
+impl<T> ExclusiveRow<T> {
+ pub(crate) fn get_mut(&mut self) -> &mut T {
+ &mut self.0
+ }
+}
+
impl<T> Default for PassColumn<T> {
fn default() -> Self {
Self { chunks: Vec::new() }
diff --git a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
index 14d7fdb186f..d86aca50e4c 100644
--- a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
+++ b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
@@ -221,7 +221,8 @@ impl TextContent {
pub(crate) struct TextMemos {
/// Written in place, while a fork of the arena reads them as they were when it was made.
chunks: super::pass_column::ForkSharedRows<Option<ChunksOfText>>,
- grapheme_segmenters: super::pass_column::PassColumn<Option<GraphemeSegmenterOfText>>,
+ grapheme_segmenters:
+ super::pass_column::PassColumn<super::pass_column::ExclusiveRow<Option<GraphemeSegmenterOfText>>>,
}
/// The chunks a run made of a row's rendered text, and that text.
@@ -290,6 +291,7 @@ impl TextMemos {
read: impl FnOnce(&super::text_chunker::GraphemeSegmenter) -> R,
) -> R {
self.grapheme_segmenters.with_row_mut(text_state as usize, |memo| {
+ let memo = memo.get_mut();
if !memo.as_ref().is_some_and(|memo| Arc::ptr_eq(&memo.rendered, rendered)) {
*memo = Some(GraphemeSegmenterOfText {
segmenter: super::text_chunker::GraphemeSegmenter::new(&rendered.text),
@@ -310,7 +312,7 @@ impl TextMemos {
let index = text_state as usize;
self.chunks.reset_row_where(index, Option::is_some);
if let Some(segmenter) = self.grapheme_segmenters.row_mut(index) {
- *segmenter = None;
+ *segmenter.get_mut() = None;
}
}
}
diff --git a/Libraries/LibWeb/Rust/src/layout/run_state.rs b/Libraries/LibWeb/Rust/src/layout/run_state.rs
index 09082ca2837..82ce3ccc588 100644
--- a/Libraries/LibWeb/Rust/src/layout/run_state.rs
+++ b/Libraries/LibWeb/Rust/src/layout/run_state.rs
@@ -22,7 +22,6 @@ pub(crate) struct LayoutScratch {
pub(super) layout_trace: super::trace::LayoutTrace,
/// The chunks and grapheme segmenters of the text rows the passes laid out.
text_memos: super::rendered_text::TextMemos,
- inline_content_preparation_buffers: Cell<super::prepared_inline_content::InlineContentPreparationBuffers>,
prepared_inline_content_memos: super::prepared_inline_content::PreparedInlineContentMemos,
fragment_builder_scratch: fragment_tree::FragmentBuilderScratch,
}
@@ -138,10 +137,10 @@ impl HostFindings {
}
}
-// The scratch can move to the thread a layout stage runs on.
+// The scratch can move to the thread a layout stage runs on, and the runs of a pass can share it across threads.
const _: () = {
- const fn assert_send<T: Send>() {}
- assert_send::<LayoutScratch>();
+ const fn assert_send_and_sync<T: Send + Sync>() {}
+ assert_send_and_sync::<LayoutScratch>();
};
impl LayoutScratch {
@@ -177,12 +176,6 @@ impl LayoutScratch {
&self.prepared_inline_content_memos
}
- pub(super) fn inline_content_preparation_buffers(
- &self,
- ) -> &Cell<super::prepared_inline_content::InlineContentPreparationBuffers> {
- &self.inline_content_preparation_buffers
- }
-
/// Brings the run memos up to date with what the arena's writes since the last call did to their boxes.
pub(super) fn apply_memo_invalidations(&mut self, arena: &mut LayoutNodeArena) {
let slot_count = arena.slot_capacity();
diff --git a/Libraries/LibWeb/Rust/src/layout/trace.rs b/Libraries/LibWeb/Rust/src/layout/trace.rs
index e6033c804ac..78e1d474080 100644
--- a/Libraries/LibWeb/Rust/src/layout/trace.rs
+++ b/Libraries/LibWeb/Rust/src/layout/trace.rs
@@ -10,7 +10,6 @@ use super::layout_node_arena::IntrinsicSizeCacheKind;
use super::node_data::{NodeFlag, NodeKind, NodeSlotId};
use crate::render_state::DocumentHost;
use crate::stage::MainThread;
-use std::cell::RefCell;
use std::ffi::c_void;
use std::fmt::Write;
@@ -44,8 +43,8 @@ struct Line {
pub(crate) struct TraceRecord(Option<Trace>);
/// What a layout pass records its events into: the trace it took over from the document.
-#[derive(Clone, Default)]
-pub(crate) struct LayoutTrace(RefCell<Option<Trace>>);
+#[derive(Default)]
+pub(crate) struct LayoutTrace(std::sync::Mutex<Option<Trace>>);
/// The events traced while a scope lives nest under the line that opened it.
pub(super) struct Scope<'a> {
@@ -56,7 +55,7 @@ pub(super) struct Scope<'a> {
impl Scope<'_> {
/// Adds `text` to the end of the line that opened the scope.
pub(super) fn append(&self, text: &str) {
- self.trace.0.borrow_mut().as_mut().unwrap().lines[self.line]
+ self.trace.state().as_mut().unwrap().lines[self.line]
.text
.push_str(text);
}
@@ -64,7 +63,7 @@ impl Scope<'_> {
impl Drop for Scope<'_> {
fn drop(&mut self) {
- self.trace.0.borrow_mut().as_mut().unwrap().depth -= 1;
+ self.trace.state().as_mut().unwrap().depth -= 1;
}
}
@@ -139,15 +138,19 @@ impl TraceRecord {
}
impl LayoutTrace {
+ fn state(&self) -> std::sync::MutexGuard<'_, Option<Trace>> {
+ self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
+ }
+
#[cfg(test)]
fn begin(&self) {
- let begun = begun_trace(self.0.borrow().as_ref());
- *self.0.borrow_mut() = Some(begun);
+ let begun = begun_trace(self.state().as_ref());
+ *self.state() = Some(begun);
}
#[cfg(test)]
fn take(&self) -> String {
- text_of(self.0.borrow_mut().take())
+ text_of(self.state().take())
}
fn scope(
@@ -156,7 +159,7 @@ impl LayoutTrace {
owner: Option<NodeSlotId>,
text: impl FnOnce() -> String,
) -> Option<Scope<'_>> {
- let mut state = self.0.borrow_mut();
+ let mut state = self.state();
let trace = state.as_mut()?;
let line = trace.lines.len();
trace.lines.push(Line {
@@ -171,17 +174,17 @@ impl LayoutTrace {
}
pub(super) fn is_recording(&self) -> bool {
- self.0.borrow().is_some()
+ self.state().is_some()
}
/// Takes over the trace the document kept in `record`, for a pass to go on with it.
pub(super) fn take_over_from(&self, record: &mut TraceRecord) {
- *self.0.borrow_mut() = record.0.take();
+ *self.state() = record.0.take();
}
/// Hands the trace back to `record` once the pass is over.
pub(super) fn hand_back_to(&self, record: &mut TraceRecord) {
- record.0 = self.0.take();
+ record.0 = self.state().take();
}
pub(super) fn pass(&self, partial_root: Option<NodeSlotId>) -> Option<Scope<'_>> {
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index 1f853016259..3938dcfff3d 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -108,7 +108,7 @@ RENDER_STATE_ALLOWED = {
"css/declaration_block.rs:NEXT_DECLARATION_BLOCK_IDENTITY",
"css/rule.rs:NEXT_RULE_IDENTITY",
"css/style_sheet.rs:NEXT_SHEET_IDENTITY",
- "layout/fragment_tree.rs:NEXT_IDENTITY",
+ "layout/fragment_tree.rs:NEXT_UNRESERVED_IDENTITY",
"render_state/owner.rs:NEXT",
],
),
@@ -125,6 +125,7 @@ RENDER_STATE_ALLOWED = {
["render_state/owner.rs:DROPPED_AFTER_HOLD"],
),
f"{RENDER_STATE_CRATE}/src/render_state.rs:STACK_BASE": "per-thread cache of the thread's own stack bounds",
+ f"{RENDER_STATE_CRATE}/src/layout/layout_pass.rs:WORKER_SCRATCH_OF_THIS_THREAD": "per-thread spare layout buffers and the fragment identities the thread reserved; a thread without one only allocates more and reserves another range",
f"{RENDER_STATE_CRATE}/src/stage_thread.rs:UNFINISHED_HANDED": "per-thread count of the jobs the thread made for each stage thread that have yet to run",
**render_state_entries(
BUILT_ONCE,