[PATCH 11/32] mm/khugepaged: store new folio before adding it to LRU

From: David Hildenbrand (Arm)

Date: Sun Nov 29 2026 - 05:10:31 EST


From: Chris Mason <mason@xxxxxxxxxx>

collapse_file() adds the new folio to the LRU before adding it to the
page cache. If SHM_LOCKed, the folio will be added to the unevictable
LRU. A concurrent SHM_UNLOCK walks the page cache to make all folios
evictable again, and can miss the new folio:

collapse_file() SHM_UNLOCK
=============== ==========
folio_add_lru(new_folio)
/* unevictable */
shmem_unlock_mapping()
/* misses new_folio */
xas_store(&xas, new_folio)

Consequently, if SHM_UNLOCK races with a collapse in a SHM_LOCKed SysV
shared memory segment, the new folio can get stranded on the unevictable
LRU.

Let's improve it by adding the new folio to the LRU only after adding it
to the page cache.

There is a more fundamental race that must be sorted out to fix this
completely: check_move_unevictable_folios() skips folios that are not on
the LRU without taking the lruvec lock, while lru_add() checks evictability
before marking the folio as being on the LRU. That affects all folios that
are added to the LRU, and requires a more generic fix.

This has low urgency, as it only strands a folio on the unevictable LRU.
No need to CC stable.

Fixes: a2e17cc2efc7 ("mm/khugepaged: maintain page cache uptodate flag")
Signed-off-by: Chris Mason <mason@xxxxxxxxxx>
[ david: simplify description and comment ]
Signed-off-by: David Hildenbrand (Arm) <david@xxxxxxxxxx>
---
mm/khugepaged.c | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/mm/khugepaged.c b/mm/khugepaged.c
index 708a73f45dd81..c25f732f2bf84 100644
--- a/mm/khugepaged.c
+++ b/mm/khugepaged.c
@@ -2647,7 +2647,6 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,

if (is_shmem)
folio_mark_dirty(new_folio);
- folio_add_lru(new_folio);

/* Join all the small entries into a single multi-index entry. */
xas_set_order(&xas, start, HPAGE_PMD_ORDER);
@@ -2655,6 +2654,13 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
WARN_ON_ONCE(xas_error(&xas));
xas_unlock_irq(&xas);

+ /*
+ * If SHM_LOCKed, the folio will be added to the unevictable LRU. Do
+ * that after adding it to the page cache, so a concurrent SHM_UNLOCK
+ * reliably finds it to make it evictable again.
+ */
+ folio_add_lru(new_folio);
+
/*
* Remove pte page tables, so we can re-fault the page as huge. A
* caller that wants the PMD mapped now is told to go and do that.

--
2.56.1