From: Shakeel Butt <shakeel.butt@linux.dev>
To: Andrew Morton <akpm@linux-foundation.org>,
Johannes Weiner <hannes@cmpxchg.org>,
David Hildenbrand <david@kernel.org>
Cc: Michal Hocko <mhocko@kernel.org>,
Roman Gushchin <roman.gushchin@linux.dev>,
Muchun Song <muchun.song@linux.dev>,
Qi Zheng <qi.zheng@linux.dev>, Zi Yan <ziy@nvidia.com>,
Lorenzo Stoakes <ljs@kernel.org>,
Vlastimil Babka <vbabka@kernel.org>,
Kairui Song <kasong@tencent.com>, Nhat Pham <nphamcs@gmail.com>,
Usama Arif <usama.arif@linux.dev>,
Hugh Dickins <hughd@google.com>,
Meta kernel team <kernel-team@meta.com>,
linux-mm@kvack.org, linux-kernel@vger.kernel.org
Subject: [PATCH 1/4] mm/swap: free orphaned swap cache instead of leaving it to reclaim
Date: Mon, 30 Nov 2026 10:27:52 -0800 [thread overview]
Message-ID: <20261130182755.666042-2-shakeel.butt@linux.dev> (raw)
In-Reply-To: <20261130182755.666042-1-shakeel.butt@linux.dev>
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
next prev parent reply other threads:[~2026-11-30 18:28 UTC|newest]
Thread overview: 5+ messages / expand[flat|nested] mbox.gz Atom feed top
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 [this message]
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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261130182755.666042-2-shakeel.butt@linux.dev \
--to=shakeel.butt@linux.dev \
--cc=akpm@linux-foundation.org \
--cc=david@kernel.org \
--cc=hannes@cmpxchg.org \
--cc=hughd@google.com \
--cc=kasong@tencent.com \
--cc=kernel-team@meta.com \
--cc=linux-kernel@vger.kernel.org \
--cc=linux-mm@kvack.org \
--cc=ljs@kernel.org \
--cc=mhocko@kernel.org \
--cc=muchun.song@linux.dev \
--cc=nphamcs@gmail.com \
--cc=qi.zheng@linux.dev \
--cc=roman.gushchin@linux.dev \
--cc=usama.arif@linux.dev \
--cc=vbabka@kernel.org \
--cc=ziy@nvidia.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox