Skip to contentSkip to conversation

mm: synchronize with PTE table reclaim for all folio sizes

PATCH Superseded Baolin Wang 7 participants 33 messages Nov 5 – Nov 16

Subsystems (5)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Baolin Wang

author reviewer
#0 lore raw

PATCH 1/1 mm: synchronize with PTE table reclaim for all folio sizes

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios") has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in madvise(MADV_DONTNEED)")
---
 mm/page_vma_mapped.c | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +1 -4
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
 			spin_unlock(pvmw->ptl);
 			pvmw->ptl = NULL;
 		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
+			if (pvmw->flags & PVMW_SYNC)
 				sync_with_folio_pmd_zap(mm, pvmw->pmd);
 
 			goto next_pmd;
Signature · 1 line
2.47.3
reviewer Acked-by on v1 1/1
#1 lore raw
Quoted 61 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios") has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in madvise(MADV_DONTNEED)")
---
  mm/page_vma_mapped.c | 5 +----
  1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -0
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
  			spin_unlock(pvmw->ptl);

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 299

Quoted 10 lines
mm/page_vma_mapped.c +1 -4
  			pvmw->ptl = NULL;
  		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
+			if (pvmw->flags & PVMW_SYNC)
  				sync_with_folio_pmd_zap(mm, pvmw->pmd);
 
  			goto next_pmd;

Thanks,
Qi

reviewer Reviewed-by on v1 1/1
#2 lore raw
In reply to Baolin Wang
Quoted 3 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

Good catch!

Quoted 56 lines

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios") has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in madvise(MADV_DONTNEED)")

---
mm/page_vma_mapped.c | 5 +----

1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -0
index e6b6170c2f4f..8797467b6f0c 100644

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 296

Quoted 8 lines
mm/page_vma_mapped.c +1 -4
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
 			spin_unlock(pvmw->ptl);
 			pvmw->ptl = NULL;
 		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
+			if (pvmw->flags & PVMW_SYNC)

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization that the caller explicitly asked for ;)

LGTM, thanks!

Quoted 7 lines
mm/page_vma_mapped.c +0 -0
 				sync_with_folio_pmd_zap(mm, pvmw->pmd);
 
 			goto next_pmd;
Signature · 1 line
2.47.3
reviewer
#3 lore raw
Quoted 68 lines · Lance Yang
Quoted 3 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

Good catch!

Quoted 60 lines

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios") has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in madvise(MADV_DONTNEED)")

---
mm/page_vma_mapped.c | 5 +----

1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -1
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
 			spin_unlock(pvmw->ptl);
 			pvmw->ptl = NULL;
 		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
Quoted 8 lines

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 296

Quoted 4 lines
mm/page_vma_mapped.c +1 -3
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
+			if (pvmw->flags & PVMW_SYNC)

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization that the caller explicitly asked for ;)

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Cheers, Lance

Quoted 11 lines

LGTM, thanks!

Quoted 7 lines
mm/page_vma_mapped.c +0 -0
 				sync_with_folio_pmd_zap(mm, pvmw->pmd);
 
 			goto next_pmd;
Signature · 1 line
2.47.3
author reviewer
#4 lore raw

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 81 lines · Lance Yang
Quoted 69 lines · Lance Yang
Quoted 3 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

Good catch!

Quoted 61 lines

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim)                      CPU 1 (MADV_DONTNEED) --------------------------------    -------------------------------- folio_lock(F)
try_to_unmap(F, TTU_SYNC)
                                    zap_pte_range(full PMD range) spin_lock(ptl) clear PTEs zap_empty_pte_table() spin_trylock(pml) pmd_clear() spin_unlock(pml)

  page_vma_mapped_walk()
    observe !pmd_present(pmde)
    nr_pages < HPAGE_PMD_NR
    skip synchronization
    return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F) tlb_flush_mmu_tlbonly() tlb_flush_rmaps() remove F's rmaps spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios") has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in madvise(MADV_DONTNEED)")

---
mm/page_vma_mapped.c | 5 +----

1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -1
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct 
 page_vma_mapped_walk *pvmw)
             spin_unlock(pvmw->ptl);
             pvmw->ptl = NULL;
         } else if (!pmd_present(pmde)) {
-            if ((pvmw->flags & PVMW_SYNC) &&
Quoted 8 lines

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 296

Quoted 4 lines
mm/page_vma_mapped.c +1 -3
-                thp_vma_suitable_order(vma, pvmw->address,
-                           PMD_ORDER) &&
-                (pvmw->nr_pages >= HPAGE_PMD_NR))
+            if (pvmw->flags & PVMW_SYNC)

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization that the caller explicitly asked for ;)

Quoted 4 lines

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

#5 lore raw
Quoted 20 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 8 lines · Lance Yang
Quoted 5 lines · Lance Yang

Good catch!

Quoted 8 lines
Quoted 3 lines

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization that the caller explicitly asked for ;)

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Quoted 6 lines

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

That makes sense. I hope this doesn't throw a big wrench into our reclaim performance numbers.

Can someone benchmark this?

But maybe we should really follow-up with the folio-size based optimization in sync_with_folio_pmd_zap(), where we only need a memory barrier (and sufficient documentation why something that cannot be PMD-mapped can get away cheaper).

Signature · 3 lines
Cheers,

David
author reviewer
#6 lore raw
Quoted 25 lines · David Hildenbrand (Arm)
Quoted 24 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 8 lines · Lance Yang
Quoted 5 lines · Lance Yang

Good catch!

Quoted 8 lines
Quoted 3 lines

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization that the caller explicitly asked for ;)

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

Quoted 7 lines
Quoted 2 lines

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

That makes sense. I hope this doesn't throw a big wrench into our reclaim performance numbers.

Can someone benchmark this?

Sure. I'll measure it if no one objects to this change.

Quoted 3 lines

But maybe we should really follow-up with the folio-size based optimization in sync_with_folio_pmd_zap(), where we only need a memory barrier (and sufficient documentation why something that cannot be PMD-mapped can get away cheaper).

OK. I'll do this later.

reviewer
#7 lore raw
In reply to David Hildenbrand (Arm)
Quoted 28 lines · David Hildenbrand (Arm)
Quoted 20 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 8 lines · Lance Yang
Quoted 5 lines · Lance Yang

Good catch!

Quoted 8 lines
Quoted 3 lines

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization that the caller explicitly asked for ;)

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Quoted 6 lines

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Quoted 8 lines

That makes sense. I hope this doesn't throw a big wrench into our reclaim performance numbers.

Can someone benchmark this?

But maybe we should really follow-up with the folio-size based optimization in sync_with_folio_pmd_zap(), where we only need a memory barrier (and sufficient documentation why something that cannot be PMD-mapped can get away cheaper).

Dug into the history a bit :D

TTU_SYNC goes back to Hugh's THP splitting fix [1]. A racing zap could clear the PTE/PMD before updating mapcount, so the walker could skip the lock and return before the accounting caught up.

Barry later enabled it for large-folio reclaim [2], to avoid skipping temporarily cleared PTEs and ending up with a partially unmapped folio. He mentioned that small folios had the same race, but with just one PTE, they couldn't be partially unmapped. That's where the large-folio check in shrink_folio_list() came from.

Then PTE table reclaim [3] added another way to end up with an empty PMD, even for a folio that can't be PMD-mapped. The truncation fix [4] moved the rmap flush before the PMD clear and extended synchronization in zap_pmd_range() to cover those folios too.

Looking back at the truncation discussion [5], you also pointed out that page_vma_mapped_walk() needed checking, and suggested a possible folio-size based optimization in the helper.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/92aba2b319a734913f18ba41e7d86a265f0b84e2.1733305182.git.zhengqi.arch@bytedance.com/
[4] https://lore.kernel.org/all/14ebbd556cc4941f0ebc43da59fa6a2fdca25dc8.1793148609.git.baolin.wang@linux.alibaba.com/
[5] https://lore.kernel.org/all/[email protected]/

So, how about starting with order-0 folios?

---8<---

include/linux/rmap.h +3 -0
index 74cca0e3c726..d01fe8282417 100644
@@ -872,6 +872,8 @@ struct page_vma_mapped_walk {
 	spinlock_t *ptl;
 	unsigned int flags;
 	bool pgoff_is_anon : 1;
+	/* Set from the folio, not the number of pages being walked. */
+	bool folio_is_order0 : 1;
 };
 
 #define DEFINE_FOLIO_VMA_WALK(name, _folio, _vma, _address, _flags)	\
@@ -883,6 +885,7 @@ struct page_vma_mapped_walk {
 		.address = _address,					\
 		.flags = _flags,					\
 		.pgoff_is_anon = folio_test_anon(_folio),		\
+		.folio_is_order0 = !folio_test_large(_folio),	\
 	}
 
 static inline void page_vma_mapped_walk_done(struct page_vma_mapped_walk *pvmw)
mm/internal.h +18 -10
index 9b8864a8540a..e70869b38292 100644
@@ -592,21 +592,29 @@ void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte);
  * sync_with_folio_pmd_zap - sync with concurrent zapping of folios
  * @mm: The mm_struct.
  * @pmdp: Pointer to the pmd that was found to be pmd_none().
+ * @order0: True if the target is known to be an order-0 folio.
  *
- * When we find a pmd_none() while unmapping a folio without holding the PTL,
- * zap_huge_pmd() may have cleared the PMD but not yet updated the folio
- * mapcount, and zap_empty_pte_table() clears the PMD only after the rmaps
- * for the table have been removed, but nothing orders the pmd_none() read
- * against later mapcount reads. Skipping the PMD without synchronization
- * could make folio unmapping code assume that unmapping failed.
+ * An empty PMD does not guarantee that a later mapcount read sees the
+ * completed rmap updates. For PMD-mapped folios, zap_huge_pmd() clears
+ * the PMD before updating mapcount, so we must wait for the PMD lock.
  *
- * Wait for concurrent zapping to complete by grabbing the PTL.
+ * Order-0 folios cannot be PMD-mapped. Their fully ordered
+ * atomic_add_negative() updates mapcount before PTE table reclaim clears
+ * the PMD. The PTE lock preserves this ordering if another CPU reclaims
+ * the table. A read barrier therefore suffices for order-0 folios.
+ * Keep taking the PMD lock for all other folios.
  */
-static inline void sync_with_folio_pmd_zap(struct mm_struct *mm, pmd_t *pmdp)
+static inline void sync_with_folio_pmd_zap(struct mm_struct *mm, pmd_t *pmdp,
+					   bool order0)
 {
-	spinlock_t *ptl = pmd_lock(mm, pmdp);
+	if (order0) {
+		/* Order the PMD read before subsequent mapcount reads. */
+		smp_rmb();
+	} else {
+		spinlock_t *ptl = pmd_lock(mm, pmdp);
 
-	spin_unlock(ptl);
+		spin_unlock(ptl);
+	}
 }
 
 struct zap_details;
mm/memory.c +2 -1
index 44376321180b..8955d1cd31b0 100644
@@ -2112,7 +2112,8 @@ static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
 			/* fall through */
 		} else if (pmd_none(*pmd)) {
 			if (details && details->single_folio)
-				sync_with_folio_pmd_zap(tlb->mm, pmd);
+				sync_with_folio_pmd_zap(tlb->mm, pmd,
+							!folio_test_large(details->single_folio));
 			addr = next;
 			continue;
 		}
mm/page_vma_mapped.c +4 -5
index e6b6170c2f4f..36881f8fd45e 100644
@@ -293,11 +293,9 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
 			spin_unlock(pvmw->ptl);
 			pvmw->ptl = NULL;
 		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
-				sync_with_folio_pmd_zap(mm, pvmw->pmd);
+			if (pvmw->flags & PVMW_SYNC)
+				sync_with_folio_pmd_zap(mm, pvmw->pmd,
+							pvmw->folio_is_order0);
 
 			goto next_pmd;
 		}
@@ -379,6 +377,7 @@ unsigned long page_mapped_in_vma(const struct page *page,
 		.nr_pages = 1,
 		.vma = vma,
 		.flags = PVMW_SYNC,
+		.folio_is_order0 = !folio_test_large(folio),
 	};
 
 	if (folio_test_anon(folio))
mm/vmscan.c +5 -14
index 7db6be53f3a9..79cfa9bc475b 100644
@@ -1434,26 +1434,17 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 		 * processes. Try to unmap it here.
 		 */
 		if (folio_mapped(folio)) {
-			enum ttu_flags flags = TTU_BATCH_FLUSH;
+			enum ttu_flags flags = TTU_BATCH_FLUSH | TTU_SYNC;
 			bool was_swapbacked = folio_test_swapbacked(folio);
 
 			if (folio_test_pmd_mappable(folio))
 				flags |= TTU_SPLIT_HUGE_PMD;
+
 			/*
-			 * Without TTU_SYNC, try_to_unmap will only begin to
-			 * hold PTL from the first present PTE within a large
-			 * folio. Some initial PTEs might be skipped due to
-			 * races with parallel PTE writes in which PTEs can be
-			 * cleared temporarily before being written new present
-			 * values. This will lead to a large folio is still
-			 * mapped while some subpages have been partially
-			 * unmapped after try_to_unmap; TTU_SYNC helps
-			 * try_to_unmap acquire PTL from the first PTE,
-			 * eliminating the influence of temporary PTE values.
+			 * Synchronize with concurrent rmap updates before checking
+			 * folio_mapped(). Also avoid skipping temporarily cleared
+			 * PTEs, which could leave a large folio partially mapped.
 			 */
-			if (folio_test_large(folio))
-				flags |= TTU_SYNC;
-
 			try_to_unmap(folio, flags);
 			if (folio_mapped(folio)) {
 				stat->nr_unmap_fail += nr_pages;

--

atomic_add_negative() provides full ordering for mapcount updates. With 243cf1f67b36, rmap removal completes before clearing PMD, including when another CPU reclaims an empty table under PTE lock. So smp_rmb() is enough here, without an extra writer-side barrier.

nr_pages == 1 isn't enough to identify an order-0 folio, since page_mapped_in_vma() also checks individual pages of large folios.

We can then enable TTU_SYNC for order-0 reclaim and use smp_rmb() on an empty PMD, while keeping PMD locking for large folios.

(Haven't benchmarked it yet) ...

Cheers, Lance

#8 lore raw
Quoted 66 lines · Lance Yang
Quoted 11 lines · David Hildenbrand (Arm)
Quoted 9 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Quoted 8 lines

That makes sense. I hope this doesn't throw a big wrench into our reclaim performance numbers.

Can someone benchmark this?

But maybe we should really follow-up with the folio-size based optimization in sync_with_folio_pmd_zap(), where we only need a memory barrier (and sufficient documentation why something that cannot be PMD-mapped can get away cheaper).

Dug into the history a bit :D

TTU_SYNC goes back to Hugh's THP splitting fix [1]. A racing zap could clear the PTE/PMD before updating mapcount, so the walker could skip the lock and return before the accounting caught up.

Barry later enabled it for large-folio reclaim [2], to avoid skipping temporarily cleared PTEs and ending up with a partially unmapped folio. He mentioned that small folios had the same race, but with just one PTE, they couldn't be partially unmapped. That's where the large-folio check in shrink_folio_list() came from.

Then PTE table reclaim [3] added another way to end up with an empty PMD, even for a folio that can't be PMD-mapped. The truncation fix [4] moved the rmap flush before the PMD clear and extended synchronization in zap_pmd_range() to cover those folios too.

Looking back at the truncation discussion [5], you also pointed out that page_vma_mapped_walk() needed checking, and suggested a possible folio-size based optimization in the helper.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/92aba2b319a734913f18ba41e7d86a265f0b84e2.1733305182.git.zhengqi.arch@bytedance.com/
[4] https://lore.kernel.org/all/14ebbd556cc4941f0ebc43da59fa6a2fdca25dc8.1793148609.git.baolin.wang@linux.alibaba.com/
[5] https://lore.kernel.org/all/[email protected]/

So, how about starting with order-0 folios?

---8<---

include/linux/rmap.h +2 -0
index 74cca0e3c726..d01fe8282417 100644
@@ -872,6 +872,8 @@ struct page_vma_mapped_walk {
 	spinlock_t *ptl;
 	unsigned int flags;
 	bool pgoff_is_anon : 1;
+	/* Set from the folio, not the number of pages being walked. */
+	bool folio_is_order0 : 1;
 };
 
 #define DEFINE_FOLIO_VMA_WALK(name, _folio, _vma, _address, _flags)	\

include/linux/rmap.h struct page_vma_mapped_walk { · line 889

Quoted 5 lines
include/linux/rmap.h +1 -0
@@ -883,6 +885,7 @@ struct page_vma_mapped_walk {
 		.address = _address,					\
 		.flags = _flags,					\
 		.pgoff_is_anon = folio_test_anon(_folio),		\
+		.folio_is_order0 = !folio_test_large(_folio),	\
 	}

We should pass the actual folio ;)

But yes, this goes into the direction I had in mind.

But I do wonder whether we need a separate fix first before we improve it?

Signature · 3 lines
Cheers,

David
author reviewer
#9 lore raw
In reply to Lance Yang
Quoted 51 lines · Lance Yang
Quoted 28 lines · David Hildenbrand (Arm)
Quoted 20 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 8 lines · Lance Yang
Quoted 5 lines · Lance Yang

Good catch!

Quoted 8 lines
Quoted 3 lines

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization that the caller explicitly asked for ;)

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Quoted 6 lines

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Quoted 8 lines

That makes sense. I hope this doesn't throw a big wrench into our reclaim performance numbers.

Can someone benchmark this?

But maybe we should really follow-up with the folio-size based optimization in sync_with_folio_pmd_zap(), where we only need a memory barrier (and sufficient documentation why something that cannot be PMD-mapped can get away cheaper).

Dug into the history a bit :D

TTU_SYNC goes back to Hugh's THP splitting fix [1]. A racing zap could clear the PTE/PMD before updating mapcount, so the walker could skip the lock and return before the accounting caught up.

Barry later enabled it for large-folio reclaim [2], to avoid skipping temporarily cleared PTEs and ending up with a partially unmapped folio. He mentioned that small folios had the same race, but with just one PTE, they couldn't be partially unmapped. That's where the large-folio check in shrink_folio_list() came from.

Quoted 8 lines

Then PTE table reclaim [3] added another way to end up with an empty PMD, even for a folio that can't be PMD-mapped. The truncation fix [4] moved the rmap flush before the PMD clear and extended synchronization in zap_pmd_range() to cover those folios too.

Looking back at the truncation discussion [5], you also pointed out that page_vma_mapped_walk() needed checking, and suggested a possible folio-size based optimization in the helper.

Thanks.

Quoted 153 lines

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/92aba2b319a734913f18ba41e7d86a265f0b84e2.1733305182.git.zhengqi.arch@bytedance.com/
[4] https://lore.kernel.org/all/14ebbd556cc4941f0ebc43da59fa6a2fdca25dc8.1793148609.git.baolin.wang@linux.alibaba.com/
[5] https://lore.kernel.org/all/[email protected]/

So, how about starting with order-0 folios?

---8<---

include/linux/rmap.h +3 -0
index 74cca0e3c726..d01fe8282417 100644
@@ -872,6 +872,8 @@ struct page_vma_mapped_walk {
  	spinlock_t *ptl;
  	unsigned int flags;
  	bool pgoff_is_anon : 1;
+	/* Set from the folio, not the number of pages being walked. */
+	bool folio_is_order0 : 1;
  };
 
  #define DEFINE_FOLIO_VMA_WALK(name, _folio, _vma, _address, _flags)	\
@@ -883,6 +885,7 @@ struct page_vma_mapped_walk {
  		.address = _address,					\
  		.flags = _flags,					\
  		.pgoff_is_anon = folio_test_anon(_folio),		\
+		.folio_is_order0 = !folio_test_large(_folio),	\
  	}
 
  static inline void page_vma_mapped_walk_done(struct page_vma_mapped_walk *pvmw)
mm/internal.h +18 -10
index 9b8864a8540a..e70869b38292 100644
@@ -592,21 +592,29 @@ void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte);
   * sync_with_folio_pmd_zap - sync with concurrent zapping of folios
   * @mm: The mm_struct.
   * @pmdp: Pointer to the pmd that was found to be pmd_none().
+ * @order0: True if the target is known to be an order-0 folio.
   *
- * When we find a pmd_none() while unmapping a folio without holding the PTL,
- * zap_huge_pmd() may have cleared the PMD but not yet updated the folio
- * mapcount, and zap_empty_pte_table() clears the PMD only after the rmaps
- * for the table have been removed, but nothing orders the pmd_none() read
- * against later mapcount reads. Skipping the PMD without synchronization
- * could make folio unmapping code assume that unmapping failed.
+ * An empty PMD does not guarantee that a later mapcount read sees the
+ * completed rmap updates. For PMD-mapped folios, zap_huge_pmd() clears
+ * the PMD before updating mapcount, so we must wait for the PMD lock.
   *
- * Wait for concurrent zapping to complete by grabbing the PTL.
+ * Order-0 folios cannot be PMD-mapped. Their fully ordered
+ * atomic_add_negative() updates mapcount before PTE table reclaim clears
+ * the PMD. The PTE lock preserves this ordering if another CPU reclaims
+ * the table. A read barrier therefore suffices for order-0 folios.
+ * Keep taking the PMD lock for all other folios.
   */
-static inline void sync_with_folio_pmd_zap(struct mm_struct *mm, pmd_t *pmdp)
+static inline void sync_with_folio_pmd_zap(struct mm_struct *mm, pmd_t *pmdp,
+					   bool order0)
  {
-	spinlock_t *ptl = pmd_lock(mm, pmdp);
+	if (order0) {
+		/* Order the PMD read before subsequent mapcount reads. */
+		smp_rmb();
+	} else {
+		spinlock_t *ptl = pmd_lock(mm, pmdp);
 
-	spin_unlock(ptl);
+		spin_unlock(ptl);
+	}
  }
 
  struct zap_details;
mm/memory.c +2 -1
index 44376321180b..8955d1cd31b0 100644
@@ -2112,7 +2112,8 @@ static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
  			/* fall through */
  		} else if (pmd_none(*pmd)) {
  			if (details && details->single_folio)
-				sync_with_folio_pmd_zap(tlb->mm, pmd);
+				sync_with_folio_pmd_zap(tlb->mm, pmd,
+							!folio_test_large(details->single_folio));
  			addr = next;
  			continue;
  		}
mm/page_vma_mapped.c +4 -5
index e6b6170c2f4f..36881f8fd45e 100644
@@ -293,11 +293,9 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
  			spin_unlock(pvmw->ptl);
  			pvmw->ptl = NULL;
  		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
-				sync_with_folio_pmd_zap(mm, pvmw->pmd);
+			if (pvmw->flags & PVMW_SYNC)
+				sync_with_folio_pmd_zap(mm, pvmw->pmd,
+							pvmw->folio_is_order0);
 
  			goto next_pmd;
  		}
@@ -379,6 +377,7 @@ unsigned long page_mapped_in_vma(const struct page *page,
  		.nr_pages = 1,
  		.vma = vma,
  		.flags = PVMW_SYNC,
+		.folio_is_order0 = !folio_test_large(folio),
  	};
 
  	if (folio_test_anon(folio))
mm/vmscan.c +5 -15
index 7db6be53f3a9..79cfa9bc475b 100644
@@ -1434,26 +1434,17 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
  		 * processes. Try to unmap it here.
  		 */
  		if (folio_mapped(folio)) {
-			enum ttu_flags flags = TTU_BATCH_FLUSH;
+			enum ttu_flags flags = TTU_BATCH_FLUSH | TTU_SYNC;
  			bool was_swapbacked = folio_test_swapbacked(folio);
 
  			if (folio_test_pmd_mappable(folio))
  				flags |= TTU_SPLIT_HUGE_PMD;
+
  			/*
-			 * Without TTU_SYNC, try_to_unmap will only begin to
-			 * hold PTL from the first present PTE within a large
-			 * folio. Some initial PTEs might be skipped due to
-			 * races with parallel PTE writes in which PTEs can be
-			 * cleared temporarily before being written new present
-			 * values. This will lead to a large folio is still
-			 * mapped while some subpages have been partially
-			 * unmapped after try_to_unmap; TTU_SYNC helps
-			 * try_to_unmap acquire PTL from the first PTE,
-			 * eliminating the influence of temporary PTE values.
+			 * Synchronize with concurrent rmap updates before checking
+			 * folio_mapped(). Also avoid skipping temporarily cleared
+			 * PTEs, which could leave a large folio partially mapped.
  			 */
-			if (folio_test_large(folio))
-				flags |= TTU_SYNC;
-
  			try_to_unmap(folio, flags);
  			if (folio_mapped(folio)) {
  				stat->nr_unmap_fail += nr_pages;
--
Quoted 4 lines

atomic_add_negative() provides full ordering for mapcount updates. With 243cf1f67b36, rmap removal completes before clearing PMD, including when another CPU reclaims an empty table under PTE lock. So smp_rmb() is enough here, without an extra writer-side barrier.

I'm afraid the memory barrier here is subtle. __folio_remove_rmap() is complex, and in the CONFIG_NO_PAGE_MAPCOUNT branch, folio_sub_return_large_mapcount() doesn't provide full ordering, so we may still need smp_wmb().

Anyway, as David said, let's fix this race first. Memory barrier optimization requires careful analysis and clear documentation.

reviewer
#10 lore raw
Quoted 59 lines · Baolin Wang
Quoted 56 lines · Lance Yang
Quoted 28 lines · David Hildenbrand (Arm)
Quoted 20 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 8 lines · Lance Yang
Quoted 5 lines · Lance Yang

Good catch!

Quoted 8 lines
Quoted 3 lines

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization that the caller explicitly asked for ;)

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Quoted 6 lines

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Quoted 8 lines

That makes sense. I hope this doesn't throw a big wrench into our reclaim performance numbers.

Can someone benchmark this?

But maybe we should really follow-up with the folio-size based optimization in sync_with_folio_pmd_zap(), where we only need a memory barrier (and sufficient documentation why something that cannot be PMD-mapped can get away cheaper).

Dug into the history a bit :D

TTU_SYNC goes back to Hugh's THP splitting fix [1]. A racing zap could clear the PTE/PMD before updating mapcount, so the walker could skip the lock and return before the accounting caught up.

Barry later enabled it for large-folio reclaim [2], to avoid skipping temporarily cleared PTEs and ending up with a partially unmapped folio. He mentioned that small folios had the same race, but with just one PTE, they couldn't be partially unmapped. That's where the large-folio check in shrink_folio_list() came from.

Then PTE table reclaim [3] added another way to end up with an empty PMD, even for a folio that can't be PMD-mapped. The truncation fix [4] moved the rmap flush before the PMD clear and extended synchronization in zap_pmd_range() to cover those folios too.

Quoted 5 lines
Quoted 3 lines

Looking back at the truncation discussion [5], you also pointed out that page_vma_mapped_walk() needed checking, and suggested a possible folio-size based optimization in the helper.

Thanks.

Cheers!

Quoted 153 lines
Quoted 153 lines

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/92aba2b319a734913f18ba41e7d86a265f0b84e2.1733305182.git.zhengqi.arch@bytedance.com/
[4] https://lore.kernel.org/all/14ebbd556cc4941f0ebc43da59fa6a2fdca25dc8.1793148609.git.baolin.wang@linux.alibaba.com/
[5] https://lore.kernel.org/all/[email protected]/

So, how about starting with order-0 folios?

---8<---

include/linux/rmap.h +3 -0
index 74cca0e3c726..d01fe8282417 100644
@@ -872,6 +872,8 @@ struct page_vma_mapped_walk {
  	spinlock_t *ptl;
  	unsigned int flags;
  	bool pgoff_is_anon : 1;
+	/* Set from the folio, not the number of pages being walked. */
+	bool folio_is_order0 : 1;
  };
 
  #define DEFINE_FOLIO_VMA_WALK(name, _folio, _vma, _address, _flags)	\
@@ -883,6 +885,7 @@ struct page_vma_mapped_walk {
  		.address = _address,					\
  		.flags = _flags,					\
  		.pgoff_is_anon = folio_test_anon(_folio),		\
+		.folio_is_order0 = !folio_test_large(_folio),	\
  	}
 
  static inline void page_vma_mapped_walk_done(struct page_vma_mapped_walk *pvmw)
mm/internal.h +18 -10
index 9b8864a8540a..e70869b38292 100644
@@ -592,21 +592,29 @@ void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte);
   * sync_with_folio_pmd_zap - sync with concurrent zapping of folios
   * @mm: The mm_struct.
   * @pmdp: Pointer to the pmd that was found to be pmd_none().
+ * @order0: True if the target is known to be an order-0 folio.
   *
- * When we find a pmd_none() while unmapping a folio without holding the PTL,
- * zap_huge_pmd() may have cleared the PMD but not yet updated the folio
- * mapcount, and zap_empty_pte_table() clears the PMD only after the rmaps
- * for the table have been removed, but nothing orders the pmd_none() read
- * against later mapcount reads. Skipping the PMD without synchronization
- * could make folio unmapping code assume that unmapping failed.
+ * An empty PMD does not guarantee that a later mapcount read sees the
+ * completed rmap updates. For PMD-mapped folios, zap_huge_pmd() clears
+ * the PMD before updating mapcount, so we must wait for the PMD lock.
   *
- * Wait for concurrent zapping to complete by grabbing the PTL.
+ * Order-0 folios cannot be PMD-mapped. Their fully ordered
+ * atomic_add_negative() updates mapcount before PTE table reclaim clears
+ * the PMD. The PTE lock preserves this ordering if another CPU reclaims
+ * the table. A read barrier therefore suffices for order-0 folios.
+ * Keep taking the PMD lock for all other folios.
   */
-static inline void sync_with_folio_pmd_zap(struct mm_struct *mm, pmd_t *pmdp)
+static inline void sync_with_folio_pmd_zap(struct mm_struct *mm, pmd_t *pmdp,
+					   bool order0)
  {
-	spinlock_t *ptl = pmd_lock(mm, pmdp);
+	if (order0) {
+		/* Order the PMD read before subsequent mapcount reads. */
+		smp_rmb();
+	} else {
+		spinlock_t *ptl = pmd_lock(mm, pmdp);
 
-	spin_unlock(ptl);
+		spin_unlock(ptl);
+	}
  }
 
  struct zap_details;
mm/memory.c +2 -1
index 44376321180b..8955d1cd31b0 100644
@@ -2112,7 +2112,8 @@ static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
  			/* fall through */
  		} else if (pmd_none(*pmd)) {
  			if (details && details->single_folio)
-				sync_with_folio_pmd_zap(tlb->mm, pmd);
+				sync_with_folio_pmd_zap(tlb->mm, pmd,
+							!folio_test_large(details->single_folio));
  			addr = next;
  			continue;
  		}
mm/page_vma_mapped.c +4 -5
index e6b6170c2f4f..36881f8fd45e 100644
@@ -293,11 +293,9 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
  			spin_unlock(pvmw->ptl);
  			pvmw->ptl = NULL;
  		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
-				sync_with_folio_pmd_zap(mm, pvmw->pmd);
+			if (pvmw->flags & PVMW_SYNC)
+				sync_with_folio_pmd_zap(mm, pvmw->pmd,
+							pvmw->folio_is_order0);
 
  			goto next_pmd;
  		}
@@ -379,6 +377,7 @@ unsigned long page_mapped_in_vma(const struct page *page,
  		.nr_pages = 1,
  		.vma = vma,
  		.flags = PVMW_SYNC,
+		.folio_is_order0 = !folio_test_large(folio),
  	};
 
  	if (folio_test_anon(folio))
mm/vmscan.c +5 -15
index 7db6be53f3a9..79cfa9bc475b 100644
@@ -1434,26 +1434,17 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
  		 * processes. Try to unmap it here.
  		 */
  		if (folio_mapped(folio)) {
-			enum ttu_flags flags = TTU_BATCH_FLUSH;
+			enum ttu_flags flags = TTU_BATCH_FLUSH | TTU_SYNC;
  			bool was_swapbacked = folio_test_swapbacked(folio);
 
  			if (folio_test_pmd_mappable(folio))
  				flags |= TTU_SPLIT_HUGE_PMD;
+
  			/*
-			 * Without TTU_SYNC, try_to_unmap will only begin to
-			 * hold PTL from the first present PTE within a large
-			 * folio. Some initial PTEs might be skipped due to
-			 * races with parallel PTE writes in which PTEs can be
-			 * cleared temporarily before being written new present
-			 * values. This will lead to a large folio is still
-			 * mapped while some subpages have been partially
-			 * unmapped after try_to_unmap; TTU_SYNC helps
-			 * try_to_unmap acquire PTL from the first PTE,
-			 * eliminating the influence of temporary PTE values.
+			 * Synchronize with concurrent rmap updates before checking
+			 * folio_mapped(). Also avoid skipping temporarily cleared
+			 * PTEs, which could leave a large folio partially mapped.
  			 */
-			if (folio_test_large(folio))
-				flags |= TTU_SYNC;
-
  			try_to_unmap(folio, flags);
  			if (folio_mapped(folio)) {
  				stat->nr_unmap_fail += nr_pages;
--
Quoted 9 lines
Quoted 4 lines

atomic_add_negative() provides full ordering for mapcount updates. With 243cf1f67b36, rmap removal completes before clearing PMD, including when another CPU reclaims an empty table under PTE lock. So smp_rmb() is enough here, without an extra writer-side barrier.

I'm afraid the memory barrier here is subtle. __folio_remove_rmap() is complex, and in the CONFIG_NO_PAGE_MAPCOUNT branch, folio_sub_return_large_mapcount() doesn't provide full ordering, so we may still need smp_wmb().

Yeah, agreed for large folios. In the diff above, only order-0 folios use smp_rmb().

Note that order-0 folios take the fully ordered atomic_add_negative() branch and skip the CONFIG_NO_PAGE_MAPCOUNT branch entirely.

static __always_inline void __folio_remove_rmap(struct folio *folio,
struct page *page, int nr_pages, struct vm_area_struct *vma, enum pgtable_level level)

{
	...
	switch (level) {
	case PGTABLE_LEVEL_PTE:
		if (!folio_test_large(folio)) {
			nr = atomic_add_negative(-1, &folio->_mapcount);
			break;
		}

		if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
			nr = folio_sub_return_large_mapcount(folio, nr_pages, vma);
			...
		}
		...
	}
	...
}

And large folios still take the PMD lock :D

Quoted 3 lines

Anyway, as David said, let's fix this race first. Memory barrier optimization requires careful analysis and clear documentation.

Yep, fine by me :D The fix goes first, of course. Thanks!

Cheers, Lance

author reviewer
#11 lore raw
Quoted 76 lines · Lance Yang
Quoted 59 lines · Baolin Wang
Quoted 56 lines · Lance Yang
Quoted 28 lines · David Hildenbrand (Arm)
Quoted 20 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 8 lines · Lance Yang
Quoted 5 lines · Lance Yang

Good catch!

Quoted 8 lines
Quoted 3 lines

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization that the caller explicitly asked for ;)

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Quoted 6 lines

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Quoted 8 lines

That makes sense. I hope this doesn't throw a big wrench into our reclaim performance numbers.

Can someone benchmark this?

But maybe we should really follow-up with the folio-size based optimization in sync_with_folio_pmd_zap(), where we only need a memory barrier (and sufficient documentation why something that cannot be PMD-mapped can get away cheaper).

Dug into the history a bit :D

TTU_SYNC goes back to Hugh's THP splitting fix [1]. A racing zap could clear the PTE/PMD before updating mapcount, so the walker could skip the lock and return before the accounting caught up.

Barry later enabled it for large-folio reclaim [2], to avoid skipping temporarily cleared PTEs and ending up with a partially unmapped folio. He mentioned that small folios had the same race, but with just one PTE, they couldn't be partially unmapped. That's where the large-folio check in shrink_folio_list() came from.

Then PTE table reclaim [3] added another way to end up with an empty PMD, even for a folio that can't be PMD-mapped. The truncation fix [4] moved the rmap flush before the PMD clear and extended synchronization in zap_pmd_range() to cover those folios too.

Quoted 5 lines
Quoted 3 lines

Looking back at the truncation discussion [5], you also pointed out that page_vma_mapped_walk() needed checking, and suggested a possible folio-size based optimization in the helper.

Thanks.

Cheers!

Quoted 7 lines
Quoted 7 lines

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/92aba2b319a734913f18ba41e7d86a265f0b84e2.1733305182.git.zhengqi.arch@bytedance.com/
[4] https://lore.kernel.org/all/14ebbd556cc4941f0ebc43da59fa6a2fdca25dc8.1793148609.git.baolin.wang@linux.alibaba.com/
[5] https://lore.kernel.org/all/[email protected]/

So, how about starting with order-0 folios?

.......

Quoted 11 lines
Quoted 10 lines
Quoted 5 lines

atomic_add_negative() provides full ordering for mapcount updates. With 243cf1f67b36, rmap removal completes before clearing PMD, including when another CPU reclaims an empty table under PTE lock. So smp_rmb() is enough here, without an extra writer-side barrier.

I'm afraid the memory barrier here is subtle. __folio_remove_rmap() is complex, and in the CONFIG_NO_PAGE_MAPCOUNT branch, folio_sub_return_large_mapcount() doesn't provide full ordering, so we may still need smp_wmb().

Quoted 5 lines

Yeah, agreed for large folios. In the diff above, only order-0 folios use smp_rmb().

Note that order-0 folios take the fully ordered atomic_add_negative() branch and skip the CONFIG_NO_PAGE_MAPCOUNT branch entirely.

Yes.

Quoted 21 lines

static __always_inline void __folio_remove_rmap(struct folio *folio,
struct page *page, int nr_pages, struct vm_area_struct *vma, enum pgtable_level level)

{
	...
	switch (level) {
	case PGTABLE_LEVEL_PTE:
		if (!folio_test_large(folio)) {
			nr = atomic_add_negative(-1, &folio->_mapcount);
			break;
		}

		if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
			nr = folio_sub_return_large_mapcount(folio, nr_pages, vma);
			...
		}
		...
	}
	...
}
Quoted 1 line

And large folios still take the PMD lock :D

IIUC, the memory barrier optimization targets all non-PMD-sized folios (including large folios). That is, for PMD-sized large folios we still use the original PMD lock, while for other non-PMD-sized folios we can use memory barriers to sync.

#12 lore raw
Quoted 50 lines · Baolin Wang
Quoted 9 lines · Lance Yang
Quoted 4 lines · Baolin Wang

Thanks.

Cheers!

.......

Quoted 11 lines
Quoted 5 lines

I'm afraid the memory barrier here is subtle. __folio_remove_rmap() is complex, and in the CONFIG_NO_PAGE_MAPCOUNT branch, folio_sub_return_large_mapcount() doesn't provide full ordering, so we may still need smp_wmb().

Yeah, agreed for large folios. In the diff above, only order-0 folios use smp_rmb().

Note that order-0 folios take the fully ordered atomic_add_negative() branch and skip the CONFIG_NO_PAGE_MAPCOUNT branch entirely.

Yes.

Quoted 21 lines

static __always_inline void __folio_remove_rmap(struct folio *folio,
struct page *page, int nr_pages, struct vm_area_struct *vma, enum pgtable_level level)

{
	...
	switch (level) {
	case PGTABLE_LEVEL_PTE:
		if (!folio_test_large(folio)) {
			nr = atomic_add_negative(-1, &folio->_mapcount);
			break;
		}

		if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
			nr = folio_sub_return_large_mapcount(folio, nr_pages, vma);
			...
		}
		...
	}
	...
}
Quoted 6 lines
Quoted 1 line

And large folios still take the PMD lock :D

IIUC, the memory barrier optimization targets all non-PMD-sized folios (including large folios). That is, for PMD-sized large folios we still use the original PMD lock, while for other non-PMD-sized folios we can use memory barriers to sync.

It would be nice to prototype a patch and document the required memory barriers and how it is expected to work.

Signature · 3 lines
Cheers,

David
reviewer
#13 lore raw
In reply to Baolin Wang
Quoted 99 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 90 lines · Lance Yang
Quoted 78 lines · Lance Yang
Quoted 5 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped
folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race
with concurrent page table reclamation via zap_empty_pte_table().

Good catch!

Quoted 68 lines

page_vma_mapped_walk() is used by many functions including try_to_unmap(),
try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(),
page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap()
and try_to_migrate(), the other callers do not perform post-walk accounting
checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios")
has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in

madvise(MADV_DONTNEED)")

---
mm/page_vma_mapped.c | 5 +----

1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -2
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct
 page_vma_mapped_walk *pvmw)
            spin_unlock(pvmw->ptl);
            pvmw->ptl = NULL;
        } else if (!pmd_present(pmde)) {
-            if ((pvmw->flags & PVMW_SYNC) &&
-                thp_vma_suitable_order(vma, pvmw->address,
Quoted 8 lines

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 296

Quoted 3 lines
mm/page_vma_mapped.c +1 -2
-                           PMD_ORDER) &&
-                (pvmw->nr_pages >= HPAGE_PMD_NR))
+            if (pvmw->flags & PVMW_SYNC)

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization
that the caller explicitly asked for ;)

Quoted 4 lines

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Quoted 6 lines

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Baolin, thanks for reaching out to me. I added that flag mainly for large folios.

I observed cases where PTEs for large folios are partially cleared during certain transition states, for example, when PTEs are cleared before being modified:

pte = ptep_get_and_clear();
pte modification;
set_pte_at();

In such cases, page_vma_mapped_walk() skips the empty entries and starts from the next valid one.

This may result in partially unmapping PTEs for large folios and trigger unexpected folio splits. At the time, I was particularly concerned about unnecessary folio splitting, so my focus was mainly on large folios.

However, I also noticed that a similar race can occur with small folios. In that case, the folio may simply remain unreclaimed by the reclamation path.

However, my main concern at the time was avoiding unnecessary folio splits.

Your new race also seems to amplify the same situation. However, I don't think this problem necessarily depends on the commit you mentioned. It has been around for a long time.

If the concern is reclaim failure, I agree that there is no fundamental difference between large folios and small folios.

Best,
Barry

author reviewer
#14 lore raw
Quoted 119 lines · Barry Song
Quoted 99 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 90 lines · Lance Yang
Quoted 78 lines · Lance Yang
Quoted 5 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped
folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race
with concurrent page table reclamation via zap_empty_pte_table().

Good catch!

Quoted 68 lines

page_vma_mapped_walk() is used by many functions including try_to_unmap(),
try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(),
page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap()
and try_to_migrate(), the other callers do not perform post-walk accounting
checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios")
has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in

madvise(MADV_DONTNEED)")

---
mm/page_vma_mapped.c | 5 +----

1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -2
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct
 page_vma_mapped_walk *pvmw)
             spin_unlock(pvmw->ptl);
             pvmw->ptl = NULL;
         } else if (!pmd_present(pmde)) {
-            if ((pvmw->flags & PVMW_SYNC) &&
-                thp_vma_suitable_order(vma, pvmw->address,
Quoted 8 lines

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 296

Quoted 3 lines
mm/page_vma_mapped.c +1 -2
-                           PMD_ORDER) &&
-                (pvmw->nr_pages >= HPAGE_PMD_NR))
+            if (pvmw->flags & PVMW_SYNC)

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization
that the caller explicitly asked for ;)

Quoted 4 lines

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Quoted 6 lines

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Baolin, thanks for reaching out to me. I added that flag mainly for large folios.

I observed cases where PTEs for large folios are partially cleared during certain transition states, for example, when PTEs are cleared before being modified:

pte = ptep_get_and_clear();
pte modification;
set_pte_at();

Quoted 7 lines

In such cases, page_vma_mapped_walk() skips the empty entries and starts from the next valid one.

This may result in partially unmapping PTEs for large folios and trigger unexpected folio splits. At the time, I was particularly concerned about unnecessary folio splitting, so my focus was mainly on large folios.

Thanks for the information.

Quoted 10 lines

However, I also noticed that a similar race can occur with small folios. In that case, the folio may simply remain unreclaimed by the reclamation path.

However, my main concern at the time was avoiding unnecessary folio splits.

Your new race also seems to amplify the same situation. However, I don't think this problem necessarily depends on the commit you mentioned. It has been around for a long time.

Agree.

Quoted 2 lines

If the concern is reclaim failure, I agree that there is no fundamental difference between large folios and small folios.

OK. And I did a quick measurement to reclaim anon and file folios via the memory.reclaim interface.

From test results, reclaiming 1G small anonymous folios (using zram as swap) shows no significant performance change. However, reclaiming 1G mapped clean small file folios does show an observable regression if the TTU_SYNC flag is set.

Without TTU_SYNC for small folios:
time echo 1G > /sys/fs/cgroup/test/memory.reclaim
real 0m0.178s
user 0m0.000s
sys 0m0.178s

With TTU_SYNC for small folios:
real 0m0.315s
user 0m0.000s
sys 0m0.314s

So for the current patch, I'd prefer to keep things as is: only sync when TTU_SYNC is set. Without setting the TTU_SYNC flag, keep the original logic, meaning the caller can tolerate some racy checks.

Any other thoughts?

reviewer
#15 lore raw
Quoted 162 lines · Baolin Wang
Quoted 119 lines · Barry Song
Quoted 99 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 90 lines · Lance Yang
Quoted 78 lines · Lance Yang
Quoted 5 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped
folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race
with concurrent page table reclamation via zap_empty_pte_table().

Good catch!

Quoted 68 lines

page_vma_mapped_walk() is used by many functions including try_to_unmap(),
try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(),
page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap()
and try_to_migrate(), the other callers do not perform post-walk accounting
checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios")
has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in

madvise(MADV_DONTNEED)")

---
mm/page_vma_mapped.c | 5 +----

1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -2
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct
 page_vma_mapped_walk *pvmw)
             spin_unlock(pvmw->ptl);
             pvmw->ptl = NULL;
         } else if (!pmd_present(pmde)) {
-            if ((pvmw->flags & PVMW_SYNC) &&
-                thp_vma_suitable_order(vma, pvmw->address,
Quoted 8 lines

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 296

Quoted 3 lines
mm/page_vma_mapped.c +1 -2
-                           PMD_ORDER) &&
-                (pvmw->nr_pages >= HPAGE_PMD_NR))
+            if (pvmw->flags & PVMW_SYNC)

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization
that the caller explicitly asked for ;)

Quoted 4 lines

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Quoted 6 lines

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Baolin, thanks for reaching out to me. I added that flag mainly for large folios.

I observed cases where PTEs for large folios are partially cleared during certain transition states, for example, when PTEs are cleared before being modified:

pte = ptep_get_and_clear();
pte modification;
set_pte_at();

Quoted 7 lines

In such cases, page_vma_mapped_walk() skips the empty entries and starts from the next valid one.

This may result in partially unmapping PTEs for large folios and trigger unexpected folio splits. At the time, I was particularly concerned about unnecessary folio splitting, so my focus was mainly on large folios.

Thanks for the information.

Quoted 10 lines

However, I also noticed that a similar race can occur with small folios. In that case, the folio may simply remain unreclaimed by the reclamation path.

However, my main concern at the time was avoiding unnecessary folio splits.

Your new race also seems to amplify the same situation. However, I don't think this problem necessarily depends on the commit you mentioned. It has been around for a long time.

Agree.

Quoted 2 lines

If the concern is reclaim failure, I agree that there is no fundamental difference between large folios and small folios.

OK. And I did a quick measurement to reclaim anon and file folios via the memory.reclaim interface.

From test results, reclaiming 1G small anonymous folios (using zram as swap) shows no significant performance change. However, reclaiming 1G mapped clean small file folios does show an observable regression if the TTU_SYNC flag is set.

Without TTU_SYNC for small folios:
time echo 1G > /sys/fs/cgroup/test/memory.reclaim
real 0m0.178s
user 0m0.000s
sys 0m0.178s

Quoted 4 lines

With TTU_SYNC for small folios:
real 0m0.315s
user 0m0.000s
sys 0m0.314s

Nice numbers, cool!

Quoted 5 lines

So for the current patch, I'd prefer to keep things as is: only sync when TTU_SYNC is set. Without setting the TTU_SYNC flag, keep the original logic, meaning the caller can tolerate some racy checks.

Any other thoughts?

One thing I want to pin down first, for the order-0 folios, was that run with TTU_SYNC going through the pmd lock, or did it already go the smp_rmb() way?

My guess is the first one, right?

If so, please keep the fix as is and only sync when the caller asks for it (at least, order-0 folios should not go the pmd lock way) :D

Cheers, Lance

reviewer
#16 lore raw
Quoted 177 lines · Lance Yang
Quoted 162 lines · Baolin Wang
Quoted 119 lines · Barry Song
Quoted 99 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 90 lines · Lance Yang
Quoted 78 lines · Lance Yang
Quoted 5 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped
folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race
with concurrent page table reclamation via zap_empty_pte_table().

Good catch!

Quoted 68 lines

page_vma_mapped_walk() is used by many functions including try_to_unmap(),
try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(),
page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap()
and try_to_migrate(), the other callers do not perform post-walk accounting
checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios")
has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in

madvise(MADV_DONTNEED)")

---
mm/page_vma_mapped.c | 5 +----

1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -2
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct
 page_vma_mapped_walk *pvmw)
              spin_unlock(pvmw->ptl);
              pvmw->ptl = NULL;
          } else if (!pmd_present(pmde)) {
-            if ((pvmw->flags & PVMW_SYNC) &&
-                thp_vma_suitable_order(vma, pvmw->address,
Quoted 8 lines

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct · line 297

Quoted 3 lines
mm/page_vma_mapped.c +1 -2
-                           PMD_ORDER) &&
-                (pvmw->nr_pages >= HPAGE_PMD_NR))
+            if (pvmw->flags & PVMW_SYNC)

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization
that the caller explicitly asked for ;)

Quoted 4 lines

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Quoted 6 lines

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Baolin, thanks for reaching out to me. I added that flag mainly for large folios.

I observed cases where PTEs for large folios are partially cleared during certain transition states, for example, when PTEs are cleared before being modified:

pte = ptep_get_and_clear();
pte modification;
set_pte_at();

Quoted 7 lines

In such cases, page_vma_mapped_walk() skips the empty entries and starts from the next valid one.

This may result in partially unmapping PTEs for large folios and trigger unexpected folio splits. At the time, I was particularly concerned about unnecessary folio splitting, so my focus was mainly on large folios.

Thanks for the information.

Quoted 10 lines

However, I also noticed that a similar race can occur with small folios. In that case, the folio may simply remain unreclaimed by the reclamation path.

However, my main concern at the time was avoiding unnecessary folio splits.

Your new race also seems to amplify the same situation. However, I don't think this problem necessarily depends on the commit you mentioned. It has been around for a long time.

Agree.

Quoted 2 lines

If the concern is reclaim failure, I agree that there is no fundamental difference between large folios and small folios.

OK. And I did a quick measurement to reclaim anon and file folios via the memory.reclaim interface.

From test results, reclaiming 1G small anonymous folios (using zram as
swap) shows no significant performance change. However, reclaiming 1G mapped clean small file folios does show an observable regression if the TTU_SYNC flag is set.

Without TTU_SYNC for small folios:
time echo 1G > /sys/fs/cgroup/test/memory.reclaim
real 0m0.178s
user 0m0.000s
sys 0m0.178s

Quoted 4 lines

With TTU_SYNC for small folios:
real 0m0.315s
user 0m0.000s
sys 0m0.314s

Nice numbers, cool!

Quoted 5 lines

So for the current patch, I'd prefer to keep things as is: only sync when TTU_SYNC is set. Without setting the TTU_SYNC flag, keep the original logic, meaning the caller can tolerate some racy checks.

Any other thoughts?

Quoted 8 lines

One thing I want to pin down first, for the order-0 folios, was that run with TTU_SYNC going through the pmd lock, or did it already go the smp_rmb() way?

My guess is the first one, right?

If so, please keep the fix as is and only sync when the caller asks for it (at least, order-0 folios should not go the pmd lock way) :D

In addition:

For order-0 folios, we'd miss reclaim and reactivate a cold folio.

That doesn't sound too bad, especially for such a rare race.

so keeping the current behavior seems reasonable given the sync overhead ;)

Quoted 1 line

Cheers, Lance

author reviewer
#17 lore raw
Quoted 179 lines · Lance Yang
Quoted 176 lines · Lance Yang
Quoted 163 lines · Baolin Wang
Quoted 120 lines · Barry Song
Quoted 100 lines · Baolin Wang

CC Barry, who added the TTU_SYNC in shrink_folio_list().

Quoted 91 lines · Lance Yang
Quoted 79 lines · Lance Yang
Quoted 5 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped
folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race
with concurrent page table reclamation via zap_empty_pte_table().

Good catch!

Quoted 69 lines

page_vma_mapped_walk() is used by many functions including try_to_unmap(),
try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(),
page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap()
and try_to_migrate(), the other callers do not perform post-walk accounting
checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim)                      CPU 1 (MADV_DONTNEED)
--------------------------------
--------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
                                      zap_pte_range(full PMD range) spin_lock(ptl) clear PTEs zap_empty_pte_table() spin_trylock(pml) pmd_clear() spin_unlock(pml)

    page_vma_mapped_walk()
      observe !pmd_present(pmde)
      nr_pages < HPAGE_PMD_NR
      skip synchronization
      return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F) tlb_flush_mmu_tlbonly() tlb_flush_rmaps() remove F's rmaps spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios")
has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in

madvise(MADV_DONTNEED)")

---
mm/page_vma_mapped.c | 5 +----

1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -2
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct
 page_vma_mapped_walk *pvmw)
               spin_unlock(pvmw->ptl);
               pvmw->ptl = NULL;
           } else if (!pmd_present(pmde)) {
-            if ((pvmw->flags & PVMW_SYNC) &&
-                thp_vma_suitable_order(vma, pvmw->address,
Quoted 8 lines

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct · line 297

Quoted 3 lines
mm/page_vma_mapped.c +1 -2
-                           PMD_ORDER) &&
-                (pvmw->nr_pages >= HPAGE_PMD_NR))
+            if (pvmw->flags & PVMW_SYNC)

Right. Whether the folio can be PMD-mapped doesn't tell us whether its PTE table can be reclaimed, so those extra checks can skip synchronization
that the caller explicitly asked for ;)

Quoted 4 lines

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Quoted 6 lines

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Baolin, thanks for reaching out to me. I added that flag mainly for large folios.

I observed cases where PTEs for large folios are partially cleared during certain transition states, for example, when PTEs are cleared before being modified:

pte = ptep_get_and_clear();
pte modification;
set_pte_at();

Quoted 7 lines

In such cases, page_vma_mapped_walk() skips the empty entries and starts from the next valid one.

This may result in partially unmapping PTEs for large folios and trigger unexpected folio splits. At the time, I was particularly concerned about unnecessary folio splitting, so my focus was mainly on large folios.

Thanks for the information.

Quoted 10 lines

However, I also noticed that a similar race can occur with small folios. In that case, the folio may simply remain unreclaimed by the reclamation path.

However, my main concern at the time was avoiding unnecessary folio splits.

Your new race also seems to amplify the same situation. However, I don't think this problem necessarily depends on the commit you mentioned. It has been around for a long time.

Agree.

Quoted 2 lines

If the concern is reclaim failure, I agree that there is no fundamental difference between large folios and small folios.

OK. And I did a quick measurement to reclaim anon and file folios via the memory.reclaim interface.

 From test results, reclaiming 1G small anonymous folios (using zram as swap) shows no significant performance change. However, reclaiming 1G mapped clean small file folios does show an observable regression if the TTU_SYNC flag is set.

Without TTU_SYNC for small folios:
time echo 1G > /sys/fs/cgroup/test/memory.reclaim
real    0m0.178s
user    0m0.000s
sys    0m0.178s

Quoted 4 lines

With TTU_SYNC for small folios:
real    0m0.315s
user    0m0.000s
sys    0m0.314s

Nice numbers, cool!

Quoted 4 lines

So for the current patch, I'd prefer to keep things as is: only sync when TTU_SYNC is set. Without setting the TTU_SYNC flag, keep the original logic, meaning the caller can tolerate some racy checks.

Quoted 7 lines
Quoted 7 lines
Quoted 1 line

Any other thoughts?

One thing I want to pin down first, for the order-0 folios, was that run with TTU_SYNC going through the pmd lock, or did it already go the smp_rmb() way?

My guess is the first one, right?

Right. I didn't add the memory barriers optimization (will do in a follow-up). The test changes are as follows:

mm/vmscan.c +0 -5
index daa7e37c2236..6a95a4fdc64c 100644
@@ -1434,11 +1434,6 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
                 * processes. Try to unmap it here.
                 */
                if (folio_mapped(folio)) {
-                       enum ttu_flags flags = TTU_BATCH_FLUSH;
-                       bool was_swapbacked = folio_test_swapbacked(folio);
-
-                       if (folio_test_pmd_mappable(folio))
-                               flags |= TTU_SPLIT_HUGE_PMD;
                        /*
                         * Without TTU_SYNC, try_to_unmap will only 

begin to
* hold PTL from the first present PTE within a
large
@@ -1451,8 +1446,11 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
* try_to_unmap acquire PTL from the first PTE,
* eliminating the influence of temporary PTE
values.

                         */

- if (folio_test_large(folio))
- flags |= TTU_SYNC;
+ enum ttu_flags flags = TTU_BATCH_FLUSH | TTU_SYNC;
+ bool was_swapbacked = folio_test_swapbacked(folio);
+
+ if (folio_test_pmd_mappable(folio))
+ flags |= TTU_SPLIT_HUGE_PMD;

                        try_to_unmap(folio, flags);
                        if (folio_mapped(folio)) {
Quoted 11 lines
Quoted 2 lines

If so, please keep the fix as is and only sync when the caller asks for it (at least, order-0 folios should not go the pmd lock way) :D

In addition:

For order-0 folios, we'd miss reclaim and reactivate a cold folio.

That doesn't sound too bad, especially for such a rare race.

so keeping the current behavior seems reasonable given the sync overhead ;)

That's also my thought:)

reviewer
#18 lore raw
In reply to Baolin Wang

On Fri, Nov 6, 2026 at 4:55 PM Baolin Wang
<[email protected]> wrote:
[...]

Quoted 68 lines
Quoted 23 lines
Quoted 11 lines
Quoted 4 lines

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Baolin, thanks for reaching out to me. I added that flag mainly for large folios.

I observed cases where PTEs for large folios are partially cleared during certain transition states, for example, when PTEs are cleared before being modified:

pte = ptep_get_and_clear();
pte modification;
set_pte_at();

Quoted 7 lines

In such cases, page_vma_mapped_walk() skips the empty entries and starts from the next valid one.

This may result in partially unmapping PTEs for large folios and trigger unexpected folio splits. At the time, I was particularly concerned about unnecessary folio splitting, so my focus was mainly on large folios.

Thanks for the information.

Quoted 10 lines

However, I also noticed that a similar race can occur with small folios. In that case, the folio may simply remain unreclaimed by the reclamation path.

However, my main concern at the time was avoiding unnecessary folio splits.

Your new race also seems to amplify the same situation. However, I don't think this problem necessarily depends on the commit you mentioned. It has been around for a long time.

Agree.

Quoted 2 lines

If the concern is reclaim failure, I agree that there is no fundamental difference between large folios and small folios.

OK. And I did a quick measurement to reclaim anon and file folios via the memory.reclaim interface.

From test results, reclaiming 1G small anonymous folios (using zram as
swap) shows no significant performance change. However, reclaiming 1G mapped clean small file folios does show an observable regression if the TTU_SYNC flag is set.

Without TTU_SYNC for small folios:
time echo 1G > /sys/fs/cgroup/test/memory.reclaim

real    0m0.178s
user    0m0.000s
sys     0m0.178s

With TTU_SYNC for small folios:

real    0m0.315s
user    0m0.000s
sys     0m0.314s
Quoted 5 lines

So for the current patch, I'd prefer to keep things as is: only sync when TTU_SYNC is set. Without setting the TTU_SYNC flag, keep the original logic, meaning the caller can tolerate some racy checks.

Any other thoughts?

I'm still struggling to understand where the regression comes from. You're doing echo 1G > /sys/fs/cgroup/test/memory.reclaim without the concurrent CPU 1 (MADV_DONTNEED) operation that causes the race.

so the regression actually comes from other places, maybe here?

static bool map_pte(struct page_vma_mapped_walk *pvmw, pmd_t *pmdvalp,
spinlock_t **ptlp)

{
        bool is_migration;
        pte_t ptent;

        if (pvmw->flags & PVMW_SYNC) {
                /* Use the stricter lookup */
                pvmw->pte = pte_offset_map_lock(pvmw->vma->vm_mm, pvmw->pmd,
                                                pvmw->address, &pvmw->ptl);
                *ptlp = pvmw->ptl;
                return !!pvmw->pte;
        }
       ...
}

Am I missing something?

Best,
Barry

author reviewer
#19 lore raw
Quoted 75 lines · Barry Song

On Fri, Nov 6, 2026 at 4:55 PM Baolin Wang
<[email protected]> wrote:
[...]

Quoted 72 lines
Quoted 23 lines
Quoted 11 lines
Quoted 4 lines

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Baolin, thanks for reaching out to me. I added that flag mainly for large folios.

I observed cases where PTEs for large folios are partially cleared during certain transition states, for example, when PTEs are cleared before being modified:

pte = ptep_get_and_clear();
pte modification;
set_pte_at();

Quoted 7 lines

In such cases, page_vma_mapped_walk() skips the empty entries and starts from the next valid one.

This may result in partially unmapping PTEs for large folios and trigger unexpected folio splits. At the time, I was particularly concerned about unnecessary folio splitting, so my focus was mainly on large folios.

Thanks for the information.

Quoted 10 lines

However, I also noticed that a similar race can occur with small folios. In that case, the folio may simply remain unreclaimed by the reclamation path.

However, my main concern at the time was avoiding unnecessary folio splits.

Your new race also seems to amplify the same situation. However, I don't think this problem necessarily depends on the commit you mentioned. It has been around for a long time.

Agree.

Quoted 2 lines

If the concern is reclaim failure, I agree that there is no fundamental difference between large folios and small folios.

OK. And I did a quick measurement to reclaim anon and file folios via the memory.reclaim interface.

From test results, reclaiming 1G small anonymous folios (using zram as
swap) shows no significant performance change. However, reclaiming 1G mapped clean small file folios does show an observable regression if the TTU_SYNC flag is set.

Without TTU_SYNC for small folios:
time echo 1G > /sys/fs/cgroup/test/memory.reclaim

real    0m0.178s
user    0m0.000s
sys     0m0.178s

With TTU_SYNC for small folios:

real    0m0.315s
user    0m0.000s
sys     0m0.314s

So for the current patch, I'd prefer to keep things as is: only sync when TTU_SYNC is set. Without setting the TTU_SYNC flag, keep the original logic, meaning the caller can tolerate some racy checks.

Quoted 8 lines
Quoted 1 line

Any other thoughts?

I'm still struggling to understand where the regression comes from. You're doing echo 1G > /sys/fs/cgroup/test/memory.reclaim without the concurrent CPU 1 (MADV_DONTNEED) operation that causes the race.

so the regression actually comes from other places, maybe here?

Yes, I think so. But I haven't had time to dig into how this affects my tests yet. I'll dig into this later.

author reviewer
#20 lore raw

Hi Barry,

Quoted 80 lines · Baolin Wang
Quoted 77 lines · Barry Song

On Fri, Nov 6, 2026 at 4:55 PM Baolin Wang
<[email protected]> wrote:
[...]

Quoted 73 lines
Quoted 23 lines
Quoted 11 lines
Quoted 4 lines

Ouch ... one thing I missed ... what about order-0 reclaim?

shrink_folio_list() only sets TTU_SYNC for large folio, so can't we still hit the same race there?

Thanks Lance. But this matches the purpose of the TTU_SYNC flag, which is used to avoid racy checks with PVMW_SYNC. If no TTU_SYNC flag is set, it means the caller can tolerate some racy checks.

For this case, I think we should set TTU_SYNC unconditionally in shrink_folio_list(). Barry, what do you think?

Baolin, thanks for reaching out to me. I added that flag mainly for large folios.

I observed cases where PTEs for large folios are partially cleared during certain transition states, for example, when PTEs are cleared before being modified:

pte = ptep_get_and_clear();
pte modification;
set_pte_at();

Quoted 7 lines

In such cases, page_vma_mapped_walk() skips the empty entries and starts from the next valid one.

This may result in partially unmapping PTEs for large folios and trigger unexpected folio splits. At the time, I was particularly concerned about unnecessary folio splitting, so my focus was mainly on large folios.

Thanks for the information.

Quoted 10 lines

However, I also noticed that a similar race can occur with small folios. In that case, the folio may simply remain unreclaimed by the reclamation path.

However, my main concern at the time was avoiding unnecessary folio splits.

Your new race also seems to amplify the same situation. However, I don't think this problem necessarily depends on the commit you mentioned. It has been around for a long time.

Agree.

Quoted 2 lines

If the concern is reclaim failure, I agree that there is no fundamental difference between large folios and small folios.

OK. And I did a quick measurement to reclaim anon and file folios via the memory.reclaim interface.

  From test results, reclaiming 1G small anonymous folios (using zram as swap) shows no significant performance change. However, reclaiming 1G mapped clean small file folios does show an observable regression if the TTU_SYNC flag is set.

Without TTU_SYNC for small folios:
time echo 1G > /sys/fs/cgroup/test/memory.reclaim
real    0m0.178s
user    0m0.000s
sys     0m0.178s

With TTU_SYNC for small folios:
real    0m0.315s
user    0m0.000s
sys     0m0.314s

So for the current patch, I'd prefer to keep things as is: only sync when TTU_SYNC is set. Without setting the TTU_SYNC flag, keep the original logic, meaning the caller can tolerate some racy checks.

Any other thoughts?

Quoted 8 lines
Quoted 6 lines

I'm still struggling to understand where the regression comes from. You're doing echo 1G > /sys/fs/cgroup/test/memory.reclaim without the concurrent CPU 1 (MADV_DONTNEED) operation that causes the race.

so the regression actually comes from other places, maybe here?

Yes, I think so. But I haven't had time to dig into how this affects my tests yet. I'll dig into this later.

Sorry for the rough quick measurement last Friday :(.

I found the first memory.reclaim() trigger has high variance because folio_check_references() activates folios. After the folios' reference flag are consumed, memory.reclaim() shows no regression with or without the TTU_SYNC flag, and the data is relatively stable.

However, my testing is simple and doesn't cover concurrent stress scenarios. Whether to set the TTU_SYNC flag for small folios can be discussed in a separate patch, along with how to evaluate the impact.

reviewer
#21 lore raw
Quoted 2 lines · Baolin Wang

Hi Barry,

[...]

Quoted 8 lines

Sorry for the rough quick measurement last Friday :(.

I found the first memory.reclaim() trigger has high variance because folio_check_references() activates folios. After the folios' reference flag are consumed, memory.reclaim() shows no regression with or without the TTU_SYNC flag, and the data is relatively stable.

We have MADV_PAGEOUT, which bypasses folio_check_references(). Could it help make the test more stable?

mm: madvise: pageout: ignore references rather than clearing young
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=2864f3d0f5831a

Quoted 3 lines

However, my testing is simple and doesn't cover concurrent stress scenarios. Whether to set the TTU_SYNC flag for small folios can be discussed in a separate patch, along with how to evaluate the impact.

Thanks,
Barry

#22 lore raw
In reply to Baolin Wang
Quoted 10 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

Quoted 4 lines

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

This is very handwavy. Do you have numbers? Does this actually make sense?

Signature · 1 line
Pedro
author reviewer
#23 lore raw
Quoted 11 lines · Pedro Falcato
Quoted 10 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

Quoted 6 lines
Quoted 4 lines

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

This is very handwavy. Do you have numbers? Does this actually make sense?

This is hard to measure in practice. But in theory, if we can't reclaim cold large folios that are actually unmapped due to the racy checks, it could cause cold/hot inversion (e.g., in MGLRU) and increase refaults. In extreme cases, failing to reclaim unmapped large folios could even cause OOM.

#24 lore raw
Quoted 19 lines · Baolin Wang
Quoted 16 lines · Pedro Falcato
Quoted 14 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

Quoted 7 lines
Quoted 1 line

This is very handwavy. Do you have numbers? Does this actually make sense?

This is hard to measure in practice. But in theory, if we can't reclaim cold large folios that are actually unmapped due to the racy checks, it could cause cold/hot inversion (e.g., in MGLRU) and increase refaults. In extreme cases, failing to reclaim unmapped large folios could even cause OOM.

Yeah, but the question is if it really matters in practice.

I agree that page_mapped_in_vma() should sync properly, but the current impact might not be as severe.

Signature · 3 lines
Cheers,

David
author reviewer
#25 lore raw
Quoted 28 lines · David Hildenbrand (Arm)
Quoted 19 lines · Baolin Wang
Quoted 16 lines · Pedro Falcato
Quoted 14 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

Quoted 7 lines
Quoted 1 line

This is very handwavy. Do you have numbers? Does this actually make sense?

This is hard to measure in practice. But in theory, if we can't reclaim cold large folios that are actually unmapped due to the racy checks, it could cause cold/hot inversion (e.g., in MGLRU) and increase refaults. In extreme cases, failing to reclaim unmapped large folios could even cause OOM.

Quoted 4 lines

Yeah, but the question is if it really matters in practice.

I agree that page_mapped_in_vma() should sync properly, but the current impact might not be as severe.

Yes, what I meant is the theoretical impact. In practice, this race is not easy to trigger with no real reports so far, or the impact is tolerable.

But I still think the fix is needed, as it matches the purpose of the TTU_SYNC flag.

#26 lore raw
Quoted 34 lines · Baolin Wang
Quoted 30 lines · David Hildenbrand (Arm)
Quoted 19 lines · Baolin Wang
Quoted 16 lines · Pedro Falcato
Quoted 14 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

Quoted 7 lines
Quoted 1 line

This is very handwavy. Do you have numbers? Does this actually make sense?

This is hard to measure in practice. But in theory, if we can't reclaim cold large folios that are actually unmapped due to the racy checks, it could cause cold/hot inversion (e.g., in MGLRU) and increase refaults. In extreme cases, failing to reclaim unmapped large folios could even cause OOM.

Yeah, but the question is if it really matters in practice.

Quoted 8 lines
Quoted 2 lines

I agree that page_mapped_in_vma() should sync properly, but the current impact might not be as severe.

Yes, what I meant is the theoretical impact. In practice, this race is not easy to trigger with no real reports so far, or the impact is tolerable.

But I still think the fix is needed, as it matches the purpose of the TTU_SYNC flag.

I assume the impact comes from LRU over-protecting folios that remain mapped after try_to_unmap().

                        try_to_unmap(folio, flags);
                        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;
                        }

folios are activated - over protected in LRU.

The racy window should be quite small in theory, so the impact might not be that severe. There is no evidence that it could lead to OOM.

For large folios, the impact could be greater because we are over-protecting more memory, potentially increasing with the folio order. For small folios, we are only over-protecting a single 4KB page.

So perhaps the current TTU_SYNC flag for large folios is reasonable. Baolin's patch to respect the flag, which currently applies to large folios, also seems reasonable, as long as we don't extend it to small folios and introduce regressions, possibly in map_pte()?

I'm also wondering whether we should downgrade ACTIVATE to KEEP, which would allow racy folios to be reclaimed sooner.

mm/vmscan.c +0 -0
index 071a6eaef1a1..726266e49533 100644
@@ -1353,7 +1353,7 @@ static unsigned int shrink_folio_list(struct

list_head *folio_list,

                                if (!was_swapbacked &&
                                    folio_test_swapbacked(folio))
                                        stat->nr_lazyfree_fail += nr_pages;
-                               goto activate_locked;
+                               goto keep_locked;
                        }
                }

Maybe it's just a silly idea, or perhaps over-engineering :-)

Thanks,
Barry

author reviewer
#27 lore raw
Quoted 58 lines · Barry Song
Quoted 34 lines · Baolin Wang
Quoted 30 lines · David Hildenbrand (Arm)
Quoted 19 lines · Baolin Wang
Quoted 16 lines · Pedro Falcato
Quoted 14 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

Quoted 7 lines
Quoted 1 line

This is very handwavy. Do you have numbers? Does this actually make sense?

This is hard to measure in practice. But in theory, if we can't reclaim cold large folios that are actually unmapped due to the racy checks, it could cause cold/hot inversion (e.g., in MGLRU) and increase refaults. In extreme cases, failing to reclaim unmapped large folios could even cause OOM.

Yeah, but the question is if it really matters in practice.

Quoted 8 lines
Quoted 2 lines

I agree that page_mapped_in_vma() should sync properly, but the current impact might not be as severe.

Yes, what I meant is the theoretical impact. In practice, this race is not easy to trigger with no real reports so far, or the impact is tolerable.

But I still think the fix is needed, as it matches the purpose of the TTU_SYNC flag.

I assume the impact comes from LRU over-protecting folios that remain mapped after try_to_unmap().

                         try_to_unmap(folio, flags);
                         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;
                         }

folios are activated - over protected in LRU.

Quoted 8 lines

The racy window should be quite small in theory, so the impact might not be that severe. There is no evidence that it could lead to OOM.

For large folios, the impact could be greater because we are over-protecting more memory, potentially increasing with the folio order. For small folios, we are only over-protecting a single 4KB page.

Agree.

Quoted 16 lines

So perhaps the current TTU_SYNC flag for large folios is reasonable. Baolin's patch to respect the flag, which currently applies to large folios, also seems reasonable, as long as we don't extend it to small folios and introduce regressions, possibly in map_pte()?

I'm also wondering whether we should downgrade ACTIVATE to KEEP, which would allow racy folios to be reclaimed sooner.

mm/vmscan.c +0 -0
index 071a6eaef1a1..726266e49533 100644

mm/vmscan.c static unsigned int shrink_folio_list(struct · line 1359

Quoted 8 lines
mm/vmscan.c +1 -1
@@ -1353,7 +1353,7 @@ static unsigned int shrink_folio_list(struct
 list_head *folio_list,
                                 if (!was_swapbacked &&
                                     folio_test_swapbacked(folio))
                                         stat->nr_lazyfree_fail += nr_pages;
-                               goto activate_locked;
+                               goto keep_locked;
                         }
                 }

Sounds reasonable to me. It's also not easy to measure the impact. As mentioned earlier, this kind of racy check scenario probably doesn't have much impact anyway.

#28 lore raw
In reply to Baolin Wang
Quoted 61 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios") has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in madvise(MADV_DONTNEED)")
---
 mm/page_vma_mapped.c | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -0
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
 			spin_unlock(pvmw->ptl);

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 299

Quoted 10 lines
mm/page_vma_mapped.c +1 -4
 			pvmw->ptl = NULL;
 		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
+			if (pvmw->flags & PVMW_SYNC)
 				sync_with_folio_pmd_zap(mm, pvmw->pmd);
 
 			goto next_pmd;

Baolin, how to proceed with that? Are you intending a resend? Including some of the performance impact and ways forward to optimize?

Signature · 3 lines
Cheers,

David
author reviewer
#29 lore raw
Quoted 71 lines · David Hildenbrand (Arm)
Quoted 70 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios") has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in madvise(MADV_DONTNEED)")
---
  mm/page_vma_mapped.c | 5 +----
  1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +1 -4
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
  			spin_unlock(pvmw->ptl);
  			pvmw->ptl = NULL;
  		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
+			if (pvmw->flags & PVMW_SYNC)
  				sync_with_folio_pmd_zap(mm, pvmw->pmd);
 
Quoted 4 lines

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 299

Quoted 1 line
mm/page_vma_mapped.c +0 -0
  			goto next_pmd;

Baolin, how to proceed with that? Are you intending a resend? Including some of the performance impact and ways forward to optimize?

I hope we can merge this fix first if no other objections. As I replied to Barry, whether to set TTU_SYNC for small folios should be done in a separate patch (this is a pre-existing issue) with proper measurement (though it may be hard to measure the actual impact). What do you think?

#30 lore raw
Quoted 79 lines · Baolin Wang
Quoted 71 lines · David Hildenbrand (Arm)
Quoted 70 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios") has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in madvise(MADV_DONTNEED)")
---
  mm/page_vma_mapped.c | 5 +----
  1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +1 -4
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
  			spin_unlock(pvmw->ptl);
  			pvmw->ptl = NULL;
  		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
+			if (pvmw->flags & PVMW_SYNC)
  				sync_with_folio_pmd_zap(mm, pvmw->pmd);
 
Quoted 4 lines

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 299

Quoted 1 line
mm/page_vma_mapped.c +0 -0
  			goto next_pmd;

Baolin, how to proceed with that? Are you intending a resend? Including some of the performance impact and ways forward to optimize?

Quoted 4 lines

I hope we can merge this fix first if no other objections. As I replied to Barry, whether to set TTU_SYNC for small folios should be done in a separate patch (this is a pre-existing issue) with proper measurement (though it may be hard to measure the actual impact). What do you think?

Can you update the patch description to include some of the performance aspects and planned next steps?

Signature · 3 lines
Cheers,

David
author reviewer
#31 lore raw
Quoted 80 lines · David Hildenbrand (Arm)
Quoted 79 lines · Baolin Wang
Quoted 75 lines · David Hildenbrand (Arm)
Quoted 61 lines · Baolin Wang

Similar to commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios"), the '!pmd_present()' check in page_vma_mapped_walk() can also race with concurrent page table reclamation via zap_empty_pte_table().

page_vma_mapped_walk() is used by many functions including try_to_unmap(), try_to_migrate(), folio_mkclean(), pfn_mkclean_range(), remove_migration_ptes(), page_mapped_in_vma(), and mapping_wrprotect_range(). Except for try_to_unmap() and try_to_migrate(), the other callers do not perform post-walk accounting checks, so the race has no observable impact on them.

For migration, the race can cause unnecessary retries. For reclaim via try_to_unmap(), the race can cause failure to reclaim a folio that is in fact already unmapped (as shown below), which may lead to unexpected OOM or increased refaults.

CPU 0 (reclaim) CPU 1 (MADV_DONTNEED)
-------------------------------- --------------------------------
folio_lock(F)
try_to_unmap(F, TTU_SYNC)
zap_pte_range(full PMD range)
spin_lock(ptl) clear PTEs zap_empty_pte_table()
spin_trylock(pml) pmd_clear() spin_unlock(pml)

page_vma_mapped_walk()
observe !pmd_present(pmde)
nr_pages < HPAGE_PMD_NR
skip synchronization
return false

try_to_unmap() returns
folio_mapped(F) == true
nr_unmap_fail += folio_nr_pages(F)
tlb_flush_mmu_tlbonly() tlb_flush_rmaps()
remove F's rmaps
spin_unlock(ptl)

Commit 243cf1f67b36 ("mm: memory: fix truncation removing mapped folios") has already moved the PMD clear operation (via zap_empty_pte_table()) to after tlb_flush_rmaps(). Similarly, page_vma_mapped_walk() also needs to use sync_with_folio_pmd_zap() to synchronize and avoid memory ordering issues on weakly ordered CPUs.

Fixes 6375e95f381e ("mm: pgtable: reclaim empty PTE page in madvise(MADV_DONTNEED)")
---
   mm/page_vma_mapped.c | 5 +----
   1 file changed, 1 insertion(+), 4 deletions(-)
mm/page_vma_mapped.c +0 -0
index e6b6170c2f4f..8797467b6f0c 100644
@@ -293,10 +293,7 @@ bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw)
   			spin_unlock(pvmw->ptl);

mm/page_vma_mapped.c bool page_vma_mapped_walk(struct page_vma_mapped_walk *pvmw) · line 299

Quoted 10 lines
mm/page_vma_mapped.c +1 -4
   			pvmw->ptl = NULL;
   		} else if (!pmd_present(pmde)) {
-			if ((pvmw->flags & PVMW_SYNC) &&
-			    thp_vma_suitable_order(vma, pvmw->address,
-						   PMD_ORDER) &&
-			    (pvmw->nr_pages >= HPAGE_PMD_NR))
+			if (pvmw->flags & PVMW_SYNC)
   				sync_with_folio_pmd_zap(mm, pvmw->pmd);
 
   			goto next_pmd;

Baolin, how to proceed with that? Are you intending a resend? Including some of the performance impact and ways forward to optimize?

Quoted 7 lines
Quoted 4 lines

I hope we can merge this fix first if no other objections. As I replied to Barry, whether to set TTU_SYNC for small folios should be done in a separate patch (this is a pre-existing issue) with proper measurement (though it may be hard to measure the actual impact). What do you think?

Can you update the patch description to include some of the performance aspects and planned next steps?

Sure.

However, regarding performance aspects, I'm not sure what kind of testing you expect. Since this fixes a uncommon concurrent race, do you want performance data under that race condition, or impact on common paths like try_to_unmap/try_to_migrate()?

#32 lore raw
Quoted 15 lines · Baolin Wang
Quoted 11 lines · David Hildenbrand (Arm)
Quoted 7 lines · Baolin Wang

I hope we can merge this fix first if no other objections. As I replied to Barry, whether to set TTU_SYNC for small folios should be done in a separate patch (this is a pre-existing issue) with proper measurement (though it may be hard to measure the actual impact). What do you think?

Can you update the patch description to include some of the performance aspects and planned next steps?

Quoted 6 lines

Sure.

However, regarding performance aspects, I'm not sure what kind of testing you expect. Since this fixes a uncommon concurrent race, do you want performance data under that race condition, or impact on common paths like try_to_unmap/try_to_migrate()?

Right, I think you had some numbers here that would be worthwhile to include:

https://lore.kernel.org/r/[email protected]

Signature · 3 lines
Cheers,

David