Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=95.215.58.139 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796063296; b=kCskiRBl2yYSwJl0r+GS4ViWzoWBR0cW5lqW3RWIFvj4vBmLmpQwSeqNiX22OW5nflb1 dPJyY1KEZy5Sxi9fmHEZfUvDj/yERXSUMNpXsLo4nxk7w8NaeD5C7KBDKWgv/FQgz1nG5 EABwrSK07COCHOX0GE7SZGdMMA+vtMm53atPJcqSEHXfH/YwCmZNnl545toik7sAFJlV9 8Z1JCWBdE8hO4TQVr5k876U7sFPXlXmTjBq69WFlvIAqovdusd1iSjorV20z/XpP50n/J 1Y0iJrSAc4HxxbW98Yn3wxG/ieaHkQbXGVR0aOf2aW0yTv6GHDueBhVN69RiDv/OeZg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796063296; h=DMARC-Filter:X-Envelope-To:DKIM-Signature:X-Envelope-To:Received: X-Mizu-Trace-ID:X-Migadu-Flow:From:To:Cc:Subject:Date:Message-ID: X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=gQfhEzI7TCBU6XIbBToTjpWHGEbEunbNuiFu1CDaT/E=; b=DstF8FDe5ALYzolBzX3op6lUkYnt3dQiwTXhSg8Jr/jaCD53EzblQhQ3MD9ULbR1FdN5 8h8rSzSkF0vPOzPq9xoRQO8tDFQxezqa/EJGgv741hFzDNbEosAy9w3AHygtXDNKw8mIR r5ejCT8SCAFPPUFU5JevMXr+Toiu4oAIjBahhDDUAMLBPDD4C9XtXfvtbECeqXrWdNkjD UbEpSnWWdz8G6Xvk4Yd3bferS8hOVLyTVBD3iBkSecLo9NLdS/iGTsiLJBBSSV3bVXq7M yGBQ82oyDsBJMN44G1hi5LKECVjuX4JswmcQNXL1du2M3TzmmMv9l+f3byBvoHb+jWg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.dev; spf=pass smtp.mailfrom=linux.dev; dkim=pass header.d=linux.dev header.i=@linux.dev header.a=rsa-sha256 header.s=key1 header.b=hynZXdId; arc=none smtp.remote-ip=95.215.58.139 Received: from mta1.migadu.com (out-139.mta1.migadu.com [95.215.58.139]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 24C96606A327 for ; Mon, 30 Nov 2026 18:28:14 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 24C96606A327 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.dev Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key, unprotected) header.d=linux.dev header.i=@linux.dev header.a=rsa-sha256 header.s=key1 header.b=hynZXdId X-Envelope-To: linux-kernel@vger.kernel.org DKIM-Signature: a=rsa-sha256; bh=f1eWVKd30GvS3wsCmv5dpnTEOybkzWBsH0KkLzLUzJE=; c=simple/simple; d=linux.dev; h=from:to:subject:date:message-id:mime-version:content-type; s=key1; t=1796063292; v=1; x=1796668092; b=hynZXdIdf5ynnkdOG/SdLvXgppD+PpFG2QdjxtrBjLdFBC4RdClE1aZpU4ZDoZ0vNLbrQRyf B7rNcJB/JuhcZx5cfXRjehVFx/shBtJ3VOafXmC+orBYJJXgeaja27rrUkX8Q9ioI07DidKh+Hj Fy+ezF33H4isx6DgdZLeGHYw= X-Envelope-To: linux-kernel@vger.kernel.org Received: by smtp.migadu.com with ESMTPS id 70f9337cd2f77300; Mon, 30 Nov 2026 18:28:12 +0000 X-Mizu-Trace-ID: 70f9337cd2f77300 X-Migadu-Flow: FLOW_OUT From: Shakeel Butt 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@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 Message-ID: <20261130182755.666042-2-shakeel.butt@linux.dev> X-Mailer: git-send-email 2.53.1 In-Reply-To: <20261130182755.666042-1-shakeel.butt@linux.dev> References: <20261130182755.666042-1-shakeel.butt@linux.dev> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit 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 --- 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 #include #include +#include #include #include @@ -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