Truly independent web browser
LibWeb: Keep fork-shared layout memos in rows the host writes in place
Aliaksandr Kalenik092d0abc6fe0
diff --git a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rsindex 20049328c91..16f33bfb717 100644--- a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs+++ b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs@@ -443,9 +443,6 @@ const EARLIER_ENTRIES_PER_BOX: usize = 3;const LAYOUT_COMMITS_AN_UNCOMMITTED_ENTRY_SURVIVES_UNUSED: u64 = 2;-/// How many boxes' entries a chunk of [`FcRunCacheStore::slots`] holds: a write after a fork copies this many.-const FC_RUN_CACHE_SLOTS_PER_CHUNK: usize = 128;-#[derive(Clone, Copy, Default)]struct StoredEntrySummary {fragment_cache_epoch: u32,@@ -498,31 +495,45 @@ impl FcRunCacheSlot {/// Per-document store of completed run results, surviving across layout passes in the layout stage's scratch: per box/// the latest entry, the one whose fragments the box committed where a later store moved it aside, and a few earlier/// ones.-#[derive(Clone, Default)]+#[derive(Default)]pub(crate) struct FcRunCacheStore {- /// In chunks a fork of the arena shares until either side writes one, so forking does not copy every box's entries.- slots: RefCell<crate::cow_column::CowVec<FcRunCacheSlot, FC_RUN_CACHE_SLOTS_PER_CHUNK>>,+ /// Written in place, while a fork of the arena reads them as they were when it was made.+ slots: super::pass_column::ForkSharedRows<FcRunCacheSlot>,/// Noted between passes, and only read during one.inline_layout_damage: Vec<InlineLayoutDamage>,- pending_sweep_slots: RefCell<Vec<u32>>,- enrolled_for_sweep: RefCell<Vec<bool>>,+ queued_for_sweep: super::pass_column::PassFlags,}impl FcRunCacheStore {- pub(super) fn enqueue_for_sweep(&self, slot: u32) {- let mut enrolled = self.enrolled_for_sweep.borrow_mut();- if enrolled.len() <= slot as usize {- enrolled.resize(slot as usize + 1, false);- }- if !enrolled[slot as usize] {- enrolled[slot as usize] = true;- self.pending_sweep_slots.borrow_mut().push(slot);+ pub(super) fn fork(&self) -> Self {+ Self {+ slots: self.slots.fork(),+ inline_layout_damage: self.inline_layout_damage.clone(),+ queued_for_sweep: self.queued_for_sweep.copy(),}}+ pub(super) fn cover_slots(&mut self, slot_count: usize) {+ self.slots.cover_slots(slot_count);+ self.queued_for_sweep.cover_slots(slot_count);+ }++ pub(super) fn enqueue_for_sweep(&self, slot: u32) {+ self.queued_for_sweep.raise(slot as usize);+ }++ #[cfg(test)]+ fn for_test() -> Self {+ let mut store = Self::default();+ store.cover_slots(1024);+ store+ }+fn slot_holds_entries(&self, slot: u32) -> bool {- self.slots.borrow().get(slot as usize).is_some_and(|entries| {- entries.latest.is_some() || entries.committed.is_some() || !entries.earlier.is_empty()+ self.slots.with_row(slot as usize, |entries| {+ entries.is_some_and(|entries| {+ entries.latest.is_some() || entries.committed.is_some() || !entries.earlier.is_empty()+ })})}@@ -548,31 +559,32 @@ impl FcRunCacheStore {summary_allows: impl Fn(StoredEntrySummary) -> bool,mut answers: impl FnMut(&FcRunCacheEntry) -> bool,) -> Option<std::sync::Arc<FcRunCacheEntry>> {- let slots = self.slots.borrow();- let entries = slots.get(slot as usize)?;- if let Some(entry) = [- (&entries.committed, entries.committed_summary),- (&entries.latest, entries.latest_summary),- ]- .into_iter()- .filter(|(_, summary)| summary_allows(*summary))- .filter_map(|(entry, _)| entry.as_ref())- .find(|entry| answers(entry))- {- return Some(entry.clone());- }- entries- .earlier- .iter()- .filter(|entry| summary_allows(StoredEntrySummary::of(Some(entry))))+ self.slots.with_row(slot as usize, |entries| {+ let entries = entries?;+ if let Some(entry) = [+ (&entries.committed, entries.committed_summary),+ (&entries.latest, entries.latest_summary),+ ]+ .into_iter()+ .filter(|(_, summary)| summary_allows(*summary))+ .filter_map(|(entry, _)| entry.as_ref()).find(|entry| answers(entry))- .cloned()+ {+ return Some(entry.clone());+ }+ entries+ .earlier+ .iter()+ .filter(|entry| summary_allows(StoredEntrySummary::of(Some(entry))))+ .find(|entry| answers(entry))+ .cloned()+ })}pub(crate) fn remove_entry(&mut self, slot: u32) {- if self.slot_holds_entries(slot) {- self.slots.get_mut()[slot as usize] = FcRunCacheSlot::default();- }+ self.slots.reset_row_where(slot as usize, |entries| {+ entries.latest.is_some() || entries.committed.is_some() || !entries.earlier.is_empty()+ });self.forget_inline_layout_damage(slot);}@@ -665,35 +677,32 @@ impl FcRunCacheStore {) -> std::sync::Arc<FcRunCacheEntry> {let slot = box_.slot_index();entry.structural_epoch_bumps_when_stored = self.structural_epoch_bumps_of(box_);- let mut slots = self.slots.borrow_mut();- if slots.len() <= slot as usize {- slots.resize_with_default(slot as usize + 1);- }- let entries = &mut slots[slot as usize];- entries.earlier.retain(|earlier| earlier.key != entry.key);- let mut displaced = entries.committed.take_if(|committed| committed.key == entry.key);- match entries.latest.take() {- Some(latest) if latest.key == entry.key => displaced = Some(latest),- Some(latest) if is_committed(&latest) => {- displaced = entries.committed.replace(latest).or(displaced);- }- Some(latest) => {- let earlier = &mut entries.earlier;- if earlier.len() == EARLIER_ENTRIES_PER_BOX {- let oldest_result_only_or_oldest = earlier- .iter()- .rposition(|earlier| earlier.outputs.root.is_none())- .unwrap_or(EARLIER_ENTRIES_PER_BOX - 1);- displaced = Some(earlier.remove(oldest_result_only_or_oldest)).or(displaced);+ let stored = self.slots.with_row_mut(slot as usize, |entries| {+ entries.earlier.retain(|earlier| earlier.key != entry.key);+ let mut displaced = entries.committed.take_if(|committed| committed.key == entry.key);+ match entries.latest.take() {+ Some(latest) if latest.key == entry.key => displaced = Some(latest),+ Some(latest) if is_committed(&latest) => {+ displaced = entries.committed.replace(latest).or(displaced);+ }+ Some(latest) => {+ let earlier = &mut entries.earlier;+ if earlier.len() == EARLIER_ENTRIES_PER_BOX {+ let oldest_result_only_or_oldest = earlier+ .iter()+ .rposition(|earlier| earlier.outputs.root.is_none())+ .unwrap_or(EARLIER_ENTRIES_PER_BOX - 1);+ displaced = Some(earlier.remove(oldest_result_only_or_oldest)).or(displaced);+ }+ earlier.insert(0, latest);}- earlier.insert(0, latest);+ None => {}}- None => {}- }- let stored = shared_entry_in_allocation_of(displaced, entry);- entries.latest = Some(stored.clone());- entries.refresh_summaries();- drop(slots);+ let stored = shared_entry_in_allocation_of(displaced, entry);+ entries.latest = Some(stored.clone());+ entries.refresh_summaries();+ stored+ });// NB: Invalidation can occur between probing a run and storing its result.self.enqueue_for_sweep(slot);stored@@ -712,17 +721,12 @@ impl FcRunCacheStore {let Self {slots,inline_layout_damage,- pending_sweep_slots,- enrolled_for_sweep: enrolled,+ queued_for_sweep,} = self;- let slots = slots.get_mut();- let enrolled = enrolled.get_mut();- let pending_sweep_slots = pending_sweep_slots.get_mut();- let mut slots_holding_entries_that_may_go_unused = Vec::new();- for slot in pending_sweep_slots.drain(..) {- enrolled[slot as usize] = false;- let Some(entries) = slots.get_mut(slot as usize) else {- continue;+ queued_for_sweep.retain_raised_flags(|slot| {+ let slot = slot as u32;+ let Some(entries) = slots.row_mut(slot as usize) else {+ return false;};let mut earlier = std::mem::take(&mut entries.earlier);entries.committed.take_if(|committed| !keep(slot, committed.validity));@@ -733,8 +737,8 @@ impl FcRunCacheStore {if entries.latest.as_deref().is_some_and(&mut is_committed) {entries.committed = None;} else if let Some(index) = earlier.iter().position(|earlier| {- // NB: An earlier entry was not committed when a later store moved it aside, so only a replay since can- // have committed its fragments.+ // NB: An earlier entry was not committed when a later store moved it aside, so only a replay since+ // can have committed its fragments.earlier.was_used_by_the_last_layout(layout_commit_count) && is_committed(earlier)}) {entries.committed = Some(earlier.remove(index));@@ -750,12 +754,9 @@ impl FcRunCacheStore {if entries.latest.is_none() && !earlier.is_empty() {entries.latest = Some(earlier.remove(0));}- if earlier.iter().any(|earlier| earlier.holds_fragments())+ let may_go_unused = earlier.iter().any(|earlier| earlier.holds_fragments())|| (entries.committed.is_some()- && entries.latest.as_ref().is_some_and(|latest| latest.holds_fragments()))- {- slots_holding_entries_that_may_go_unused.push(slot);- }+ && entries.latest.as_ref().is_some_and(|latest| latest.holds_fragments()));entries.earlier = earlier;entries.refresh_summaries();if entries.latest.is_none()@@ -764,11 +765,8 @@ impl FcRunCacheStore {{*damage = InlineLayoutDamage::default();}- }- for slot in slots_holding_entries_that_may_go_unused {- enrolled[slot as usize] = true;- pending_sweep_slots.push(slot);- }+ may_go_unused+ });}}@@ -1105,7 +1103,10 @@ mod tests {}fn width_of_committed_entry(store: &FcRunCacheStore, slot: u32) -> Option<AvailableSize> {- store.slots.borrow()[slot as usize]+ store+ .slots+ .with_row(slot as usize, |entries| entries.cloned())+ .unwrap().committed.as_ref().map(|entry| entry.key.input.available_space.inline_size)@@ -1126,7 +1127,7 @@ mod tests {#[test]fn sweep_checks_changed_entries_without_discarding_reusable_stale_data_early() {- let mut store = FcRunCacheStore::default();+ let mut store = FcRunCacheStore::for_test();let entry = |epoch| entry(at(300), epoch, None, 0);store.store(Node::new(0, 1), entry(1), nothing_is_committed);store.store(Node::new(1, 1), entry(1), nothing_is_committed);@@ -1163,7 +1164,7 @@ mod tests {#[test]fn a_store_keeps_the_entry_whose_fragments_the_box_committed_beside_newer_ones() {- let mut store = FcRunCacheStore::default();+ let mut store = FcRunCacheStore::for_test();let box_ = Node::new(0, 1);store.store(box_,@@ -1194,7 +1195,7 @@ mod tests {#[test]fn the_sweep_keeps_the_entry_whose_fragments_the_box_committed_and_its_fragments() {- let mut store = FcRunCacheStore::default();+ let mut store = FcRunCacheStore::for_test();let box_ = Node::new(0, 1);store.store(box_,@@ -1207,7 +1208,10 @@ mod tests {nothing_is_committed,);store.sweep_pending_entries(|_, _| true, mark_entries_of_key(at(300)), 1);- let committed = store.slots.borrow()[0]+ let committed = store+ .slots+ .with_row(0, |entries| entries.cloned())+ .unwrap().committed.clone().expect("the earlier entry whose fragments the box committed moves beside the latest one");@@ -1236,7 +1240,7 @@ mod tests {#[test]fn an_earlier_entry_committed_in_place_of_the_latest_one_stays_beside_later_stores() {- let mut store = FcRunCacheStore::default();+ let mut store = FcRunCacheStore::for_test();let box_ = Node::new(0, 1);store.store(box_,@@ -1272,7 +1276,7 @@ mod tests {#[test]fn a_committed_entry_that_no_longer_describes_the_committed_subtree_goes() {- let mut store = FcRunCacheStore::default();+ let mut store = FcRunCacheStore::for_test();let box_ = Node::new(0, 1);store.store(box_,@@ -1292,7 +1296,7 @@ mod tests {#[test]fn entries_holding_fragments_the_box_never_committed_go_after_two_unused_layout_commits_beside_one_it_did() {- let mut store = FcRunCacheStore::default();+ let mut store = FcRunCacheStore::for_test();let box_ = Node::new(0, 1);store.store(box_,@@ -1330,7 +1334,7 @@ mod tests {#[test]fn the_latest_entry_of_a_box_that_committed_none_of_its_entries_stays() {- let mut store = FcRunCacheStore::default();+ let mut store = FcRunCacheStore::for_test();let box_ = Node::new(0, 1);store.store(box_,@@ -1345,7 +1349,7 @@ mod tests {#[test]fn earlier_entries_make_room_oldest_first_and_results_of_runs_without_fragments_first() {- let store = FcRunCacheStore::default();+ let store = FcRunCacheStore::for_test();let box_ = Node::new(0, 1);store.store(box_,@@ -1384,7 +1388,7 @@ mod tests {fn queued_memo_invalidations_count_structural_changes_only_while_the_box_holds_entries() {use crate::layout::in_flow_block_cache::InFlowBlockCacheStore;use crate::layout::memo_invalidations::MemoInvalidations;- let mut store = FcRunCacheStore::default();+ let mut store = FcRunCacheStore::for_test();let mut in_flow_block_cache = InFlowBlockCacheStore::default();let mut text_memos = crate::layout::rendered_text::TextMemos::default();let mut prepared_inline_content = crate::layout::prepared_inline_content::PreparedInlineContentMemos::default();@@ -1437,7 +1441,7 @@ mod tests {#[test]fn a_store_keeps_the_inline_damage_an_earlier_entry_saw() {- let mut store = FcRunCacheStore::default();+ let mut store = FcRunCacheStore::for_test();let box_ = Node::new(0, 1);store.store(box_,diff --git a/Libraries/LibWeb/Rust/src/layout/in_flow_block_cache.rs b/Libraries/LibWeb/Rust/src/layout/in_flow_block_cache.rsindex a79c5e88899..9c09ce48b2d 100644--- a/Libraries/LibWeb/Rust/src/layout/in_flow_block_cache.rs+++ b/Libraries/LibWeb/Rust/src/layout/in_flow_block_cache.rs@@ -86,16 +86,23 @@ struct InFlowBlockSlot {}/// Per-document store of in-flow block layouts, surviving across layout passes in the layout stage's scratch.-#[derive(Clone, Default)]+#[derive(Default)]pub(crate) struct InFlowBlockCacheStore {- /// In chunks a fork of the arena shares until either side writes one, so forking does not copy every box's entries.- entries: RefCell<crate::cow_column::CowVec<InFlowBlockSlot, IN_FLOW_BLOCK_SLOTS_PER_CHUNK>>,+ /// Written in place, while a fork of the arena reads them as they were when it was made.+ entries: super::pass_column::ForkSharedRows<InFlowBlockSlot>,}-/// How many boxes' entries a chunk of [`InFlowBlockCacheStore::entries`] holds: a write after a fork copies this many.-const IN_FLOW_BLOCK_SLOTS_PER_CHUNK: usize = 128;-impl InFlowBlockCacheStore {+ pub(super) fn fork(&self) -> Self {+ Self {+ entries: self.entries.fork(),+ }+ }++ pub(super) fn cover_slots(&mut self, slot_count: usize) {+ self.entries.cover_slots(slot_count);+ }+/// The stored layout of the box in `slot` for `key` that placed the fragment the box committed, `committed_identity`.pub(super) fn matching(&self,@@ -104,49 +111,42 @@ impl InFlowBlockCacheStore {key: &InFlowBlockKey,committed_identity: u64,) -> Option<std::sync::Arc<InFlowBlockEntry>> {- let entries = self.entries.borrow();- let slot = entries.get(slot as usize)?;- [&slot.committed, &slot.latest]- .into_iter()- .flatten()- .find(|entry| {- entry.validity == validity && entry.key == *key && entry.fragment_identity == committed_identity- })- .cloned()+ self.entries.with_row(slot as usize, |slot| {+ [&slot?.committed, &slot?.latest]+ .into_iter()+ .flatten()+ .find(|entry| {+ entry.validity == validity && entry.key == *key && entry.fragment_identity == committed_identity+ })+ .cloned()+ })}/// Stores `entry`, keeping the entry that placed the box's committed fragment, `committed_identity`.pub(super) fn store(&self, slot: u32, entry: InFlowBlockEntry, committed_identity: Option<u64>) {- let mut entries = self.entries.borrow_mut();- if entries.len() <= slot as usize {- entries.resize_with_default(slot as usize + 1);- }- let slot = &mut entries[slot as usize];- let places_committed_fragment = |entry: &Option<std::sync::Arc<InFlowBlockEntry>>| {- entry- .as_ref()- .is_some_and(|entry| Some(entry.fragment_identity) == committed_identity)- };- if places_committed_fragment(&slot.latest) {- slot.committed = slot.latest.take();- } else if !places_committed_fragment(&slot.committed) {- slot.committed = None;- }- // An entry nothing else holds is written in place rather than allocated again.- if let Some(existing) = slot.latest.as_mut().and_then(std::sync::Arc::get_mut) {- *existing = entry;- return;- }- slot.latest = Some(std::sync::Arc::new(entry));+ self.entries.with_row_mut(slot as usize, |slot| {+ let places_committed_fragment = |entry: &Option<std::sync::Arc<InFlowBlockEntry>>| {+ entry+ .as_ref()+ .is_some_and(|entry| Some(entry.fragment_identity) == committed_identity)+ };+ if places_committed_fragment(&slot.latest) {+ slot.committed = slot.latest.take();+ } else if !places_committed_fragment(&slot.committed) {+ slot.committed = None;+ }+ // An entry nothing else holds is written in place rather than allocated again.+ if let Some(existing) = slot.latest.as_mut().and_then(std::sync::Arc::get_mut) {+ *existing = entry;+ return;+ }+ slot.latest = Some(std::sync::Arc::new(entry));+ });}pub(crate) fn remove_entry(&mut self, slot: u32) {- let entries = self.entries.get_mut();- if entries- .get(slot as usize)- .is_some_and(|entries| entries.latest.is_some() || entries.committed.is_some())- {- entries[slot as usize] = InFlowBlockSlot::default();- }+ self.entries.reset_row_where(slot as usize, |entries| {+ entries.latest.is_some() || entries.committed.is_some()+ });}}diff --git a/Libraries/LibWeb/Rust/src/layout/pass_column.rs b/Libraries/LibWeb/Rust/src/layout/pass_column.rsindex 885828bbe7a..4002685b94b 100644--- a/Libraries/LibWeb/Rust/src/layout/pass_column.rs+++ b/Libraries/LibWeb/Rust/src/layout/pass_column.rs@@ -92,6 +92,10 @@ impl<T: Default> PassColumn<T> {// SAFETY: `&mut self` rules out any other reference into the column's chunks.Some(&mut unsafe { chunk.as_mut() }?.rows)}++ fn covered_rows(&self) -> usize {+ self.chunks.len() * ROWS_PER_CHUNK+ }}struct ChunkTable<'column, T> {@@ -164,6 +168,339 @@ fn make_chunk<T: Default>(slot: &AtomicPtr<PassChunk<T>>) -> &PassChunk<T> {}}+#[derive(Default)]+pub(crate) struct PassFlags {+ flags: PassColumn<bool>,+ chunks_holding_raised_flags: Vec<std::sync::atomic::AtomicBool>,+}++impl PassFlags {+ pub(crate) fn cover_slots(&mut self, slot_count: usize) {+ self.flags.cover_slots(slot_count);+ let chunk_count = slot_count.div_ceil(ROWS_PER_CHUNK);+ if self.chunks_holding_raised_flags.len() < chunk_count {+ self.chunks_holding_raised_flags+ .resize_with(chunk_count, Default::default);+ }+ }++ #[inline]+ pub(crate) fn raise(&self, index: usize) {+ self.flags.with_row_mut(index, |flag| *flag = true);+ let chunk_holds_raised_flags = &self.chunks_holding_raised_flags[index / ROWS_PER_CHUNK];+ if !chunk_holds_raised_flags.load(std::sync::atomic::Ordering::Relaxed) {+ chunk_holds_raised_flags.store(true, std::sync::atomic::Ordering::Relaxed);+ }+ }++ pub(crate) fn retain_raised_flags(&mut self, mut keeps_flag_raised: impl FnMut(usize) -> bool) {+ let Self {+ flags,+ chunks_holding_raised_flags,+ } = self;+ for (chunk_index, chunk_holds_raised_flags) in chunks_holding_raised_flags.iter_mut().enumerate() {+ if !*chunk_holds_raised_flags.get_mut() {+ continue;+ }+ let Some(rows) = flags.rows_of_chunk_mut(chunk_index) else {+ continue;+ };+ let mut holds_raised_flags = false;+ for (row_index, flag) in rows.iter_mut().enumerate() {+ if *flag.get_mut() {+ *flag.get_mut() = keeps_flag_raised(chunk_index * ROWS_PER_CHUNK + row_index);+ holds_raised_flags |= *flag.get_mut();+ }+ }+ *chunk_holds_raised_flags.get_mut() = holds_raised_flags;+ }+ }++ pub(crate) fn copy(&self) -> Self {+ let mut copy = Self::default();+ copy.cover_slots(self.flags.covered_rows());+ for (chunk_index, chunk_holds_raised_flags) in self.chunks_holding_raised_flags.iter().enumerate() {+ if !chunk_holds_raised_flags.load(std::sync::atomic::Ordering::Relaxed) {+ continue;+ }+ for index in chunk_index * ROWS_PER_CHUNK..(chunk_index + 1) * ROWS_PER_CHUNK {+ if self.flags.with_row(index, |flag| flag.is_some_and(|flag| *flag)) {+ copy.raise(index);+ }+ }+ }+ copy+ }+}++pub(crate) struct ForkSharedRows<T> {+ host_rows: std::sync::Arc<HostRows<T>>,+ chunk_table_of_the_host: ChunkTableOfTheHost<T>,+ fork_side: Option<ForkSide<T>>,+}++struct ChunkTableOfTheHost<T> {+ chunks: std::ptr::NonNull<OwnedChunk<T>>,+ chunk_count: usize,+}++// SAFETY: It points into the chunk table of the host's column, which is Send and Sync as `HostRows` is.+unsafe impl<T: Send> Send for ChunkTableOfTheHost<T> {}+// SAFETY: As above.+unsafe impl<T: Send + Sync> Sync for ChunkTableOfTheHost<T> {}++impl<T> ChunkTableOfTheHost<T> {+ fn of(column: &PassColumn<T>) -> Self {+ Self {+ chunks: std::ptr::NonNull::new(column.chunks.as_ptr().cast_mut()).expect("a Vec's pointer is never null"),+ chunk_count: column.chunks.len(),+ }+ }++ fn of_a_fork() -> Self {+ Self {+ chunks: std::ptr::NonNull::dangling(),+ chunk_count: 0,+ }+ }+}++struct HostRows<T> {+ rows: UnsafeCell<PassColumn<T>>,+ fork_generation_each_row_was_saved_for: UnsafeCell<PassColumn<u32>>,+ live_fork: UnsafeCell<Option<std::sync::Arc<RowsSavedForFork<T>>>>,+ fork_generations_handed_out: UnsafeCell<u32>,+}++// SAFETY: The host's state and its forks reach these rows only while they hold their document's render state, which+// one thread at a time does, and they never hold it at once with another thread laying out the same rows: a fork is+// made from the host between its jobs, and a dropped fork only lets go of its `Arc`. Within one layout pass, a row and+// its saved copy are written only by the run that lays out the row's box.+unsafe impl<T: Send + Sync> Sync for HostRows<T> {}++struct RowsSavedForFork<T> {+ generation: u32,+ rows_the_host_held_at_fork: usize,+ rows: PassColumn<Option<T>>,+}++// SAFETY: The host writes these rows and its fork reads them, never at once, as for `HostRows`.+unsafe impl<T: Send + Sync> Sync for RowsSavedForFork<T> {}++struct ForkSide<T> {+ rows_saved_by_host: std::sync::Arc<RowsSavedForFork<T>>,+ own_rows: PassColumn<Option<T>>,+ reads_host_rows: bool,+}++impl<T> Default for ForkSharedRows<T> {+ fn default() -> Self {+ Self::with_host_rows(PassColumn::default(), PassColumn::default())+ }+}++impl<T> ForkSharedRows<T> {+ fn with_host_rows(rows: PassColumn<T>, fork_generation_each_row_was_saved_for: PassColumn<u32>) -> Self {+ Self {+ chunk_table_of_the_host: ChunkTableOfTheHost::of(&rows),+ host_rows: std::sync::Arc::new(HostRows {+ rows: UnsafeCell::new(rows),+ fork_generation_each_row_was_saved_for: UnsafeCell::new(fork_generation_each_row_was_saved_for),+ live_fork: UnsafeCell::new(None),+ fork_generations_handed_out: UnsafeCell::new(0),+ }),+ fork_side: None,+ }+ }+}++impl<T: Clone + Default> ForkSharedRows<T> {+ #[inline]+ fn host_rows(&self) -> &PassColumn<T> {+ // SAFETY: The host's column grows only in `cover_slots`, while neither the host nor a fork lays out.+ unsafe { &*self.host_rows.rows.get() }+ }++ #[inline]+ fn host_table_of_the_host(&self) -> ChunkTable<'_, T> {+ debug_assert!(self.fork_side.is_none());+ ChunkTable {+ // SAFETY: `chunk_table_of_the_host` points into the chunk table of the host's column, which `host_rows`+ // keeps alive. Only the host's `cover_slots` grows that table, and it points this at the grown table.+ chunks: unsafe {+ ak::slice_from_raw_parts(+ self.chunk_table_of_the_host.chunks.as_ptr(),+ self.chunk_table_of_the_host.chunk_count,+ )+ },+ }+ }++ #[inline]+ fn live_fork(&self) -> Option<&RowsSavedForFork<T>> {+ // SAFETY: The live fork changes only as the host makes a fork or covers its rows, between its passes.+ unsafe { (*self.host_rows.live_fork.get()).as_deref() }+ }++ pub(crate) fn fork(&self) -> Self {+ assert!(+ self.fork_side.is_none(),+ "a render state is forked only from the host's state"+ );+ let rows_the_host_held_at_fork = self.host_rows().covered_rows();+ // SAFETY: The host makes a fork between its jobs, while no fork lays out.+ let generation = unsafe {+ let handed_out = &mut *self.host_rows.fork_generations_handed_out.get();+ *handed_out += 1;+ *handed_out+ };+ let mut rows = PassColumn::default();+ rows.cover_slots(rows_the_host_held_at_fork);+ let rows_saved_by_host = std::sync::Arc::new(RowsSavedForFork {+ generation,+ rows_the_host_held_at_fork,+ rows,+ });+ // SAFETY: As above.+ unsafe {+ *self.host_rows.live_fork.get() = Some(std::sync::Arc::clone(&rows_saved_by_host));+ }+ Self {+ host_rows: std::sync::Arc::clone(&self.host_rows),+ chunk_table_of_the_host: ChunkTableOfTheHost::of_a_fork(),+ fork_side: Some(ForkSide {+ rows_saved_by_host,+ own_rows: PassColumn::default(),+ reads_host_rows: true,+ }),+ }+ }++ pub(crate) fn cover_slots(&mut self, slot_count: usize) {+ match &mut self.fork_side {+ None => {+ // SAFETY: The host covers its rows between its passes, while no fork lays out.+ unsafe {+ (*self.host_rows.rows.get()).cover_slots(slot_count);+ (*self.host_rows.fork_generation_each_row_was_saved_for.get()).cover_slots(slot_count);+ let live_fork = &mut *self.host_rows.live_fork.get();+ if live_fork+ .as_ref()+ .is_some_and(|fork| std::sync::Arc::strong_count(fork) == 1)+ {+ *live_fork = None;+ }+ }+ self.chunk_table_of_the_host = ChunkTableOfTheHost::of(self.host_rows());+ }+ Some(fork_side) => {+ fork_side.own_rows.cover_slots(slot_count);+ // SAFETY: The fork covers its rows between its passes, while the host does not lay out.+ let live_fork = unsafe { &*self.host_rows.live_fork.get() };+ if !live_fork+ .as_ref()+ .is_some_and(|live_fork| std::sync::Arc::ptr_eq(live_fork, &fork_side.rows_saved_by_host))+ {+ fork_side.reads_host_rows = false;+ }+ }+ }+ }++ #[inline]+ pub(crate) fn with_row<R>(&self, index: usize, read: impl FnOnce(Option<&T>) -> R) -> R {+ let Some(fork_side) = &self.fork_side else {+ return self.host_table_of_the_host().with_row(index, read);+ };+ fork_side.own_rows.with_row(index, |own_row| match own_row {+ Some(Some(row)) => read(Some(row)),+ _ => self.with_row_the_fork_was_made_with(fork_side, index, read),+ })+ }++ fn with_row_the_fork_was_made_with<R>(+ &self,+ fork_side: &ForkSide<T>,+ index: usize,+ read: impl FnOnce(Option<&T>) -> R,+ ) -> R {+ let saved = &fork_side.rows_saved_by_host;+ saved.rows.with_row(index, |saved_row| match saved_row {+ Some(Some(row)) => read(Some(row)),+ _ if fork_side.reads_host_rows && index < saved.rows_the_host_held_at_fork => {+ self.host_rows().with_row(index, read)+ }+ _ => read(None),+ })+ }++ #[inline]+ pub(crate) fn with_row_mut<R>(&self, index: usize, write: impl FnOnce(&mut T) -> R) -> R {+ let Some(fork_side) = &self.fork_side else {+ if let Some(live_fork) = self.live_fork()+ && index < live_fork.rows_the_host_held_at_fork+ {+ self.save_row_for(live_fork, index);+ }+ return self.host_table_of_the_host().with_row_mut(index, write);+ };+ fork_side.own_rows.with_row_mut(index, |own_row| {+ write(own_row.get_or_insert_with(|| {+ self.with_row_the_fork_was_made_with(fork_side, index, |row| row.cloned().unwrap_or_default())+ }))+ })+ }++ fn save_row_for(&self, live_fork: &RowsSavedForFork<T>, index: usize) {+ // SAFETY: As for `host_rows`.+ let saved_for = unsafe { &*self.host_rows.fork_generation_each_row_was_saved_for.get() };+ saved_for.with_row_mut(index, |saved_for| {+ if *saved_for == live_fork.generation {+ return;+ }+ *saved_for = live_fork.generation;+ live_fork.rows.with_row_mut(index, |saved_row| {+ if saved_row.is_none() {+ *saved_row = Some(+ self.host_table_of_the_host()+ .with_row(index, |row| row.cloned().unwrap_or_default()),+ );+ }+ });+ });+ }++ pub(crate) fn row_mut(&mut self, index: usize) -> Option<&mut T> {+ if self.fork_side.is_some() {+ self.with_row_mut(index, |_| ());+ return self.fork_side.as_mut()?.own_rows.row_mut(index)?.as_mut();+ }+ if let Some(live_fork) = self.live_fork()+ && index < live_fork.rows_the_host_held_at_fork+ {+ self.save_row_for(live_fork, index);+ }+ // SAFETY: The host writes its rows between its passes, while no fork lays out, and `&mut self` rules out any+ // other reference into them from the host.+ unsafe { &mut *self.host_rows.rows.get() }.row_mut(index)+ }++ pub(crate) fn reset_row_where(&mut self, index: usize, holds: impl Fn(&T) -> bool) {+ if self.fork_side.is_none() && self.live_fork().is_none() {+ // SAFETY: As in `row_mut`.+ if let Some(row) = unsafe { &mut *self.host_rows.rows.get() }.row_mut(index)+ && holds(row)+ {+ *row = T::default();+ }+ return;+ }+ if self.with_row(index, |row| row.is_some_and(&holds)) {+ self.with_row_mut(index, |row| *row = T::default());+ }+ }+}+struct RowBorrow<'chunk> {#[cfg(debug_assertions)]state: &'chunk std::sync::atomic::AtomicI32,@@ -223,3 +560,96 @@ impl Drop for RowBorrow<'_> {}}}++#[cfg(test)]+mod tests {+ use super::ForkSharedRows;++ fn row(rows: &ForkSharedRows<u32>, index: usize) -> u32 {+ rows.with_row(index, |row| row.copied().unwrap_or_default())+ }++ fn write(rows: &ForkSharedRows<u32>, index: usize, value: u32) {+ rows.with_row_mut(index, |row| *row = value);+ }++ #[test]+ fn a_fork_reads_the_rows_the_host_held_when_it_was_made() {+ let mut host = ForkSharedRows::default();+ host.cover_slots(300);+ write(&host, 5, 1);+ write(&host, 200, 2);+ let mut fork = host.fork();+ fork.cover_slots(300);+ host.cover_slots(300);+ write(&host, 5, 10);+ write(&host, 7, 11);+ write(&host, 250, 12);+ write(&host, 260, 13);+ assert_eq!([5, 7, 200, 250, 260].map(|index| row(&fork, index)), [1, 0, 2, 0, 0]);+ assert_eq!(+ [5, 7, 200, 250, 260].map(|index| row(&host, index)),+ [10, 11, 2, 12, 13]+ );+ }++ #[test]+ fn a_fork_keeps_its_own_writes_over_rows_the_host_saves_for_it_later() {+ let mut host = ForkSharedRows::default();+ host.cover_slots(10);+ write(&host, 5, 1);+ write(&host, 6, 2);+ let mut fork = host.fork();+ fork.cover_slots(10);+ write(&fork, 5, 20);+ host.cover_slots(10);+ write(&host, 5, 10);+ write(&host, 6, 30);+ assert_eq!([5, 6].map(|index| row(&fork, index)), [20, 2]);+ assert_eq!([5, 6].map(|index| row(&host, index)), [10, 30]);+ }++ #[test]+ fn rows_past_those_the_host_held_when_the_fork_was_made_read_empty_in_the_fork() {+ let mut host = ForkSharedRows::default();+ host.cover_slots(100);+ let mut fork = host.fork();+ host.cover_slots(300);+ write(&host, 200, 5);+ fork.cover_slots(300);+ assert_eq!(row(&fork, 200), 0);+ write(&fork, 201, 7);+ assert_eq!(row(&fork, 201), 7);+ assert_eq!([200, 201].map(|index| row(&host, index)), [5, 0]);+ }++ #[test]+ fn an_earlier_fork_stops_reading_the_host_rows_once_a_newer_fork_is_made() {+ let mut host = ForkSharedRows::default();+ host.cover_slots(10);+ write(&host, 5, 1);+ write(&host, 6, 2);+ let mut earlier = host.fork();+ host.cover_slots(10);+ write(&host, 5, 10);+ let mut newer = host.fork();+ host.cover_slots(10);+ write(&host, 6, 20);+ earlier.cover_slots(10);+ newer.cover_slots(10);+ assert_eq!([5, 6].map(|index| row(&earlier, index)), [1, 0]);+ assert_eq!([5, 6].map(|index| row(&newer, index)), [10, 2]);+ }++ #[test]+ fn the_host_stops_saving_rows_once_its_fork_is_dropped() {+ let mut host = ForkSharedRows::<u32>::default();+ host.cover_slots(10);+ let fork = host.fork();+ host.cover_slots(10);+ assert!(host.live_fork().is_some());+ drop(fork);+ host.cover_slots(10);+ assert!(host.live_fork().is_none());+ }+}diff --git a/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs b/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rsindex 5a473b8ca2d..eb192ff28ed 100644--- a/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs+++ b/Libraries/LibWeb/Rust/src/layout/prepared_inline_content.rs@@ -261,13 +261,13 @@ impl PreparedInlineContent {#[derive(Default)]pub(crate) struct PreparedInlineContentMemos {- by_slot: RefCell<Vec<Option<Arc<PreparedInlineContent>>>>,+ by_slot: super::pass_column::ForkSharedRows<Option<Arc<PreparedInlineContent>>>,}impl PreparedInlineContentMemos {pub(crate) fn fork(&self) -> Self {Self {- by_slot: self.by_slot.clone(),+ by_slot: self.by_slot.fork(),}}@@ -276,26 +276,21 @@ impl PreparedInlineContentMemos {block_container: Node,validity: FcRunCacheValidity,) -> Option<Arc<PreparedInlineContent>> {- self.by_slot- .borrow()- .get(block_container.slot_index() as usize)?- .as_ref()- .filter(|kept| kept.validity == validity)- .cloned()+ self.by_slot.with_row(block_container.slot_index() as usize, |kept| {+ kept?.as_ref().filter(|kept| kept.validity == validity).cloned()+ })}pub(crate) fn keep(&self, block_container: Node, prepared: Arc<PreparedInlineContent>) {- let index = block_container.slot_index() as usize;- let mut by_slot = self.by_slot.borrow_mut();- if by_slot.len() <= index {- by_slot.resize_with(index + 1, || None);- }- by_slot[index] = Some(prepared);+ self.by_slot+ .with_row_mut(block_container.slot_index() as usize, |kept| *kept = Some(prepared));+ }++ pub(super) fn cover_slots(&mut self, slot_count: usize) {+ self.by_slot.cover_slots(slot_count);}pub(crate) fn forget(&mut self, slot: u32) {- if let Some(kept) = self.by_slot.get_mut().get_mut(slot as usize) {- *kept = None;- }+ self.by_slot.reset_row_where(slot as usize, Option::is_some);}}diff --git a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs b/Libraries/LibWeb/Rust/src/layout/rendered_text.rsindex c543615ff2d..2d0b2faf7c3 100644--- a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs+++ b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs@@ -8,7 +8,6 @@ use super::LayoutNodeArena;use super::node_data::NodeSlotId;use super::text_transform::{TextRenderingOptions, may_require_bidi_processing, render_text};use crate::css::css_enums::text_transform;-use std::cell::RefCell;use std::sync::Arc;/// Selects the beginning or end of a transformed span for offsets inside it.@@ -220,14 +219,11 @@ impl TextContent {/// text is still that text.#[derive(Default)]pub(crate) struct TextMemos {- /// In chunks a fork of the arena shares until either side writes one, so forking does not copy every row's memo.- chunks: RefCell<crate::cow_column::CowVec<Option<ChunksOfText>, CHUNK_MEMOS_PER_CHUNK>>,+ /// 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>>,}-/// How many rows' chunk memos a chunk of [`TextMemos::chunks`] holds: a write after a fork copies this many.-const CHUNK_MEMOS_PER_CHUNK: usize = 128;-/// The chunks a run made of a row's rendered text, and that text.#[derive(Clone)]struct ChunksOfText {@@ -245,7 +241,7 @@ impl TextMemos {/// The memos of a fork of the arena, which keeps the chunks and makes grapheme segmenters anew.pub(crate) fn fork(&self) -> Self {Self {- chunks: self.chunks.clone(),+ chunks: self.chunks.fork(),grapheme_segmenters: Default::default(),}}@@ -260,11 +256,14 @@ impl TextMemos {compute: impl FnOnce() -> super::text_chunker::ChunkedText,) -> Arc<CachedTextChunks> {let index = node.slot_index() as usize;- if let Some(Some(memo)) = self.chunks.borrow().get(index)- && Arc::ptr_eq(&memo.rendered, rendered)- && memo.chunks.key == *key- {- return memo.chunks.clone();+ let memoized = self.chunks.with_row(index, |memo| match memo {+ Some(Some(memo)) if Arc::ptr_eq(&memo.rendered, rendered) && memo.chunks.key == *key => {+ Some(memo.chunks.clone())+ }+ _ => None,+ });+ if let Some(memoized) = memoized {+ return memoized;}// A nested measurement can request a different key while an iterator@@ -274,13 +273,11 @@ impl TextMemos {key: key.clone(),chunks: compute(),});- let mut chunks = self.chunks.borrow_mut();- if chunks.len() <= index {- chunks.resize_with_default(index + 1);- }- chunks[index] = Some(ChunksOfText {- rendered: rendered.clone(),- chunks: entry.clone(),+ self.chunks.with_row_mut(index, |memo| {+ *memo = Some(ChunksOfText {+ rendered: rendered.clone(),+ chunks: entry.clone(),+ });});entry}@@ -305,15 +302,13 @@ impl TextMemos {}pub(super) fn cover_slots(&mut self, slot_count: usize) {+ self.chunks.cover_slots(slot_count);self.grapheme_segmenters.cover_slots(slot_count);}/// Lets go of what the memos keep for the row in `slot`, which the arena freed.pub(crate) fn forget(&mut self, slot: u32) {- let chunks = self.chunks.get_mut();- if chunks.get(slot as usize).is_some_and(Option::is_some) {- chunks[slot as usize] = None;- }+ self.chunks.reset_row_where(slot as usize, Option::is_some);if let Some(segmenter) = self.grapheme_segmenters.row_mut(slot as usize) {*segmenter = None;}@@ -528,7 +523,8 @@ mod tests {frozen_font_list_fill_generation: 0,splits_at_orientation_changes: false,};- let memos = TextMemos::default();+ let mut memos = TextMemos::default();+ memos.cover_slots(1);let node = NodeSlotId::new(0, 1);let mut previous = memos.text_chunks(node, content.rendered(), &key, ChunkedText::default);for language in [@@ -698,6 +694,7 @@ mod tests {assert!(kept(&scratch, validity).is_none());assert!(kept(&fork, validity).is_some_and(|kept| Arc::ptr_eq(&kept, &prepared.upgrade().unwrap())));drop(fork);+ scratch.apply_memo_invalidations(&mut arena);assert!(prepared.upgrade().is_none());let (validity, prepared) = keep(&arena, &scratch);diff --git a/Libraries/LibWeb/Rust/src/layout/run_state.rs b/Libraries/LibWeb/Rust/src/layout/run_state.rsindex 6b87469f972..46a30f85bf9 100644--- a/Libraries/LibWeb/Rust/src/layout/run_state.rs+++ b/Libraries/LibWeb/Rust/src/layout/run_state.rs@@ -149,8 +149,8 @@ impl LayoutScratch {/// the rest anew.pub(super) fn fork(&self) -> Self {Self {- fc_run_cache_store: self.fc_run_cache_store.clone(),- in_flow_block_cache_store: self.in_flow_block_cache_store.clone(),+ fc_run_cache_store: self.fc_run_cache_store.fork(),+ in_flow_block_cache_store: self.in_flow_block_cache_store.fork(),text_memos: self.text_memos.fork(),prepared_inline_content_memos: self.prepared_inline_content_memos.fork(),..Self::default()@@ -189,6 +189,9 @@ impl LayoutScratch {self.intrinsic_size_caches.cover_slots(slot_count);self.text_memos.cover_slots(slot_count);self.fragment_builder_scratch.cover_slots(slot_count);+ self.fc_run_cache_store.cover_slots(slot_count);+ self.in_flow_block_cache_store.cover_slots(slot_count);+ self.prepared_inline_content_memos.cover_slots(slot_count);arena.take_memo_invalidations().apply_to(&mut self.fc_run_cache_store,&mut self.in_flow_block_cache_store,