[PATCH v4 15/17] mm/huge_memory: clean up after-split folio freeing in __folio_split

From: Kairui Song via B4 Relay

Date: Mon Sep 07 2026 - 14:18:18 EST


From: Kairui Song <kasong@xxxxxxxxxxx>

Replace free_folio_and_swap_cache() with an explicit folio_free_swap()
and folio_put() in the after-split loop. free_folio_and_swap_cache()
unlocks the folio, then free_swap_cache() must trylock it again and
re-check folio_mapped() before freeing the swap cache entries; if the
trylock loses a race, the entries are left behind even though the folio
reference is dropped. The sub folios are still locked and unmapped
here, so just directly call folio_free_swap() under the lock,
unlock and drop the reference. This makes the swap cache freeing
deterministic and the reference drop explicit.

Reviewed-by: Zi Yan <ziy@xxxxxxxxxx>
Reviewed-by: Yeoreum Yun <yeoreum.yun@xxxxxxx>
Signed-off-by: Kairui Song <kasong@xxxxxxxxxxx>
---
mm/huge_memory.c | 13 ++++++++-----
1 file changed, 8 insertions(+), 5 deletions(-)

diff --git a/mm/huge_memory.c b/mm/huge_memory.c
index 6ce58a5d93d8..f2862556d715 100644
--- a/mm/huge_memory.c
+++ b/mm/huge_memory.c
@@ -4300,7 +4300,8 @@ static int __folio_split(struct folio *folio, unsigned int new_order,
struct list_head *list, enum split_type split_type)
{
struct folio *end_folio = folio_next(folio);
- bool is_anon = folio_test_anon(folio);
+ const bool is_anon = folio_test_anon(folio);
+ const bool is_swapcache = folio_test_swapcache(folio);
int old_order = folio_order(folio);
struct folio *new_folio, *next;
int ret;
@@ -4340,14 +4341,16 @@ static int __folio_split(struct folio *folio, unsigned int new_order,
if (new_folio == page_folio(lock_at))
continue;

- folio_unlock(new_folio);
/*
* Subpages whose mapping has been zapped may be freed
* earlier, but freeing them requires taking the
- * lru_lock, so we defer put_page() on tail pages until
+ * lru_lock, so we defer folio_put() on tail pages until
* after the split completes.
*/
- free_folio_and_swap_cache(new_folio);
+ if (is_swapcache && !folio_mapped(new_folio))
+ folio_free_swap(new_folio);
+ folio_unlock(new_folio);
+ folio_put(new_folio);
}

out:
@@ -4374,7 +4377,7 @@ static int __folio_split(struct folio *folio, unsigned int new_order,
* isolated from LRU (if applicable)
*
* Upon return, the folio is not remapped, split folios are not added to LRU,
- * free_folio_and_swap_cache() is not called, and new folios remain locked.
+ * folio_free_swap() is not called, and new folios remain locked.
*
* Return: 0 on success, -EAGAIN if the folio cannot be split (e.g., due to
* insufficient reference count or extra pins).

--
2.55.0