[PATCH 3/4] mm/memory: free the swap cache folio that a KSM copy leaves behind

From: Shakeel Butt

Date: Mon Nov 30 2026 - 13:28:28 EST


When do_swap_page() finds a swap cache folio that it may not map,
ksm_might_need_to_copy() gives it a copy to map instead. This happens
for a KSM folio that lost its stable node or while KSM is unmerging, and
for a folio that another process mapped into an unrelated anon_vma.
do_swap_page() maps the copy and drops the swap count of the original,
which stays in the swap cache. If that was the last reference to its
slots and nothing maps it, the original is an orphan. Only LRU reclaim
would free it, and with it its slots and their memcg ID.

This happens to KSM pages that unrelated processes share. After the
page is swapped out, the first process to fault maps the swap cache
folio into its own anon_vma. If that process exits, every later fault on
the slot by an unrelated process gets a copy, and the last one leaves
the original behind.

Free the original with folio_free_orphan_swap() while it is still
locked; if it is under writeback, that queues it. The check covers all
slots of the folio, because one of the sharing processes can swap the
slot in as part of a large folio, and the copy takes only one page.

Two unrelated processes share 4,096 KSM pages, which are swapped out.
One faults them in and exits, then the other faults them in. That left
4,096 orphans before this patch and none after. The test used only
small folios.

Fixes: 5ad6468801d2 ("ksm: let shared pages be swappable")
Signed-off-by: Shakeel Butt <shakeel.butt@xxxxxxxxx>
---
mm/memory.c | 6 ++++++
1 file changed, 6 insertions(+)

diff --git a/mm/memory.c b/mm/memory.c
index 82e1ec8e44e7..67b7564a0623 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -5368,6 +5368,12 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)

folio_unlock(folio);
if (unlikely(folio != swapcache)) {
+ /*
+ * The copy is mapped and the slot's count was dropped. If
+ * nothing maps swapcache and its slots have no references
+ * left, only reclaim would remove it from the swap cache.
+ */
+ folio_free_orphan_swap(swapcache);
/*
* Hold the lock to avoid the swap entry to be reused
* until we take the PT lock for the pte_same() check
--
2.53.1-Meta