Skip to contentSkip to conversation

mm: fixes for stale TLB entries due to delayed/batched TLB flushes

PATCH Applied David Hildenbrand (Arm) 2 participants 11 messages Dec 1 – Dec 2

Subsystems (8)
lore
Share & tools
lore

David Hildenbrand (Arm)

author maintainer
#0 lore raw

v2 cover mm: fixes for stale TLB entries due to delayed/batched TLB flushes

These are the two remaining fixes from v1, whereby we fix two stale TLB issues with TTU_BATCH_FLUSH during reclaim.

Patch #1: Don't defer TLB flushes when unmapping lazyfree folios. Handles
mapping a new anon folio after reclaim discarded a lazyfree folio (do_anonymous_page(), migrate_vma_insert_page(), UFFDIO_COPY, UFFDIO_MOVE).

Patch #2: Unlock unmapped folios only after the deferred TLB flush. Handles
refaulting a new page-cache folio, CoW of a folio that is still in the page-cache, and swapping in a new folio (do_swap_page(), unuse_pte(), UFFDIO_CONTINUE). Also handles invalidation replacing a folio that reclaim kept, and write() modifying a new page-cache folio.

There is one remaining problem that I describe in the cover letter of v1 in detail.

Testing
-------

I threw a bunch of selftests at it and had AI generate some stress tests, in particular for the benchmarks below. I also ran stress-ng to force reclaim.

I managed to reproduce both issues, as described in the patch descriptions.

Stale reads out of 1024000 checked pages in 2000 iterations:

base series

  lazyfree,  MGLRU            16242         0
  lazyfree,  classic LRU      16274         0
  swapcache, MGLRU            24076         0
  swapcache, classic LRU      23028         0

Performance Impact
------------------

I ran some benchmarks on v1 in an x86-64 VM with limited CPUs, RAM and zram enabled. Running inside a VM might make TLB flushes more expensive, so the results below might be a bit exaggerated. AI results below.

Classic LRU, 4 threads randomly touching a working set twice the size of their memcg for 30 seconds. Pages touched per second:

base series
anon-rw 681k 1055k
anon-ro 1013k 1027k

  file-ro        417k       419k
  file-rw        173k       183k
  lazyfree      1512k       333k

Swapping out dirty anon folios ("anon-rw") is about 55% faster, because patch #2 now also batches TLB flushes of stale writable TLB entries. That is what Zhang Peng's series [1] tried to achieve, and his work also inspired how patch #2 locks folios again, but the used mechanism is different.

Reclaiming clean anon folios ("anon-ro"), clean page-cache folios ("file-ro") and dirty page-cache folios ("file-rw") is not noticeably affected.

Reclaiming lazyfree folios ("lazyfree") is about 4.5x slower, because we stop batching TLB flushes when discarding them entirely, which seems to be the right thing to do for now. We can look into optimizing this separately later.

Kairui tested v1 as well on x86-64 under memory pressure (40 GiB in one process with swap, 4 processes concurrently, and 4 memcg-limited cgroups reclaiming concurrently) [2]: TLB shootdown IPIs dropped by 90% and wall time by 30%. Reclaiming clean page-cache folios seemed unchanged, and on arm64 nothing changed either.

[1] https://lore.kernel.org/linux-mm/[email protected]/
[2] https://lore.kernel.org/linux-mm/CAMgjq7DWWCF_iB+GmTciuXr=m=uk7mMmidvY=8yg6MH98X4oPg@mail.gmail.com/

---
Changes in v2:
- #1 and #2 are upstream now
- Rebase on top of mm-core/for-next
- "mm/rmap: don't defer TLB flushes when unmapping lazyfree folios"
- Avoid line split
- "mm/vmscan: unlock unmapped folios only after the deferred TLB flush"
- Label the three phases in the comments
- Finish reclaiming a batch before collecting more folios, even if
reclaim added folios to folio_list (e.g., splitting a shmem folio)
- Activate folios that went under writeback while unlocked
- Update the description of (c) and drop the outdated migration
example from the patch description now that that stuff is fixed
upstream
- Collect tags
- Link to v1: https://patch.msgid.link/[email protected]

---
David Hildenbrand (Arm) (2):
mm/rmap: don't defer TLB flushes when unmapping lazyfree folios mm/vmscan: unlock unmapped folios only after the deferred TLB flush

 mm/internal.h |   5 ++
 mm/rmap.c     |  19 ++++++-
 mm/shmem.c    |   2 +-
 mm/swap.h     |   5 +-
 mm/swapfile.c |   7 ++-
 mm/vmscan.c   | 175 ++++++++++++++++++++++++++++++++++++++++++++++++++++++----
 6 files changed, 197 insertions(+), 16 deletions(-)

---
base-commit: 40e0fcedf9c39c3a4a0100323c101506b4206394
change-id: 20261114-file_folio_flush-7d1749fab2d8

Best regards,

Signature · 1 line
David Hildenbrand (Arm) <[email protected]>
author maintainer
#1 lore raw

PATCH v2 1/2 mm/rmap: don't defer TLB flushes when unmapping lazyfree folios

When reclaim discards a lazyfree folio, it clears the PTE but delays the TLB flush. Until flushed, mapping a new folio into the now-none PTE can leave some CPUs still reading from the old folio while others already write to the new folio.

This is hard to trigger in practice and would mostly look like a weird use-after-free bug in an allocator that uses MADV_FREE, but it can be reproduced reliably with three threads pinned to different CPUs:

(1) Thread A populates the pages, MADV_FREE's them and then MADV_PAGEOUT's them.
(2) Thread B reads all pages to keep TLB entries cached and verifies the content of pages published by thread C.
(3) Thread C waits until mincore() indicates that a page is no longer present, writes a new value to it, and publishes it to thread B.

Thread B can then read the old value after the new folio was mapped and the content updated.

One way to handle it would be adding conditional flushes to do_anonymous_page(), migrate_vma_insert_page(), UFFDIO_COPY and UFFDIO_MOVE ... essentially anywhere we install new anonymous folios, which would mean that these places flush quite frequently on concurrent reclaim.

To perform targeted flushes, we'd have to keep some PTE markers behind, which is also rather nasty and not an easy fix.

So let's not defer the TLB flush for lazyfree folios, which includes folios in VM_DROPPABLE mappings.

To avoid flushing if the folio was redirtied or has additional references, perform all non-deferred TLB flushes only once we know that we won't restore the PTEs, right before removing the rmap.

The downside is that we no longer batch TLB flushes when discarding lazyfree folios, which harms performance, but is the right thing to do for now.

Fixes 854e9ed09ded ("mm: support madvise(MADV_FREE)")
---
 mm/rmap.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
mm/rmap.c +12 -2
index 038435994b99a..7459722d22d9f 100644
@@ -2218,6 +2218,7 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 	struct mmu_notifier_range range;
 	enum ttu_flags flags = (enum ttu_flags)(long)arg;
 	unsigned long nr_pages = 1, end_addr;
+	bool flush;
 	unsigned long pfn;
 	int ptes = 0;
 
@@ -2243,6 +2244,7 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 
 	while (page_vma_mapped_walk(&pvmw)) {
 		nr_pages = 1;
+		flush = false;
 
 		/*
 		 * If the folio is in an mlock()d vma, we must not swap it out.
@@ -2329,11 +2331,17 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 			 * architecture must guarantee that a clear->dirty
 			 * transition on a cached TLB entry is written through
 			 * and traps if the PTE is unmapped.
+			 *
+			 * If we don't defer the flush, we flush only once we
+			 * know that we won't restore the PTEs below. We never
+			 * defer the flush for lazyfree folios: if we discard
+			 * them, the PTE will be none, and a page fault could
+			 * map a new folio while stale TLB entries still exist.
 			 */
-			if (should_defer_flush(mm, flags))
+			if (!folio_test_lazyfree(folio) && should_defer_flush(mm, flags))
 				set_tlb_ubc_flush_pending(mm, pteval, address, end_addr);
 			else
-				flush_tlb_range(vma, address, end_addr);
+				flush = true;
 			if (pte_dirty(pteval))
 				folio_mark_dirty(folio);
 		} else {
@@ -2392,6 +2400,8 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 			add_mm_counter(mm, mm_counter_file(folio), -nr_pages);
 		}
 finish_unmap:
+		if (flush)
+			flush_tlb_range(vma, address, end_addr);
 		folio_remove_rmap_ptes(folio, page, nr_pages, vma);
 		if (vma_test_any_mask(vma, VMA_LOCKED_MASK))
 			mlock_drain_local();
Signature · 1 line
2.56.1
author maintainer
#7 lore raw

PATCH v2 2/2 mm/vmscan: unlock unmapped folios only after the deferred TLB flush

In reply to David Hildenbrand (Arm)

try_to_unmap() with TTU_BATCH_FLUSH zaps the PTEs, transfers the PTE dirty bit to the folio and defers the TLB flush. Until the TLB is flushed, other CPUs might still access the folio through stale TLB entries.

However, reclaim unlocks folios it keeps and removes folios it frees from the page-cache / swap-cache before performing the deferred TLB flush.

Stale writable TLB entries are currently handled by flushing them right after try_to_unmap() if the folio is dirty, so writes through stale TLB entries cannot get lost, but they are also not batched.

Stale read-only TLB entries, on the other hand, are problematic:

(1) A page fault can map a new page-cache folio, or swap in a new folio once reclaim removed the old one from the swap-cache (e.g., a clean swap-cache folio, or a dirty folio mapped by clean PTEs after synchronous swap-out to zram or zswap). Modifications of the new folio (e.g., through write() or page table mappings) are then not visible to CPUs that still read the old folio.

(2) A CoW fault in a MAP_PRIVATE mapping can copy a page-cache folio that reclaim kept. Writes go to the new anon folio, while other CPUs still read the old folio.

(3) Invalidation (e.g., invalidate_inode_pages2()) can remove a folio that reclaim kept from the page-cache without flushing the TLB, as the folio is no longer mapped. A page fault can then map a new folio while other CPUs still read the old folio.

This can be reproduced easily by swapping out an anon memory range with MADV_PAGEOUT, reading it back in, and swapping it out again (MADV_PAGEOUT) while one thread keeps reading the range and another thread writes to pages as soon as reclaim removed the folios from the swap-cache. The first thread will occasionally read the old content.

Fix it by reclaiming folios in batches of up to 64 folios:

(a) Lock each folio, check whether we want to reclaim it, and unmap it. Keep the folio locked if any deferred TLB flush is pending after unmapping it, otherwise unlock it right away.

(b) Flush the TLB once, and unlock all folios that are still locked.

(c) Lock the folios again, one at a time, to try reclaiming them. Activate folios that are still or again mapped, or that are under writeback by now (marking them for immediate reclaim, like we do in (a)), and skip folios that are poisoned by now, or that somebody else holds locked.

As others might map or unmap folios while they are unlocked, we might now activate or reclaim some folios that we would previously have kept or activated, which is fine.

Keeping folios locked until the TLB flush makes sure that nobody can remove them from the page-cache / swap-cache, copy them or start writeback. Page faults will either wait on the folio lock, or find the old folio and map it again, which is fine.

Unlocking folios before trying to reclaim them makes sure that we never hold more than one folio lock while performing I/O or waiting on the filesystem.

The idea of unlocking folios and locking them again using a trylock before trying to reclaim them was inspired by [1] from Zhang Peng.

As nobody can start writeback before the TLB flush, we no longer have to flush stale writable TLB entries right after try_to_unmap(), so remove the try_to_unmap_flush_dirty() call and batch these flushes as well. This effectively enables batching TLB flushes of stale writable TLB entries, which is what [1] tried to achieve.

We must not wait for a folio lock, a folio flag or I/O while keeping other folios locked, as that could deadlock. So flush the TLB and unlock the batch early before waiting for writeback (legacy memcg), and before allocating swap space would perform synchronous discard I/O (folio_alloc_swap() now returns -EBUSY if allocation failed but retrying with synchronous discard might help).

Allocating swap space can otherwise only sleep when allocating memory for the swap table, which cannot enter direct reclaim or compaction, as reclaim runs with PF_MEMALLOC.

We'll limit batching to 64 folios for now; the limit mostly matters for, e.g., MADV_PAGEOUT and DAMON that can pass more, or when reclaim splits large folios.

Note that khugepaged and batched (async) folio migration already keep up to HPAGE_PMD_NR (e.g., 512 with 4 KiB pages) small folios locked after unmapping them with a deferred TLB flush. Both also call MMU notifiers while keeping other folios locked, just like we do now.

Keep code churn to a minimum. Some follow-up cleanups and optimizations make sense, in particular:

(1) Cleanly separate the stages of shrink_folio_list() (see the TODO).

(2) Avoid unlocking and locking folios again that do not require a TLB flush. But only if it's worth it and doesn't make the code too ugly.

(3) Remove the remaining try_to_unmap_flush() calls before freeing folios; we only free folios that we flushed already or that we never unmapped.

(4) Remove the now-unused try_to_unmap_flush_dirty() infrastructure.

Fixes 72b252aed506 ("mm: send one IPI per CPU to TLB flush all entries after unmapping pages")
---
 mm/internal.h |   5 ++
 mm/rmap.c     |   5 ++
 mm/shmem.c    |   2 +-
 mm/swap.h     |   5 +-
 mm/swapfile.c |   7 ++-
 mm/vmscan.c   | 175 ++++++++++++++++++++++++++++++++++++++++++++++++++++++----
 6 files changed, 185 insertions(+), 14 deletions(-)
mm/internal.h +5 -0
index 96cb55d7816b1..06c895a4078f1 100644
@@ -1246,6 +1246,7 @@ extern struct workqueue_struct *mm_percpu_wq;
 #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
 void try_to_unmap_flush(void);
 void try_to_unmap_flush_dirty(void);
+bool try_to_unmap_flush_pending(void);
 void flush_tlb_batched_pending(struct mm_struct *mm);
 #else
 static inline void try_to_unmap_flush(void)
@@ -1254,6 +1255,10 @@ static inline void try_to_unmap_flush(void)
 static inline void try_to_unmap_flush_dirty(void)
 {
 }
+static inline bool try_to_unmap_flush_pending(void)
+{
+	return false;
+}
 static inline void flush_tlb_batched_pending(struct mm_struct *mm)
 {
 }
mm/rmap.c +5 -0
index 7459722d22d9f..f7f08649f27e3 100644
@@ -731,6 +731,11 @@ void try_to_unmap_flush_dirty(void)
 		try_to_unmap_flush();
 }
 
+bool try_to_unmap_flush_pending(void)
+{
+	return current->tlb_ubc.flush_required;
+}
+
 static void set_tlb_ubc_flush_pending(struct mm_struct *mm, pte_t pteval,
 		unsigned long start, unsigned long end)
 {
mm/shmem.c +1 -1
index a5713109c843c..fe749cfd529a8 100644
@@ -1954,7 +1954,7 @@ int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio,
 		folio_mark_uptodate(folio);
 	}
 
-	ret = folio_alloc_swap(folio);
+	ret = folio_alloc_swap(folio, /* may_sync_discard= */ true);
 	if (!ret) {
 		bool first_swapped = shmem_recalc_inode(inode, 0, nr_pages);
 		int error;
mm/swap.h +3 -2
index d5bf21f517dce..b77c8a071a0a8 100644
@@ -243,7 +243,7 @@ extern int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp);
  *
  * folio_put_swap(): does the opposite thing of folio_dup_swap().
  */
-int folio_alloc_swap(struct folio *folio);
+int folio_alloc_swap(struct folio *folio, bool may_sync_discard);
 int folio_dup_swap(struct folio *folio, struct page *page);
 void folio_put_swap(struct folio *folio, struct page *page);
 
@@ -363,7 +363,8 @@ static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry)
 	return NULL;
 }
 
-static inline int folio_alloc_swap(struct folio *folio)
+static inline int folio_alloc_swap(struct folio *folio,
+		bool may_sync_discard)
 {
 	return -EINVAL;
 }
mm/swapfile.c +6 -1
index c2af13eb15b33..03b9484b88fc9 100644
@@ -1737,16 +1737,19 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 /**
  * folio_alloc_swap - allocate swap space for a folio
  * @folio: folio we want to move to swap
+ * @may_sync_discard: whether we may wait for synchronous discard I/O
  *
  * Allocate swap space for the folio and add the folio to the
  * swap cache.
  *
  * Context: Caller needs to hold the folio lock.
  * Return: %0 on success, %-E2BIG if splitting the folio might allow swapout,
+ * %-EBUSY if allocation failed but retrying with @may_sync_discard might
+ * succeed,
  * %-ENOSPC if no global swap space is available, or %-ENOMEM if splitting
  * would not help.
  */
-int folio_alloc_swap(struct folio *folio)
+int folio_alloc_swap(struct folio *folio, bool may_sync_discard)
 {
 	unsigned int order = folio_order(folio);
 	unsigned int size = 1 << order;
@@ -1779,6 +1782,8 @@ int folio_alloc_swap(struct folio *folio)
 	local_unlock(&percpu_swap_cluster.lock);
 
 	if (!order && unlikely(!folio_test_swapcache(folio))) {
+		if (!may_sync_discard)
+			return -EBUSY;
 		if (swap_sync_discard())
 			goto again;
 	}
mm/vmscan.c +165 -10

233 lines not on this page · raw message

Signature · 1 line
2.56.1
author maintainer Applied
#10 lore raw
In reply to David Hildenbrand (Arm)
Quoted 9 lines · David Hildenbrand (Arm)

These are the two remaining fixes from v1, whereby we fix two stale TLB issues with TTU_BATCH_FLUSH during reclaim.

Patch #1: Don't defer TLB flushes when unmapping lazyfree folios. Handles
mapping a new anon folio after reclaim discarded a lazyfree folio (do_anonymous_page(), migrate_vma_insert_page(), UFFDIO_COPY, UFFDIO_MOVE).

[...]

Applied, thanks!

tree: mm/core.git
branch: for-next-fixes

Applied patches will appear soon in mm-next, followed by linux-next.

Please report any outstanding bugs that were missed during review, so we can either drop the patch series or decide how to fix it up.

It is encouraged to provide Acked-bys, Reviewed-bys, and Tested-bys even though the patches have already been applied. If possible, patch trailers will be updated.

Note that commit hashes shown below are subject to change due to rebase, trailer updates or similar. Further, this is not a guarantee that the patches will go upstream. If in doubt, please check the listed branch.

[1/2] mm/rmap: don't defer TLB flushes when unmapping lazyfree folios

      https://git.kernel.org/mm/core/c/1bde274f
[2/2] mm/vmscan: unlock unmapped folios only after the deferred TLB flush
      https://git.kernel.org/mm/core/c/aa304dfe
Signature · 3 lines
Cheers,

David
maintainer Reviewed-by on v2 1/2
#2 lore raw

Re: [PATCH v2 1/2] mm/rmap: don't defer TLB flushes when unmapping lazyfree folios

In reply to David Hildenbrand (Arm)
Quoted 35 lines · David Hildenbrand (Arm)

When reclaim discards a lazyfree folio, it clears the PTE but delays the TLB flush. Until flushed, mapping a new folio into the now-none PTE can leave some CPUs still reading from the old folio while others already write to the new folio.

This is hard to trigger in practice and would mostly look like a weird use-after-free bug in an allocator that uses MADV_FREE, but it can be reproduced reliably with three threads pinned to different CPUs:

(1) Thread A populates the pages, MADV_FREE's them and then MADV_PAGEOUT's them.
(2) Thread B reads all pages to keep TLB entries cached and verifies the content of pages published by thread C.
(3) Thread C waits until mincore() indicates that a page is no longer present, writes a new value to it, and publishes it to thread B.

Thread B can then read the old value after the new folio was mapped and the content updated.

One way to handle it would be adding conditional flushes to do_anonymous_page(), migrate_vma_insert_page(), UFFDIO_COPY and UFFDIO_MOVE ... essentially anywhere we install new anonymous folios, which would mean that these places flush quite frequently on concurrent reclaim.

To perform targeted flushes, we'd have to keep some PTE markers behind, which is also rather nasty and not an easy fix.

So let's not defer the TLB flush for lazyfree folios, which includes folios in VM_DROPPABLE mappings.

To avoid flushing if the folio was redirtied or has additional references, perform all non-deferred TLB flushes only once we know that we won't restore the PTEs, right before removing the rmap.

Quoted 8 lines

The downside is that we no longer batch TLB flushes when discarding lazyfree folios, which harms performance, but is the right thing to do for now.

Fixes 854e9ed09ded ("mm: support madvise(MADV_FREE)")

Lazyfree seems like yet another silly edge case thing we shouldn't have done (or maybe should have done better :)

But anyway, LGTM so:

But see below, claude came up with a thing about contpte when restoring PTEs.

Quoted 31 lines
---
 mm/rmap.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
mm/rmap.c +5 -0
index 038435994b99a..7459722d22d9f 100644
@@ -2218,6 +2218,7 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 	struct mmu_notifier_range range;
 	enum ttu_flags flags = (enum ttu_flags)(long)arg;
 	unsigned long nr_pages = 1, end_addr;
+	bool flush;
 	unsigned long pfn;
 	int ptes = 0;
 
@@ -2243,6 +2244,7 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 
 	while (page_vma_mapped_walk(&pvmw)) {
 		nr_pages = 1;
+		flush = false;
 
 		/*
 		 * If the folio is in an mlock()d vma, we must not swap it out.
@@ -2329,11 +2331,17 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 			 * architecture must guarantee that a clear->dirty
 			 * transition on a cached TLB entry is written through
 			 * and traps if the PTE is unmapped.
+			 *
+			 * If we don't defer the flush, we flush only once we
+			 * know that we won't restore the PTEs below. We never

mm/rmap.c static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma, · line 2344

Quoted 10 lines
mm/rmap.c +5 -2
+			 * defer the flush for lazyfree folios: if we discard
+			 * them, the PTE will be none, and a page fault could
+			 * map a new folio while stale TLB entries still exist.
 			 */
-			if (should_defer_flush(mm, flags))
+			if (!folio_test_lazyfree(folio) && should_defer_flush(mm, flags))
 				set_tlb_ubc_flush_pending(mm, pteval, address, end_addr);
 			else
-				flush_tlb_range(vma, address, end_addr);
+				flush = true;

Hmm it's like 'should defer' or 'should defer a little bit' :)

But I can't see how the 'slight' delay does any harm and as the commit msg says you avoid unnecessary flushes.

Claude mentioned something though it says this exit case the 'not restore PTEs' one can make contpte_set_ptes() restore a previously non-cont block as cont, leaving non-cont TLB entries overlapping new cont ones.

So it's a question of whether the hw tolerates that or not.

Quoted 14 lines
mm/rmap.c +2 -1
 			if (pte_dirty(pteval))
 				folio_mark_dirty(folio);
 		} else {
@@ -2392,6 +2400,8 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 			add_mm_counter(mm, mm_counter_file(folio), -nr_pages);
 		}
 finish_unmap:
+		if (flush)
+			flush_tlb_range(vma, address, end_addr);
 		folio_remove_rmap_ptes(folio, page, nr_pages, vma);
 		if (vma_test_any_mask(vma, VMA_LOCKED_MASK))
 			mlock_drain_local();
 
--
Quoted 2 lines

2.56.1

--
Cheers, Lorenzo

author maintainer
#3 lore raw

Re: [PATCH v2 1/2] mm/rmap: don't defer TLB flushes when unmapping lazyfree folios

Quoted 45 lines · Lorenzo Stoakes (ARM)
Quoted 35 lines · David Hildenbrand (Arm)

When reclaim discards a lazyfree folio, it clears the PTE but delays the TLB flush. Until flushed, mapping a new folio into the now-none PTE can leave some CPUs still reading from the old folio while others already write to the new folio.

This is hard to trigger in practice and would mostly look like a weird use-after-free bug in an allocator that uses MADV_FREE, but it can be reproduced reliably with three threads pinned to different CPUs:

(1) Thread A populates the pages, MADV_FREE's them and then MADV_PAGEOUT's them.
(2) Thread B reads all pages to keep TLB entries cached and verifies the content of pages published by thread C.
(3) Thread C waits until mincore() indicates that a page is no longer present, writes a new value to it, and publishes it to thread B.

Thread B can then read the old value after the new folio was mapped and the content updated.

One way to handle it would be adding conditional flushes to do_anonymous_page(), migrate_vma_insert_page(), UFFDIO_COPY and UFFDIO_MOVE ... essentially anywhere we install new anonymous folios, which would mean that these places flush quite frequently on concurrent reclaim.

To perform targeted flushes, we'd have to keep some PTE markers behind, which is also rather nasty and not an easy fix.

So let's not defer the TLB flush for lazyfree folios, which includes folios in VM_DROPPABLE mappings.

To avoid flushing if the folio was redirtied or has additional references, perform all non-deferred TLB flushes only once we know that we won't restore the PTEs, right before removing the rmap.

Quoted 8 lines

The downside is that we no longer batch TLB flushes when discarding lazyfree folios, which harms performance, but is the right thing to do for now.

Fixes 854e9ed09ded ("mm: support madvise(MADV_FREE)")
Quoted 6 lines

Lazyfree seems like yet another silly edge case thing we shouldn't have done (or maybe should have done better :)

But anyway, LGTM so:

Thanks.

Quoted 47 lines

But see below, claude came up with a thing about contpte when restoring PTEs.

Quoted 31 lines
---
 mm/rmap.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
mm/rmap.c +5 -0
index 038435994b99a..7459722d22d9f 100644
@@ -2218,6 +2218,7 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 	struct mmu_notifier_range range;
 	enum ttu_flags flags = (enum ttu_flags)(long)arg;
 	unsigned long nr_pages = 1, end_addr;
+	bool flush;
 	unsigned long pfn;
 	int ptes = 0;
 
@@ -2243,6 +2244,7 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 
 	while (page_vma_mapped_walk(&pvmw)) {
 		nr_pages = 1;
+		flush = false;
 
 		/*
 		 * If the folio is in an mlock()d vma, we must not swap it out.
@@ -2329,11 +2331,17 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 			 * architecture must guarantee that a clear->dirty
 			 * transition on a cached TLB entry is written through
 			 * and traps if the PTE is unmapped.
+			 *
+			 * If we don't defer the flush, we flush only once we
+			 * know that we won't restore the PTEs below. We never

mm/rmap.c static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma, · line 2344

Quoted 10 lines
mm/rmap.c +5 -2
+			 * defer the flush for lazyfree folios: if we discard
+			 * them, the PTE will be none, and a page fault could
+			 * map a new folio while stale TLB entries still exist.
 			 */
-			if (should_defer_flush(mm, flags))
+			if (!folio_test_lazyfree(folio) && should_defer_flush(mm, flags))
 				set_tlb_ubc_flush_pending(mm, pteval, address, end_addr);
 			else
-				flush_tlb_range(vma, address, end_addr);
+				flush = true;

Hmm it's like 'should defer' or 'should defer a little bit' :)

Quoted 6 lines

But I can't see how the 'slight' delay does any harm and as the commit msg says you avoid unnecessary flushes.

Claude mentioned something though it says this exit case the 'not restore PTEs' one can make contpte_set_ptes() restore a previously non-cont block as cont, leaving non-cont TLB entries overlapping new cont ones.

That's arch code problems, and would be pre-existing. I'll ping some people to understand if something in arch code might need fixing.

Signature · 3 lines
Cheers,

David
#8 lore raw

Re: [PATCH v2 2/2] mm/vmscan: unlock unmapped folios only after the deferred TLB flush

In reply to David Hildenbrand (Arm)
Quoted 106 lines · David Hildenbrand (Arm)

try_to_unmap() with TTU_BATCH_FLUSH zaps the PTEs, transfers the PTE dirty bit to the folio and defers the TLB flush. Until the TLB is flushed, other CPUs might still access the folio through stale TLB entries.

However, reclaim unlocks folios it keeps and removes folios it frees from the page-cache / swap-cache before performing the deferred TLB flush.

Stale writable TLB entries are currently handled by flushing them right after try_to_unmap() if the folio is dirty, so writes through stale TLB entries cannot get lost, but they are also not batched.

Stale read-only TLB entries, on the other hand, are problematic:

(1) A page fault can map a new page-cache folio, or swap in a new folio once reclaim removed the old one from the swap-cache (e.g., a clean swap-cache folio, or a dirty folio mapped by clean PTEs after synchronous swap-out to zram or zswap). Modifications of the new folio (e.g., through write() or page table mappings) are then not visible to CPUs that still read the old folio.

(2) A CoW fault in a MAP_PRIVATE mapping can copy a page-cache folio that reclaim kept. Writes go to the new anon folio, while other CPUs still read the old folio.

(3) Invalidation (e.g., invalidate_inode_pages2()) can remove a folio that reclaim kept from the page-cache without flushing the TLB, as the folio is no longer mapped. A page fault can then map a new folio while other CPUs still read the old folio.

This can be reproduced easily by swapping out an anon memory range with MADV_PAGEOUT, reading it back in, and swapping it out again (MADV_PAGEOUT) while one thread keeps reading the range and another thread writes to pages as soon as reclaim removed the folios from the swap-cache. The first thread will occasionally read the old content.

Fix it by reclaiming folios in batches of up to 64 folios:

(a) Lock each folio, check whether we want to reclaim it, and unmap it. Keep the folio locked if any deferred TLB flush is pending after unmapping it, otherwise unlock it right away.

(b) Flush the TLB once, and unlock all folios that are still locked.

(c) Lock the folios again, one at a time, to try reclaiming them. Activate folios that are still or again mapped, or that are under writeback by now (marking them for immediate reclaim, like we do in (a)), and skip folios that are poisoned by now, or that somebody else holds locked.

As others might map or unmap folios while they are unlocked, we might now activate or reclaim some folios that we would previously have kept or activated, which is fine.

Keeping folios locked until the TLB flush makes sure that nobody can remove them from the page-cache / swap-cache, copy them or start writeback. Page faults will either wait on the folio lock, or find the old folio and map it again, which is fine.

Unlocking folios before trying to reclaim them makes sure that we never hold more than one folio lock while performing I/O or waiting on the filesystem.

The idea of unlocking folios and locking them again using a trylock before trying to reclaim them was inspired by [1] from Zhang Peng.

As nobody can start writeback before the TLB flush, we no longer have to flush stale writable TLB entries right after try_to_unmap(), so remove the try_to_unmap_flush_dirty() call and batch these flushes as well. This effectively enables batching TLB flushes of stale writable TLB entries, which is what [1] tried to achieve.

We must not wait for a folio lock, a folio flag or I/O while keeping other folios locked, as that could deadlock. So flush the TLB and unlock the batch early before waiting for writeback (legacy memcg), and before allocating swap space would perform synchronous discard I/O (folio_alloc_swap() now returns -EBUSY if allocation failed but retrying with synchronous discard might help).

Allocating swap space can otherwise only sleep when allocating memory for the swap table, which cannot enter direct reclaim or compaction, as reclaim runs with PF_MEMALLOC.

We'll limit batching to 64 folios for now; the limit mostly matters for, e.g., MADV_PAGEOUT and DAMON that can pass more, or when reclaim splits large folios.

Note that khugepaged and batched (async) folio migration already keep up to HPAGE_PMD_NR (e.g., 512 with 4 KiB pages) small folios locked after unmapping them with a deferred TLB flush. Both also call MMU notifiers while keeping other folios locked, just like we do now.

Keep code churn to a minimum. Some follow-up cleanups and optimizations make sense, in particular:

(1) Cleanly separate the stages of shrink_folio_list() (see the TODO).

(2) Avoid unlocking and locking folios again that do not require a TLB flush. But only if it's worth it and doesn't make the code too ugly.

(3) Remove the remaining try_to_unmap_flush() calls before freeing folios; we only free folios that we flushed already or that we never unmapped.

Quoted 8 lines

(4) Remove the now-unused try_to_unmap_flush_dirty() infrastructure.

Fixes 72b252aed506 ("mm: send one IPI per CPU to TLB flush all entries after unmapping pages")

Hmm this seems like a really heavyweight and significant change to be backporting, especially so far.

It's like you're implementing a whole new mechanism here, but also backporting it.

I wonder a bit how the net of these backported patches are going to interact honestly. But maybe I worry too much:)

Maybe I'm just a bit frustrated at the rate of change going on ATM and how completely unmanageable it is to keep up with it all.

I fear waking up to an mm with about 20 new mechanisms I wasn't aware of + now I have to figure them out/support them/etc :)))

Quoted 215 lines
---
 mm/internal.h |   5 ++
 mm/rmap.c     |   5 ++
 mm/shmem.c    |   2 +-
 mm/swap.h     |   5 +-
 mm/swapfile.c |   7 ++-
 mm/vmscan.c   | 175 ++++++++++++++++++++++++++++++++++++++++++++++++++++++----
 6 files changed, 185 insertions(+), 14 deletions(-)
mm/internal.h +5 -0
index 96cb55d7816b1..06c895a4078f1 100644
@@ -1246,6 +1246,7 @@ extern struct workqueue_struct *mm_percpu_wq;
 #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
 void try_to_unmap_flush(void);
 void try_to_unmap_flush_dirty(void);
+bool try_to_unmap_flush_pending(void);
 void flush_tlb_batched_pending(struct mm_struct *mm);
 #else
 static inline void try_to_unmap_flush(void)
@@ -1254,6 +1255,10 @@ static inline void try_to_unmap_flush(void)
 static inline void try_to_unmap_flush_dirty(void)
 {
 }
+static inline bool try_to_unmap_flush_pending(void)
+{
+	return false;
+}
 static inline void flush_tlb_batched_pending(struct mm_struct *mm)
 {
 }
mm/rmap.c +5 -0
index 7459722d22d9f..f7f08649f27e3 100644
@@ -731,6 +731,11 @@ void try_to_unmap_flush_dirty(void)
 		try_to_unmap_flush();
 }
 
+bool try_to_unmap_flush_pending(void)
+{
+	return current->tlb_ubc.flush_required;
+}
+
 static void set_tlb_ubc_flush_pending(struct mm_struct *mm, pte_t pteval,
 		unsigned long start, unsigned long end)
 {
mm/shmem.c +1 -1
index a5713109c843c..fe749cfd529a8 100644
@@ -1954,7 +1954,7 @@ int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio,
 		folio_mark_uptodate(folio);
 	}
 
-	ret = folio_alloc_swap(folio);
+	ret = folio_alloc_swap(folio, /* may_sync_discard= */ true);
 	if (!ret) {
 		bool first_swapped = shmem_recalc_inode(inode, 0, nr_pages);
 		int error;
mm/swap.h +3 -2
index d5bf21f517dce..b77c8a071a0a8 100644
@@ -243,7 +243,7 @@ extern int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp);
  *
  * folio_put_swap(): does the opposite thing of folio_dup_swap().
  */
-int folio_alloc_swap(struct folio *folio);
+int folio_alloc_swap(struct folio *folio, bool may_sync_discard);
 int folio_dup_swap(struct folio *folio, struct page *page);
 void folio_put_swap(struct folio *folio, struct page *page);
 
@@ -363,7 +363,8 @@ static inline struct swap_info_struct *__swap_entry_to_info(swp_entry_t entry)
 	return NULL;
 }
 
-static inline int folio_alloc_swap(struct folio *folio)
+static inline int folio_alloc_swap(struct folio *folio,
+		bool may_sync_discard)
 {
 	return -EINVAL;
 }
mm/swapfile.c +6 -1
index c2af13eb15b33..03b9484b88fc9 100644
@@ -1737,16 +1737,19 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 /**
  * folio_alloc_swap - allocate swap space for a folio
  * @folio: folio we want to move to swap
+ * @may_sync_discard: whether we may wait for synchronous discard I/O
  *
  * Allocate swap space for the folio and add the folio to the
  * swap cache.
  *
  * Context: Caller needs to hold the folio lock.
  * Return: %0 on success, %-E2BIG if splitting the folio might allow swapout,
+ * %-EBUSY if allocation failed but retrying with @may_sync_discard might
+ * succeed,
  * %-ENOSPC if no global swap space is available, or %-ENOMEM if splitting
  * would not help.
  */
-int folio_alloc_swap(struct folio *folio)
+int folio_alloc_swap(struct folio *folio, bool may_sync_discard)
 {
 	unsigned int order = folio_order(folio);
 	unsigned int size = 1 << order;
@@ -1779,6 +1782,8 @@ int folio_alloc_swap(struct folio *folio)
 	local_unlock(&percpu_swap_cluster.lock);
 
 	if (!order && unlikely(!folio_test_swapcache(folio))) {
+		if (!may_sync_discard)
+			return -EBUSY;
 		if (swap_sync_discard())
 			goto again;
 	}
mm/vmscan.c +89 -0
index 053f8e437bdd8..fb3a801ecbfbf 100644
@@ -1155,6 +1155,105 @@ static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
 	return false;
 }
 
+/*
+ * Maximum number of staged folios that shrink_folio_list() collects before
+ * it flushes the TLB.
+ */
+#define MAX_STAGED_FOLIOS	64
+
+struct staged_folios {
+	/* Locked folios, waiting for the TLB flush. */
+	struct list_head unflushed;
+	/* Unlocked folios, after the TLB flush (if required). */
+	struct list_head flushed;
+	/* Number of folios in the current batch. */
+	unsigned int nr_folios;
+	/* Whether we are reclaiming the folios of the current batch. */
+	bool reclaiming;
+};
+
+static bool staged_folios_empty(struct staged_folios *staged)
+{
+	return list_empty(&staged->unflushed) &&
+	       list_empty(&staged->flushed);
+}
+
+static void staged_folios_add(struct staged_folios *staged,
+		struct folio *folio, bool unmapped)
+{
+	if (unmapped && try_to_unmap_flush_pending()) {
+		/* Keep the folio locked until we flushed the TLB. */
+		list_add_tail(&folio->lru, &staged->unflushed);
+	} else {
+		folio_unlock(folio);
+		list_add_tail(&folio->lru, &staged->flushed);
+	}
+	staged->nr_folios++;
+}
+
+static void staged_folios_flush(struct staged_folios *staged)
+{
+	struct folio *folio;
+
+	try_to_unmap_flush();
+	list_for_each_entry(folio, &staged->unflushed, lru)
+		folio_unlock(folio);
+	list_splice_tail_init(&staged->unflushed, &staged->flushed);
+}
+
+static struct folio *staged_folios_next(struct staged_folios *staged,
+		struct list_head *folio_list)
+{
+	struct folio *folio;
+
+	if (staged_folios_empty(staged))
+		return NULL;
+	/*
+	 * (a) Collect more folios until we have enough or there are no more.
+	 * Once we started reclaiming the folios of a batch, finish that first,
+	 * even if reclaim (e.g., splitting a folio) added folios to folio_list.
+	 */
+	if (!staged->reclaiming && staged->nr_folios < MAX_STAGED_FOLIOS &&
+	    !list_empty(folio_list))
+		return NULL;
+
+	/*
+	 * (b) Flush the TLB and unlock the folios that waited for the flush.
+	 * Nothing to do if we already did that for this batch.
+	 */
+	staged_folios_flush(staged);
+	staged->reclaiming = true;
+
+	/* (c) Hand out the next folio to reclaim. */
+	folio = list_first_entry(&staged->flushed, struct folio, lru);
+	list_del(&folio->lru);
+	/* We handed out all folios: start collecting again (a). */
+	if (list_empty(&staged->flushed)) {
+		staged->nr_folios = 0;
+		staged->reclaiming = false;
+	}
+	return folio;
+}
+
+static int staged_folios_alloc_swap(struct staged_folios *staged,
+		struct folio *folio)
+{
+	bool may_sync_discard = list_empty(&staged->unflushed);
+	int ret;
+
+	ret = folio_alloc_swap(folio, may_sync_discard);
+	if (ret != -EBUSY)
+		return ret;

mm/vmscan.c static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask) · line 1256

Quoted 10 lines
mm/vmscan.c +10 -0
+
+	/*
+	 * Don't wait for synchronous discard I/O while keeping other folios
+	 * locked: there is potential for deadlocks and long delays.
+	 */
+	staged_folios_flush(staged);
+	may_sync_discard = true;
+	return folio_alloc_swap(folio, may_sync_discard);
+}
+

I genuinely do not think I've ever seen a Cc: stable patch add this much before, it's really crazy.

Can we find some way of breaking this up or something? :)

Quoted 29 lines
mm/vmscan.c +14 -1
 /*
  * shrink_folio_list() returns the number of reclaimed pages
  */
@@ -1166,6 +1265,10 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 	struct folio_batch free_folios;
 	LIST_HEAD(ret_folios);
 	LIST_HEAD(demote_folios);
+	struct staged_folios staged = {
+		.unflushed = LIST_HEAD_INIT(staged.unflushed),
+		.flushed = LIST_HEAD_INIT(staged.flushed),
+	};
 	unsigned int nr_reclaimed = 0, nr_demoted = 0;
 	unsigned int pgactivate = 0;
 	bool do_demote_pass;
@@ -1177,15 +1280,43 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 	do_demote_pass = can_demote(pgdat->node_id, sc, memcg);
 
 retry:
-	while (!list_empty(folio_list)) {
+	/*
+	 * We reclaim folios in batches, in three phases:
+	 *
+	 * (a) Collect: we take folios from folio_list to pre-process them
+	 *     (lock, check, unmap). Then, they move to the staged(unflushed)
+	 *     list. If no TLB flush is pending for a folio, it moves to the
+	 *     staged(flushed) list directly.
+	 *
+	 * (b) Flush: once we collected a batch of staged folios, or there are
+	 *     no more folios to pre-process, we perform a single TLB flush and

mm/vmscan.c static unsigned int shrink_folio_list(struct list_head *folio_list, · line 1302

Quoted 10 lines
mm/vmscan.c +10 -0
+	 *     move the staged(unflushed) folios to the staged(flushed) list
+	 *     after unlocking them.
+	 *
+	 * (c) Reclaim: we take folios from the staged(flushed) list to actually
+	 *     reclaim them, or to activate them if they are still mapped. Once
+	 *     we took all folios of the batch, we start collecting again (a).
+	 *
+	 * Once all lists are empty, we are done.
+	 *
+	 * TODO: the stages of this algorithm should be cleanly separated.

I mean this TODO is I guess you intended this patch to be reworked right? :)

Quoted 51 lines
mm/vmscan.c +16 -2
+	 */
+	while (!list_empty(folio_list) || !staged_folios_empty(&staged)) {
 		struct address_space *mapping;
 		struct folio *folio;
 		enum folio_references references = FOLIOREF_RECLAIM;
 		bool dirty, writeback;
+		bool unmapped = false;
 		unsigned int nr_pages;
 
 		cond_resched();
 
+		folio = staged_folios_next(&staged, folio_list);
+		if (folio) {
+			nr_pages = folio_nr_pages(folio);
+			goto reclaim_staged;
+		}
+
 		folio = lru_to_folio(folio_list);
 		list_del(&folio->lru);
 
@@ -1324,6 +1455,11 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 			/* Case 3 above */
 			} else {
 				folio_unlock(folio);
+				/*
+				 * Don't wait for writeback while keeping
+				 * staged folios locked.
+				 */
+				staged_folios_flush(&staged);
 				folio_wait_writeback(folio);
 				/* then go back and try same folio again */
 				list_add_tail(&folio->lru, folio_list);
@@ -1382,7 +1518,7 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 				    split_folio_to_list(folio, folio_list))
 					goto activate_locked;
 			}
-			ret = folio_alloc_swap(folio);
+			ret = staged_folios_alloc_swap(&staged, folio);
 			if (ret) {
 				int __maybe_unused order = folio_order(folio);
 
@@ -1401,7 +1537,7 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 				}
 #endif
 				count_mthp_stat(order, MTHP_STAT_SWPOUT_FALLBACK);
-				if (folio_alloc_swap(folio))
+				if (staged_folios_alloc_swap(&staged, folio))
 					goto activate_locked_split;
 			}
 			/*

mm/vmscan.c static unsigned int shrink_folio_list(struct list_head *folio_list, · line 1594

Quoted 10 lines
mm/vmscan.c +1 -6
@@ -1455,21 +1591,40 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 				flags |= TTU_SYNC;
 
 			try_to_unmap(folio, flags);
-			/*
-			 * Flush deferred writable TLB entries before we could
-			 * drop the folio lock and others could start writeback.
-			 */
-			if (folio_test_dirty(folio))
-				try_to_unmap_flush_dirty();
+			unmapped = true;

This seems like you're throwing in an optimisation for fun here too, which isn't really great.

But claude raised the fact that PTE markers rely on this too (e.g. guard regions can be applied to file-backed mappings, but also UFFDIO_POISON) and you'll get writers writing through stale TLB entries this way, which seems like a really bad (TM) thing.

It's gross to have to 'just know' to think about these things here but I think this should be reconsidered?

Quoted 39 lines
mm/vmscan.c +25 -2
 			if (folio_mapped(folio)) {
 				stat->nr_unmap_fail += nr_pages;
 				if (!was_swapbacked &&
 				    folio_test_swapbacked(folio))
 					stat->nr_lazyfree_fail += nr_pages;
-				goto activate_locked;
 			}
 		}
 
+		staged_folios_add(&staged, folio, unmapped);
+		continue;
+
+reclaim_staged:
+		if (!folio_trylock(folio))
+			goto keep;
+
+		/*
+		 * We failed to unmap the folio, or it was mapped again while it
+		 * was unlocked.
+		 */
+		if (folio_mapped(folio))
+			goto activate_locked;
+		/*
+		 * While the folio was unlocked, writeback might have started, or
+		 * it might have been poisoned.
+		 */
+		if (folio_test_writeback(folio)) {
+			folio_set_reclaim(folio);
+			stat->nr_writeback += nr_pages;
+			goto activate_locked;
+		}
+		if (folio_contain_hwpoisoned_page(folio))
+			goto keep_locked;
+
 		/*
 		 * Folio is unmapped now so it cannot be newly pinned anymore.
 		 * No point in trying to reclaim folio if it is pinned.
 
--
Quoted 2 lines

2.56.1

I think the rest of it needs to be chopped up to be really reviewable, or at least it's late here so :)

--
Cheers, Lorenzo

#4 lore raw

Re: [PATCH v2 1/2] mm/rmap: don't defer TLB flushes when unmapping lazyfree folios

In reply to David Hildenbrand (Arm)
Quoted 9 lines · David Hildenbrand (Arm)
Quoted 6 lines · Lorenzo Stoakes (ARM)

Lazyfree seems like yet another silly edge case thing we shouldn't have done (or maybe should have done better :)

But anyway, LGTM so:

Thanks.

NP.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
---
 mm/rmap.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
mm/rmap.c +0 -0
index 038435994b99a..7459722d22d9f 100644

[ ... ]

Quoted 23 lines
Quoted 23 lines
Quoted 7 lines
mm/rmap.c +3 -0
@@ -2329,11 +2331,17 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 			 * architecture must guarantee that a clear->dirty
 			 * transition on a cached TLB entry is written through
 			 * and traps if the PTE is unmapped.
+			 *
+			 * If we don't defer the flush, we flush only once we
+			 * know that we won't restore the PTEs below. We never

mm/rmap.c static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma, · line 2344

Quoted 10 lines
mm/rmap.c +5 -2
+			 * defer the flush for lazyfree folios: if we discard
+			 * them, the PTE will be none, and a page fault could
+			 * map a new folio while stale TLB entries still exist.
 			 */
-			if (should_defer_flush(mm, flags))
+			if (!folio_test_lazyfree(folio) && should_defer_flush(mm, flags))
 				set_tlb_ubc_flush_pending(mm, pteval, address, end_addr);
 			else
-				flush_tlb_range(vma, address, end_addr);
+				flush = true;

Hmm it's like 'should defer' or 'should defer a little bit' :)

But I can't see how the 'slight' delay does any harm and as the commit msg says you avoid unnecessary flushes.

Quoted 6 lines
Quoted 3 lines

Claude mentioned something though it says this exit case the 'not restore PTEs' one can make contpte_set_ptes() restore a previously non-cont block as cont, leaving non-cont TLB entries overlapping new cont ones.

That's arch code problems, and would be pre-existing. I'll ping some people to understand if something in arch code might need fixing.

Great thanks! Will leave with you :)

--
Cheers, Lorenzo

author maintainer
#5 lore raw

Re: [PATCH v2 1/2] mm/rmap: don't defer TLB flushes when unmapping lazyfree folios

In reply to David Hildenbrand (Arm)
Quoted 105 lines · David Hildenbrand (Arm)
Quoted 45 lines · Lorenzo Stoakes (ARM)
Quoted 35 lines · David Hildenbrand (Arm)

When reclaim discards a lazyfree folio, it clears the PTE but delays the TLB flush. Until flushed, mapping a new folio into the now-none PTE can leave some CPUs still reading from the old folio while others already write to the new folio.

This is hard to trigger in practice and would mostly look like a weird use-after-free bug in an allocator that uses MADV_FREE, but it can be reproduced reliably with three threads pinned to different CPUs:

(1) Thread A populates the pages, MADV_FREE's them and then MADV_PAGEOUT's them.
(2) Thread B reads all pages to keep TLB entries cached and verifies the content of pages published by thread C.
(3) Thread C waits until mincore() indicates that a page is no longer present, writes a new value to it, and publishes it to thread B.

Thread B can then read the old value after the new folio was mapped and the content updated.

One way to handle it would be adding conditional flushes to do_anonymous_page(), migrate_vma_insert_page(), UFFDIO_COPY and UFFDIO_MOVE ... essentially anywhere we install new anonymous folios, which would mean that these places flush quite frequently on concurrent reclaim.

To perform targeted flushes, we'd have to keep some PTE markers behind, which is also rather nasty and not an easy fix.

So let's not defer the TLB flush for lazyfree folios, which includes folios in VM_DROPPABLE mappings.

To avoid flushing if the folio was redirtied or has additional references, perform all non-deferred TLB flushes only once we know that we won't restore the PTEs, right before removing the rmap.

Quoted 8 lines

The downside is that we no longer batch TLB flushes when discarding lazyfree folios, which harms performance, but is the right thing to do for now.

Fixes 854e9ed09ded ("mm: support madvise(MADV_FREE)")
Quoted 6 lines

Lazyfree seems like yet another silly edge case thing we shouldn't have done (or maybe should have done better :)

But anyway, LGTM so:

Thanks.

Quoted 50 lines

But see below, claude came up with a thing about contpte when restoring PTEs.

Quoted 31 lines
---
 mm/rmap.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
mm/rmap.c +5 -0
index 038435994b99a..7459722d22d9f 100644
@@ -2218,6 +2218,7 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 	struct mmu_notifier_range range;
 	enum ttu_flags flags = (enum ttu_flags)(long)arg;
 	unsigned long nr_pages = 1, end_addr;
+	bool flush;
 	unsigned long pfn;
 	int ptes = 0;
 
@@ -2243,6 +2244,7 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 
 	while (page_vma_mapped_walk(&pvmw)) {
 		nr_pages = 1;
+		flush = false;
 
 		/*
 		 * If the folio is in an mlock()d vma, we must not swap it out.
@@ -2329,11 +2331,17 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 			 * architecture must guarantee that a clear->dirty
 			 * transition on a cached TLB entry is written through
 			 * and traps if the PTE is unmapped.
+			 *
+			 * If we don't defer the flush, we flush only once we
+			 * know that we won't restore the PTEs below. We never

mm/rmap.c static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma, · line 2344

Quoted 10 lines
mm/rmap.c +5 -2
+			 * defer the flush for lazyfree folios: if we discard
+			 * them, the PTE will be none, and a page fault could
+			 * map a new folio while stale TLB entries still exist.
 			 */
-			if (should_defer_flush(mm, flags))
+			if (!folio_test_lazyfree(folio) && should_defer_flush(mm, flags))
 				set_tlb_ubc_flush_pending(mm, pteval, address, end_addr);
 			else
-				flush_tlb_range(vma, address, end_addr);
+				flush = true;

Hmm it's like 'should defer' or 'should defer a little bit' :)

But I can't see how the 'slight' delay does any harm and as the commit msg says you avoid unnecessary flushes.

Quoted 6 lines
Quoted 3 lines

Claude mentioned something though it says this exit case the 'not restore PTEs' one can make contpte_set_ptes() restore a previously non-cont block as cont, leaving non-cont TLB entries overlapping new cont ones.

That's arch code problems, and would be pre-existing. I'll ping some people to understand if something in arch code might need fixing.

Ah, now I get it, moving the flush after the set_pte_at restoration. In general, arch code must properly handle the TLB when shattering/merging cont ptes, that's not core-mm's responsibility. (we simply restore what was set earlier; if any of that shattered a cont-pte, the arch code must perform the flushes itself)

Signature · 3 lines
Cheers,

David
#6 lore raw

Re: [PATCH v2 1/2] mm/rmap: don't defer TLB flushes when unmapping lazyfree folios

Quoted 110 lines · David Hildenbrand (Arm)
Quoted 109 lines · David Hildenbrand (Arm)
Quoted 45 lines · Lorenzo Stoakes (ARM)
Quoted 35 lines · David Hildenbrand (Arm)

When reclaim discards a lazyfree folio, it clears the PTE but delays the TLB flush. Until flushed, mapping a new folio into the now-none PTE can leave some CPUs still reading from the old folio while others already write to the new folio.

This is hard to trigger in practice and would mostly look like a weird use-after-free bug in an allocator that uses MADV_FREE, but it can be reproduced reliably with three threads pinned to different CPUs:

(1) Thread A populates the pages, MADV_FREE's them and then MADV_PAGEOUT's them.
(2) Thread B reads all pages to keep TLB entries cached and verifies the content of pages published by thread C.
(3) Thread C waits until mincore() indicates that a page is no longer present, writes a new value to it, and publishes it to thread B.

Thread B can then read the old value after the new folio was mapped and the content updated.

One way to handle it would be adding conditional flushes to do_anonymous_page(), migrate_vma_insert_page(), UFFDIO_COPY and UFFDIO_MOVE ... essentially anywhere we install new anonymous folios, which would mean that these places flush quite frequently on concurrent reclaim.

To perform targeted flushes, we'd have to keep some PTE markers behind, which is also rather nasty and not an easy fix.

So let's not defer the TLB flush for lazyfree folios, which includes folios in VM_DROPPABLE mappings.

To avoid flushing if the folio was redirtied or has additional references, perform all non-deferred TLB flushes only once we know that we won't restore the PTEs, right before removing the rmap.

Quoted 8 lines

The downside is that we no longer batch TLB flushes when discarding lazyfree folios, which harms performance, but is the right thing to do for now.

Fixes 854e9ed09ded ("mm: support madvise(MADV_FREE)")
Quoted 6 lines

Lazyfree seems like yet another silly edge case thing we shouldn't have done (or maybe should have done better :)

But anyway, LGTM so:

Thanks.

Quoted 53 lines

But see below, claude came up with a thing about contpte when restoring PTEs.

Quoted 31 lines
---
 mm/rmap.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
mm/rmap.c +5 -0
index 038435994b99a..7459722d22d9f 100644
@@ -2218,6 +2218,7 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 	struct mmu_notifier_range range;
 	enum ttu_flags flags = (enum ttu_flags)(long)arg;
 	unsigned long nr_pages = 1, end_addr;
+	bool flush;
 	unsigned long pfn;
 	int ptes = 0;
 
@@ -2243,6 +2244,7 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 
 	while (page_vma_mapped_walk(&pvmw)) {
 		nr_pages = 1;
+		flush = false;
 
 		/*
 		 * If the folio is in an mlock()d vma, we must not swap it out.
@@ -2329,11 +2331,17 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 			 * architecture must guarantee that a clear->dirty
 			 * transition on a cached TLB entry is written through
 			 * and traps if the PTE is unmapped.
+			 *
+			 * If we don't defer the flush, we flush only once we
+			 * know that we won't restore the PTEs below. We never

mm/rmap.c static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma, · line 2344

Quoted 10 lines
mm/rmap.c +5 -2
+			 * defer the flush for lazyfree folios: if we discard
+			 * them, the PTE will be none, and a page fault could
+			 * map a new folio while stale TLB entries still exist.
 			 */
-			if (should_defer_flush(mm, flags))
+			if (!folio_test_lazyfree(folio) && should_defer_flush(mm, flags))
 				set_tlb_ubc_flush_pending(mm, pteval, address, end_addr);
 			else
-				flush_tlb_range(vma, address, end_addr);
+				flush = true;

Hmm it's like 'should defer' or 'should defer a little bit' :)

But I can't see how the 'slight' delay does any harm and as the commit msg says you avoid unnecessary flushes.

Claude mentioned something though it says this exit case the 'not restore PTEs' one can make contpte_set_ptes() restore a previously non-cont block as cont, leaving non-cont TLB entries overlapping new cont ones.

Quoted 7 lines
Quoted 2 lines

That's arch code problems, and would be pre-existing. I'll ping some people to understand if something in arch code might need fixing.

Ah, now I get it, moving the flush after the set_pte_at restoration. In general, arch code must properly handle the TLB when shattering/merging cont ptes, that's not core-mm's responsibility. (we simply restore what was set earlier; if any of that shattered a cont-pte, the arch code must perform the flushes itself)

Ack. Yeah struck me that the expectation would be, if the original PTE entries are restored, that the TLB would remain valid, and any other change that might happen is indeed arch's responsibility.

Quoted 5 lines

--
Cheers,

David

--
Cheers, Lorenzo

author maintainer
#9 lore raw

Re: [PATCH v2 2/2] mm/vmscan: unlock unmapped folios only after the deferred TLB flush

In reply to Lorenzo Stoakes (ARM)

[...]

Quoted 19 lines
Quoted 10 lines

(1) Cleanly separate the stages of shrink_folio_list() (see the TODO).

(2) Avoid unlocking and locking folios again that do not require a TLB flush. But only if it's worth it and doesn't make the code too ugly.

(3) Remove the remaining try_to_unmap_flush() calls before freeing folios; we only free folios that we flushed already or that we never unmapped.

Quoted 8 lines

(4) Remove the now-unused try_to_unmap_flush_dirty() infrastructure.

Fixes 72b252aed506 ("mm: send one IPI per CPU to TLB flush all entries after unmapping pages")
Quoted 5 lines

Hmm this seems like a really heavyweight and significant change to be backporting, especially so far.

Quoted 1 line

It's like you're implementing a whole new mechanism here, but also backporting

it.

No way around fixing it without destroying performance, I'm afraid. I tried and it would mean giving up delayed tlb flushing completely for reclaim, which is just unacceptable.

It's a slightly biggger fix, yes, but I tried to be as little intrusive as possible. That's why I'm not sending it as a hotfix but will give it a bit of soaking time in -next.

Quoted 6 lines

I wonder a bit how the net of these backported patches are going to interact honestly. But maybe I worry too much:)

Maybe I'm just a bit frustrated at the rate of change going on ATM and how completely unmanageable it is to keep up with it all.

Yeah. Fortunately we have memory reclaim experts around that know this code better than I do.

Quoted 3 lines

I fear waking up to an mm with about 20 new mechanisms I wasn't aware of + now I have to figure them out/support them/etc :)))

Yes, same feeling here having to write fixes for serious problems on a weekly basis.

[...]

Quoted 4 lines
Quoted 4 lines
mm/vmscan.c +4 -0
+	/*
+	 * Don't wait for synchronous discard I/O while keeping other folios
+	 * locked: there is potential for deadlocks and long delays.
+	 */
Quoted 8 lines

mm/vmscan.c static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask) · line 1256

Quoted 5 lines
mm/vmscan.c +5 -0
+	staged_folios_flush(staged);
+	may_sync_discard = true;
+	return folio_alloc_swap(folio, may_sync_discard);
+}
+

I genuinely do not think I've ever seen a Cc: stable patch add this much before, it's really crazy.

Oh, you didn't see my PAE patches back then? This here is trivial lol.

Quoted 2 lines

Can we find some way of breaking this up or something? :)

I wrote this fix to minimally impact existing code. We are just adding helpers here to make the changes to shrink_folio_list() below as minimal as possible.

I don't see how splitting up the current patch would make any sense.

Doing the full thing with cleanups first would be something different, but there is no way we could backport that.

[...]

Quoted 15 lines
Quoted 15 lines
mm/vmscan.c +14 -1
-	while (!list_empty(folio_list)) {
+	/*
+	 * We reclaim folios in batches, in three phases:
+	 *
+	 * (a) Collect: we take folios from folio_list to pre-process them
+	 *     (lock, check, unmap). Then, they move to the staged(unflushed)
+	 *     list. If no TLB flush is pending for a folio, it moves to the
+	 *     staged(flushed) list directly.
+	 *
+	 * (b) Flush: once we collected a batch of staged folios, or there are
+	 *     no more folios to pre-process, we perform a single TLB flush and
+	 *     move the staged(unflushed) folios to the staged(flushed) list
+	 *     after unlocking them.
+	 *
+	 * (c) Reclaim: we take folios from the staged(flushed) list to actually
Quoted 8 lines

mm/vmscan.c static unsigned int shrink_folio_list(struct list_head *folio_list, · line 1302

Quoted 6 lines
mm/vmscan.c +6 -0
+	 *     reclaim them, or to activate them if they are still mapped. Once
+	 *     we took all folios of the batch, we start collecting again (a).
+	 *
+	 * Once all lists are empty, we are done.
+	 *
+	 * TODO: the stages of this algorithm should be cleanly separated.

I mean this TODO is I guess you intended this patch to be reworked right? :)

You mean the code? Yes, as also spelled out in the description above. Not this patch.

[...]

Quoted 10 lines

mm/vmscan.c static unsigned int shrink_folio_list(struct list_head *folio_list, · line 1594

Quoted 7 lines
mm/vmscan.c +1 -6
-			/*
-			 * Flush deferred writable TLB entries before we could
-			 * drop the folio lock and others could start writeback.
-			 */
-			if (folio_test_dirty(folio))
-				try_to_unmap_flush_dirty();
+			unmapped = true;

This seems like you're throwing in an optimisation for fun here too, which isn't really great.

I think it's the same thing we effectively had before: if nobody set delayed flushes, no flush for the folio was required.

So it's not something new. if we didn't unmap, there is no need to flush for this folio.

Quoted 5 lines

But claude raised the fact that PTE markers rely on this too (e.g. guard regions can be applied to file-backed mappings, but also UFFDIO_POISON) and you'll get writers writing through stale TLB entries this way, which seems like a really bad (TM) thing.

There might be other delayed TLB flushing issues, sure. I would be surprised if there wouldn't be some, because it's complicated.

I spelled one out in the cover letter of v1.

We have flush_tlb_batched_pending() to sync against exactly what you describe.

I am pretty sure guard marker installation so far missed to call flush_tlb_batched_pending(). They really have to if they want to make sure no stale TLB entries can be used.

zapping will call flush_tlb_batched_pending(), but if guard markers don't need that, there might be stale tlb entries (which wont cause corruption or anything like that).

I had uffd in mind when working on this. But I was able to convince myself (well, AI helped) that it's just no something relevant to happen for uffd.

uffd will just fail if something is already mapped. Which is why it's only used either after zapping (flush_tlb_batched_pending()) or on unpopulated ranges. so the race doesn't matter, in particular, about UFFDIO_POISON.

Even for guard markers, there is only a tiny time window where you could still access the stale entries (while the folio is still in the page cache). It's hard to believe that that's really relevant in practice.

The right fix would be to throw in a flush_tlb_batched_pending(), if we care.

But that's completely independent of the changes here. That's just "syncing with reclaim" in a way people envisioned. Unfortunately.

Quoted 3 lines

It's gross to have to 'just know' to think about these things here but I think this should be reconsidered?

Yes, a lot of the delayed tlb flushing is "you have to do the right thing". But I don't see us changing that in a fix :)

We'll definetly need better docs, and I packed quite some information into my recent tlb flushing commit descriptions + cover letters.

[...[

Quoted 4 lines
Quoted 1 line

I think the rest of it needs to be chopped up to be really reviewable, or at least it's late here so :)

This is not really the material you're supposed to review after a long day :) .

If Kairui, Zi and others that are familiar with this code give it their blessing, it should be good enough as a fix.

Signature · 3 lines
Cheers,

David