mm/swap: free swap cache folios the zap path gave up on
Subsystems (2)
PATCH 1/1 mm/swap: free swap cache folios the zap path gave up on
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.
Such a slot has swap count 0 and an unmapped folio pinned in the swap cache, left there after a process exited or did MADV_DONTNEED. No page table holds its swap entry any more, so nothing comes back for the slot; LRU reclaim drops it eventually, and the allocator only reclaims such slots once swap is half full. The growth stopped exactly there:
at 50% of the device, where vm_swap_full() becomes true.
The race is readahead against a zap in a neighbouring thread. Readahead works on virtual addresses, so a fault at the end of thread A's range pulls in the entries at the start of thread B's range:
thread A thread B
do_swap_page()
swap_vma_readahead()
swap_cache_read_folio(B's entry)
folio locked, added to cache
swap_read_folio() MADV_DONTNEED
zswap_load() / bio in flight zap_nonpresent_ptes()
. swap_put_entries_cluster()
. swap count 1 -> 0
. __try_to_reclaim_swap()
. folio_trylock() fails
. gives up
folio_unlock()
folio_put()
-> slot: swap count 0, folio in swap cache, not mapped, never freed
The lock is one reason it gives up. The other is writeback: with a block device as backing store, B's own PAGEOUT leaves the folio in the swap cache under writeback, and when the DONTNEED comes __try_to_reclaim_swap() gets the lock but folio_swapcache_freeable() refuses. The write completes, nobody frees the slot. The present-PTE side has the same two outcomes through free_swap_cache().
Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
2. swapoff/swapon clears it, as does memory.reclaim on the right cgroup. That is a workaround, not a fix.
3. Have the side that gives up come back later. This patch.
The zap runs under the PTL and the fault path takes the folio lock before the PTL, so waiting there is out; a worker has to do it. On a lost trylock or a writeback refusal under TTRS_UNMAPPED, __try_to_reclaim_swap() schedules si->sweep_work. The worker walks the in-use clusters and, for every slot with swap count 0 whose folio is unmapped, calls __try_to_reclaim_swap() with TTRS_WAIT, which takes the folio lock and waits for writeback instead of giving up. free_swap_cache() now calls __try_to_reclaim_swap() as well, so both paths give up, and wake the worker, in the same place.
For now the worker scans every in-use cluster of the device; marking the clusters that need it can reduce that later.
--- include/linux/swap.h | 1 + mm/swap.h | 1 + mm/swap_state.c | 9 ++-- mm/swapfile.c | 101 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 104 insertions(+), 8 deletions(-)
include/linux/swap.h +1 -0
@@ -267,6 +267,7 @@ struct swap_info_struct {*/ struct work_struct discard_work;/* discard worker */ struct work_struct reclaim_work;/* reclaim worker */ +struct work_struct sweep_work;/* frees swap cache only slots a zap gave up on */ struct list_head discard_clusters;/* discard clusters list */ struct plist_node avail_list;/* entry in swap_avail_head */ const struct swap_ops *ops;
mm/swap.h +1 -0
@@ -309,6 +309,7 @@ static inline bool folio_matches_swap_entry(const struct folio *folio,* - See the comment of get_swap_device() for more complex usage. */ bool swap_cache_has_folio (swp_entry_t entry); +void swap_reclaim_entry (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);
mm/swap_state.c +3 -6
@@ -598,16 +598,13 @@ void swap_writeback_dropbehind_folio(struct folio *folio)* * Its ok to check the swapcache flag without the folio lock * here because we are going to recheck again inside -* folio_free_swap() _with_ the lock. +* __try_to_reclaim_swap() _with_ the lock. * - Marcelo */ 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)) +swap_reclaim_entry (folio->swap); }/*
mm/swapfile.c +99 -2
143 lines not on this page · raw message
Signature · 1 line
2.43.0
Andrew Morton
maintainerQuoted 9 lines · On Wed, 14 Oct 2026 17:08:19 +0800 Jiayuan Chen <[email protected]> wrote:
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.
Quoted 6 lines
Such a slot has swap count 0 and an unmapped folio pinned in the swap cache, left there after a process exited or did
MADV_DONTNEED. No page table holds its swap entry any more, so nothing comes back for the slot; LRU reclaim drops it eventually, and the allocator only reclaims such slots once swap is half full. The growth stopped exactly there:
at 50% of the device, wherevm_swap_full()becomes true.
That's a pretty nasty problem - thanks for working on it.
Quoted 20 lines
Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
2. swapoff/swapon clears it, as does memory.reclaim on the right cgroup. That is a workaround, not a fix.
3. Have the side that gives up come back later. This patch.The zap runs under the PTL and the fault path takes the folio lock before the PTL, so waiting there is out; a worker has to do it. On a lost trylock or a writeback refusal under
TTRS_UNMAPPED,__try_to_reclaim_swap()schedulessi->sweep_work. The worker walks the in-use clusters and, for every slot with swap count 0 whose folio is unmapped, calls__try_to_reclaim_swap()withTTRS_WAIT, which takes the folio lock and waits for writeback instead of giving up.free_swap_cache()now calls__try_to_reclaim_swap()as well, so both paths give up, and wake the worker, in the same place.
Quoted 2 lines
For now the worker scans every in-use cluster of the device; marking the clusters that need it can reduce that later.
It's a substantial patch. There's no quick-n-dirty fixup we can prepare for backporting into older kernels?
Quoted 5 lines
include/linux/swap.h | 1 + mm/swap.h | 1 + mm/swap_state.c | 9 ++-- mm/swapfile.c | 101 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 104 insertions(+), 8 deletions(-)
Sashiko had a few things to say:
https://sashiko.dev/#/patchset/[email protected]
Quoted 39 lines · Andrew Morton
Quoted 9 lines · On Wed, 14 Oct 2026 17:08:19 +0800 Jiayuan Chen <[email protected]> wrote:
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.Quoted 6 lines
Such a slot has swap count 0 and an unmapped folio pinned in the swap cache, left there after a process exited or did
MADV_DONTNEED. No page table holds its swap entry any more, so nothing comes back for the slot; LRU reclaim drops it eventually, and the allocator only reclaims such slots once swap is half full. The growth stopped exactly there:
at 50% of the device, wherevm_swap_full()becomes true.That's a pretty nasty problem - thanks for working on it.
Quoted 20 lines
Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
2. swapoff/swapon clears it, as does memory.reclaim on the right cgroup. That is a workaround, not a fix.
3. Have the side that gives up come back later. This patch.The zap runs under the PTL and the fault path takes the folio lock before the PTL, so waiting there is out; a worker has to do it. On a lost trylock or a writeback refusal under
TTRS_UNMAPPED,__try_to_reclaim_swap()schedulessi->sweep_work. The worker walks the in-use clusters and, for every slot with swap count 0 whose folio is unmapped, calls__try_to_reclaim_swap()withTTRS_WAIT, which takes the folio lock and waits for writeback instead of giving up.free_swap_cache()now calls__try_to_reclaim_swap()as well, so both paths give up, and wake the worker, in the same place.
Quoted 4 lines
Quoted 2 lines
For now the worker scans every in-use cluster of the device; marking the clusters that need it can reduce that later.
It's a substantial patch. There's no quick-n-dirty fixup we can prepare for backporting into older kernels?
I couldn't find a small one. I tried the other options listed in the changelog, and each was either incomplete or spread over many places.
The zap can only trylock, and the folio can be held by many things at that moment: readahead (sync and async reads), writeback, zswap writeback, reclaim, migration, folio split and so on. Fixing it on that side means patching each of them, and missing one leaves the leak. This patch fixes it in the one place they all have in common, the zap that gives up.
As for older kernels, I found this on 6.6 and I'm happy to do the backports.
Quoted 8 lines
Quoted 5 lines
include/linux/swap.h | 1 + mm/swap.h | 1 + mm/swap_state.c | 9 ++-- mm/swapfile.c | 101 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 104 insertions(+), 8 deletions(-)Sashiko had a few things to say:
https://sashiko.dev/#/patchset/[email protected]
Thanks. The large folio split and the offset step are real and come
from TTRS_WAIT.
The swap_cache_get_folio() race is pre-existing, I could reproduce it and will send a separate fix.
Nhat Pham
reviewerQuoted 6 lines · Jiayuan Chen
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged
That's a really nasty situation.
Quoted 3 lines
to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.
Is it not similar to cold file caches?
The recommendation for these kind of scenarios (for both file and anon) is to adopt a proactive reclaimer (in the same vein as senpai). That's what we do internally.
Quoted 3 lines
Cc Jiayuan Chen <[email protected]>Signed-off-by Jiayuan Chen <[email protected]>
Code looks solid to me otherwise. Maybe include some numbers from your testing in the cover letter to verify that the swap cache usage drop.
Hi Nhat
Quoted 6 lines · Nhat Pham
Quoted 5 lines · Jiayuan Chen
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged
Quoted 6 lines
That's a really nasty situation.
Quoted 3 lines
to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.
Is it not similar to cold file caches?
Not quite. A cold file cache can still be hit later. These folios can't: no page table holds the swap entry any more, so nothing will ever look them up again. They also hold swap slots, not just RAM, and the allocator skips those slots until swap is half full.
Quoted 3 lines
The recommendation for these kind of scenarios (for both file and anon) is to adopt a proactive reclaimer (in the same vein as senpai). That's what we do internally.
Proactive reclaim does free them, but it works around the leak rather than fixing it. In our case they were charged to cgroups that had already been removed, so there was no cgroup left to reclaim from, and reclaiming from the parent pushed out live anon first
Quoted 4 lines
Quoted 2 lines
Cc Jiayuan Chen <[email protected]>Signed-off-by Jiayuan Chen <[email protected]>Code looks solid to me otherwise. Maybe include some numbers from your testing in the cover letter to verify that the swap cache usage drop.
Thanks, will do in next version.
Quoted 9 lines · Jiayuan Chen
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.
Hi, thanks for the report.
Quoted 6 lines
Such a slot has swap count 0 and an unmapped folio pinned in the swap cache, left there after a process exited or did
MADV_DONTNEED. No page table holds its swap entry any more, so nothing comes back for the slot; LRU reclaim drops it eventually, and the allocator only reclaims such slots once swap is half full. The growth stopped exactly there:
at 50% of the device, wherevm_swap_full()becomes true.
Hmm, I think this indicates a much cleaner fix is available. vm_swap_full is inherited from the old allocator, we can instead just let the allocator reclaim the slot if the slot have a count of 0 and ignore vm_swap_full at that point.
Will this work? (Just a minimal implementation for reference, will be even better if we can avoid the overhead).
mm/swapfile.c +0 -0
@@ -212,6 +212,9 @@ static int __try_to_reclaim_swap(struct
swap_info_struct *si,
nr_pages = folio_nr_pages(folio);
ret = -nr_pages;+ if (folio_mapped(folio) && !vm_swap_full())
+ goto out;
+
/*
* We hold a folio lock here. We have to use trylock for
* avoiding deadlock. This is a special case and you should
@@ -903,8 +906,6 @@ static bool cluster_scan_range(struct swap_info_struct *si,
if (swp_tb_is_null(swp_tb))
continue;
if (swp_tb_is_folio(swp_tb) && !__swp_tb_get_count(swp_tb)) {
- if (!vm_swap_full())
- return false;
*need_reclaim = true;
continue;
}Or, from the LRU's side, put swap readahead folios at the tail. I'm actually trying to do that and it's not very easily doable at the moment but will soon be easy to do.
Quoted 6 lines
Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
In fact, readahead checks the count before starts the read. It should prevent some of the problems but seems not enough.
And another idea, what if we just add dropbehind flag or rotate the folio, if folio_try_lock failed in __try_to_reclaim_swap?
Quoted 42 lines · Kairui Song
Quoted 8 lines · Jiayuan Chen
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.Hi, thanks for the report.
Quoted 6 lines
Such a slot has swap count 0 and an unmapped folio pinned in the swap cache, left there after a process exited or did
MADV_DONTNEED. No page table holds its swap entry any more, so nothing comes back for the slot; LRU reclaim drops it eventually, and the allocator only reclaims such slots once swap is half full. The growth stopped exactly there:
at 50% of the device, wherevm_swap_full()becomes true.Hmm, I think this indicates a much cleaner fix is available.
vm_swap_fullis inherited from the old allocator, we can instead just let the allocator reclaim the slot if the slot have a count of 0 and ignorevm_swap_fullat that point.Will this work? (Just a minimal implementation for reference, will be even better if we can avoid the overhead).
mm/swapfile.c +3
-0@@ -212,6 +212,9 @@ static int __try_to_reclaim_swap(structswap_info_struct *si, nr_pages =folio_nr_pages (folio); ret = -nr_pages; +if (folio_mapped (folio) && !vm_swap_full ()) + goto out; +/* * We hold a folio lock here. We have to use trylock for * avoiding deadlock. This is a special case and you should
mm/swapfile.c static bool cluster_scan_range(struct swap_info_struct *si, · line 911
Quoted 8 lines
mm/swapfile.c +0
-2@@ -903,8 +906,6 @@ static bool cluster_scan_range(struct swap_info_struct *si,if (swp_tb_is_null (swp_tb))continue ;if (swp_tb_is_folio (swp_tb) && !__swp_tb_get_count (swp_tb)) { -if (!vm_swap_full ()) -return false; *need_reclaim = true;continue ; }
Hi Kairui,
I tried it on our box (224 CPUs, 931 GiB swap partition). It doesn't help there: after 100 rounds of the reproducer the leftover is 291 GB with it and 309 GB without, and both stop growing at the same place, 488 GB, half of the device:
# cat /proc/swaps Filename Type Size Used Priority /dev/nvme1n1p1 partition 976561148 489006260 -1
# cat /proc/meminfo | grep Swap SwapCached: 489006260 kB SwapTotal: 976561148 kB SwapFree: 487554888 kB
cluster_alloc_swap_entry() picks clusters from nonfull_clusters first, then free_clusters; it looks at frag_clusters only when both are empty, and at full_clusters only when vm_swap_full(). A cluster gets onto nonfull_clusters in partial_free_cluster(), that is when __swap_cluster_free_entries() frees a slot in it; after alloc_swap_scan_cluster() has used it, relocate_cluster() moves it to frag or full.
A leftover slot has count 0 and a folio, so __swap_cluster_free_entries() never runs for it. Once the live slots of a cluster are gone, nothing calls partial_free_cluster() on it again, it stays on frag or full, and cluster_alloc_swap_entry() doesn't pick it until the device is half full. That is what the swap table looked like after the run:
list clusters leftover slots
FULL 106415 54484480 (all 512 slots leftover) FRAG 44822 18471614
NONFULL 1 0
Making cluster_alloc_swap_entry() revisit those clusters means changing the list policy.
Quoted 3 lines
Or, from the LRU's side, put swap readahead folios at the tail. I'm actually trying to do that and it's not very easily doable at the moment but will soon be easy to do.
That helps the RAM side under pressure but doesn't give the slots back.
Quoted 8 lines
Quoted 6 lines
Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
In fact, readahead checks the count before starts the read. It should prevent some of the problems but seems not enough.
Right, the count is still 1 at that point. The zap drops it to 0 while the read is in flight, after the folio is already in the swap cache.
Quoted 2 lines
And another idea, what if we just add dropbehind flag or rotate the folio, if
folio_try_lockfailed in__try_to_reclaim_swap?
dropbehind would work for readahead and writeback if the read completion honoured it too; today only folio_end_writeback() does, for zswap writeback folios, and swap_writeback_dropbehind_folio() expects the folio off the LRU. It still misses other lock holders (migration, split, ...). Rotating only helps under memory pressure.
Quoted 121 lines · Jiayuan Chen
Quoted 42 lines · Kairui Song
Quoted 8 lines · Jiayuan Chen
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.Hi, thanks for the report.
Quoted 6 lines
Such a slot has swap count 0 and an unmapped folio pinned in the swap cache, left there after a process exited or did
MADV_DONTNEED. No page table holds its swap entry any more, so nothing comes back for the slot; LRU reclaim drops it eventually, and the allocator only reclaims such slots once swap is half full. The growth stopped exactly there:
at 50% of the device, wherevm_swap_full()becomes true.Hmm, I think this indicates a much cleaner fix is available.
vm_swap_fullis inherited from the old allocator, we can instead just let the allocator reclaim the slot if the slot have a count of 0 and ignorevm_swap_fullat that point.Will this work? (Just a minimal implementation for reference, will be even better if we can avoid the overhead).
mm/swapfile.c +3
-0@@ -212,6 +212,9 @@ static int __try_to_reclaim_swap(structswap_info_struct *si, nr_pages =folio_nr_pages (folio); ret = -nr_pages; +if (folio_mapped (folio) && !vm_swap_full ()) + goto out; +/* * We hold a folio lock here. We have to use trylock for * avoiding deadlock. This is a special case and you should
mm/swapfile.c static bool cluster_scan_range(struct swap_info_struct *si, · line 911
Quoted 8 lines
mm/swapfile.c +0
-2@@ -903,8 +906,6 @@ static bool cluster_scan_range(struct swap_info_struct *si,if (swp_tb_is_null (swp_tb))continue ;if (swp_tb_is_folio (swp_tb) && !__swp_tb_get_count (swp_tb)) { -if (!vm_swap_full ()) -return false; *need_reclaim = true;continue ; }Hi Kairui,
I tried it on our box (224 CPUs, 931 GiB swap partition). It doesn't help there: after 100 rounds of the reproducer the leftover is 291 GB with it and 309 GB without, and both stop growing at the same place, 488 GB, half of the device:
# cat /proc/swaps Filename Type Size Used Priority /dev/nvme1n1p1 partition 976561148 489006260 -1# cat /proc/meminfo | grep Swap SwapCached: 489006260 kB SwapTotal: 976561148 kB SwapFree: 487554888 kB
cluster_alloc_swap_entry()picks clusters fromnonfull_clustersfirst, thenfree_clusters; it looks atfrag_clustersonly when both are empty, and atfull_clustersonly whenvm_swap_full(). A cluster gets ontononfull_clustersinpartial_free_cluster(), that is when__swap_cluster_free_entries()frees a slot in it; afteralloc_swap_scan_cluster()has used it,relocate_cluster()moves it to frag or full.A leftover slot has count 0 and a folio, so
__swap_cluster_free_entries()never runs for it. Once the live slots of a cluster are gone, nothing callspartial_free_cluster()on it again, it stays on frag or full, andcluster_alloc_swap_entry()doesn't pick it until the device is half full. That is what the swap table looked like after the run:list clusters leftover slots
FULL 106415 54484480 (all 512 slots leftover)
FRAG 44822 18471614
NONFULL 1 0Making
cluster_alloc_swap_entry()revisit those clusters means changing the list policy.Quoted 3 lines
Or, from the LRU's side, put swap readahead folios at the tail. I'm actually trying to do that and it's not very easily doable at the moment but will soon be easy to do.
That helps the RAM side under pressure but doesn't give the slots back.
Quoted 8 lines
Quoted 6 lines
Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
In fact, readahead checks the count before starts the read. It should prevent some of the problems but seems not enough.
Right, the count is still 1 at that point. The zap drops it to 0 while the read is in flight, after the folio is already in the swap cache.
Quoted 2 lines
And another idea, what if we just add dropbehind flag or rotate the folio, if
folio_try_lockfailed in__try_to_reclaim_swap?
Quoted 5 lines
dropbehind would work for readahead and writeback if the read completion honoured it too; today only
folio_end_writeback()does, for zswap writeback folios, andswap_writeback_dropbehind_folio()expects the folio off the LRU. It still misses other lock holders (migration, split, ...). Rotating only helps under memory pressure.
Right.. But I think it will be much better to avoid such folios from hunging in the swap cache in the first place instead of having a worker to reclaim them. I'm not strongly against adding a reclaimer if other approaches are too difficult at this point though.
Nhat Pham
reviewerQuoted 123 lines · Kairui Song
Quoted 121 lines · Jiayuan Chen
Quoted 42 lines · Kairui Song
Quoted 8 lines · Jiayuan Chen
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.Hi, thanks for the report.
Quoted 6 lines
Such a slot has swap count 0 and an unmapped folio pinned in the swap cache, left there after a process exited or did
MADV_DONTNEED. No page table holds its swap entry any more, so nothing comes back for the slot; LRU reclaim drops it eventually, and the allocator only reclaims such slots once swap is half full. The growth stopped exactly there:
at 50% of the device, wherevm_swap_full()becomes true.Hmm, I think this indicates a much cleaner fix is available.
vm_swap_fullis inherited from the old allocator, we can instead just let the allocator reclaim the slot if the slot have a count of 0 and ignorevm_swap_fullat that point.Will this work? (Just a minimal implementation for reference, will be even better if we can avoid the overhead).
mm/swapfile.c +3
-0@@ -212,6 +212,9 @@ static int __try_to_reclaim_swap(structswap_info_struct *si, nr_pages =folio_nr_pages (folio); ret = -nr_pages; +if (folio_mapped (folio) && !vm_swap_full ()) + goto out; +/* * We hold a folio lock here. We have to use trylock for * avoiding deadlock. This is a special case and you should
mm/swapfile.c static bool cluster_scan_range(struct swap_info_struct *si, · line 911
Quoted 8 lines
mm/swapfile.c +0
-2@@ -903,8 +906,6 @@ static bool cluster_scan_range(struct swap_info_struct *si,if (swp_tb_is_null (swp_tb))continue ;if (swp_tb_is_folio (swp_tb) && !__swp_tb_get_count (swp_tb)) { -if (!vm_swap_full ()) -return false; *need_reclaim = true;continue ; }Hi Kairui,
I tried it on our box (224 CPUs, 931 GiB swap partition). It doesn't help there: after 100 rounds of the reproducer the leftover is 291 GB with it and 309 GB without, and both stop growing at the same place, 488 GB, half of the device:
# cat /proc/swaps Filename Type Size Used Priority /dev/nvme1n1p1 partition 976561148 489006260 -1# cat /proc/meminfo | grep Swap SwapCached: 489006260 kB SwapTotal: 976561148 kB SwapFree: 487554888 kB
cluster_alloc_swap_entry()picks clusters fromnonfull_clustersfirst, thenfree_clusters; it looks atfrag_clustersonly when both are empty, and atfull_clustersonly whenvm_swap_full(). A cluster gets ontononfull_clustersinpartial_free_cluster(), that is when__swap_cluster_free_entries()frees a slot in it; afteralloc_swap_scan_cluster()has used it,relocate_cluster()moves it to frag or full.A leftover slot has count 0 and a folio, so
__swap_cluster_free_entries()never runs for it. Once the live slots of a cluster are gone, nothing callspartial_free_cluster()on it again, it stays on frag or full, andcluster_alloc_swap_entry()doesn't pick it until the device is half full. That is what the swap table looked like after the run:list clusters leftover slots
FULL 106415 54484480 (all 512 slots leftover)
FRAG 44822 18471614
NONFULL 1 0Making
cluster_alloc_swap_entry()revisit those clusters means changing the list policy.Quoted 3 lines
Or, from the LRU's side, put swap readahead folios at the tail. I'm actually trying to do that and it's not very easily doable at the moment but will soon be easy to do.
That helps the RAM side under pressure but doesn't give the slots back.
Quoted 8 lines
Quoted 6 lines
Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
In fact, readahead checks the count before starts the read. It should prevent some of the problems but seems not enough.
Right, the count is still 1 at that point. The zap drops it to 0 while the read is in flight, after the folio is already in the swap cache.
Quoted 2 lines
And another idea, what if we just add dropbehind flag or rotate the folio, if
folio_try_lockfailed in__try_to_reclaim_swap?
Quoted 5 lines
Quoted 5 lines
dropbehind would work for readahead and writeback if the read completion honoured it too; today only
folio_end_writeback()does, for zswap writeback folios, andswap_writeback_dropbehind_folio()expects the folio off the LRU. It still misses other lock holders (migration, split, ...). Rotating only helps under memory pressure.
Yeah might be worth trying. You'd have to modify readahead and zswap load logic to check folio_mapped() etc. I suppose...
I'm not sure how reliable it will be FWIW. There is still a race window right? Albeit a bit smaller - the readahead thread might check the dropbehind flag before __try_to_reclaim_swap() sets it.
Quoted 5 lines
Right.. But I think it will be much better to avoid such folios from hunging in the swap cache in the first place instead of having a worker to reclaim them. I'm not strongly against adding a reclaimer if other approaches are too difficult at this point though.
Also, IIRC, dropbehind can only be handled in task context, right? We'd need to make readahead bios to complete in task context (BIO_COMPLETE_IN_TASK). I wonder if this has any perf implications.
Another idea: how about, in swap_read_folio(), where we are guaranteed to have the folio's lock, we check if folio is mapped. If it's not, invoke folio_free_swap(), unlock, put, then drop that folio from the submit batch? That takes care of the readahead race. Seems safe to me (I assume if a folio is not mapped and swap count == 0, then it's a pure readahead artifact, but maybe I'm missing a case).
The write direction already tries folio_free_swap() before submitting the writeback, FWIW. So that takes care of both directions. But who knows - maybe we still have a small race window, and that's bad enough.
Quoted 1 line · Nhat Pham
On
[...]
Quoted 69 lines
/proc/meminfo| grep SwapSwapCached: 489006260 kB SwapTotal: 976561148 kB SwapFree: 487554888 kB
cluster_alloc_swap_entry()picks clusters fromnonfull_clustersfirst, thenfree_clusters; it looks atfrag_clustersonly when both are empty, and atfull_clustersonly whenvm_swap_full(). A cluster gets ontononfull_clustersinpartial_free_cluster(), that is when__swap_cluster_free_entries()frees a slot in it; afteralloc_swap_scan_cluster()has used it,relocate_cluster()moves it to frag or full.A leftover slot has count 0 and a folio, so
__swap_cluster_free_entries()never runs for it. Once the live slots of a cluster are gone, nothing callspartial_free_cluster()on it again, it stays on frag or full, andcluster_alloc_swap_entry()doesn't pick it until the device is half full. That is what the swap table looked like after the run:list clusters leftover slots
FULL 106415 54484480 (all 512 slots leftover)
FRAG 44822 18471614
NONFULL 1 0Making
cluster_alloc_swap_entry()revisit those clusters means changing the list policy.Quoted 21 lines
Quoted 21 lines
Quoted 3 lines
Or, from the LRU's side, put swap readahead folios at the tail. I'm actually trying to do that and it's not very easily doable at the moment but will soon be easy to do.
That helps the RAM side under pressure but doesn't give the slots back.
Quoted 8 lines
Quoted 6 lines
Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
In fact, readahead checks the count before starts the read. It should prevent some of the problems but seems not enough.
Right, the count is still 1 at that point. The zap drops it to 0 while the read is in flight, after the folio is already in the swap cache.
Quoted 8 lines
Quoted 8 lines
Quoted 2 lines
And another idea, what if we just add dropbehind flag or rotate the folio, if
folio_try_lockfailed in__try_to_reclaim_swap?dropbehind would work for readahead and writeback if the read completion honoured it too; today only
folio_end_writeback()does, for zswap writeback folios, andswap_writeback_dropbehind_folio()expects the folio off the LRU. It still misses other lock holders (migration, split, ...). Rotating only helps under memory pressure.Yeah might be worth trying. You'd have to modify readahead and zswap load logic to check
folio_mapped()etc. I suppose...I'm not sure how reliable it will be FWIW. There is still a race window right? Albeit a bit smaller - the readahead thread might check the dropbehind flag before
__try_to_reclaim_swap()sets it.Quoted 4 lines
Right.. But I think it will be much better to avoid such folios from hunging in the swap cache in the first place instead of having a worker to reclaim them. I'm not strongly against adding a reclaimer if other approaches are too difficult at this point though.
Quoted 8 lines
Also, IIRC, dropbehind can only be handled in task context, right? We'd need to make readahead bios to complete in task context (
BIO_COMPLETE_IN_TASK). I wonder if this has any perf implications.Another idea: how about, in
swap_read_folio(), where we are guaranteed to have the folio's lock, we check if folio is mapped. If it's not, invokefolio_free_swap(), unlock, put, then drop that folio from the submit batch?
At that point the swap count is still 1; the zap comes while the read is in flight. Checking after the read works for the synchronous zswap path, which I tried first, but the bdev read is unlocked in swap_bio_read_end_io(), in interrupt context, where the slot cannot be freed.
Quoted 6 lines
That takes care of the readahead race. Seems safe to me (I assume if a folio is not mapped and swap count == 0, then it's a pure readahead artifact, but maybe I'm missing a case).
The write direction already tries
folio_free_swap()before submitting the writeback, FWIW.
Same shape: the zap arrives after that check, while the folio is under writeback. On our box with a swap partition that is where most of the leftover came from.
Every check on the holder's side runs while the count is still 1. Only the zap sees it go to 0, and it cannot wait. That is why the patch has the zap hand it over instead (very nasty i know it :( ).
Quoted 3 lines
So that takes care of both directions. But who
knows - maybe we still have a small race window, and that's bad enough.
Nhat Pham
reviewerQuoted 86 lines · Jiayuan Chen
Quoted 1 line · Nhat Pham
On
[...]
Quoted 69 lines
/proc/meminfo| grep SwapSwapCached: 489006260 kB SwapTotal: 976561148 kB SwapFree: 487554888 kB
cluster_alloc_swap_entry()picks clusters fromnonfull_clustersfirst, thenfree_clusters; it looks atfrag_clustersonly when both are empty, and atfull_clustersonly whenvm_swap_full(). A cluster gets ontononfull_clustersinpartial_free_cluster(), that is when__swap_cluster_free_entries()frees a slot in it; afteralloc_swap_scan_cluster()has used it,relocate_cluster()moves it to frag or full.A leftover slot has count 0 and a folio, so
__swap_cluster_free_entries()never runs for it. Once the live slots of a cluster are gone, nothing callspartial_free_cluster()on it again, it stays on frag or full, andcluster_alloc_swap_entry()doesn't pick it until the device is half full. That is what the swap table looked like after the run:list clusters leftover slots
FULL 106415 54484480 (all 512 slots leftover)
FRAG 44822 18471614
NONFULL 1 0Making
cluster_alloc_swap_entry()revisit those clusters means changing the list policy.Quoted 21 lines
Quoted 21 lines
Quoted 3 lines
Or, from the LRU's side, put swap readahead folios at the tail. I'm actually trying to do that and it's not very easily doable at the moment but will soon be easy to do.
That helps the RAM side under pressure but doesn't give the slots back.
Quoted 8 lines
Quoted 6 lines
Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
In fact, readahead checks the count before starts the read. It should prevent some of the problems but seems not enough.
Right, the count is still 1 at that point. The zap drops it to 0 while the read is in flight, after the folio is already in the swap cache.
Quoted 8 lines
Quoted 8 lines
Quoted 2 lines
And another idea, what if we just add dropbehind flag or rotate the folio, if
folio_try_lockfailed in__try_to_reclaim_swap?dropbehind would work for readahead and writeback if the read completion honoured it too; today only
folio_end_writeback()does, for zswap writeback folios, andswap_writeback_dropbehind_folio()expects the folio off the LRU. It still misses other lock holders (migration, split, ...). Rotating only helps under memory pressure.Yeah might be worth trying. You'd have to modify readahead and zswap load logic to check
folio_mapped()etc. I suppose...I'm not sure how reliable it will be FWIW. There is still a race window right? Albeit a bit smaller - the readahead thread might check the dropbehind flag before
__try_to_reclaim_swap()sets it.Quoted 4 lines
Right.. But I think it will be much better to avoid such folios from hunging in the swap cache in the first place instead of having a worker to reclaim them. I'm not strongly against adding a reclaimer if other approaches are too difficult at this point though.
Quoted 8 lines
Also, IIRC, dropbehind can only be handled in task context, right? We'd need to make readahead bios to complete in task context (
BIO_COMPLETE_IN_TASK). I wonder if this has any perf implications.Another idea: how about, in
swap_read_folio(), where we are guaranteed to have the folio's lock, we check if folio is mapped. If it's not, invokefolio_free_swap(), unlock, put, then drop that folio from the submit batch?
Quoted 5 lines
At that point the swap count is still 1; the zap comes while the read is in flight. Checking after the read works for the synchronous zswap path, which I tried first, but the bdev read is unlocked in
swap_bio_read_end_io(), in interrupt context, where the slot cannot be freed.
Zap drops swap count first, then try to free swap cache. You're saying the read check the swap count before zap dropping it, but still holds the lock by the time zap try to free swap cache? :(
I was kinda hoping this kind of interleaving would be rare :(
And yeah, I think if we want to free the slot after read, readahead swap IOs have to be submitted with BIO_COMPLETE_IN_TASK. zswap writeback's dropbehind relied on that...
Quoted 9 lines
Quoted 8 lines
That takes care of the readahead race. Seems safe to me (I assume if a folio is not mapped and swap count == 0, then it's a pure readahead artifact, but maybe I'm missing a case).
The write direction already tries
folio_free_swap()before submitting the writeback, FWIW.
Quoted 7 lines
Same shape: the zap arrives after that check, while the folio is under writeback. On our box with a swap partition that is where most of the leftover came from.
Every check on the holder's side runs while the count is still 1. Only the zap sees it go to 0, and it cannot wait. That is why the patch has the zap hand it over instead (very nasty i know it :( ).
Yeah I got no smarter ideas :( sweep_work it is...
Quoted 1 line · Nhat Pham
On Mon, Oct 19, 2026 at 7:37 AM Jiayuan Chen <[email protected]> wrote:
[...]
Quoted 12 lines
Quoted 12 lines
Quoted 12 lines
Quoted 4 lines
Right.. But I think it will be much better to avoid such folios from hunging in the swap cache in the first place instead of having a worker to reclaim them. I'm not strongly against adding a reclaimer if other approaches are too difficult at this point though.
Also, IIRC, dropbehind can only be handled in task context, right? We'd need to make readahead bios to complete in task context (
BIO_COMPLETE_IN_TASK). I wonder if this has any perf implications.Another idea: how about, in
swap_read_folio(), where we are guaranteed to have the folio's lock, we check if folio is mapped. If it's not, invokefolio_free_swap(), unlock, put, then drop that folio from the submit batch?
Quoted 8 lines
Quoted 5 lines
At that point the swap count is still 1; the zap comes while the read is in flight. Checking after the read works for the synchronous zswap path, which I tried first, but the bdev read is unlocked in
swap_bio_read_end_io(), in interrupt context, where the slot cannot be freed.Zap drops swap count first, then try to free swap cache. You're saying the read check the swap count before zap dropping it, but still holds the lock by the time zap try to free swap cache? :(
Yes, exactly that. With the check in swap_read_folio():
thread A (readahead) thread B swap_cache_alloc_folio(B's entry)
folio locked, added to cache
swap count 1 (B's PTE)swap_read_folio()
folio_free_swap()
count is 1, nothing to do
zswap_load() / submit_bio()
. MADV_DONTNEED
. swap count 1 -> 0 . __try_to_reclaim_swap() . folio_trylock() fails . gives up read completesfolio_unlock()folio_put()
-> count 0, folio in swap cache, unmapped
The check runs before the zap, so it sees count 1. The zap comes while A holds the lock for the read.
Checking after the read instead is what I tried first. It works for the synchronous path and not for the bdev one:
zswap (sync) bdev (async) swap_read_folio() swap_read_folio() zswap_load() submit_bio()
. <- zap, count 1 -> 0 return <- zap, count 1 -> 0 read done, lock still held ...
count is 0: free the slot, fine swap_bio_read_end_io() (irq) folio_unlock() folio_unlock()
no ci->lock here, slot stays
The write side is the same picture with swap_writeout() and end_swap_bio_write().
Quoted 1 line
I was kinda hoping this kind of interleaving would be rare :(
It is rare per event, but it adds up. On production it takes days to leave a few GiB behind. The DONTNEED there comes from jemalloc, which issues it on every free the application does, so it never stops. Our reproducer is the extreme case, built only to verify the problem: it leaves 480 GB in about an hour. I'll put the numbers in the commit message.
Quoted 3 lines
And yeah, I think if we want to free the slot after read, readahead swap IOs have to be submitted with
BIO_COMPLETE_IN_TASK. zswap writeback's dropbehind relied on that...
Right, and that would still leave the writeback side. The worker covers both in one place.
Quoted 16 lines
Quoted 8 lines
Quoted 8 lines
That takes care of the readahead race. Seems safe to me (I assume if a folio is not mapped and swap count == 0, then it's a pure readahead artifact, but maybe I'm missing a case).
The write direction already tries
folio_free_swap()before submitting the writeback, FWIW.Quoted 7 lines
Same shape: the zap arrives after that check, while the folio is under writeback. On our box with a swap partition that is where most of the leftover came from.
Every check on the holder's side runs while the count is still 1. Only the zap sees it go to 0, and it cannot wait. That is why the patch has the zap hand it over instead (very nasty i know it :( ).
Yeah I got no smarter ideas :(
sweep_workit is...
Quoted 111 lines · Jiayuan Chen
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.Such a slot has swap count 0 and an unmapped folio pinned in the swap cache, left there after a process exited or did
MADV_DONTNEED. No page table holds its swap entry any more, so nothing comes back for the slot; LRU reclaim drops it eventually, and the allocator only reclaims such slots once swap is half full. The growth stopped exactly there:
at 50% of the device, wherevm_swap_full()becomes true.The race is readahead against a zap in a neighbouring thread. Readahead works on virtual addresses, so a fault at the end of thread A's range pulls in the entries at the start of thread B's range:
thread A thread B
do_swap_page()
swap_vma_readahead()
swap_cache_read_folio(B's entry)
folio locked, added to cache
swap_read_folio()MADV_DONTNEED
zswap_load()/ bio in flightzap_nonpresent_ptes()
.swap_put_entries_cluster()
. swap count 1 -> 0
.__try_to_reclaim_swap()
.folio_trylock()fails
. gives up
folio_unlock()
folio_put()
-> slot: swap count 0, folio in swap cache, not mapped, never freedThe lock is one reason it gives up. The other is writeback: with a block device as backing store, B's own PAGEOUT leaves the folio in the swap cache under writeback, and when the DONTNEED comes
__try_to_reclaim_swap()gets the lock butfolio_swapcache_freeable()refuses. The write completes, nobody frees the slot. The present-PTE side has the same two outcomes throughfree_swap_cache().Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
2. swapoff/swapon clears it, as does memory.reclaim on the right cgroup. That is a workaround, not a fix.
3. Have the side that gives up come back later. This patch.The zap runs under the PTL and the fault path takes the folio lock before the PTL, so waiting there is out; a worker has to do it. On a lost trylock or a writeback refusal under
TTRS_UNMAPPED,__try_to_reclaim_swap()schedulessi->sweep_work. The worker walks the in-use clusters and, for every slot with swap count 0 whose folio is unmapped, calls__try_to_reclaim_swap()withTTRS_WAIT, which takes the folio lock and waits for writeback instead of giving up.free_swap_cache()now calls__try_to_reclaim_swap()as well, so both paths give up, and wake the worker, in the same place.For now the worker scans every in-use cluster of the device; marking the clusters that need it can reduce that later.
Cc Jiayuan Chen <[email protected]>Signed-off-by Jiayuan Chen <[email protected]>--- include/linux/swap.h | 1 + mm/swap.h | 1 + mm/swap_state.c | 9 ++-- mm/swapfile.c | 101 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 104 insertions(+), 8 deletions(-)include/linux/swap.h +1
-0@@ -267,6 +267,7 @@ struct swap_info_struct {*/ struct work_struct discard_work;/* discard worker */ struct work_struct reclaim_work;/* reclaim worker */ +struct work_struct sweep_work;/* frees swap cache only slots a zap gave up on */ struct list_head discard_clusters;/* discard clusters list */ struct plist_node avail_list;/* entry in swap_avail_head */ const struct swap_ops *ops;mm/swap.h +1
-0@@ -309,6 +309,7 @@ static inline bool folio_matches_swap_entry(const struct folio *folio,* - See the comment of get_swap_device() for more complex usage. */ bool swap_cache_has_folio (swp_entry_t entry); +void swap_reclaim_entry (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);mm/swap_state.c +1
-1@@ -598,16 +598,13 @@ void swap_writeback_dropbehind_folio(struct folio *folio)* * Its ok to check the swapcache flag without the folio lock * here because we are going to recheck again inside -* folio_free_swap() _with_ the lock. +* __try_to_reclaim_swap() _with_ the lock. * - Marcelo
mm/swap_state.c void swap_writeback_dropbehind_folio(struct folio *folio) · line 607
Quoted 10 lines
mm/swap_state.c +2
-5*/ 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)) +swap_reclaim_entry (folio->swap);
One problem here, if folio is not locked, you might read garbage from folio->swap.
Quoted 38 lines
mm/swap_state.c +0
-0}/* mm/swapfile.c +13
-1@@ -172,6 +172,8 @@ static long swap_usage_in_pages(struct swap_info_struct *si)#define TTRS_UNMAPPED 0x2/* Reclaim the swap entry if swap is getting full */ #define TTRS_FULL 0x4 +/* May sleep: wait for the folio lock and for writeback instead of giving up */ +#define TTRS_WAIT 0x8static bool swap_only_has_cache (struct swap_cluster_info *ci,unsigned long offset,int nr_pages)@@ -217,9 +219,19 @@ static int __try_to_reclaim_swap(struct swap_info_struct *si,* avoiding deadlock. This is a special case and you should * use folio_free_swap() with explicit folio_lock() in usual * operations. +* +* The zap path (TTRS_UNMAPPED) is the one caller for which giving +* up means the slot is never looked at again: it stays allocated +* with count 0 and an unmapped folio pinned in the swap cache. Let +* the sweep worker, which can wait, come back for it. */ -if (!folio_trylock (folio)) +if (flags &TTRS_WAIT ) { +folio_lock (folio); + }else if (!folio_trylock (folio)) { +if (flags &TTRS_UNMAPPED ) +schedule_work (&si->sweep_work); goto out; + }/* * Offset could point to the middle of a large folio, or folio
mm/swapfile.c static int __try_to_reclaim_swap(struct swap_info_struct *si, · line 248
Quoted 5 lines
mm/swapfile.c +2
-0@@ -232,11 +244,20 @@ static int __try_to_reclaim_swap(struct swap_info_struct *si, } offset =swp_offset (folio->swap); +if (flags &TTRS_WAIT ) +folio_wait_writeback (folio);
You may merge this into the TTRS_WAIT check above?
Quoted 34 lines
mm/swapfile.c +22
-1+ 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)) { +/* Same for a folio the zap caught under writeback. */ +if ((flags &TTRS_UNMAPPED ) &&folio_test_writeback (folio)) +schedule_work (&si->sweep_work); goto out_unlock; + }/* * It's safe to delete the folio from swap cache only if the folio @@ -1099,6 +1120,80 @@ static void swap_reclaim_work(struct work_struct *work)swap_reclaim_full_clusters (si, true); } +/* +* Free the slots a zap could not take back: swap cache only, count 0, folio +* not mapped. The zap runs under the PTL, so when the folio was locked (a +* readahead or an asynchronous swap-in still reading into it) or under +* writeback, __try_to_reclaim_swap() had to give up and scheduled us. Such +* a slot is reachable by nobody but LRU reclaim: no page table holds its +* entry, and the allocator skips it until swap is half full. Here we can +* wait for the lock and the writeback. +*/ +static void swap_sweep_work (struct work_struct *work) +{ +struct swap_info_struct *si; +struct swap_cluster_info *ci; +unsigned long offset, end, swp_tb;
mm/swapfile.c static void swap_reclaim_work(struct work_struct *work) · line 1146
Quoted 10 lines
mm/swapfile.c +10
-0+unsigned long nr_clusters; +int nr_reclaim; + + si = container_of(work, struct swap_info_struct, sweep_work); + nr_clusters =DIV_ROUND_UP (si->max,SWAPFILE_CLUSTER ); + +for (unsigned long i =0 ; i < nr_clusters; i++) { + ci = si->cluster_info + i; + offset = i *SWAPFILE_CLUSTER ; + end =min (si->max, offset +SWAPFILE_CLUSTER );
IIUC scanning the whole device for one pending folio reclaim doesnt' look good..
Quoted 1 line · Kairui Song
On Wed, Oct 14, 2026 at 5:10 PM Jiayuan Chen <[email protected]> wrote:
[...]
Quoted 13 lines
Quoted 13 lines
mm/swap_state.c +1
-2@@ -598,16 +598,13 @@ void swap_writeback_dropbehind_folio(struct folio *folio)* * Its ok to check the swapcache flag without the folio lock * here because we are going to recheck again inside -* folio_free_swap() _with_ the lock. +* __try_to_reclaim_swap() _with_ the lock. * - Marcelo */ void free_swap_cache (struct folio *folio) { - if (folio_test_swapcache(folio) && !folio_mapped(folio) &&
Quoted 8 lines
mm/swap_state.c void swap_writeback_dropbehind_folio(struct folio *folio) · line 607
Quoted 6 lines
mm/swap_state.c +2
-4- folio_trylock(folio)) { -folio_free_swap (folio); -folio_unlock (folio); - } +if (folio_test_swapcache (folio) && !folio_mapped (folio)) +swap_reclaim_entry (folio->swap);One problem here, if folio is not locked, you might read garbage from
folio->swap.
Right, keep the trylock in free_swap_cache() and only read folio->swap under it.
Quoted 42 lines
Quoted 42 lines
mm/swap_state.c +0
-0}/* mm/swapfile.c +13
-1@@ -172,6 +172,8 @@ static long swap_usage_in_pages(struct swap_info_struct *si)#define TTRS_UNMAPPED 0x2/* Reclaim the swap entry if swap is getting full */ #define TTRS_FULL 0x4 +/* May sleep: wait for the folio lock and for writeback instead of giving up */ +#define TTRS_WAIT 0x8static bool swap_only_has_cache (struct swap_cluster_info *ci,unsigned long offset,int nr_pages)@@ -217,9 +219,19 @@ static int __try_to_reclaim_swap(struct swap_info_struct *si,* avoiding deadlock. This is a special case and you should * use folio_free_swap() with explicit folio_lock() in usual * operations. +* +* The zap path (TTRS_UNMAPPED) is the one caller for which giving +* up means the slot is never looked at again: it stays allocated +* with count 0 and an unmapped folio pinned in the swap cache. Let +* the sweep worker, which can wait, come back for it. */ -if (!folio_trylock (folio)) +if (flags &TTRS_WAIT ) { +folio_lock (folio); + }else if (!folio_trylock (folio)) { +if (flags &TTRS_UNMAPPED ) +schedule_work (&si->sweep_work); goto out; + }/* * Offset could point to the middle of a large folio, or folio @@ -232,11 +244,20 @@ static int __try_to_reclaim_swap(struct swap_info_struct *si, } offset =swp_offset (folio->swap);
Quoted 3 lines
mm/swapfile.c static int __try_to_reclaim_swap(struct swap_info_struct *si, · line 248
Quoted 2 lines
mm/swapfile.c +2
-0+if (flags &TTRS_WAIT ) +folio_wait_writeback (folio);You may merge this into the
TTRS_WAITcheck above?
Right !
Quoted 37 lines
Quoted 37 lines
mm/swapfile.c +25
-1+ 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)) { +/* Same for a folio the zap caught under writeback. */ +if ((flags &TTRS_UNMAPPED ) &&folio_test_writeback (folio)) +schedule_work (&si->sweep_work); goto out_unlock; + }/* * It's safe to delete the folio from swap cache only if the folio @@ -1099,6 +1120,80 @@ static void swap_reclaim_work(struct work_struct *work)swap_reclaim_full_clusters (si, true); } +/* +* Free the slots a zap could not take back: swap cache only, count 0, folio +* not mapped. The zap runs under the PTL, so when the folio was locked (a +* readahead or an asynchronous swap-in still reading into it) or under +* writeback, __try_to_reclaim_swap() had to give up and scheduled us. Such +* a slot is reachable by nobody but LRU reclaim: no page table holds its +* entry, and the allocator skips it until swap is half full. Here we can +* wait for the lock and the writeback. +*/ +static void swap_sweep_work (struct work_struct *work) +{ +struct swap_info_struct *si; +struct swap_cluster_info *ci; +unsigned long offset, end, swp_tb; +unsigned long nr_clusters; +int nr_reclaim; +
Quoted 8 lines
mm/swapfile.c static void swap_reclaim_work(struct work_struct *work) · line 1146
Quoted 7 lines
mm/swapfile.c +7
-0+ si = container_of(work, struct swap_info_struct, sweep_work); + nr_clusters =DIV_ROUND_UP (si->max,SWAPFILE_CLUSTER ); + +for (unsigned long i =0 ; i < nr_clusters; i++) { + ci = si->cluster_info + i; + offset = i *SWAPFILE_CLUSTER ; + end =min (si->max, offset +SWAPFILE_CLUSTER );IIUC scanning the whole device for one pending folio reclaim doesnt' look good..
Agreed. What I'd really like is a mark on the cluster itself, so the worker only walks the clusters that need it (mentioned in commit message). That needs more thought though, especially with Andrew's point about backporting in mind, so I want to be careful there.
Quoted 112 lines · Jiayuan Chen
From: Jiayuan Chen <[email protected]>
On our production hosts we saw swap cache only pages keep growing for days:
on a box with a 500 GiB swap partition, 250 GiB of RAM and 250 GiB of swap slots were held by folios that no process mapped any more, charged to cgroups whose workloads had long exited. The only way to get them back was swapoff, and with other services actively swapping on the same host that is not an option.Such a slot has swap count 0 and an unmapped folio pinned in the swap cache, left there after a process exited or did
MADV_DONTNEED. No page table holds its swap entry any more, so nothing comes back for the slot; LRU reclaim drops it eventually, and the allocator only reclaims such slots once swap is half full. The growth stopped exactly there:
at 50% of the device, wherevm_swap_full()becomes true.The race is readahead against a zap in a neighbouring thread. Readahead works on virtual addresses, so a fault at the end of thread A's range pulls in the entries at the start of thread B's range:
thread A thread B
do_swap_page()
swap_vma_readahead()
swap_cache_read_folio(B's entry)
folio locked, added to cache
swap_read_folio()MADV_DONTNEED
zswap_load()/ bio in flightzap_nonpresent_ptes()
.swap_put_entries_cluster()
. swap count 1 -> 0
.__try_to_reclaim_swap()
.folio_trylock()fails
. gives up
folio_unlock()
folio_put()
-> slot: swap count 0, folio in swap cache, not mapped, never freedThe lock is one reason it gives up. The other is writeback: with a block device as backing store, B's own PAGEOUT leaves the folio in the swap cache under writeback, and when the DONTNEED comes
__try_to_reclaim_swap()gets the lock butfolio_swapcache_freeable()refuses. The write completes, nobody frees the slot. The present-PTE side has the same two outcomes throughfree_swap_cache().Options considered:
1. Fix it on the readahead side: after the read, check the swap count and free the slot. Covers the lock, not writeback, and the asynchronous read path unlocks in the bio completion where the slot cannot be freed. Two places to patch, neither clean.
2. swapoff/swapon clears it, as does memory.reclaim on the right cgroup. That is a workaround, not a fix.
3. Have the side that gives up come back later. This patch.The zap runs under the PTL and the fault path takes the folio lock before the PTL, so waiting there is out; a worker has to do it. On a lost trylock or a writeback refusal under
TTRS_UNMAPPED,__try_to_reclaim_swap()schedulessi->sweep_work. The worker walks the in-use clusters and, for every slot with swap count 0 whose folio is unmapped, calls__try_to_reclaim_swap()withTTRS_WAIT, which takes the folio lock and waits for writeback instead of giving up.free_swap_cache()now calls__try_to_reclaim_swap()as well, so both paths give up, and wake the worker, in the same place.For now the worker scans every in-use cluster of the device; marking the clusters that need it can reduce that later.
Cc Jiayuan Chen <[email protected]>Signed-off-by Jiayuan Chen <[email protected]>--- include/linux/swap.h | 1 + mm/swap.h | 1 + mm/swap_state.c | 9 ++-- mm/swapfile.c | 101 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 104 insertions(+), 8 deletions(-)include/linux/swap.h +1
-0@@ -267,6 +267,7 @@ struct swap_info_struct {*/ struct work_struct discard_work;/* discard worker */ struct work_struct reclaim_work;/* reclaim worker */ +struct work_struct sweep_work;/* frees swap cache only slots a zap gave up on */ struct list_head discard_clusters;/* discard clusters list */ struct plist_node avail_list;/* entry in swap_avail_head */ const struct swap_ops *ops;mm/swap.h +1
-0@@ -309,6 +309,7 @@ static inline bool folio_matches_swap_entry(const struct folio *folio,* - See the comment of get_swap_device() for more complex usage. */ bool swap_cache_has_folio (swp_entry_t entry); +void swap_reclaim_entry (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);mm/swap_state.c +1
-1@@ -598,16 +598,13 @@ void swap_writeback_dropbehind_folio(struct folio *folio)* * Its ok to check the swapcache flag without the folio lock * here because we are going to recheck again inside -* folio_free_swap() _with_ the lock. +* __try_to_reclaim_swap() _with_ the lock. * - Marcelo */ void free_swap_cache (struct folio *folio)
mm/swap_state.c void swap_writeback_dropbehind_folio(struct folio *folio) · line 609
Quoted 10 lines
mm/swap_state.c +2
-5{ -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)) +swap_reclaim_entry (folio->swap); }
I spent some more time on this and I'm not happy with any of the options I have. Advice welcome.
1. Trigger the worker where the zap gives up (this patch). On the swap entry side that works, __try_to_reclaim_swap() has the si. On the present PTE side it doesn't: free_swap_cache() lost the trylock, so it can't read folio->swap to find the si, as Kairui pointed out. And that trylock-and-give-up is not in one place, free_swap_cache(), do_wp_page() and __uprobe_write() all have their own copy. Chasing every one of them doesn't feel right.
2. Clean up at memcg offline. Doesn't cover the root cgroup or a cgroup that stays alive, and on mm-new the folios are reparented at offline anyway, so there is nothing left to find there.
3. A swapon flag, say --clean-cache, that enables the cleanup.
Pro: covers everything, and the cleanup can live in its own function without touching the existing paths. Con: we know to turn it on because we hit this, others won't. Needs util-linux too.
4. A per-device worker that walks the device on its own, say 1024 clusters per second, backing off when a pass finds nothing.
Pro: same as 3, and nothing to turn on. Con: a worker that wakes up on its own for this, I expect objections.
5. A sysctl (or a drop_caches bit) to kick the cleanup by hand.
Pro: same as 4, all in the worker. Con: same as 3, someone has to know to poke it.