Linux-mm Archive on lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH 0/4] mm, memcg: stop orphaned swap cache from using up memcg IDs
@ 2026-11-30 18:27 Shakeel Butt
  2026-11-30 18:27 ` [PATCH 1/4] mm/swap: free orphaned swap cache instead of leaving it to reclaim Shakeel Butt
                   ` (3 more replies)
  0 siblings, 4 replies; 7+ messages in thread
From: Shakeel Butt @ 2026-11-30 18:27 UTC (permalink / raw)
  To: Andrew Morton, Johannes Weiner, David Hildenbrand
  Cc: Michal Hocko, Roman Gushchin, Muchun Song, Qi Zheng, Zi Yan,
	Lorenzo Stoakes, Vlastimil Babka, Kairui Song, Nhat Pham,
	Usama Arif, Hugh Dickins, Meta kernel team, linux-mm,
	linux-kernel

On Meta hosts that run many short-lived cgroups, about 13,000 new ones
per hour, creating a memory cgroup started to fail with -EBUSY. All
65,535 memcg IDs were in use, nearly all by deleted cgroups, so systemd
could not start units and container setup failed. drgn showed what held
the IDs:

- a 7.1 host: 58,431 IDs in use; 57,803 of the 57,806 dead ones held
  only by orphaned swap cache, 262K slots (1 GB)
- a 6.16 host: 22,777 IDs in use; all 22,284 dead ones held only by
  orphaned swap cache, 1M slots (4 GB)

An orphan is a swap cache folio that nothing maps and whose swap slots
have no references. It can never be swapped back in, but it keeps its
memory and its slots until LRU reclaim frees it. Each slot records the
ID of its memcg, and the ID stays allocated while any slot records it,
even after the cgroup is deleted.

On these hosts, reclaim did not free the orphans for days. memory.low
protects the parent cgroups, and since LRU reparenting (f1cf8d2f36dc)
the deleted cgroups no longer hold the folios, so reclaim of those
cgroups does not find them either. That makes orphans pile up faster on
7.1 than on 6.16, but both leak.

On 7.1, the leak still shows up in nr_dying_subsys_memory in
cgroup.stat, because a deleted memcg stays around while its ID is held.
Since commit 8290f45995f5 ("memcg: move memcg private ID refcount to
objcg") in 7.4, the memcg is freed and only its ID stays, so that count
can be 0 while the IDs run out. Then the only sign the kernel gives is
the warning from "memcg: warn when memory cgroup IDs run out", which is
already in mm-unstable.

The kernel normally removes such a folio from the swap cache when the
last reference to its slots, or its last mapping, goes away. Each patch
fixes a case where that does not happen:

- Patch 1: the folio is locked or under writeback at that moment. Retry
  from a delayed work, and sweep all swap clusters if the retry queue
  overflows.
- Patch 2: the process exits while the folio is unmapped for migration
  or a split, or a split hands back an orphan.
- Patch 3: do_swap_page() maps a KSM copy and drops the last swap
  reference of the original.
- Patch 4: reclaim gives swap to a folio whose process has already
  exited. This was the largest source in a VM test.

Swap slots can also outlive their cgroup for reasons that are not bugs,
for example a tmpfs file left behind. This series does not change that.

The series is based on mm-everything-2026-11-30-07-23, which already has
two related patches: "memcg: free the private ID of a memcg that never
comes online" [1] and "memcg: warn when memory cgroup IDs run out" [2].

Testing in a VM with 8 CPUs, 4 GB of memory and 8 GB of swap:

- 1,200 short-lived cgroups, 8 at a time, that each swap under
  memory.high and exit, under global memory pressure and with
  memory.low on their parent. Dead memcg IDs left at the end:

                                 without the series   with it
    v7.4-rc3                     132, 27, 21, 39,     0 in 5 runs
                                 15, 108
    mm-everything-2026-11-30     51, 17               0 in 5 runs

  Four of the runs with the series used KASAN, lockdep and DEBUG_VM. A
  KCSAN run reported nothing in the new code. In traced runs without
  patches 3 and 4, 53 of the 64 orphans left got their swap from
  reclaim, 51 of them from kswapd, after their process had exited.
- A 1 GB process killed three times while thousands of its folios were
  under slow swap writeback: the retry queue overflowed, the sweeps
  freed every orphan, and a sweep took about 63 ms with 3 GB of swap in
  use.
- Two processes sharing 4,096 KSM pages: without patch 3, 4,096 orphans
  and the ID of their dead cgroup stay; with it, none.
- A THP swapped out whole, then partly unmapped and split through
  debugfs: without patch 2 one orphan stays; with it, none.
- swapoff and swapon in a loop under KASAN and lockdep: no reports.
  Each patch builds with W=1, and the series also builds with
  CONFIG_SWAP=n, CONFIG_MEMCG=n and for i386.

[1] https://lore.kernel.org/all/20261124000439.967403-1-shakeel.butt@linux.dev/
[2] https://lore.kernel.org/all/20261124020800.2313930-1-shakeel.butt@linux.dev/

Shakeel

Shakeel Butt (4):
  mm/swap: free orphaned swap cache instead of leaving it to reclaim
  mm: free swap cache that migration or a split leaves unmapped
  mm/memory: free the swap cache folio that a KSM copy leaves behind
  mm/vmscan: don't give swap to an anon folio that nothing maps

 mm/huge_memory.c |  10 +-
 mm/memory.c      |   6 ++
 mm/migrate.c     |   9 ++
 mm/swap.h        |  17 +++
 mm/swap_state.c  |  12 ++-
 mm/swapfile.c    | 263 ++++++++++++++++++++++++++++++++++++++++++++++-
 mm/vmscan.c      |  26 +++++
 7 files changed, 334 insertions(+), 9 deletions(-)


base-commit: f05a21e03b2fa69a4fc3130e148349985d62ff8e
-- 
2.53.1-Meta



^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH 1/4] mm/swap: free orphaned swap cache instead of leaving it to reclaim
  2026-11-30 18:27 [PATCH 0/4] mm, memcg: stop orphaned swap cache from using up memcg IDs Shakeel Butt
@ 2026-11-30 18:27 ` Shakeel Butt
  2026-11-30 18:27 ` [PATCH 2/4] mm: free swap cache that migration or a split leaves unmapped Shakeel Butt
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 7+ messages in thread
From: Shakeel Butt @ 2026-11-30 18:27 UTC (permalink / raw)
  To: Andrew Morton, Johannes Weiner, David Hildenbrand
  Cc: Michal Hocko, Roman Gushchin, Muchun Song, Qi Zheng, Zi Yan,
	Lorenzo Stoakes, Vlastimil Babka, Kairui Song, Nhat Pham,
	Usama Arif, Hugh Dickins, Meta kernel team, linux-mm,
	linux-kernel

On Meta hosts that run many short-lived cgroups, creating a memory
cgroup started to fail with -EBUSY: all 65,535 memcg IDs were in use,
nearly all by dead cgroups. drgn showed that orphaned swap cache held
them:

- a 7.1 host: 57,803 of 57,806 dead memcg IDs held only by orphans,
  262K orphan slots (1 GB)
- a 6.16 host: all 22,284 dead memcg IDs held only by orphans, 1M
  orphan slots (4 GB)

These counts include orphans from every source. The later patches in
this series handle the sources that this one does not.

An orphan is a swap cache folio that nothing maps and whose slots have
no references. It can never be swapped back in, but it keeps its
memory, its slots and their memcg IDs until LRU reclaim frees it. When
the last reference to a slot, or the last mapping of the folio, goes
away, the kernel tries to remove the folio from the swap cache. But it
only trylocks the folio, gives up if the folio is under writeback, and
never tries again. So a process that exits while reclaim, readahead or
migration holds the folio lock, or during swap writeback, leaves
orphans. This predates git history, so there is no Fixes tag.

On those hosts, reclaim did not reach the orphans for days. memory.low
protected the parent cgroups, and the dead cgroups no longer hold their
folios since commit f1cf8d2f36dc ("mm: memcontrol: eliminate the problem
of dying memory cgroup for LRU folios"), so reclaim of the dead cgroups
does not find them either.

Queue the slots of such an orphan and retry from a delayed work after
100 ms. Only slots without references are queued, and an orphan under
writeback is queued again until the writeback ends. If the queue of
1,024 entries is full, a second delayed work sweeps all swap clusters
10 seconds later; overflows while it is pending don't add another. The
sweep reads only the clusters in use and holds the device reference for
one cluster at a time, so swapoff doesn't wait for it.

Both works run only while there are orphans to free, and they are
cheap. In a VM test that kills a 1 GB process three times while its
folios are under swap writeback, with swap writes throttled to 16 MB/s
and 3 GB of swap in use, 1.1 GB of it in the swap cache, kprobes on the
two work functions showed 12 retry runs taking 7 ms in total, and
sweeps of 63 to 66 ms.

Both works are freezable, so they don't retry every 100 ms while
hibernation has storage suspended. A stale queue entry is harmless: the
worker skips devices that are gone and only removes orphans.

Add folio_free_orphan_swap() for callers that hold the folio lock. It
frees the swap of an orphan, or queues it if that fails.
free_swap_cache() and the later patches use it.

Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 mm/swap.h       |  17 ++++
 mm/swap_state.c |  12 ++-
 mm/swapfile.c   | 263 +++++++++++++++++++++++++++++++++++++++++++++++-
 3 files changed, 285 insertions(+), 7 deletions(-)

diff --git a/mm/swap.h b/mm/swap.h
index d488a69c2809..e284a86e5a4c 100644
--- a/mm/swap.h
+++ b/mm/swap.h
@@ -313,6 +313,9 @@ bool swap_cache_has_folio(swp_entry_t entry);
 struct folio *swap_cache_get_folio(swp_entry_t entry);
 void *swap_cache_get_shadow(swp_entry_t entry);
 void swap_cache_del_folio(struct folio *folio);
+void swap_cache_defer_free(struct folio *folio);
+bool folio_swap_orphaned(struct folio *folio);
+bool folio_free_orphan_swap(struct folio *folio);
 struct folio *__swap_cache_alloc_folio(swp_entry_t target_entry, gfp_t gfp_mask,
 				       unsigned long orders, struct vm_fault *vmf,
 				       struct mempolicy *mpol, pgoff_t ilx);
@@ -477,6 +480,20 @@ static inline void swap_cache_del_folio(struct folio *folio)
 {
 }
 
+static inline void swap_cache_defer_free(struct folio *folio)
+{
+}
+
+static inline bool folio_swap_orphaned(struct folio *folio)
+{
+	return false;
+}
+
+static inline bool folio_free_orphan_swap(struct folio *folio)
+{
+	return false;
+}
+
 static inline void __swap_cache_del_folio(struct swap_cluster_info *ci,
 		struct folio *folio, swp_entry_t entry, void *shadow,
 		bool swapout)
diff --git a/mm/swap_state.c b/mm/swap_state.c
index da65d75ceead..57e531516d0f 100644
--- a/mm/swap_state.c
+++ b/mm/swap_state.c
@@ -618,11 +618,15 @@ void swap_writeback_dropbehind_folio(struct folio *folio)
  */
 void free_swap_cache(struct folio *folio)
 {
-	if (folio_test_swapcache(folio) && !folio_mapped(folio) &&
-	    folio_trylock(folio)) {
-		folio_free_swap(folio);
-		folio_unlock(folio);
+	if (!folio_test_swapcache(folio) || folio_mapped(folio))
+		return;
+
+	if (!folio_trylock(folio)) {
+		swap_cache_defer_free(folio);
+		return;
 	}
+	folio_free_orphan_swap(folio);
+	folio_unlock(folio);
 }
 
 /*
diff --git a/mm/swapfile.c b/mm/swapfile.c
index d59fa8220862..a534863d66e4 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -42,6 +42,7 @@
 #include <linux/suspend.h>
 #include <linux/zswap.h>
 #include <linux/plist.h>
+#include <linux/kfifo.h>
 
 #include <asm/tlbflush.h>
 #include <linux/leafops.h>
@@ -167,12 +168,90 @@ static long swap_usage_in_pages(struct swap_info_struct *si)
 #define TTRS_ANYWAY		0x1
 /*
  * Reclaim the swap entry if there are no more mappings of the
- * corresponding page
+ * corresponding page. An orphan that can't be removed right away is tried
+ * again later from swap_orphan_work.
  */
 #define TTRS_UNMAPPED		0x2
 /* Reclaim the swap entry if swap is getting full */
 #define TTRS_FULL		0x4
 
+/*
+ * An orphan is a swap cache folio that nothing maps and whose swap slots
+ * have no references left. No page table or shmem entry can bring it back
+ * from swap, but it keeps its memory, its slots and their memcg IDs until
+ * something removes it from the swap cache. That normally happens when the
+ * last reference to its slots or its last mapping goes away, but it is
+ * skipped if the folio is locked or under writeback at that moment, and
+ * reclaim may not come back to it for a long time, for example below a
+ * cgroup protected by memory.low. Queue its slots and try again from a
+ * delayed work.
+ *
+ * Slots that still have references are not queued. If the queue is full,
+ * a second delayed work sweeps all swap clusters for orphans
+ * SWAP_ORPHAN_SWEEP_DELAY later. Overflows while that sweep is pending
+ * don't queue another one, so at most one sweep runs per
+ * SWAP_ORPHAN_SWEEP_DELAY, and the retries keep their own timer.
+ *
+ * Retrying an entry is always safe, even after swapoff and swapon reused
+ * its slot: __try_to_reclaim_swap() only removes a folio that nothing maps
+ * and whose slots have no references.
+ */
+/* Retry soon, so that the memory and the slots come back quickly */
+#define SWAP_ORPHAN_RETRY_DELAY		(HZ / 10)
+/* A sweep reads every slot in use, so it runs at most this often */
+#define SWAP_ORPHAN_SWEEP_DELAY		(10 * HZ)
+
+/* The slots of a folio; the worker visits each one if it was split */
+struct swap_orphan {
+	swp_entry_t entry;
+	unsigned int nr;
+};
+
+static DEFINE_SPINLOCK(swap_orphan_lock);
+static DEFINE_KFIFO(swap_orphan_fifo, struct swap_orphan, 1024);
+/*
+ * Freezable: storage may be suspended for hibernation, see below. It is set
+ * up in swapfile_init(), before any swap device, and so any swap cache
+ * folio, can exist.
+ */
+static struct workqueue_struct *swap_orphan_wq;
+static void swap_orphan_workfn(struct work_struct *work);
+static DECLARE_DELAYED_WORK(swap_orphan_work, swap_orphan_workfn);
+static void swap_orphan_sweep(struct work_struct *work);
+static DECLARE_DELAYED_WORK(swap_orphan_sweep_work, swap_orphan_sweep);
+
+/*
+ * Queue the @nr slots of a folio from @offset to be tried again, unless one
+ * of them still has references: then the folio is not an orphan, and when
+ * that reference goes away, __try_to_reclaim_swap() runs for it again.
+ * The caller holds a reference on @si.
+ */
+static void swap_orphan_defer(struct swap_info_struct *si,
+			      unsigned long offset, unsigned int nr)
+{
+	struct swap_cluster_info *ci = __swap_offset_to_cluster(si, offset);
+	struct swap_orphan orphan = {
+		.entry = swp_entry(si->type, offset),
+		.nr = nr,
+	};
+	unsigned int ci_off = offset % SWAPFILE_CLUSTER;
+	unsigned int ci_end = ci_off + nr;
+
+	/* A folio's slots are in one cluster. This is a hint, no lock needed. */
+	do {
+		if (swp_tb_get_count(swap_table_get(ci, ci_off)) > 0)
+			return;
+	} while (++ci_off < ci_end);
+
+	if (kfifo_in_spinlocked(&swap_orphan_fifo, &orphan, 1,
+				&swap_orphan_lock))
+		queue_delayed_work(swap_orphan_wq, &swap_orphan_work,
+				   SWAP_ORPHAN_RETRY_DELAY);
+	else
+		queue_delayed_work(swap_orphan_wq, &swap_orphan_sweep_work,
+				   SWAP_ORPHAN_SWEEP_DELAY);
+}
+
 static bool swap_only_has_cache(struct swap_cluster_info *ci,
 				unsigned long offset, int nr_pages)
 {
@@ -218,8 +297,19 @@ static int __try_to_reclaim_swap(struct swap_info_struct *si,
 	 * use folio_free_swap() with explicit folio_lock() in usual
 	 * operations.
 	 */
-	if (!folio_trylock(folio))
+	if (!folio_trylock(folio)) {
+		/*
+		 * Only TTRS_UNMAPPED callers, the last put of a slot and the
+		 * orphan workers, queue an orphan; the TTRS_ANYWAY ones
+		 * reclaim slots for reuse. folio->swap can change without
+		 * the lock, so use @offset: a large folio's slots are aligned
+		 * to its size, and our reference keeps it from being split.
+		 */
+		if ((flags & TTRS_UNMAPPED) && !folio_mapped(folio))
+			swap_orphan_defer(si, round_down(offset, nr_pages),
+					  nr_pages);
 		goto out;
+	}
 
 	/*
 	 * Offset could point to the middle of a large folio, or folio
@@ -235,8 +325,18 @@ static int __try_to_reclaim_swap(struct swap_info_struct *si,
 	need_reclaim = ((flags & TTRS_ANYWAY) ||
 			((flags & TTRS_UNMAPPED) && !folio_mapped(folio)) ||
 			((flags & TTRS_FULL) && mem_cgroup_swap_full(folio)));
-	if (!need_reclaim || !folio_swapcache_freeable(folio))
+	if (!need_reclaim)
 		goto out_unlock;
+	if (!folio_swapcache_freeable(folio)) {
+		/*
+		 * Under writeback, or storage is suspended for hibernation.
+		 * The orphan workers are freezable, so they don't retry in a
+		 * loop while storage is suspended.
+		 */
+		if ((flags & TTRS_UNMAPPED) && !folio_mapped(folio))
+			swap_orphan_defer(si, offset, nr_pages);
+		goto out_unlock;
+	}
 
 	/*
 	 * It's safe to delete the folio from swap cache only if the folio
@@ -1427,6 +1527,117 @@ static bool get_swap_device_info(struct swap_info_struct *si)
 	return true;
 }
 
+static void swap_orphan_sweep_cluster(struct swap_info_struct *si,
+				      struct swap_cluster_info *ci,
+				      unsigned long offset, unsigned long end)
+{
+	unsigned long swp_tb;
+	int nr;
+
+	while (offset < end) {
+		swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER);
+		nr = 0;
+		if (swp_tb_is_folio(swp_tb) && !__swp_tb_get_count(swp_tb))
+			nr = __try_to_reclaim_swap(si, offset, TTRS_UNMAPPED);
+		offset++;
+		if (nr)
+			offset = round_up(offset, abs(nr));
+	}
+}
+
+/*
+ * Look for orphans in every swap cluster, for the slots that did not fit in
+ * the queue. Slots are read without the cluster lock; __try_to_reclaim_swap()
+ * checks the folio again under its lock. Only clusters in use have a swap
+ * table, so the cost follows the swap in use. The device reference is held
+ * for one cluster at a time, so that swapoff does not wait for the sweep.
+ */
+static void swap_orphan_sweep(struct work_struct *work)
+{
+	struct swap_info_struct *si;
+	struct swap_cluster_info *ci;
+	unsigned long offset, end;
+	int type;
+
+	for (type = 0; type < READ_ONCE(nr_swapfiles); type++) {
+		si = swap_type_to_info(type);
+		if (!si)
+			continue;
+		for (offset = 0; get_swap_device_info(si); offset = end) {
+			end = min_t(unsigned long, offset + SWAPFILE_CLUSTER,
+				    si->max);
+			if (offset >= end) {
+				put_swap_device(si);
+				break;
+			}
+			ci = __swap_offset_to_cluster(si, offset);
+			/* A cluster without a table holds no folio */
+			if (rcu_access_pointer(ci->table))
+				swap_orphan_sweep_cluster(si, ci, offset, end);
+			put_swap_device(si);
+			cond_resched();
+		}
+	}
+}
+
+static void swap_orphan_workfn(struct work_struct *work)
+{
+	unsigned long offset, end;
+	struct swap_orphan orphan;
+	struct swap_info_struct *si;
+	unsigned int n;
+	int nr;
+
+	/* Blocked entries get queued again, so only take the ones there now */
+	spin_lock_irq(&swap_orphan_lock);
+	n = kfifo_len(&swap_orphan_fifo);
+	spin_unlock_irq(&swap_orphan_lock);
+
+	while (n-- && kfifo_out_spinlocked(&swap_orphan_fifo, &orphan, 1,
+					   &swap_orphan_lock)) {
+		/* Skip quietly if the device went away since */
+		si = swap_entry_to_info(orphan.entry);
+		if (!si || !get_swap_device_info(si))
+			continue;
+		offset = swp_offset(orphan.entry);
+		end = min_t(unsigned long, offset + orphan.nr, si->max);
+		while (offset < end) {
+			nr = __try_to_reclaim_swap(si, offset, TTRS_UNMAPPED);
+			offset++;
+			if (nr)
+				offset = round_up(offset, abs(nr));
+		}
+		put_swap_device(si);
+		cond_resched();
+	}
+}
+
+/**
+ * swap_cache_defer_free - Retry freeing an unmapped swap cache folio later.
+ * @folio: The folio. It does not need to be locked, but the caller must hold
+ *         a reference, which also keeps the folio from being split.
+ *
+ * Called when an unmapped folio could not be removed from the swap cache
+ * right away, for example because it was locked or under writeback. The
+ * slots are queued only if none of them has references left.
+ */
+void swap_cache_defer_free(struct folio *folio)
+{
+	swp_entry_t entry = { .val = READ_ONCE(folio->swap.val) };
+	unsigned int nr = folio_nr_pages(folio);
+	struct swap_info_struct *si;
+
+	/* An unlocked folio can leave the swap cache under us */
+	if (!entry.val)
+		return;
+	si = swap_entry_to_info(entry);
+	if (!si || !get_swap_device_info(si))
+		return;
+	if (swp_offset(entry) + nr <= si->max)
+		swap_orphan_defer(si, swp_offset(entry), nr);
+	put_swap_device(si);
+}
+
 /*
  * Fast path try to get swap entries with specified order from current
  * CPU's swap entry pool (a cluster).
@@ -2167,6 +2378,46 @@ static bool folio_swapcache_freeable(struct folio *folio)
 	return true;
 }
 
+/**
+ * folio_swap_orphaned - Test if a swap cache folio is an orphan.
+ * @folio: The locked folio.
+ *
+ * Return: true if @folio is in the swap cache, nothing maps it, and none of
+ * its swap slots has references left, so no page table or shmem entry can
+ * bring it back from swap. KSM can still map a KSM folio through its stable
+ * node, even without the folio lock, so this does not mean nothing can
+ * reach the folio. Removing it from the swap cache is still safe, and
+ * folio_free_swap() already does it for KSM folios elsewhere: the stable
+ * node stays, and the folio is marked dirty, so its data is written again
+ * if it is swapped out later.
+ */
+bool folio_swap_orphaned(struct folio *folio)
+{
+	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
+
+	return folio_test_swapcache(folio) && !folio_mapped(folio) &&
+	       !folio_maybe_swapped(folio);
+}
+
+/**
+ * folio_free_orphan_swap - Free the swap of an orphan, or retry it later.
+ * @folio: The locked folio.
+ *
+ * If @folio is an orphan (see folio_swap_orphaned()), remove it from the
+ * swap cache and free its slots. That fails only under writeback or while
+ * storage is suspended for hibernation; then queue it to be tried again.
+ *
+ * Return: true if @folio was an orphan.
+ */
+bool folio_free_orphan_swap(struct folio *folio)
+{
+	if (!folio_swap_orphaned(folio))
+		return false;
+	if (!folio_free_swap(folio))
+		swap_cache_defer_free(folio);
+	return true;
+}
+
 /**
  * folio_free_swap() - Free the swap space used for this folio.
  * @folio: The folio to remove.
@@ -4119,6 +4370,12 @@ static int __init swapfile_init(void)
 		swap_migration_ad_supported = true;
 #endif	/* CONFIG_MIGRATION */
 
+	/* The retries and the sweep share no unlocked state, let both run */
+	swap_orphan_wq = alloc_workqueue("swap_orphan",
+					 WQ_UNBOUND | WQ_FREEZABLE, 2);
+	if (!swap_orphan_wq)
+		swap_orphan_wq = system_freezable_wq;
+
 	return 0;
 }
 subsys_initcall(swapfile_init);
-- 
2.53.1-Meta



^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [PATCH 2/4] mm: free swap cache that migration or a split leaves unmapped
  2026-11-30 18:27 [PATCH 0/4] mm, memcg: stop orphaned swap cache from using up memcg IDs Shakeel Butt
  2026-11-30 18:27 ` [PATCH 1/4] mm/swap: free orphaned swap cache instead of leaving it to reclaim Shakeel Butt
@ 2026-11-30 18:27 ` Shakeel Butt
  2026-11-30 18:27 ` [PATCH 3/4] mm/memory: free the swap cache folio that a KSM copy leaves behind Shakeel Butt
  2026-11-30 18:27 ` [PATCH 4/4] mm/vmscan: don't give swap to an anon folio that nothing maps Shakeel Butt
  3 siblings, 0 replies; 7+ messages in thread
From: Shakeel Butt @ 2026-11-30 18:27 UTC (permalink / raw)
  To: Andrew Morton, Johannes Weiner, David Hildenbrand
  Cc: Michal Hocko, Roman Gushchin, Muchun Song, Qi Zheng, Zi Yan,
	Lorenzo Stoakes, Vlastimil Babka, Kairui Song, Nhat Pham,
	Usama Arif, Hugh Dickins, Meta kernel team, linux-mm,
	linux-kernel

Migration and large folio splits replace the PTEs of a folio with
migration entries, and remove_migration_ptes() restores them afterwards.
Zapping a migration entry neither drops a swap count nor calls
free_swap_cache(). So if the process exits in between, the folio comes
back unmapped. If it is in the swap cache and its slots have no
references, it is an orphan that only LRU reclaim frees. This goes back
to when migration switched from swap entries to migration entries.

Free the swap of such a folio at the end of remove_migration_ptes(),
with folio_free_orphan_swap(). Every caller holds the folio lock, and
the folio is not under writeback: migration waits for writeback or gives
up, and a folio under writeback is not split. So the swap is normally
freed right away. The rmap walk also sees the PTEs that fork copied, so
nothing can map the folio again after it, except KSM for a KSM folio,
which is safe.

Splits have one more gap. __folio_split() frees the swap of unmapped
after-split folios, but not of the one it hands back to the caller. And
a folio that was already unmapped, such as a THP swapped out whole, is
split without remove_migration_ptes(). So if part of such a THP was
unmapped while its other slots were still in use, the folio the caller
gets back can be an orphan. Run the same helper on it in
__folio_split(). It has no slot references, and no caller needs it to
stay in the swap cache.

In a VM with 1,200 short-lived cgroups under global memory pressure, the
migration check found 0 to 12 orphans per run. A THP that was swapped
out whole, then partly unmapped and split through debugfs, left an
orphan before this patch and none after.

Fixes: 6c5240ae7f48 ("[PATCH] Swapless page migration: modify core logic")
Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 mm/huge_memory.c | 10 ++++++++--
 mm/migrate.c     |  9 +++++++++
 2 files changed, 17 insertions(+), 2 deletions(-)

diff --git a/mm/huge_memory.c b/mm/huge_memory.c
index 4fc888ddfb69..f024289930ac 100644
--- a/mm/huge_memory.c
+++ b/mm/huge_memory.c
@@ -4443,6 +4443,14 @@ static int __folio_split(struct folio *folio, unsigned int new_order,
 	 */
 	for (new_folio = folio; new_folio != end_folio; new_folio = next) {
 		next = folio_next(new_folio);
+		/*
+		 * Free the swap of an after-split folio that nothing maps and
+		 * whose slots have no references, the one kept for the caller
+		 * included: an unmapped folio is split without
+		 * remove_migration_ptes().
+		 */
+		if (!ret && is_swapcache)
+			folio_free_orphan_swap(new_folio);
 		if (new_folio == page_folio(lock_at))
 			continue;
 
@@ -4452,8 +4460,6 @@ static int __folio_split(struct folio *folio, unsigned int new_order,
 		 * lru_lock, so we defer folio_put() on tail pages until
 		 * after the split completes.
 		 */
-		if (is_swapcache && !folio_mapped(new_folio))
-			folio_free_swap(new_folio);
 		folio_unlock(new_folio);
 		folio_put(new_folio);
 	}
diff --git a/mm/migrate.c b/mm/migrate.c
index 96b66a272379..fbd69f871291 100644
--- a/mm/migrate.c
+++ b/mm/migrate.c
@@ -494,6 +494,15 @@ void remove_migration_ptes(struct folio *src, struct folio *dst,
 		rmap_walk_locked(dst, &rwc);
 	else
 		rmap_walk(dst, &rwc);
+
+	/*
+	 * If the process exited while the folio was unmapped for migration
+	 * or a split, no PTE points to it now: zapping a migration entry
+	 * neither drops a swap count nor calls free_swap_cache(). Every
+	 * caller holds the folio lock, and the folio is not under writeback,
+	 * so this normally frees the swap right away.
+	 */
+	folio_free_orphan_swap(dst);
 }
 
 /*
-- 
2.53.1-Meta



^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [PATCH 3/4] mm/memory: free the swap cache folio that a KSM copy leaves behind
  2026-11-30 18:27 [PATCH 0/4] mm, memcg: stop orphaned swap cache from using up memcg IDs Shakeel Butt
  2026-11-30 18:27 ` [PATCH 1/4] mm/swap: free orphaned swap cache instead of leaving it to reclaim Shakeel Butt
  2026-11-30 18:27 ` [PATCH 2/4] mm: free swap cache that migration or a split leaves unmapped Shakeel Butt
@ 2026-11-30 18:27 ` Shakeel Butt
  2026-11-30 18:27 ` [PATCH 4/4] mm/vmscan: don't give swap to an anon folio that nothing maps Shakeel Butt
  3 siblings, 0 replies; 7+ messages in thread
From: Shakeel Butt @ 2026-11-30 18:27 UTC (permalink / raw)
  To: Andrew Morton, Johannes Weiner, David Hildenbrand
  Cc: Michal Hocko, Roman Gushchin, Muchun Song, Qi Zheng, Zi Yan,
	Lorenzo Stoakes, Vlastimil Babka, Kairui Song, Nhat Pham,
	Usama Arif, Hugh Dickins, Meta kernel team, linux-mm,
	linux-kernel

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@linux.dev>
---
 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



^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [PATCH 4/4] mm/vmscan: don't give swap to an anon folio that nothing maps
  2026-11-30 18:27 [PATCH 0/4] mm, memcg: stop orphaned swap cache from using up memcg IDs Shakeel Butt
                   ` (2 preceding siblings ...)
  2026-11-30 18:27 ` [PATCH 3/4] mm/memory: free the swap cache folio that a KSM copy leaves behind Shakeel Butt
@ 2026-11-30 18:27 ` Shakeel Butt
  2026-11-30 18:54   ` sashiko-bot
  3 siblings, 1 reply; 7+ messages in thread
From: Shakeel Butt @ 2026-11-30 18:27 UTC (permalink / raw)
  To: Andrew Morton, Johannes Weiner, David Hildenbrand
  Cc: Michal Hocko, Roman Gushchin, Muchun Song, Qi Zheng, Zi Yan,
	Lorenzo Stoakes, Vlastimil Babka, Kairui Song, Nhat Pham,
	Usama Arif, Hugh Dickins, Meta kernel team, linux-mm,
	linux-kernel

When a process exits while reclaim has some of its folios isolated, the
folios lose their mappings, but reclaim's reference keeps them alive.
shrink_folio_list() still gives such a folio swap. If something else
also holds a reference, such as the exiting task's TLB gather, pageout()
returns PAGE_KEEP. The folio then goes back to the LRU in the swap
cache, unmapped and with no slot references. No swap count ever dropped,
so nothing queues it. It is an orphan from the start, and keeps its
slots and memcg ID until reclaim comes back, which may not happen below
a cgroup protected by memory.low.

In a VM that runs short-lived cgroups under global memory pressure, 53
of the 64 orphans left after three runs got their swap this way, 51 of
them from kswapd.

An unmapped anon folio that is not in the swap cache has no page table
or shmem entry pointing to it, so don't give it swap. It is freed when
the last reference goes away, often reclaim's own. A KSM stable node
holds no reference, but KSM can map a KSM folio again; a later pass
swaps it out then. The check runs right before the swap allocation,
after the split of a partially mapped folio, so it also catches an
unmapped first page of such a folio. An unmapped folio that is still
held elsewhere is kept or activated as before; only the swap allocation
is gone.

The last mapping can also go away after that check, while reclaim holds
the folio lock, so the exiting task's free_swap_cache() can't free the
folio. So check again after the unmap step: if the folio got swap in
this pass and is now an orphan, free its slots with
folio_free_orphan_swap() and keep it.

shrink_list() in Linux 2.6.12-rc2 already allocated swap before checking
page_mapped(), so there is no Fixes tag.

Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
 mm/vmscan.c | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)

diff --git a/mm/vmscan.c b/mm/vmscan.c
index 99cb209797b4..ddc1584d06ed 100644
--- a/mm/vmscan.c
+++ b/mm/vmscan.c
@@ -1128,6 +1128,7 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 		struct folio *folio;
 		enum folio_references references = FOLIOREF_RECLAIM;
 		bool dirty, writeback;
+		bool new_swap = false;
 		unsigned int nr_pages;
 
 		cond_resched();
@@ -1331,6 +1332,19 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 				    split_folio_to_list(folio, folio_list))
 					goto activate_locked;
 			}
+			/*
+			 * If nothing maps the folio, its last mapping went
+			 * away, usually because its process exited, and no page
+			 * table or shmem entry refers to it. It is freed when
+			 * the last reference goes away. Giving it swap would
+			 * only leave it in the swap cache if something else
+			 * still holds a reference. KSM can map a KSM folio
+			 * again; a later pass swaps it out then. This comes
+			 * after the split above, so it also skips an unmapped
+			 * first page of a partially mapped folio.
+			 */
+			if (!folio_mapped(folio))
+				goto keep_locked;
 			ret = folio_alloc_swap(folio);
 			if (ret) {
 				int __maybe_unused order = folio_order(folio);
@@ -1366,6 +1380,7 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 			 * flag for the folio solves the problem.
 			 */
 			folio_mark_dirty(folio);
+			new_swap = true;
 		}
 
 		/*
@@ -1419,6 +1434,17 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 			}
 		}
 
+		/*
+		 * If the folio got swap above but is an orphan now, its last
+		 * mapping went away in the meantime, before try_to_unmap() or
+		 * while it ran. No swap count will drop for it, and the
+		 * unmapping task's free_swap_cache() found it either not yet
+		 * in the swap cache or locked by us; it may have queued it.
+		 * Free the slots and keep the folio, as above.
+		 */
+		if (new_swap && folio_free_orphan_swap(folio))
+			goto keep_locked;
+
 		/*
 		 * Folio is unmapped now so it cannot be newly pinned anymore.
 		 * No point in trying to reclaim folio if it is pinned.
-- 
2.53.1-Meta



^ permalink raw reply related	[flat|nested] 7+ messages in thread

* Re: [PATCH 4/4] mm/vmscan: don't give swap to an anon folio that nothing maps
  2026-11-30 18:27 ` [PATCH 4/4] mm/vmscan: don't give swap to an anon folio that nothing maps Shakeel Butt
@ 2026-11-30 18:54   ` sashiko-bot
  2026-11-30 19:13     ` Shakeel Butt
  0 siblings, 1 reply; 7+ messages in thread
From: sashiko-bot @ 2026-11-30 18:54 UTC (permalink / raw)
  To: Shakeel Butt, Andrew Morton, Johannes Weiner, David Hildenbrand
  Cc: Michal Hocko, Roman Gushchin, Muchun Song, Qi Zheng, Zi Yan,
	Lorenzo Stoakes, Vlastimil Babka, Kairui Song, Nhat Pham,
	Usama Arif, Hugh Dickins, Meta kernel team, linux-mm

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Medium] mm/vmscan: unadjusted sc->nr_scanned in shrink_folio_list()
  after folio split
- [Medium] mm/vmscan: redundant shrink_folio_list() retry in MGLRU
  evict_folios()
--

commit adf73a464f11b1c23175eec0f7510cddfa8d6dc1
Author: Shakeel Butt <shakeel.butt@linux.dev>

mm/vmscan: don't give swap to an anon folio that nothing maps

This commit skips swap allocation in shrink_folio_list() for unmapped
anonymous folios that are not in the swap cache, and frees newly allocated
swap slots if the folio becomes an orphan during the unmap step.

> diff --git a/mm/vmscan.c b/mm/vmscan.c
> index 99cb209797b4b..ddc1584d06eda 100644
> --- a/mm/vmscan.c
> +++ b/mm/vmscan.c

[ ... ]

> @@ -1331,6 +1332,19 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
>  				    split_folio_to_list(folio, folio_list))
>  					goto activate_locked;
>  			}
> +			/*
> +			 * If nothing maps the folio, its last mapping went
> +			 * away, usually because its process exited, and no page
> +			 * table or shmem entry refers to it. It is freed when
> +			 * the last reference goes away. Giving it swap would
> +			 * only leave it in the swap cache if something else
> +			 * still holds a reference. KSM can map a KSM folio
> +			 * again; a later pass swaps it out then. This comes
> +			 * after the split above, so it also skips an unmapped
> +			 * first page of a partially mapped folio.
> +			 */
> +			if (!folio_mapped(folio))
> +				goto keep_locked;

[Severity: Medium]
When split_folio_to_list() splits a partially mapped large folio and its
first page is unmapped, does jumping to keep_locked overcount
sc->nr_scanned by nr_pages - 1?

shrink_folio_list() initially adds the full large folio's nr_pages to
sc->nr_scanned, and each split tail page added to folio_list is counted
again when the loop pops it.  Jumping to keep_locked skips the post-split
fixup after the swap allocation block:

mm/vmscan.c:shrink_folio_list() {
    ...
		if ((nr_pages > 1) && !folio_test_large(folio)) {
			sc->nr_scanned -= (nr_pages - 1);
			nr_pages = 1;
		}
    ...
}

Inflating sc->nr_scanned skews vmpressure reporting, reclaim throttling
checks, and kswapd scan targets.

[Severity: Medium]
Under MGLRU, does jumping to keep_locked before folio_mark_dirty() cause
evict_folios() to run a second shrink_folio_list() pass on every unmapped
non-swapcache anonymous folio?

Because unmapping an anonymous folio does not set PG_dirty, returning via
keep_locked leaves the folio inactive, unmapped, clean, and not under
writeback.  evict_folios() treats any such folio as one that finished
writeback while isolated and retries shrink_folio_list() on it before
move_folios_to_lru() can drop reclaim's reference:

mm/vmscan.c:evict_folios() {
    ...
		/* retry folios that may have missed folio_rotate_reclaimable() */
		if (!skip_retry && !folio_test_active(folio) && !folio_mapped(folio) &&
		    !folio_test_dirty(folio) && !folio_test_writeback(folio)) {
			list_move(&folio->lru, &clean);
			continue;
		}
    ...
}

The retry hits goto keep_locked again without reclaiming the folio and
counts nr_pages in sc->nr_scanned a second time.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261130182755.666042-1-shakeel.butt@linux.dev?part=4


^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: [PATCH 4/4] mm/vmscan: don't give swap to an anon folio that nothing maps
  2026-11-30 18:54   ` sashiko-bot
@ 2026-11-30 19:13     ` Shakeel Butt
  0 siblings, 0 replies; 7+ messages in thread
From: Shakeel Butt @ 2026-11-30 19:13 UTC (permalink / raw)
  To: sashiko-reviews
  Cc: Andrew Morton, Johannes Weiner, David Hildenbrand, Michal Hocko,
	Roman Gushchin, Muchun Song, Qi Zheng, Zi Yan, Lorenzo Stoakes,
	Vlastimil Babka, Kairui Song, Nhat Pham, Usama Arif, Hugh Dickins,
	Meta kernel team, linux-mm

On Mon, Nov 30, 2026 at 06:54:30PM +0000, sashiko-bot@kernel.org wrote:
> Thank you for your contribution! Sashiko AI review found 2 potential
> issues to consider:
> - [Medium] mm/vmscan: unadjusted sc->nr_scanned in shrink_folio_list()
>   after folio split
> - [Medium] mm/vmscan: redundant shrink_folio_list() retry in MGLRU
>   evict_folios()
> --
> 
> commit adf73a464f11b1c23175eec0f7510cddfa8d6dc1
> Author: Shakeel Butt <shakeel.butt@linux.dev>
> 
> mm/vmscan: don't give swap to an anon folio that nothing maps
> 
> This commit skips swap allocation in shrink_folio_list() for unmapped
> anonymous folios that are not in the swap cache, and frees newly allocated
> swap slots if the folio becomes an orphan during the unmap step.
> 
> > diff --git a/mm/vmscan.c b/mm/vmscan.c
> > index 99cb209797b4b..ddc1584d06eda 100644
> > --- a/mm/vmscan.c
> > +++ b/mm/vmscan.c
> 
> [ ... ]
> 
> > @@ -1331,6 +1332,19 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
> >  				    split_folio_to_list(folio, folio_list))
> >  					goto activate_locked;
> >  			}
> > +			/*
> > +			 * If nothing maps the folio, its last mapping went
> > +			 * away, usually because its process exited, and no page
> > +			 * table or shmem entry refers to it. It is freed when
> > +			 * the last reference goes away. Giving it swap would
> > +			 * only leave it in the swap cache if something else
> > +			 * still holds a reference. KSM can map a KSM folio
> > +			 * again; a later pass swaps it out then. This comes
> > +			 * after the split above, so it also skips an unmapped
> > +			 * first page of a partially mapped folio.
> > +			 */
> > +			if (!folio_mapped(folio))
> > +				goto keep_locked;
> 
> [Severity: Medium]
> When split_folio_to_list() splits a partially mapped large folio and its
> first page is unmapped, does jumping to keep_locked overcount
> sc->nr_scanned by nr_pages - 1?

Yes, thanks. The new check runs after the partial-map split, but it
jumps over the fixup that every other exit after a split goes through,
so the tail pages get counted twice. Will fix in v2 (after additional reviews
are in).

[...]

> 
> [Severity: Medium]
> Under MGLRU, does jumping to keep_locked before folio_mark_dirty() cause
> evict_folios() to run a second shrink_folio_list() pass on every unmapped
> non-swapcache anonymous folio?

Yeah this need to be handled better. Will do something about in v2.


^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2026-11-30 19:13 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-30 18:27 [PATCH 0/4] mm, memcg: stop orphaned swap cache from using up memcg IDs Shakeel Butt
2026-11-30 18:27 ` [PATCH 1/4] mm/swap: free orphaned swap cache instead of leaving it to reclaim Shakeel Butt
2026-11-30 18:27 ` [PATCH 2/4] mm: free swap cache that migration or a split leaves unmapped Shakeel Butt
2026-11-30 18:27 ` [PATCH 3/4] mm/memory: free the swap cache folio that a KSM copy leaves behind Shakeel Butt
2026-11-30 18:27 ` [PATCH 4/4] mm/vmscan: don't give swap to an anon folio that nothing maps Shakeel Butt
2026-11-30 18:54   ` sashiko-bot
2026-11-30 19:13     ` Shakeel Butt

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox